okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0f1e5e4cb
main
1"""Focused pack compatibility tests; run .venv/bin/python -m unittest discover -s tools -p test_iq_pack.py.""" 2import contextlib 3import hashlib 4import io 5import json 6from pathlib import Path 7import sys 8import tempfile 9import unittest 10from unittest .mock import patch 11 12import numpy as np 13 14sys .path .insert (0 ,str (Path (__file__ ).resolve ().parent ))# runnable from the repo root too 15 16from _paths import gguf_lib 17import iq_pack # needs numpy + gguf_reader only: import it unguarded 18 19try : 20_gguf = gguf_lib ()# tools/strata_gguf.py (STRATA_GGUF_PY selects llama.cpp's gguf-py; it exits when that is not a gguf-py folder) 21GGUFWriter ,Q ,quants = _gguf .GGUFWriter ,_gguf .GGMLQuantizationType ,_gguf .quants 22except SystemExit : 23GGUF_PY = None 24else : 25GGUF_PY = "found" 26 27 28def require_gguf_py (test ): 29"""setUpClass for the classes that build GGUF fixtures: skip (not fail) on a checkout without llama.cpp.""" 30@classmethod 31def setUpClass (cls ): 32if GGUF_PY is None : 33raise unittest .SkipTest ("STRATA_GGUF_PY does not name a gguf-py folder" ) 34return setUpClass 35 36 37def write_gguf (path ,tensors ,split = None ,arch = True ): 38"""`split` = (no, count, tensors): llama.cpp's gguf-split keys (0-based split.no).""" 39writer = GGUFWriter (path ,"qwen4exp" ) 40if not arch :# a later shard of a split: no model metadata 41writer .remove_key ("general.architecture" ) 42if split is not None : 43writer .add_uint16 ("split.no" ,split [0 ]) 44writer .add_uint16 ("split.count" ,split [1 ]) 45writer .add_int32 ("split.tensors.count" ,split [2 ]) 46for name ,values ,kind in tensors : 47writer .add_tensor (name ,quants .quantize (values ,kind ),raw_dtype = kind ) 48writer .write_header_to_file () 49writer .write_kv_data_to_file () 50writer .write_tensors_to_file () 51writer .close () 52 53 54class CompatibilityTests (unittest .TestCase ): 55setUpClass = require_gguf_py (unittest .TestCase ) 56def test_bf16_halfway_rounds_to_even (self ): 57values = np .array ([0x3F808000 ,0x3F818000 ,0xBF808000 ,0xBF818000 ],dtype = np .uint32 ) 58got = np .frombuffer (iq_pack .bf16_bytes (values .view (np .uint8 ),"F32" ),dtype = np .uint16 ) 59np .testing .assert_array_equal (got , [0x3F80 ,0x3F82 ,0xBF80 ,0xBF82 ]) 60 61def test_nonfinite_conversion_refused (self ): 62with self .assertRaisesRegex (ValueError ,"non-finite" ): 63iq_pack .bf16_bytes (np .array ([np .nan ],dtype = np .float32 ).view (np .uint8 ),"F32" ) 64 65def test_projection_conversion_and_native_bytes (self ): 66with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 67root = Path (tmp ) 68source = root / "model.gguf" 69values = np .linspace (- 1 ,1 ,256 ,dtype = np .float32 ).reshape (2 ,128 ) 70router = np .full ((2 ,128 ),0.10001 ,dtype = np .float32 ) 71names = ["blk.0.hc_attn_down.weight" ,"output_hc_up.weight" , 72"blk.0.ssm_alpha.weight" ,"blk.3.indexer.q_proj.weight" ,"blk.1.ple_value.weight" ] 73write_gguf (source , [(n ,values ,Q .Q8_0 )for n in names ]+ [ 74 ("blk.1.ple_key.weight" ,values ,Q .Q8_0 ), 75 ("blk.0.ffn_gate_inp.weight" ,router ,Q .F32 ), 76 ("blk.0.attn_qkv.weight" ,values ,Q .Q8_0 ), 77 ("per_layer_token_embd.weight" ,values ,Q .Q8_0 ), 78 ]) 79before = source .read_bytes () 80model = iq_pack .Model (source ) 81with contextlib .redirect_stdout (io .StringIO ()): 82self .assertEqual (iq_pack .index_standalone (source ,root ,model ,True ),0 ) 83_ ,rows = iq_pack .read_index (root / "index.txt" ) 84dense = (root / "dense.bin" ).read_bytes () 85# A scalar oracle independent of the BF16 encoder: choose the nearest BF16 value, 86# using the even representation at exact ties. 87decoded = quants .dequantize (quants .quantize (values ,Q .Q8_0 ),Q .Q8_0 ).ravel () 88def rounded (x ): 89bits = int (np .float32 (x ).view (np .uint32 )) 90return (bits >> 16 )+ ((bits & 65535 )> 32768 or 91 ((bits & 65535 )== 32768 and (bits >> 16 )& 1 )) 92expected = np .array ([rounded (x )for x in decoded ],dtype = np .uint16 ) 93for name in names : 94row = rows [name ] 95self .assertEqual (row [2 ],"4" ) 96offset ,size = int (row [3 ]),int (row [4 ]) 97np .testing .assert_array_equal (np .frombuffer (dense [offset :offset + size ],dtype = np .uint16 ),expected ) 98for name in ["blk.0.attn_qkv.weight" ,"blk.1.ple_key.weight" ]:# a Q8_0 PLE key stays native 99native = rows [name ] 100self .assertEqual (native [2 ],"0" ) 101self .assertEqual (native [4 ],"0" ) 102self .assertEqual (native [9 ],"8" ) 103self .assertNotIn ("per_layer_token_embd.weight" ,rows ) 104self .assertEqual (source .read_bytes (),before ) 105self .assertEqual (len (json .loads ((root / "compat-bf16.json" ).read_text ())["tensors" ]),6 ) 106conv = json .loads ((root / "conversions.json" ).read_text ()) 107self .assertEqual (sorted (r ["name" ]for r in conv ["tensors" ]),sorted (names + ["blk.0.ffn_gate_inp.weight" ])) 108 109def test_default_still_refuses_inexact_f32_router (self ): 110with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 111root = Path (tmp ) 112source = root / "model.gguf" 113write_gguf (source , [("blk.0.ffn_gate_inp.weight" ,np .full ((2 ,32 ),0.10001 ,np .float32 ),Q .F32 )]) 114with contextlib .redirect_stdout (io .StringIO ()): 115self .assertEqual (iq_pack .index_standalone (source ,root ,iq_pack .Model (source )),1 ) 116 117def test_existing_bf16_pack_remains_byte_identical (self ): 118with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 119root = Path (tmp ) 120source = root / "model.gguf" 121values = np .linspace (- 2 ,2 ,256 ,dtype = np .float32 ).reshape (2 ,128 ) 122write_gguf (source , [("blk.0.hc_attn_down.weight" ,values ,Q .BF16 )]) 123with contextlib .redirect_stdout (io .StringIO ()): 124self .assertEqual (iq_pack .index_standalone (source ,root ,iq_pack .Model (source )),0 ) 125self .assertEqual ((root / "dense.bin" ).read_bytes (),quants .quantize (values ,Q .BF16 ).tobytes ()) 126 127def test_quantized_control_weights_need_explicit_conversion (self ): 128with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 129root = Path (tmp ) 130source = root / "model.gguf" 131write_gguf (source , [("blk.0.hc_attn_down.weight" ,np .ones ((2 ,32 ),np .float32 ),Q .Q8_0 )]) 132 (root / "dense.bin" ).write_bytes (b"previous pack" ) 133with contextlib .redirect_stdout (io .StringIO ()): 134self .assertEqual (iq_pack .index_standalone (source ,root ,iq_pack .Model (source )),1 ) 135self .assertEqual ((root / "dense.bin" ).read_bytes (),b"previous pack" ) 136 137def test_q2_ple_and_large_tensors_stay_native (self ): 138self .assertFalse (iq_pack .needs_bf16 ("blk.1.ple_key.weight" ,"Q2_0" )) 139self .assertFalse (iq_pack .needs_bf16 ("blk.1.ple_key.weight" ,"Q8_0" )) 140self .assertFalse (iq_pack .needs_bf16 ("blk.1.ple_key.weight" ,"IQ3_XXS" )) 141self .assertFalse (iq_pack .needs_bf16 ("blk.1.ple_key.weight" ,"IQ4_XS" )) 142self .assertTrue (iq_pack .needs_bf16 ("blk.1.ple_key.weight" ,"Q6_K" )) 143for name in ["blk.0.ffn_gate_exps.weight" ,"token_embd.weight" ,"output.weight" , 144"per_layer_token_embd.weight" ,"blk.0.attn_qkv.weight" ]: 145self .assertFalse (iq_pack .needs_bf16 (name ,"IQ3_XXS" )) 146 147def test_iq_ple_keys_are_indexed_without_conversion (self ): 148for kind ,block_bytes in [(Q .IQ3_XXS ,98 ), (Q .IQ4_XS ,136 )]: 149with self .subTest (kind = kind ),tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 150root = Path (tmp ) 151source = root / "model.gguf" 152writer = GGUFWriter (source ,"qwen4exp" ) 153writer .add_tensor ("blk.1.ple_key.weight" ,np .zeros ((2 ,block_bytes ),dtype = np .uint8 ), 154raw_dtype = kind ) 155writer .write_header_to_file () 156writer .write_kv_data_to_file () 157writer .write_tensors_to_file () 158writer .close () 159before = source .read_bytes () 160with contextlib .redirect_stdout (io .StringIO ()): 161self .assertEqual (iq_pack .index_standalone (source ,root ,iq_pack .Model (source )),0 ) 162_ ,rows = iq_pack .read_index (root / "index.txt" ) 163row = rows ["blk.1.ple_key.weight" ] 164self .assertEqual (row [2 ],"0" ) 165self .assertEqual ((root / "dense.bin" ).read_bytes (),b"" ) 166self .assertEqual (json .loads ((root / "conversions.json" ).read_text ())["tensors" ], []) 167self .assertEqual (source .read_bytes (),before ) 168 169def test_experts_bin_is_kept_only_with_this_ggufs_blobs (self ): 170with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 171root = Path (tmp ) 172out = root / "pack" 173 (out / "tokenizer" ).mkdir (parents = True ) 174for name in ["vocab.json" ,"chat_template.jinja" ]: 175 (out / "tokenizer" / name ).touch () 176 177def model (name ,scale ): 178path = root / name 179write_gguf (path , [("blk.%d.hc_attn_down.weight" % l ,np .ones ((2 ,32 ),np .float32 ),Q .BF16 ) 180for l in range (3 )]+ 181 [("blk.%d.ffn_gate_inp.weight" % l ,np .ones ((4 ,32 ),np .float32 ),Q .BF16 ) 182for l in range (3 )]+ 183 [("blk.%d.ffn_%s_exps.weight" % (l ,r ), 184scale * np .arange (4 * 2 * 32 ,dtype = np .float32 ).reshape (4 ,2 ,32 )/ 256 ,Q .Q8_0 ) 185for l in range (3 )for r in ("gate" ,"up" ,"down" )]) 186return path 187 188def pack (path ): 189log = io .StringIO () 190argv = ["iq_pack.py" ,"--gguf" ,str (path ),"--out" ,str (out ),"--experts-bin" ] 191with patch .object (sys ,"argv" ,argv ),contextlib .redirect_stdout (log ): 192self .assertEqual (iq_pack .main (),0 ) 193return log .getvalue () 194 195first = model ("a.gguf" ,1 ) 196pack (first ) 197written = (out / "experts.bin" ).read_bytes () 198self .assertIn ("not rewritten" ,pack (first )) 199self .assertEqual ((out / "experts.bin" ).read_bytes (),written ) 200# the same geometry with other weights under the same file name: the size and the sidecar (shard names 201# and sizes, native_experts.txt) match, the contents do not 202second = model ("a.gguf" ,- 1 ) 203self .assertIn ("not this GGUF's expert blobs" ,pack (second )) 204rewritten = (out / "experts.bin" ).read_bytes () 205self .assertEqual (len (rewritten ),len (written )) 206self .assertNotEqual (rewritten ,written ) 207self .assertIn ("not rewritten" ,pack (second )) 208 209def test_snapshot_symlinks_keep_split_discovery (self ): 210with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 211root = Path (tmp ) 212snap = root / "snapshot" 213snap .mkdir () 214first = snap / "model-00001-of-00002.gguf" 215second = snap / "model-00002-of-00002.gguf" 216write_gguf (root / "blob1" , [ 217 ("blk.0.hc_attn_down.weight" ,np .ones ((2 ,32 ),np .float32 ),Q .Q8_0 ), 218 ("blk.0.ffn_gate_inp.weight" ,np .ones ((512 ,32 ),np .float32 ),Q .BF16 ), 219 ],split = (0 ,2 ,5 )) 220write_gguf (root / "blob2" , [(f"blk.0.ffn_ { r } _exps.weight" ,np .ones ((512 ,2 ,32 ),np .float32 ),Q .Q8_0 ) 221for r in ("gate" ,"up" ,"down" )],split = (1 ,2 ,5 ),arch = False ) 222try : 223first .symlink_to (root / "blob1" ) 224except OSError :# Windows without Developer Mode or admin rights 225self .skipTest ("symlinks are not available here" ) 226with self .assertRaisesRegex (FileNotFoundError ,"missing model shards" ): 227iq_pack .Model (first ) 228second .symlink_to (root / "blob2" ) 229out = root / "pack" 230 (out / "tokenizer" ).mkdir (parents = True ) 231for name in ["vocab.json" ,"chat_template.jinja" ]: 232 (out / "tokenizer" / name ).touch () 233with patch .object (sys ,"argv" , ["iq_pack.py" ,"--gguf" ,str (first ),"--out" ,str (out ),"--compat-bf16" ]): 234with contextlib .redirect_stdout (io .StringIO ()): 235self .assertEqual (iq_pack .main (),0 ) 236expert_index = (out / "native_experts.txt" ).read_text () 237self .assertIn (second .name ,expert_index ) 238self .assertIn ("n_expert 512," ,expert_index ) 239 (root / "blob2" ).write_bytes ((root / "blob2" ).read_bytes ()[:- 64 ]) 240with self .assertRaisesRegex (ValueError ,"truncated tensor" ): 241iq_pack .Model (first ) 242 243 244 245def bits (u32 ): 246return np .array (u32 ,dtype = np .uint32 ).view (np .float32 ) 247 248 249def pack_one (root ,tensors ,* flags ): 250"""A one-file model of `tensors` packed into `root` (index only): (rc, printed, rows, dense, conversions).""" 251source = root / "model.gguf" 252write_gguf (source ,tensors ) 253buf = io .StringIO () 254with contextlib .redirect_stdout (buf ): 255rc = iq_pack .index_standalone (source ,root ,iq_pack .Model (source ),* flags ) 256if rc : 257return rc ,buf .getvalue (),None ,None ,None 258_ ,rows = iq_pack .read_index (root / "index.txt" ) 259conv = json .loads ((root / "conversions.json" ).read_text ()) 260return rc ,buf .getvalue (),rows , (root / "dense.bin" ).read_bytes (),conv 261 262 263def stored (rows ,dense ,name ,dtype ): 264row = rows [name ] 265return np .frombuffer (dense [int (row [3 ]):int (row [3 ])+ int (row [4 ])],dtype = dtype ) 266 267 268class ConversionTests (unittest .TestCase ): 269"""CS2: FORM decides the engine's form; exact F32->BF16 by default, rounding only with --compat-bf16, the PLE 270conv F32 -> F16 by the loader (index kind 3), non-finite values refused, every conversion in conversions.json.""" 271 272setUpClass = require_gguf_py (unittest .TestCase ) 273 274def test_exact_f32_to_bf16_by_default (self ): 275with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 276x = bits (np .arange (64 ,dtype = np .uint32 ).reshape (2 ,32 )<< 16 | 0x3F000000 )# BF16 values held as F32 277rc ,log ,rows ,dense ,conv = pack_one (Path (tmp ), [("blk.0.hc_attn_inject.weight" ,x ,Q .F32 ), 278 ("blk.0.ssm_beta.weight" ,x ,Q .F32 ), 279 ("blk.0.ssm_norm.weight" ,x ,Q .F32 )]) 280self .assertEqual (rc ,0 ,log ) 281for name in ["blk.0.hc_attn_inject.weight" ,"blk.0.ssm_beta.weight" ]: 282self .assertEqual (rows [name ][2 ],"4" ) 283np .testing .assert_array_equal (stored (rows ,dense ,name ,"<u2" ), (x .view (np .uint32 )>> 16 ).ravel ()) 284self .assertEqual (rows ["blk.0.ssm_norm.weight" ][2 ],"2" )# F32 form: as stored 285recs = {r ["name" ]:r for r in conv ["tensors" ]} 286self .assertEqual (set (recs ), {"blk.0.hc_attn_inject.weight" ,"blk.0.ssm_beta.weight" }) 287r = recs ["blk.0.ssm_beta.weight" ] 288self .assertEqual ((r ["src_type" ],r ["dst_type" ],r ["exact" ],r ["max_abs_err" ],r ["shard" ]), 289 ("F32" ,"BF16" ,True ,0.0 ,"model.gguf" )) 290self .assertEqual (r ["source_sha256" ],hashlib .sha256 (x .tobytes ()).hexdigest ()) 291self .assertEqual (conv ["schema" ],1 ) 292self .assertEqual (conv ["source_shards" ], [{"name" :"model.gguf" , 293"size" : (Path (tmp )/ "model.gguf" ).stat ().st_size }]) 294 295def test_inexact_f32_rounds_only_with_compat (self ): 296with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 297x = np .linspace (- 1 ,1 ,64 ,dtype = np .float32 ).reshape (2 ,32 )+ np .float32 (1e-4 ) 298rc ,log ,* _ = pack_one (Path (tmp ), [("blk.0.hc_ffn_inject.weight" ,x ,Q .F32 )]) 299self .assertEqual (rc ,1 ) 300self .assertIn ("not BF16" ,log ) 301rc ,log ,rows ,dense ,conv = pack_one (Path (tmp ), [("blk.0.hc_ffn_inject.weight" ,x ,Q .F32 )],True ) 302self .assertEqual (rc ,0 ,log ) 303got = stored (rows ,dense ,"blk.0.hc_ffn_inject.weight" ,"<u2" ) 304np .testing .assert_array_equal (got ,np .frombuffer (iq_pack .bf16_bytes (x .view (np .uint8 ).ravel (),"F32" ), 305dtype = "<u2" )) 306r = conv ["tensors" ][0 ] 307back = (got .astype (np .uint32 )<< 16 ).view (np .float32 ) 308self .assertFalse (r ["exact" ]) 309self .assertAlmostEqual (r ["max_abs_err" ],float (np .max (np .abs (back - x .ravel ())))) 310self .assertLessEqual (r ["max_abs_err" ],2.0 ** - 8 ) 311self .assertIn ("--compat-bf16" ,r ["method" ]) 312 313def test_non_finite_is_refused (self ): 314for bad in (0x7FC00000 ,0x7F800000 ,0xFF800000 ):# NaN and +-Inf: their low 16 bits are zero too 315with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 316x = bits ([[0x3F800000 ]* 31 + [bad ]]* 2 ) 317 (Path (tmp )/ "dense.bin" ).write_bytes (b"previous pack" ) 318for flags in ((), (True ,)): 319rc ,log ,* _ = pack_one (Path (tmp ), [("blk.0.ssm_alpha.weight" ,x ,Q .F32 )],* flags ) 320self .assertEqual (rc ,1 , (hex (bad ),flags )) 321self .assertIn ("non-finite" ,log ) 322self .assertEqual ((Path (tmp )/ "dense.bin" ).read_bytes (),b"previous pack" ) 323self .assertFalse ((Path (tmp )/ "dense.bin.tmp" ).exists ()) 324rc ,log ,* _ = pack_one (Path (tmp ), [("blk.1.ple_conv1d.weight" ,x ,Q .F32 )]) 325self .assertEqual (rc ,1 ) 326self .assertIn ("non-finite" ,log ) 327 328def test_ple_conv1d_f32_is_narrowed_by_the_loader (self ): 329with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 330conv1d = np .random .default_rng (3 ).normal (0 ,0.0062 , (32 ,4 )).astype (np .float32 ) 331rc ,log ,rows ,dense ,conv = pack_one (Path (tmp ), [("blk.1.ple_conv1d.weight" ,conv1d ,Q .F32 )]) 332self .assertEqual (rc ,0 ,log )# no --compat-bf16 needed 333row = rows ["blk.1.ple_conv1d.weight" ] 334self .assertEqual ((row [2 ],row [4 ],row [6 ]), ("3" ,str (conv1d .nbytes ),str (conv1d .nbytes // 2 ))) 335np .testing .assert_array_equal (stored (rows ,dense ,"blk.1.ple_conv1d.weight" ,"<f4" ),conv1d .ravel ()) 336r = conv ["tensors" ][0 ] 337self .assertEqual ((r ["src_type" ],r ["dst_type" ]), ("F32" ,"F16" )) 338self .assertIn ("index kind 3" ,r ["method" ]) 339h = conv1d .astype (np .float16 ).astype (np .float32 ) 340self .assertEqual (r ["exact" ],bool (np .array_equal (h ,conv1d ))) 341self .assertAlmostEqual (r ["max_abs_err" ],float (np .max (np .abs (h - conv1d )))) 342self .assertIn ("narrowed to F16 by the loader" ,log ) 343# an F16 conv (the GSQ-RCO files) stays as it is: index kind 5, nothing recorded 344rc ,log ,rows ,dense ,conv = pack_one (Path (tmp ), [("blk.1.ple_conv1d.weight" ,conv1d ,Q .F16 )]) 345self .assertEqual ((rows ["blk.1.ple_conv1d.weight" ][2 ],conv ["tensors" ]), ("5" , [])) 346# beyond F16's range: refused, not saturated 347rc ,log ,* _ = pack_one (Path (tmp ), [("blk.1.ple_conv1d.weight" ,conv1d * 1e7 ,Q .F32 )]) 348self .assertEqual (rc ,1 ) 349self .assertIn ("beyond F16" ,log ) 350 351def test_q8_0_projections_need_compat_and_are_recorded (self ): 352with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 353v = np .random .default_rng (4 ).normal (0 ,0.05 , (4 ,64 )).astype (np .float32 ) 354tensors = [("blk.1.ple_value.weight" ,v ,Q .Q8_0 ), ("blk.2.hc_attn_up.weight" ,v ,Q .Q8_0 ), 355 ("blk.1.ple_key.weight" ,v ,Q .Q8_0 )] 356rc ,log ,* _ = pack_one (Path (tmp ),tensors ) 357self .assertEqual (rc ,1 ) 358self .assertIn ("use --compat-bf16" ,log ) 359self .assertNotIn ("ple_key" ,log )# the Q8_0 key stays native 360rc ,log ,rows ,dense ,conv = pack_one (Path (tmp ),tensors ,True ) 361self .assertEqual (rc ,0 ,log ) 362self .assertEqual (rows ["blk.1.ple_key.weight" ][2 ],"0" ) 363recs = {r ["name" ]:r for r in conv ["tensors" ]} 364self .assertEqual (set (recs ), {"blk.1.ple_value.weight" ,"blk.2.hc_attn_up.weight" }) 365deq = quants .dequantize (quants .quantize (v ,Q .Q8_0 ),Q .Q8_0 ).ravel () 366got = (stored (rows ,dense ,"blk.1.ple_value.weight" ,"<u2" ).astype (np .uint32 )<< 16 ).view (np .float32 ) 367r = recs ["blk.1.ple_value.weight" ] 368self .assertEqual ((r ["src_type" ],r ["dst_type" ]), ("Q8_0" ,"BF16" )) 369self .assertAlmostEqual (r ["max_abs_err" ],float (np .max (np .abs (got - deq )))) 370self .assertEqual (conv ["compat_bf16" ],True ) 371 372 373# ---- split artifacts: Unsloth's UD-Q4_K_XL in miniature. Shard 1 holds the metadata and no tensor; shard 2 the 374# routers, layer 0 and layer 1's down; shard 3 layer 1's gate and up (a shard boundary inside a layer, like its 375# layer 11); shard 4 one float tensor. 4 experts of 32 x 32, Q8_0 and F32. 376N_EXPERT = 4 377 378 379def expert (seed ,shape ): 380return np .random .default_rng (seed ).standard_normal ((N_EXPERT ,* shape )).astype (np .float32 ) 381 382 383def split_model (root ,name = "model" ,split_layer = True ,dup = False ,split_no = None ,gate1 = None ,seed = 0 ): 384"""Writes the 4 shards; returns their paths.""" 385gate1 = Q .Q8_0 if gate1 is None else gate1 # not a default arg: the module imports without gguf-py 386gu ,dn = (32 ,32 ), (32 ,32 ) 387router = [(f"blk. { l } .ffn_gate_inp.weight" ,np .full ((N_EXPERT ,32 ),0.5 ,np .float32 ),Q .F32 )for l in (0 ,1 )] 388l0 = [(f"blk.0.ffn_ { r } _exps.weight" ,expert (seed + 10 + i ,gu if r != "down" else dn ),Q .Q8_0 ) 389for i ,r in enumerate (("gate" ,"up" ,"down" ))] 390l1_gu = [("blk.1.ffn_gate_exps.weight" ,expert (seed + 20 ,gu ),gate1 ), 391 ("blk.1.ffn_up_exps.weight" ,expert (seed + 21 ,gu ),Q .Q8_0 )] 392l1_d = [("blk.1.ffn_down_exps.weight" ,expert (seed + 22 ,dn ),Q .F32 )] 393shards = [[],router + l0 + (l1_d if split_layer else []),l1_gu + ([]if split_layer else l1_d ), 394 [("output_norm.weight" ,np .ones (32 ,np .float32 ),Q .F32 )]] 395if dup : 396shards [3 ].append (l1_gu [1 ]) 397total = sum (len (s )for s in shards ) 398paths = [] 399for i ,tensors in enumerate (shards ): 400p = root / f" { name } - { i + 1 :05d } -of-00004.gguf" 401no = split_no .get (i ,i )if split_no else i 402write_gguf (p ,tensors ,split = (no ,4 ,total ),arch = i == 0 ) 403paths .append (p ) 404return paths 405 406 407def run_pack (first ,out ,* extra ): 408 (out / "tokenizer" ).mkdir (parents = True ,exist_ok = True ) 409for n in ["vocab.json" ,"chat_template.jinja" ]: 410 (out / "tokenizer" / n ).touch () 411buf = io .StringIO () 412with patch .object (sys ,"argv" , ["iq_pack.py" ,"--gguf" ,str (first ),"--out" ,str (out ),* extra ]): 413with contextlib .redirect_stdout (buf ): 414rc = iq_pack .main () 415return rc ,buf .getvalue () 416 417 418def expected_experts (model ): 419"""experts.bin from first principles: per layer, per expert, gate | up | down slices.""" 420parts = [] 421for l in (0 ,1 ): 422ts = [model .bytes (f"blk. { l } .ffn_ { r } _exps.weight" ).reshape (N_EXPERT ,- 1 )for r in ("gate" ,"up" ,"down" )] 423parts .append (np .concatenate (ts ,axis = 1 ).tobytes ()) 424return b"" .join (parts ) 425 426 427class SplitArtifactTests (unittest .TestCase ): 428setUpClass = require_gguf_py (unittest .TestCase ) 429def test_four_shards_and_a_layer_split_per_role (self ): 430with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 431root = Path (tmp ) 432paths = split_model (root ) 433rc ,log = run_pack (paths [0 ],root / "pack" ,"--experts-bin" ) 434self .assertEqual (rc ,0 ,log ) 435text = (root / "pack" / "native_experts.txt" ).read_text () 436head ,line0 ,line1 = text .splitlines () 437self .assertTrue (head .startswith ("# strata native experts v4:" ),head ) 438self .assertIn ("(n_expert 4," ,head ) 439s2 ,s3 = paths [1 ].name ,paths [2 ].name 440self .assertEqual (line0 .split ()[8 :], [s2 ]) 441self .assertEqual (line1 .split ()[8 :], [f" { s3 } , { s3 } , { s2 } " ]) 442# every role's offset is absolute in ITS shard: shard 3's data_start for gate/up, shard 2's for down 443m = iq_pack .Model (paths [0 ]) 444for line ,l in ((line0 ,0 ), (line1 ,1 )): 445f = line .split () 446for r ,role in enumerate (("gate" ,"up" ,"down" )): 447g ,t ,_ ,_ = m .where [f"blk. { l } .ffn_ { role } _exps.weight" ] 448self .assertEqual (int (f [5 + r ]),g .data_start + t .offset ) 449self .assertNotEqual (m .where ["blk.1.ffn_gate_exps.weight" ][0 ].data_start , 450m .where ["blk.1.ffn_down_exps.weight" ][0 ].data_start ) 451self .assertEqual ((root / "pack" / "experts.bin" ).read_bytes (),expected_experts (m )) 452side = json .loads ((root / "pack" / "experts.bin.src.json" ).read_text ()) 453self .assertEqual ([s ["name" ]for s in side ["shards" ]], [p .name for p in paths ]) 454self .assertFalse (list ((root / "pack" ).glob ("*.tmp" ))) 455# the index: routers as BF16, nothing of the experts 456_ ,rows = iq_pack .read_index (root / "pack" / "index.txt" ) 457self .assertNotIn ("blk.1.ffn_gate_exps.weight" ,rows ) 458self .assertEqual (rows ["blk.1.ffn_gate_inp.weight" ][2 ],"4" ) 459 460def test_unsplit_layers_keep_the_v3_file (self ): 461with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 462root = Path (tmp ) 463paths = split_model (root ,split_layer = False ) 464rc ,log = run_pack (paths [0 ],root / "pack" ) 465self .assertEqual (rc ,0 ,log ) 466head ,line0 ,line1 = (root / "pack" / "native_experts.txt" ).read_text ().splitlines () 467self .assertTrue (head .startswith ("# strata native experts v3: layer gu_type d_type offset blob_bytes " 468"gate_off up_off down_off [shard] (n_expert 4, total " ),head ) 469self .assertEqual (line1 .split ()[8 :], [paths [2 ].name ]) 470 471def test_missing_shard (self ): 472with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 473paths = split_model (Path (tmp )) 474paths [3 ].unlink () 475with self .assertRaisesRegex (FileNotFoundError ,"missing model shards.*00004-of-00004" ): 476iq_pack .Model (paths [0 ]) 477 478def test_duplicate_tensor_across_shards (self ): 479with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 480paths = split_model (Path (tmp ),dup = True ) 481with self .assertRaisesRegex (ValueError ,"duplicate tensor blk.1.ffn_up_exps.weight" ): 482iq_pack .Model (paths [0 ]) 483 484def test_shard_of_another_split (self ): 485with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 486paths = split_model (Path (tmp ),split_no = {2 :1 }) 487with self .assertRaisesRegex (ValueError ,"does not declare itself shard 3 of 4" ): 488iq_pack .Model (paths [0 ]) 489 490def test_truncated_shard (self ): 491with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 492paths = split_model (Path (tmp )) 493paths [2 ].write_bytes (paths [2 ].read_bytes ()[:- 64 ]) 494with self .assertRaisesRegex (ValueError ,"truncated tensor" ): 495iq_pack .Model (paths [0 ]) 496 497def test_wrong_type_or_shape_leaves_the_pack_alone (self ): 498with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 499root = Path (tmp ) 500paths = split_model (root ,gate1 = Q .F32 )# layer 1: gate F32, up Q8_0 501pack = root / "pack" 502pack .mkdir () 503 (pack / "native_experts.txt" ).write_text ("previous pack" ) 504rc ,log = run_pack (paths [0 ],pack ) 505self .assertEqual (rc ,1 ) 506self .assertIn ("layer 1: gate and up differ in type" ,log ) 507self .assertEqual ((pack / "native_experts.txt" ).read_text (),"previous pack" ) 508self .assertFalse ((pack / "dense.bin" ).exists ()) 509 510def test_interrupted_pack (self ): 511with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 512root = Path (tmp ) 513paths = split_model (root ) 514pack = root / "pack" 515real = np .concatenate 516calls = [] 517 518def dies_on_layer_1 (parts ,axis ): 519calls .append (1 ) 520if len (calls )== 2 : 521raise KeyboardInterrupt ("stopped part-way" ) 522return real (parts ,axis = axis ) 523with patch .object (iq_pack .np ,"concatenate" ,dies_on_layer_1 ): 524with self .assertRaises (KeyboardInterrupt ): 525run_pack (paths [0 ],pack ,"--experts-bin" ) 526self .assertFalse ((pack / "experts.bin" ).exists ()) 527self .assertFalse ((pack / "experts.bin.src.json" ).exists ()) 528# the index stops part-way too: the old pack's files stay as they were 529before = {n : (pack / n ).read_bytes ()for n in ("index.txt" ,"dense.bin" ,"native_experts.txt" )} 530with patch .object (iq_pack ,"write_index" ,side_effect = KeyboardInterrupt ("stopped" )): 531with self .assertRaises (KeyboardInterrupt ): 532run_pack (paths [0 ],pack ) 533self .assertEqual (before , {n : (pack / n ).read_bytes ()for n in before }) 534rc ,log = run_pack (paths [0 ],pack ,"--experts-bin" ) 535self .assertEqual (rc ,0 ,log ) 536self .assertEqual ((pack / "experts.bin" ).read_bytes (),expected_experts (iq_pack .Model (paths [0 ]))) 537 538def test_interrupted_pack_continues_at_the_next_layer (self ): 539with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 540root = Path (tmp ) 541paths = split_model (root ) 542pack = root / "pack" 543real = np .concatenate 544calls = [] 545 546def dies_on_layer_1 (parts ,axis ): 547calls .append (1 ) 548if len (calls )== 2 : 549raise KeyboardInterrupt ("killed" ) 550return real (parts ,axis = axis ) 551with patch .object (iq_pack .np ,"concatenate" ,dies_on_layer_1 ): 552with self .assertRaises (KeyboardInterrupt ): 553run_pack (paths [0 ],pack ,"--experts-bin" ) 554want = expected_experts (iq_pack .Model (paths [0 ])) 555lines = [ln .split ()for ln in (pack / "native_experts.txt" ).read_text ().splitlines ()if ln and not ln .startswith ("#" )] 556one_layer = int (lines [1 ][3 ])# where layer 1 starts 557self .assertFalse ((pack / "experts.bin" ).exists ()) 558self .assertEqual ((pack / "experts.bin.tmp" ).stat ().st_size ,one_layer )# layer 0 is on disk 559self .assertEqual (json .loads ((pack / "experts.bin.tmp.json" ).read_text ())["layers" ],1 ) 560# a partial write after the recorded layer (the kill came mid-write) is cut off 561with open (pack / "experts.bin.tmp" ,"ab" )as f : 562f .write (b"garbage" ) 563written = [] 564real_layer = iq_pack .np .concatenate 565 566def counting (parts ,axis ): 567written .append (1 ) 568return real_layer (parts ,axis = axis ) 569with patch .object (iq_pack .np ,"concatenate" ,counting ): 570rc ,log = run_pack (paths [0 ],pack ,"--experts-bin" ) 571self .assertEqual (rc ,0 ,log ) 572self .assertIn ("keeping its first 1 of 2 layers and continuing with layer 1" ,log ) 573self .assertEqual ((pack / "experts.bin" ).read_bytes (),want ) 574self .assertEqual (len (written ),2 )# one layer re-read to check the kept one, one layer written 575self .assertFalse ((pack / "experts.bin.tmp" ).exists ()) 576self .assertFalse ((pack / "experts.bin.tmp.json" ).exists ()) 577self .assertEqual (json .loads ((pack / "experts.bin.src.json" ).read_text ())["bytes" ],len (want )) 578 579def test_interrupted_pack_of_another_model_is_not_continued (self ): 580with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 581root = Path (tmp ) 582 (root / "a" ).mkdir () 583 (root / "b" ).mkdir () 584other = split_model (root / "a" ,name = "other" ,seed = 100 ) 585paths = split_model (root / "b" ) 586pack = root / "pack" 587real = np .concatenate 588calls = [] 589 590def dies_on_layer_1 (parts ,axis ): 591calls .append (1 ) 592if len (calls )== 2 : 593raise KeyboardInterrupt ("killed" ) 594return real (parts ,axis = axis ) 595with patch .object (iq_pack .np ,"concatenate" ,dies_on_layer_1 ): 596with self .assertRaises (KeyboardInterrupt ): 597run_pack (other [0 ],pack ,"--experts-bin" ) 598rc ,log = run_pack (paths [0 ],pack ,"--experts-bin" )# the same geometry, other weights 599self .assertEqual (rc ,0 ,log ) 600self .assertIn ("cannot be continued: starting it again" ,log ) 601self .assertEqual ((pack / "experts.bin" ).read_bytes (),expected_experts (iq_pack .Model (paths [0 ]))) 602 603def test_a_kept_layer_that_no_longer_matches_is_not_trusted (self ): 604with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 605root = Path (tmp ) 606paths = split_model (root ) 607pack = root / "pack" 608real = np .concatenate 609calls = [] 610 611def dies_on_layer_1 (parts ,axis ): 612calls .append (1 ) 613if len (calls )== 2 : 614raise KeyboardInterrupt ("killed" ) 615return real (parts ,axis = axis ) 616with patch .object (iq_pack .np ,"concatenate" ,dies_on_layer_1 ): 617with self .assertRaises (KeyboardInterrupt ): 618run_pack (paths [0 ],pack ,"--experts-bin" ) 619data = bytearray ((pack / "experts.bin.tmp" ).read_bytes ()) 620data [0 ]^= 0xFF # the disk lost a bit 621 (pack / "experts.bin.tmp" ).write_bytes (bytes (data )) 622rc ,log = run_pack (paths [0 ],pack ,"--experts-bin" ) 623self .assertEqual (rc ,0 ,log ) 624self .assertIn ("cannot be continued" ,log ) 625self .assertEqual ((pack / "experts.bin" ).read_bytes (),expected_experts (iq_pack .Model (paths [0 ]))) 626 627def test_stale_same_size_experts_bin (self ): 628with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as tmp : 629root = Path (tmp ) 630 (root / "a" ).mkdir () 631 (root / "b" ).mkdir () 632other = split_model (root / "a" ,name = "other" ,seed = 100 ) 633paths = split_model (root / "b" ) 634pack = root / "pack" 635rc ,log = run_pack (other [0 ],pack ,"--experts-bin" )# another model, the same geometry 636self .assertEqual (rc ,0 ,log ) 637stale = (pack / "experts.bin" ).read_bytes () 638want = expected_experts (iq_pack .Model (paths [0 ])) 639self .assertEqual (len (stale ),len (want )) 640self .assertNotEqual (stale ,want ) 641# without --experts-bin the engine would read it: refused, nothing rewritten 642rc ,log = run_pack (paths [0 ],pack ) 643self .assertEqual (rc ,1 ) 644self .assertIn ("another source" ,log ) 645self .assertEqual ((pack / "experts.bin" ).read_bytes (),stale ) 646# with it: rewritten, not reused by its size 647rc ,log = run_pack (paths [0 ],pack ,"--experts-bin" ) 648self .assertEqual (rc ,0 ,log ) 649self .assertEqual ((pack / "experts.bin" ).read_bytes (),want ) 650# and now reused 651rc ,log = run_pack (paths [0 ],pack ,"--experts-bin" ) 652self .assertIn ("not rewritten" ,log ) 653# an experts.bin without its sidecar (an older packer) is rewritten too 654 (pack / "experts.bin.src.json" ).unlink () 655 (pack / "experts.bin" ).write_bytes (stale ) 656rc ,log = run_pack (paths [0 ],pack ,"--experts-bin" ) 657self .assertEqual ((pack / "experts.bin" ).read_bytes (),want ) 658 659 660class HadamardTests (unittest .TestCase ): 661"""prism.hadamard (Agention's APR files) -> hadamard.txt; anything the engine cannot rotate is refused.""" 662N_EMBD ,N_FF = 256 ,128 663 664def meta (self ,** kw ): 665names = ["blk.%d.ffn_%s_exps.weight" % (l ,r )for l in range (2 )for r in ("gate" ,"up" ,"down" )] 666m = {"prism.hadamard.version" :1 ,"prism.hadamard.block_size" :128 , 667"prism.hadamard.transform" :"normalized-sylvester-walsh-hadamard" , 668"prism.hadamard.axis" :"input-last-dimension" ,"prism.hadamard.sign_mode" :"explicit" , 669"prism.hadamard.weight_names" :names , 670"prism.hadamard.sign_widths" : [self .N_FF ,self .N_EMBD ], 671"prism.hadamard.sign_values" : [1 ,- 1 ]* (self .N_FF // 2 )+ [- 1 ,1 ]* (self .N_EMBD // 2 )} 672m .update (kw ) 673return m 674 675def layout (self ,gu = 145 ,d = 146 ): 676return [(l ,gu ,d ,0 ,0 ,None )for l in range (2 )] 677 678def test_no_metadata (self ): 679self .assertIsNone (iq_pack .hadamard_spec ({},self .layout (),self .N_EMBD ,self .N_FF )) 680 681def test_explicit_signs_written (self ): 682text = iq_pack .hadamard_spec (self .meta (),self .layout (),self .N_EMBD ,self .N_FF ) 683lines = text .splitlines () 684self .assertTrue (lines [0 ].startswith ("# strata hadamard v1" )) 685self .assertEqual (lines [1 ],"block 128" ) 686self .assertEqual (lines [2 ].split ()[:4 ], ["signs" ,str (self .N_FF ),"1" ,"-1" ]) 687self .assertEqual (len (lines [3 ].split ()),2 + self .N_EMBD ) 688self .assertEqual (lines [4 :], ["layer 0 1 1 1" ,"layer 1 1 1 1" ]) 689 690def test_refusals (self ): 691bad = { 692"transform" :self .meta (** {"prism.hadamard.transform" :"dct" }), 693"dense weight" :self .meta (** {"prism.hadamard.weight_names" : ["blk.0.attn_q.weight" ]}), 694"inverse" :self .meta (** {"prism.hadamard.inverse_weight_names" : ["token_embd.weight" ]}), 695"gate only" :self .meta (** {"prism.hadamard.weight_names" : ["blk.0.ffn_gate_exps.weight" ]}), 696"missing width" :self .meta (** {"prism.hadamard.sign_widths" : [self .N_EMBD ], 697"prism.hadamard.sign_values" : [1 ]* self .N_EMBD }), 698"bad sign" :self .meta (** {"prism.hadamard.sign_values" : [2 ]* (self .N_FF + self .N_EMBD )}), 699"block" :self .meta (** {"prism.hadamard.block_size" :96 }), 700 } 701for what ,m in bad .items (): 702with self .subTest (what ): 703got = iq_pack .hadamard_spec (m ,self .layout (),self .N_EMBD ,self .N_FF ) 704self .assertIsInstance (got ,str ) 705self .assertFalse (got .startswith ("# strata hadamard" )) 706got = iq_pack .hadamard_spec (self .meta (),self .layout (gu = 42 ),self .N_EMBD ,self .N_FF ) 707self .assertIn ("Q2_0" ,got ) 708 709 710class V31HeaderOnlyLayoutTests (unittest .TestCase ): 711"""Round 0214: the pack's expert table (iq_pack.expert_layout) read from the REAL tensor directories of Unsloth's v3.1 sets (tests/fixtures/unsloth_v31, 712header-only: no weights), so the gate == up rule and the Q5_0 downs are checked without a download.""" 713 714@staticmethod 715def layout (set_name ): 716import unsloth_v31_fixture as FX 717import gguf_reader as G 718 719class Map : 720size = 1 << 62 721with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as t : 722m = iq_pack .Model .__new__ (iq_pack .Model ) 723m .where = {} 724first = None 725for s in FX .load ()["sets" ][set_name ]["shards" ]: 726if not s ["header" ]: 727continue 728p = FX .materialize (s ,Path (t )/ s ["name" ]) 729g = G .GGUFFile (p ) 730first = first or p 731for ti in g .tensors : 732m .where [ti .name ]= (g ,ti ,Map ,p ) 733return iq_pack .expert_layout (m ,first ) 734 735def test_gate_and_up_must_agree_ud_iq1_s_is_refused (self ): 736self .assertEqual (self .layout ("UD-IQ1_S" ),"layer 18: gate and up differ in type" ) 737 738def test_q5_0_downs_are_packed_with_their_type_id (self ): 739for set_name ,n_q5 in (("UD-IQ4_XS" ,33 ), ("UD-Q3_K_XL" ,20 ), ("UD-IQ2_XS" ,1 ), ("UD-Q2_K_XL" ,1 ), ("UD-IQ3_XXS" ,0 ), ("UD-IQ1_M" ,0 )): 740with self .subTest (set = set_name ): 741layout ,text ,n_expert ,total = self .layout (set_name ) 742self .assertEqual (n_expert ,512 ) 743self .assertEqual (len (layout ),48 ) 744self .assertEqual (sum (1 for row in layout if row [5 ][2 ].type_name == "Q5_0" ),n_q5 ) 745rows = [ln .split ()for ln in text .splitlines ()[1 :]] 746self .assertEqual (sum (1 for r in rows if r [2 ]== "6" ),n_q5 )# d_type 6 = Q5_0 747self .assertEqual (total ,sum (r [4 ]* 512 for r in layout )) 748 749def test_a_layer_across_shards_makes_a_v4_table (self ): 750layout ,text ,_n ,_t = self .layout ("UD-IQ3_XXS" ) 751self .assertTrue (text .startswith ("# strata native experts v4:" )) 752self .assertEqual (sum (1 for ln in text .splitlines ()[1 :]if "," in ln .split ()[- 1 ]),1 ) 753 754 755class NativeExpertsV5Tests (unittest .TestCase ): 756"""The v5 mark (Hadamard-folded experts) rewrites only the tables the packer writes, v3 and v4.""" 757setUpClass = require_gguf_py (unittest .TestCase )# test_packer_refuses_before_writing builds GGUF fixtures 758ROWS = "0 145 146 0 100 1 2 3\n1 145 146 100 100 4 5 6\n" 759 760def table (self ,version ,tail = "(n_expert 2, total 200)" ): 761return "# strata native experts v%s: layer gu_type d_type offset ... %s\n" % (version ,tail )+ self .ROWS 762 763def test_v3_and_v4_become_v5 (self ): 764for v in ("3" ,"4" ): 765with self .subTest (v ): 766got = iq_pack .native_experts_v5 (self .table (v )) 767head ,rest = got .split ("\n" ,1 ) 768self .assertTrue (head .startswith ("# strata native experts v5: layer gu_type" )) 769self .assertTrue (head .endswith ("(n_expert 2, total 200) - v5: Hadamard-folded experts, see hadamard.txt" )) 770self .assertEqual (rest ,self .ROWS ) 771 772def test_other_versions_are_refused_by_name (self ): 773for v in ("2" ,"5" ,"6" ,"10" ): 774with self .subTest (v ): 775got = iq_pack .native_experts_v5 (self .table (v )) 776self .assertFalse (got .startswith ("# strata native experts" )) 777self .assertIn ("v%s" % v ,got ) 778self .assertIn ("v3 and v4" ,got ) 779got = iq_pack .native_experts_v5 ("# something else\n" + self .ROWS ) 780self .assertIn ("without a version header" ,got ) 781 782def test_packer_refuses_before_writing (self ): 783real = iq_pack .expert_layout 784 785def v6_layout (model ,src ): 786layout ,text ,n_expert ,offset = real (model ,src ) 787return layout ,text .replace ("native experts v3:" ,"native experts v6:" ,1 ),n_expert ,offset 788 789with tempfile .TemporaryDirectory ()as d : 790root = Path (d ) 791paths = split_model (root ,split_layer = False ) 792out = root / "pack" 793with patch .object (iq_pack ,"expert_layout" ,v6_layout ), \ 794patch .object (iq_pack ,"hadamard_spec" ,return_value = "# strata hadamard v1\nblock 32\n" ): 795rc ,log = run_pack (paths [0 ],out ) 796self .assertEqual (rc ,1 ) 797self .assertIn ("native_experts.txt v6" ,log ) 798self .assertIn ("only v3 and v4" ,log ) 799self .assertFalse ((out / "native_experts.txt" ).exists ()) 800self .assertFalse ((out / "hadamard.txt" ).exists ()) 801 802 803if __name__ == "__main__" : 804unittest .main ()