okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cd9745050
main
1"""tools/qwen4_intake.py against the headers of every model we have, and against synthetic variants of them. 2 3The headers are recorded from Hugging Face by HTTP range reads (tools/qwen4_intake_fixtures/*.json.gz: metadata without the big 4arrays, the tensor directory, the special tokens). Each test writes them back as header-only GGUF files with 5tools/gguf_writer.py's key/value encoder and runs the real reader over them, so the whole path (file -> reader -> report) is the 6one a real run takes. No weights exist anywhere in this test; no network is used unless STRATA_LIVE_HF=1. 7 8The last class reads the C++ and kernel sources and fails when a table in qwen4_intake.py no longer matches them. 9""" 10from __future__import annotations 11 12import copy 13import gzip 14import json 15import os 16import pathlib 17import re 18import struct 19import sys 20import tempfile 21import time 22import unittest 23from unittest import mock 24 25HERE = pathlib .Path (__file__ ).resolve ().parent 26ROOT = HERE .parent 27sys .path .insert (0 ,str (HERE )) 28sys .path .insert (0 ,str (ROOT )) 29 30import gguf_reader as G # noqa: E402 31import gguf_writer as W # noqa: E402 32import qwen4_intake as Q # noqa: E402 33import strata_tokenizer as ST # noqa: E402 34 35FIX = HERE / "qwen4_intake_fixtures" 36 37 38def load_fixture (name :str )-> dict : 39with gzip .open (FIX / (name + ".json.gz" ),"rt" ,encoding = "utf-8" )as f : 40return json .load (f ) 41 42 43def _tokens (count :int ,special :list )-> tuple [list [str ],list [int ]]: 44toks :list [str | None ]= [None ]* count 45types = [1 ]* count 46for i ,text ,ty in special : 47toks [i ]= text 48types [i ]= ty 49chars = iter (sorted (ST .BYTE_TO_UNICODE .values ())) 50for i in range (count ): 51if toks [i ]is None : 52c = next (chars ,None ) 53toks [i ]= c if c is not None else "tok%d" % i 54return toks ,types 55 56 57def _kv (w :W .GGUFWriter ,key :str ,v )-> bytes : 58if isinstance (v ,bool ): 59t = "bool" 60elif isinstance (v ,int ): 61t = "i64" 62elif isinstance (v ,float ): 63t = "f64" 64elif isinstance (v ,str ): 65t = "string" 66else : 67raise TypeError (key ) 68return w ._kv_bytes (key ,t ,v ) 69 70 71def write_header_only (path :pathlib .Path ,metadata :dict ,tensors :list ,alignment :int = 32 )-> None : 72w = W .GGUFWriter () 73kvs = bytearray () 74n = 0 75for key ,v in metadata .items (): 76if isinstance (v ,dict )and "__array__" in v : 77kind = v ["__array__" ] 78if key == "tokenizer.ggml.tokens" : 79toks ,_ = _tokens (v ["count" ],v .get ("special" , [])) 80kvs += w ._kv_bytes (key ,"array:string" ,toks ) 81elif key == "tokenizer.ggml.token_type" : 82kvs += w ._kv_bytes (key ,"array:i32" ,v ["_values" ]) 83elif key == "tokenizer.ggml.merges" : 84kvs += w ._kv_bytes (key ,"array:string" , []) 85else : 86items = v ["items" ] 87if items and isinstance (items [0 ],str ): 88kvs += w ._kv_bytes (key ,"array:string" ,items ) 89elif items and isinstance (items [0 ],float ): 90kvs += w ._kv_bytes (key ,"array:f64" ,items ) 91else : 92kvs += w ._kv_bytes (key ,"array:i64" ,items or []) 93else : 94kvs += _kv (w ,key ,v ) 95n += 1 96body = bytearray (struct .pack ("<IIQQ" ,G .GGUF_MAGIC ,3 ,len (tensors ),n ))+ kvs 97for name ,shape ,tid ,off in tensors : 98b = name .encode () 99body += struct .pack ("<Q" ,len (b ))+ b + struct .pack ("<I" ,len (shape ))+ struct .pack ("<%dQ" % len (shape ),* shape ) 100body += struct .pack ("<IQ" ,tid ,off ) 101body += b"\0" * ((- len (body ))% alignment ) 102path .write_bytes (bytes (body )) 103 104 105def materialise (fix :dict ,out :pathlib .Path ,mutate = None )-> list [pathlib .Path ]: 106"""Write the recorded set as header-only GGUF files into `out`. `mutate(files)` may change the copied records first.""" 107files = copy .deepcopy (fix ["files" ]) 108if mutate : 109mutate (files ) 110paths = [] 111for f in files : 112md = f ["metadata" ] 113tt = md .get ("tokenizer.ggml.token_type" ) 114if tt is not None : 115_ ,types = _tokens (md ["tokenizer.ggml.tokens" ]["count" ],md ["tokenizer.ggml.tokens" ].get ("special" , [])) 116tt ["_values" ]= types 117p = out / os .path .basename (f ["file" ]) 118write_header_only (p ,md ,f ["tensors" ],f .get ("alignment" ,32 )) 119paths .append (p ) 120return paths 121 122 123_TMP = tempfile .TemporaryDirectory (prefix = "q4intake-" ) 124_CACHE :dict [tuple ,list [pathlib .Path ]]= {} 125 126 127def files_for (name :str ,variant :str = "" ,mutate = None )-> list [pathlib .Path ]: 128key = (name ,variant ) 129if key not in _CACHE : 130d = pathlib .Path (_TMP .name )/ ("%s%s" % (name , ("-" + variant )if variant else "" )) 131d .mkdir (parents = True ,exist_ok = True ) 132_CACHE [key ]= materialise (load_fixture (name ),d ,mutate ) 133return _CACHE [key ] 134 135 136def analyse (paths ,build_tokenizer :bool = False )-> dict : 137infos = [Q .read_local (p )for p in paths ] 138rep = Q .run (infos ,build_tokenizer = build_tokenizer ) 139sets = [s for s in rep ["sets" ]if "files" in s ] 140assert len (sets )== 1 , [s .get ("files" )for s in rep ["sets" ]] 141return sets [0 ] 142 143 144FLASH_NEXT = ["fn_unsloth_ud_q4_k_xl" ,"fn_unsloth_ud_iq4_xs" ,"fn_unsloth_ud_q2_k_xl" ,"fn_unsloth_q8_0" ,"fn_ista_iq3_s" , 145"fn_ista_q2_0" ,"fn_coder_iq1_m" ,"fn_swift_iq3_s" ,"fn_gyro_s" ] 146QWEN36 = ["q36_ud_q4_k_xl" ,"q36_q8_0" ] 147 148 149class RealSets (unittest .TestCase ): 150def test_every_flash_next_set_is_case_a_on_qwen4exp (self ): 151for name in FLASH_NEXT : 152with self .subTest (name ): 153r = analyse (files_for (name )) 154v = r ["verdict" ] 155self .assertEqual (r ["family" ],"qwen4exp" ) 156self .assertEqual (v ["case" ],"A" ,v ["blockers" ]+ [str (v ["shape_fields_that_differ" ])]) 157self .assertEqual (v ["blockers" ], []) 158self .assertEqual (r ["layout" ]["ok" ],True ,r ["layout" ]) 159self .assertEqual (r ["layout" ]["found" ],r ["layout" ]["wanted" ]) 160self .assertEqual (r ["layout" ]["known_unlisted" ],7 )# per_layer_token_embd + the six PLE tensors of one layer 161self .assertIn ("cuda" ,v ["backends" ]) 162self .assertIn ("hip" ,v ["backends" ]) 163self .assertIn ("Flash-Next" ,v ["path" ]) 164self .assertEqual (r ["tokenizer" ]["pre_rule" ],"qwen35" ) 165self .assertEqual (r ["chat_template" ]["tool_call_format" ],"xml" ) 166self .assertTrue (r ["split" ]["complete" ],r ["split" ]) 167 168def test_qwen36_is_case_a_on_qwen35moe_for_cuda_and_hip_only (self ): 169for name in QWEN36 : 170with self .subTest (name ): 171r = analyse (files_for (name )) 172v = r ["verdict" ] 173self .assertEqual (r ["family" ],"qwen35moe" ) 174self .assertEqual (v ["case" ],"A" ,v ["blockers" ]) 175self .assertEqual (sorted (v ["backends" ]), ["cuda" ,"hip" ]) 176self .assertIn ("qwen35" ,v ["path" ]) 177self .assertEqual (r ["layout" ]["ok" ],True ,r ["layout" ]) 178self .assertTrue (r ["mtp" ]["in_file" ]) 179self .assertEqual (r ["mtp" ]["in_file_layers" ],1 ) 180self .assertEqual (r ["qwen35_limit_violations" ], []) 181self .assertEqual (r ["geometry" ]["n_layers" ],40 ) 182self .assertEqual (r ["differs_from_qwen36_35b" ], []) 183 184def test_deepseek_is_case_c_with_its_blockers_named (self ): 185r = analyse (files_for ("ds41_ud_q8_k_xl" )) 186v = r ["verdict" ] 187self .assertEqual (v ["case" ],"C" ) 188text = "\n" .join (v ["blockers" ]) 189self .assertIn ("deepseek41" ,text ) 190self .assertIn ("strata-dsv41" ,text ) 191self .assertIn ("joyai-llm" ,text )# the pre-tokenizer 192self .assertIn ("MXFP4" ,text )# a quant type with no kernel in any Qwen path list 193self .assertEqual (v ["backends" ], []) 194self .assertEqual (len (r ["files" ]),9 ) 195 196def test_picture_readers (self ): 197a = Q .run ([Q .read_local (files_for ("fn_unsloth_mmproj" )[0 ])],build_tokenizer = False ) 198self .assertEqual (a ["picture_readers" ][0 ]["projector_type" ],"qwen3vl_merger" ) 199self .assertTrue (a ["picture_readers" ][0 ]["supported" ]) 200self .assertEqual (a ["sets" ][0 ]["verdict" ]["case" ],"-" ) 201# a model next to its reader: the reader is listed with the set 202infos = [Q .read_local (p )for p in files_for ("q36_ud_q4_k_xl" )+ files_for ("q36_mmproj" )] 203rep = Q .run (infos ,build_tokenizer = False ) 204s = rep ["sets" ][0 ] 205self .assertEqual ([p ["projector_type" ]for p in s ["projectors" ]], ["qwen3vl_merger" ]) 206self .assertTrue (s ["projectors" ][0 ]["supported" ]) 207 208def test_tokenizer_build_and_template_on_a_real_header (self ): 209r = analyse (files_for ("fn_unsloth_ud_q4_k_xl" ),build_tokenizer = True ) 210tk = r ["tokenizer" ] 211self .assertTrue (tk ["builds" ]["ok" ],tk ["builds" ]) 212self .assertIs (tk ["builds" ]["roundtrip" ],True ) 213self .assertEqual (tk ["pre" ],"qwen35" ) 214self .assertEqual (tk ["n_tokens" ],248320 ) 215self .assertEqual (tk ["key_token_differences" ], []) 216self .assertEqual (tk ["end_of_turn_id" ],248046 ) 217self .assertTrue (r ["vocab_matches_embedding" ]) 218ct = r ["chat_template" ] 219self .assertTrue (ct ["known_as" ].startswith ("Qwen3.8-Flash-Next" )) 220self .assertTrue (ct ["has_think_tags" ]) 221self .assertTrue (ct ["enable_thinking_switch" ]) 222r2 = analyse (files_for ("fn_swift_iq3_s" )) 223self .assertEqual (r2 ["chat_template" ]["known_as" ],"Swift 1.5" ) 224r3 = analyse (files_for ("q36_ud_q4_k_xl" )) 225self .assertEqual (r3 ["chat_template" ]["known_as" ],"Qwen3.6-35B-A3B (Unsloth MTP files)" ) 226 227def test_quant_report_names_the_roles_and_backends (self ): 228r = analyse (files_for ("fn_unsloth_ud_q4_k_xl" )) 229q = r ["quant" ] 230combos = {(c ["gate" ],c ["up" ],c ["down" ])for c in q ["expert_combinations" ]} 231self .assertIn (("Q4_K" ,"Q4_K" ,"Q5_1" ),combos ) 232for b in ("cuda" ,"hip" ,"sycl" ,"metal" ): 233self .assertIn (b ,q ["backends" ]) 234self .assertEqual (q ["unknown_types" ], []) 235# Gyro's trellis experts: CUDA and HIP run them, the Metal list has them only partly; whatever the lists say, the report agrees 236g = analyse (files_for ("fn_gyro_s" )) 237self .assertTrue (g ["quant" ]["backends" ]["cuda" ]["all_types_supported" ]) 238 239 240def _bump (files ,key ,value ): 241for f in files : 242if key in f ["metadata" ]: 243f ["metadata" ][key ]= value 244 245 246def reshape_flash_next (files ,n_embd = 3072 ,n_layers = 64 ): 247"""A Flash-Next of another size: the layout tables of a model with `n_embd` and `n_layers`, the quant types of the original.""" 248f0 = files [0 ] 249md = f0 ["metadata" ] 250md ["qwen4exp.embedding_length" ]= n_embd 251md ["qwen4exp.block_count" ]= n_layers 252md ["qwen4exp.attention.compress_ratios" ]= {"__array__" :"list" ,"count" :n_layers , 253"items" : [4 if l % 4 == 3 else 0 for l in range (n_layers )]} 254g = Q .Geometry (n_embd = n_embd ,n_layers = n_layers ) 255types = {} 256for f in files : 257for name ,shape ,tid ,off in f ["tensors" ]: 258types [name ]= tid 259tensors = [] 260for name ,shape in Q .global_tensors (g ): 261tensors .append ([name ,shape ,types [name ],0 ]) 262for l in range (n_layers ): 263src = l if l < 48 else l - 16 264for name ,shape in Q .layer_tensors (g ,l ): 265tensors .append (["blk.%d.%s" % (l ,name ),shape ,types ["blk.%d.%s" % (src ,name )],0 ]) 266for name in types : 267if Q .QWEN4_UNLISTED .match (name ): 268tensors .append ([name ,next (t [1 ]for f in files for t in f ["tensors" ]if t [0 ]== name ),types [name ],0 ]) 269md ["split.count" ]= 1 270md ["split.tensors.count" ]= len (tensors ) 271md .pop ("split.no" ,None ) 272files [:]= [f0 ] 273f0 ["tensors" ]= tensors 274f0 ["file" ]= "reshaped.gguf" 275 276 277class SyntheticSets (unittest .TestCase ): 278def test_reshaped_flash_next_is_case_b_with_the_differing_fields (self ): 279r = analyse (files_for ("fn_ista_iq3_s" ,"reshaped" ,reshape_flash_next )) 280v = r ["verdict" ] 281self .assertEqual (v ["case" ],"B" ,v ["blockers" ]) 282self .assertEqual (v ["blockers" ], []) 283self .assertEqual (r ["layout" ]["ok" ],True , {k :r ["layout" ][k ][:3 ]for k in ("missing" ,"reshaped" ,"unknown" )}) 284got = {d ["key" ]: (d ["got" ],d ["kernels_built_for" ])for d in v ["shape_fields_that_differ" ]} 285self .assertEqual (got , {"qwen4exp.block_count" : (64 ,48 ),"qwen4exp.embedding_length" : (3072 ,2560 )}) 286self .assertEqual (v ["backends" ], ["cuda" ,"hip" ,"sycl" ,"metal" ][:len (v ["backends" ])]or v ["backends" ]) 287self .assertTrue (any ("geometry header" in n for n in v ["notes" ])) 288 289def test_reshaped_with_more_differences_lists_them_all (self ): 290def f (files ): 291reshape_flash_next (files ,3584 ,40 ) 292md = files [0 ]["metadata" ] 293md ["qwen4exp.expert_feed_forward_length" ]= 768 294md ["qwen4exp.expert_shared_feed_forward_length" ]= 768 295g = Q .Geometry (n_embd = 3584 ,n_layers = 40 ,n_ff = 768 ,n_ff_shexp = 768 ) 296t = {x [0 ]:x [2 ]for x in files [0 ]["tensors" ]} 297files [0 ]["tensors" ]= [[n ,s ,t .get (n ,8 ),0 ]for n ,s in Q .global_tensors (g )]+ \ 298 [["blk.%d.%s" % (l ,n ),s ,t .get ("blk.%d.%s" % (l ,n ),8 ),0 ]for l in range (40 )for n ,s in Q .layer_tensors (g ,l )] 299r = analyse (files_for ("fn_ista_iq3_s" ,"reshaped2" ,f )) 300keys = sorted (d ["key" ]for d in r ["verdict" ]["shape_fields_that_differ" ]) 301self .assertEqual (r ["verdict" ]["case" ],"B" ,r ["verdict" ]["blockers" ]) 302self .assertEqual (keys , ["qwen4exp.block_count" ,"qwen4exp.embedding_length" ,"qwen4exp.expert_feed_forward_length" , 303"qwen4exp.expert_shared_feed_forward_length" ]) 304 305def test_an_unknown_tensor_is_case_c_and_named (self ): 306def add (files ): 307files [- 1 ]["tensors" ].append (["blk.3.mystery_gate.weight" , [2560 ,2560 ],8 ,0 ]) 308r = analyse (files_for ("fn_unsloth_ud_q4_k_xl" ,"mystery" ,add )) 309v = r ["verdict" ] 310self .assertEqual (v ["case" ],"C" ) 311self .assertIn ("blk.3.mystery_gate.weight" ,"\n" .join (v ["blockers" ])) 312self .assertEqual (r ["layout" ]["unknown" ], ["blk.3.mystery_gate.weight" ]) 313 314def test_a_missing_and_a_reshaped_tensor_are_case_c (self ): 315def drop (files ): 316for f in files : 317f ["tensors" ]= [t for t in f ["tensors" ]if t [0 ]!= "blk.6.attn_qkv.weight" ] 318r = analyse (files_for ("fn_unsloth_ud_q4_k_xl" ,"missing" ,drop )) 319self .assertEqual (r ["verdict" ]["case" ],"C" ) 320self .assertEqual (r ["layout" ]["missing" ], ["blk.6.attn_qkv.weight" ]) 321 322def reshape (files ): 323for f in files : 324for t in f ["tensors" ]: 325if t [0 ]== "blk.3.attn_k.weight" : 326t [1 ]= [2560 ,1024 ] 327r = analyse (files_for ("fn_unsloth_ud_q4_k_xl" ,"reshaped-one" ,reshape )) 328self .assertEqual (r ["verdict" ]["case" ],"C" ) 329self .assertEqual ([x ["name" ]for x in r ["layout" ]["reshaped" ]], ["blk.3.attn_k.weight" ]) 330 331def test_a_quant_type_with_no_kernel_is_case_c (self ): 332def retype (files ): 333for f in files : 334for t in f ["tensors" ]: 335if t [0 ]== "blk.5.attn_qkv.weight" : 336t [2 ]= 10 # Q2_K as a dense projection: not in any native_mmvq_supported list 337r = analyse (files_for ("fn_unsloth_ud_q4_k_xl" ,"q2k" ,retype )) 338v = r ["verdict" ] 339self .assertEqual (v ["case" ],"C" ) 340self .assertTrue (any ("Q2_K" in b for b in v ["blockers" ]),v ["blockers" ]) 341 342def test_an_unknown_pre_tokenizer_is_case_c (self ): 343r = analyse (files_for ("fn_unsloth_ud_q4_k_xl" ,"pre" ,lambda fs :fs [0 ]["metadata" ].__setitem__ ("tokenizer.ggml.pre" ,"qwen4" )), 344build_tokenizer = True ) 345v = r ["verdict" ] 346self .assertEqual (v ["case" ],"C" ) 347self .assertTrue (any ("'qwen4'" in b and "pre" in b for b in v ["blockers" ]),v ["blockers" ]) 348 349def test_known_layers_under_a_new_architecture_name_are_case_b (self ): 350def rename (files ): 351for f in files : 352md = f ["metadata" ] 353for k in list (md ): 354if k .startswith ("qwen4exp." ): 355md ["qwen4x." + k [len ("qwen4exp." ):]]= md .pop (k ) 356md ["general.architecture" ]= "qwen4x" 357r = analyse (files_for ("fn_unsloth_ud_q4_k_xl" ,"renamed" ,rename )) 358v = r ["verdict" ] 359self .assertEqual (v ["case" ],"B" ,v ["blockers" ]) 360self .assertTrue (any ("qwen4x" in n and "model_family_from_arch" in n for n in v ["notes" ]),v ["notes" ]) 361 362def test_an_incomplete_split_is_case_c (self ): 363paths = files_for ("fn_unsloth_ud_q4_k_xl" ) 364r = analyse (paths [:3 ]) 365self .assertEqual (r ["verdict" ]["case" ],"C" ) 366self .assertFalse (r ["split" ]["complete" ]) 367 368def test_qwen35_limits (self ): 369def wide (files ): 370files [0 ]["metadata" ]["qwen35moe.attention.key_length" ]= 128 371files [0 ]["metadata" ]["qwen35moe.attention.value_length" ]= 128 372for t in files [0 ]["tensors" ]: 373n = t [0 ] 374if re .search (r"attn_q_norm|attn_k_norm" ,n ): 375t [1 ]= [128 ] 376elif n .endswith ("attn_q.weight" ): 377t [1 ]= [2048 ,2 * 16 * 128 ] 378elif n .endswith (("attn_k.weight" ,"attn_v.weight" )): 379t [1 ]= [2048 ,2 * 128 ] 380elif n .endswith ("attn_output.weight" ): 381t [1 ]= [16 * 128 ,2048 ] 382r = analyse (files_for ("q36_ud_q4_k_xl" ,"head128" ,wide )) 383v = r ["verdict" ] 384self .assertEqual (v ["case" ],"B" ,v ["blockers" ]) 385self .assertEqual ([d ["key" ]for d in v ["shape_fields_that_differ" ]], ["qwen35moe.attention.key_length" ]) 386 387 388class Output (unittest .TestCase ): 389def test_cli_writes_json_and_prints (self ): 390d = pathlib .Path (_TMP .name )/ "cli" 391d .mkdir (exist_ok = True ) 392for p in files_for ("fn_ista_q2_0" )+ files_for ("q36_q8_0" ): 393 (d / p .name ).write_bytes (p .read_bytes ()) 394out = d / "report.json" 395import contextlib 396import io 397buf = io .StringIO () 398with contextlib .redirect_stdout (buf ): 399self .assertEqual (Q .main ([str (d ),"--out" ,str (out ),"--no-tokenizer-build" ]),0 ) 400rep = json .loads (out .read_text ()) 401self .assertEqual (sorted (s ["verdict" ]["case" ]for s in rep ["sets" ]), ["A" ,"A" ]) 402self .assertEqual (sorted (s ["architecture" ]for s in rep ["sets" ]), ["qwen35moe" ,"qwen4exp" ]) 403self .assertIn ("CASE A" ,buf .getvalue ()) 404s = rep ["sets" ][0 ] 405for k in ("geometry" ,"layout" ,"quant" ,"tokenizer" ,"chat_template" ,"mtp" ,"projectors" ,"general" ,"split" ,"verdict" , 406"draft_catalog_entry" ,"draft_setup_config" ,"files" ): 407self .assertIn (k ,s ) 408self .assertIn ("DRAFT" ,s ["draft_catalog_entry" ]["_status" ]) 409self .assertIn ("DRAFT" ,s ["draft_setup_config" ]["_status" ]) 410 411def test_draft_entry_for_qwen36_has_the_catalog_numbers (self ): 412r = analyse (files_for ("q36_ud_q4_k_xl" )) 413e = r ["draft_catalog_entry" ] 414self .assertEqual (e ["arch" ],"qwen35moe" ) 415self .assertEqual (e ["kv_bytes_per_token" ],11 * 2 * 256 * 2 * 4 )# setup.py OWN_PATH_FAMILIES['qwen36'] 416self .assertEqual (e ["state_gb" ],0.07 ) 417self .assertEqual (e ["mtp" ],2 ) 418self .assertEqual (e ["license" ],"https://huggingface.co/Qwen/Qwen3.6-35B-A3B/blob/main/LICENSE" ) 419 420def test_a_single_header_is_fast (self ): 421t0 = time .time () 422analyse (files_for ("fn_unsloth_ud_q4_k_xl" ),build_tokenizer = True ) 423self .assertLess (time .time ()- t0 ,60 ) 424 425 426@ unittest . skipUnless ( os . environ . get ( "STRATA_LIVE_HF" ) == "1" , "set STRATA_LIVE_HF=1 to read real headers from Hugging Face" ) 427class LiveHuggingFace (unittest .TestCase ): 428def setUp (self ): 429p = mock .patch .dict (os .environ , {"STRATA_TEST_ALLOW_NETWORK" :"1" })# a live test: the tests' network guard (conftest.py) lets it through 430p .start () 431self .addCleanup (p .stop ) 432 433def test_a_repo_directory_in_under_a_minute (self ): 434t0 = time .time () 435out = pathlib .Path (_TMP .name )/ "live.json" 436Q .main (["--hf" ,"unsloth/Qwen3.8-Flash-Next-GGUF" ,"--rev" ,"38bb39ee97821de2c9009abb7e93950eec396e66" ,"--dir" ,"UD-Q4_K_XL" , 437"--out" ,str (out ),"--quiet" ]) 438dt = time .time ()- t0 439rep = json .loads (out .read_text ()) 440self .assertLess (dt ,60 ,dt ) 441self .assertEqual (rep ["sets" ][0 ]["verdict" ]["case" ],"A" ) 442self .assertTrue (rep ["sets" ][0 ]["files" ][0 ]["sha256" ])# the LFS oid, not a download 443 444 445# ================================================================================================ the tables against the sources 446def _read (rel :str )-> str : 447return (ROOT / rel ).read_text (encoding = "utf-8" ) 448 449 450def _ints (text :str ,pat :str )-> set [int ]: 451return {int (x )for x in re .findall (pat ,text )} 452 453 454def _func (text :str ,head :str )-> str : 455i = text .index (head ) 456depth ,j = 0 ,text .index ("{" ,i ) 457k = j 458while True : 459if text [k ]== "{" : 460depth += 1 461elif text [k ]== "}" : 462depth -= 1 463if depth == 0 : 464return text [i :k + 1 ] 465k += 1 466 467 468def _define (text :str ,name :str )-> set [int ]: 469"""The first (STRATA_Q6K_EXPERTS=ON) definition of a STRATA_*_FMTS list.""" 470m = re .search (r"#define %s\(X\)([^\n]*)" % name ,text ) 471return _ints (m .group (1 ),r"X\((\d+)\)" ) 472 473 474def _is_iq_ints (text :str )-> set [int ]: 475body = _func (text ,"bool is_iq(int t)" ) 476return _ints (body .split ("#else" )[0 ],r"t == (\d+)" ) 477 478 479class TablesMatchTheSources (unittest .TestCase ): 480def test_geometry_defaults (self ): 481text = _read ("include/strata/core/geometry.hpp" ) 482cpp = {m .group (1 ):int (m .group (2 ))for m in re .finditer (r"int64_t (\w+) = (\d+);" ,text )} 483py = Q .COMPILED 484for name ,val in cpp .items (): 485with self .subTest (name ): 486self .assertEqual (getattr (py ,name ),val ) 487self .assertEqual (py .rms_eps ,1e-6 ) 488self .assertEqual (py .family ,"qwen4exp" ) 489 490def test_layout_tables_name_the_same_tensors (self ): 491text = _read ("include/strata/core/family_layout.hpp" ) 492cpp = set (re .findall (r'add\("([^"]+)"' ,text ))| set (re .findall (r'push_back\(\{"([^"]+)"' ,text )) 493py = set () 494g4 ,g35 = Q .Geometry (),Q .Geometry (family = "qwen35moe" ,hc = 0 ,hc_lr = 0 ,idx_q_heads = 0 ,idx_key_dim = 0 ,n_mtp_layers = 1 ,n_layers = 40 ) 495for g in (g4 ,g35 ): 496for l in range (g .n_layers + g .n_mtp_layers ): 497py |= {n for n ,_ in Q .layer_tensors (g ,l )} 498py |= {n for n ,_ in Q .global_tensors (g )} 499py |= {n for n ,_ in Q .layer_tensors (Q .Geometry (n_mtp_layers = 1 ),48 )}# the MTP kind on the hyper-connection side 500self .assertEqual (py ,cpp ) 501 502def test_family_names_and_runs (self ): 503text = _read ("include/strata/artifact/model_family.hpp" ) 504self .assertIn ('arch == "qwen4exp"' ,text ) 505self .assertIn ('arch == "qwen35moe"' ,text ) 506self .assertIn ("model_family_runs(ModelFamily f) { return f == ModelFamily::Qwen4Exp; }" ,text ) 507 508def test_qwen35_limits_and_required_keys (self ): 509text = _read ("src/qwen35/q36_engine.cu" ) 510self .assertIn ("g.head_dim != 256 || g.ssm_state_size != 128 || g.ssm_d_conv != 4 || g.n_expert > 512 || m.top_k > 15" ,text ) 511hpp = _read ("include/strata/artifact/gguf_reader.hpp" ) 512body = _func (hpp ,"inline std::string check_architecture_qwen35moe" ) 513self .assertEqual (set (re .findall (r'"qwen35moe\.([a-z_.]+)"' ,body )),set (Q .QWEN35_REQUIRED )) 514 515def test_qwen4_geometry_keys (self ): 516hpp = _read ("include/strata/artifact/gguf_reader.hpp" ) 517body = _func (hpp ,"inline std::string read_geometry" ) 518cpp = {m .group (1 ):m .group (3 )== "true" for m in re .finditer (r'\{"([^"]+)", &core::ModelGeometry::(\w+), (true|false)\}' ,body )} 519self .assertEqual (cpp , {k :r for k ,f ,r in Q .QWEN4_KEYS }) 520pins = _func (hpp ,"inline std::string geometry_unsupported" ) 521self .assertEqual ({m .group (1 )for m in re .finditer (r'\{"([^"]+)", &core::ModelGeometry::\w+\}' ,pins )}, 522 {k for k ,_ in Q .PINNED }- {"expert_shared_feed_forward_length" }) 523 524def test_cuda_and_hip_lists (self ): 525iq = _read ("src/kernels/cuda/iq_kernels.cu" ) 526L = Q .BACKEND_LISTS ["cuda" ] 527self .assertEqual (_define (iq ,"STRATA_GU_FMTS" ),L ["gu" ]) 528self .assertEqual (_define (iq ,"STRATA_D_FMTS" ),L ["down" ]) 529self .assertEqual (_is_iq_ints (iq ),L ["is_iq" ]) 530self .assertEqual (_ints (_func (iq ,"bool embed_type_supported" ),r"t == (\d+)" ),L ["embed_extra" ]) 531self .assertIs (Q .BACKEND_LISTS ["hip" ],L ) 532# HIP compiles the same file: nothing in it narrows the lists to one vendor 533self .assertNotIn ("__HIPCC__" ,"\n" .join (re .findall (r"#define STRATA_(?:GU|D)_FMTS[^\n]*" ,iq ))) 534self .assertIn ("option(STRATA_Q6K_EXPERTS" ,_read ("CMakeLists.txt" )) 535self .assertRegex (_read ("CMakeLists.txt" ),r'option\(STRATA_Q6K_EXPERTS "[^"]*" ON\)' ) 536 537def test_mmvq_lists (self ): 538for rel in ("src/kernels/cuda/native_mmvq.cu" ,"sycl/src/kernels/cuda/native_mmvq.dp.cpp" ,"metal/src/engine/mmvq_host.cpp" ): 539with self .subTest (rel ): 540self .assertEqual (_ints (_func (_read (rel ),"bool native_mmvq_supported" ),r"ggml_type == (\d+)" ),Q .MMVQ ) 541 542def test_sycl_lists (self ): 543text = _read ("sycl/src/kernels/cuda/iq_kernels.dp.cpp" ) 544L = Q .BACKEND_LISTS ["sycl" ] 545self .assertEqual (_define (text ,"STRATA_GU_FMTS" ),L ["gu" ]) 546self .assertEqual (_define (text ,"STRATA_D_FMTS" ),L ["down" ]) 547self .assertEqual (_is_iq_ints (text ),L ["is_iq" ]) 548self .assertEqual (_ints (_func (text ,"bool embed_type_supported" ),r"t == (\d+)" ),L ["embed_extra" ]) 549 550def test_metal_lists (self ): 551text = _read ("metal/src/engine/iq_host.cpp" ) 552L = Q .BACKEND_LISTS ["metal" ] 553self .assertEqual (_ints (_func (text ,"int gu_qk(int t)" ),r"case (\d+):" ),L ["gu" ]) 554self .assertEqual (_ints (_func (text ,"int d_qk(int t)" ),r"case (\d+):" ),L ["down" ]) 555self .assertEqual (_is_iq_ints (text )| _ints (_func (text ,"bool is_tq(int t)" ),r"t == (\d+)" ),L ["is_iq" ]) 556self .assertEqual (_ints (_func (text ,"bool embed_type_supported" ),r"t == (\d+)" ),L ["embed_extra" ]) 557 558def test_block_sizes_known_for_every_expert_type (self ): 559for be ,L in Q .BACKEND_LISTS .items (): 560for t in L ["gu" ]| L ["down" ]: 561with self .subTest ((be ,t )): 562self .assertGreater (Q .block_elems (t ),0 ) 563 564def test_expert_pair_rule_matches_the_cuda_function (self ): 565iq = _read ("src/kernels/cuda/iq_kernels.cu" ) 566body = _func (iq ,"bool native_expert_supported" ) 567for frag in ("n_embd % qg == 0" ,"n_ff % qd == 0" ,"n_embd % 256 == 0" ,"(n_ff * n_embd) % 256 == 0" ,"is_iq(gu_type) && is_iq(d_type)" ): 568self .assertIn (frag ,body ) 569# Flash-Next shape: IQ4_XS (qk 256) cannot be a down at n_ff 640; at Qwen3.6's n_ff 512 it can 570self .assertFalse (Q .expert_pair_ok ("cuda" ,21 ,23 ,2560 ,640 )) 571self .assertTrue (Q .expert_pair_ok ("cuda" ,21 ,23 ,2048 ,512 )) 572self .assertTrue (Q .expert_pair_ok ("cuda" ,12 ,7 ,2560 ,640 )) 573 574def test_projector_types_come_from_the_control (self ): 575from strata_control .models import OUR_PROJECTOR_TYPES 576self .assertEqual (set (OUR_PROJECTOR_TYPES ), {"qwen3vl_merger" }) 577 578def test_reference_tokenizer_is_flash_nexts (self ): 579fix = load_fixture ("fn_unsloth_ud_q4_k_xl" )["files" ][0 ]["metadata" ] 580self .assertEqual (fix ["tokenizer.ggml.tokens" ]["sha256" ],Q .REF_TOKENIZER ["tokens_sha256" ]) 581self .assertEqual (fix ["tokenizer.ggml.merges" ]["sha256" ],Q .REF_TOKENIZER ["merges_sha256" ]) 582special = {t :i for i ,t ,_ in fix ["tokenizer.ggml.tokens" ]["special" ]} 583for t ,i in Q .REF_TOKENIZER ["key_tokens" ].items (): 584self .assertEqual (special [t ],i ) 585tpl = serve_template_hash () 586self .assertEqual (tpl [:12 ],"12827f24b742" ) 587 588 589def serve_template_hash ()-> str : 590import hashlib 591return hashlib .sha256 ((ROOT / "serve" / "chat_template.jinja" ).read_bytes ()).hexdigest () 592 593 594if __name__ == "__main__" : 595unittest .main ()