okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bc6f248ff
main
1"""A model file under a name setup does not write (renamed, a hand-written config, no name) is judged by what the file IS: its GGUF header (architecture, layers, hidden size, 2vocabulary size) against what the DFlash2 drafter pack records. A renamed Qwen3.8-Flash-Next file used to start the MTP with no word said (strata_control/drafting.py, apply).""" 3 4from __future__import annotations 5 6import json 7import struct 8import tempfile 9import unittest 10from pathlib import Path 11from unittest import mock 12 13from strata_control import drafting 14 15ROOT = Path (__file__ ).resolve ().parents [2 ] 16REAL_HEADER = ROOT / "tests" / "terminal" / "data" / "flash_next_iq3s_header.gguf" # the first 2,710 bytes of the Qwen3.8-Flash-Next IQ3_S file: the keys, no weights 17_HARDWARE = mock .patch .object (drafting ,"detect_hardware" ,return_value = ("cuda" , ["sm_120" ])) 18 19 20def setUpModule (): 21_HARDWARE .start () 22 23 24def tearDownModule (): 25_HARDWARE .stop () 26 27 28def _s (text :str )-> bytes : 29raw = text .encode () 30return struct .pack ("<Q" ,len (raw ))+ raw 31 32 33def gguf_header (arch = "qwen4exp" ,layers = 48 ,hidden = 2560 ,vocab = 248320 ,tokens = True )-> bytes : 34"""A GGUF header with the keys the drafter's test reads; the vocabulary array is announced (its count) and not written.""" 35kvs = [(_s ("general.architecture" ),struct .pack ("<I" ,8 )+ _s (arch )), 36 (_s ("general.name" ),struct .pack ("<I" ,8 )+ _s ("renamed" )), 37 (_s (f" { arch } .block_count" ),struct .pack ("<I" ,4 )+ struct .pack ("<I" ,layers )), 38 (_s (f" { arch } .context_length" ),struct .pack ("<I" ,4 )+ struct .pack ("<I" ,262144 )), 39 (_s (f" { arch } .embedding_length" ),struct .pack ("<I" ,4 )+ struct .pack ("<I" ,hidden )), 40 (_s (f" { arch } .rope.dimension_sections" ),struct .pack ("<I" ,9 )+ struct .pack ("<IQ" ,5 ,4 )+ struct .pack ("<4i" ,11 ,11 ,10 ,0 ))] 41if tokens : 42kvs .append ((_s ("tokenizer.ggml.tokens" ),struct .pack ("<I" ,9 )+ struct .pack ("<IQ" ,8 ,vocab ))) 43body = b"" .join (k + v for k ,v in kvs ) 44return b"GGUF" + struct .pack ("<IQQ" ,3 ,0 ,len (kvs ))+ body 45 46 47def pack_with (** cfg )-> bytes : 48"""The start of a DFlash2 pack: "DF2P", version, index length, the text index with its cfg lines.""" 49lines = "" .join (f"cfg { k } { v } \n" for k ,v in cfg .items ())+ "end\n" 50index = lines .encode () 51return b"DF2P" + struct .pack ("<II" ,1 ,len (index ))+ index 52 53 54class ReadingTheHeader (unittest .TestCase ): 55def test_the_real_header_of_the_flash_next_file (self ): 56self .assertEqual (drafting .gguf_facts (REAL_HEADER ), {"arch" :"qwen4exp" ,"layers" :48 ,"hidden" :2560 ,"vocab" :248320 }) 57self .assertEqual (drafting .file_fit (["--native" ,str (REAL_HEADER )]),"fits" ) 58 59def test_a_synthetic_header_and_what_it_cannot_be (self ): 60with tempfile .TemporaryDirectory ()as tmp : 61p = Path (tmp )/ "m.gguf" 62p .write_bytes (gguf_header ()) 63self .assertEqual (drafting .gguf_facts (p ), {"arch" :"qwen4exp" ,"layers" :48 ,"hidden" :2560 ,"vocab" :248320 }) 64p .write_bytes (gguf_header (tokens = False )) 65self .assertEqual (drafting .gguf_facts (p )["vocab" ],None ,"no vocabulary key: not a reason to refuse" ) 66self .assertEqual (drafting .file_fit (["--native" ,str (p )]),"fits" ) 67p .write_bytes (b"not a gguf at all, just text" * 10 ) 68self .assertIsNone (drafting .gguf_facts (p )) 69self .assertEqual (drafting .file_fit (["--native" ,str (p )]),"unknown" ) 70p .write_bytes (b"GGUF" + b"\x03\x00\x00\x00" + b"\xff" * 40 ) 71self .assertEqual (drafting .file_fit (["--native" ,str (p )]),"unknown" ,"a damaged header is no answer, never an error" ) 72self .assertEqual (drafting .file_fit (["--native" ,str (Path (tmp )/ "missing.gguf" )]),"unknown" ) 73self .assertEqual (drafting .file_fit ([]),"unknown" ) 74 75def test_the_fits_test_by_shape (self ): 76with tempfile .TemporaryDirectory ()as tmp : 77p = Path (tmp )/ "m.gguf" 78for kw ,want in ((dict (),"fits" ), (dict (hidden = 4096 ),"family" ), (dict (layers = 40 ),"family" ), (dict (layers = 46 ),"fits" ), (dict (layers = 45 ),"family" ), 79 (dict (vocab = 151936 ),"family" ), (dict (arch = "qwen35moe" ),"other" ), (dict (arch = "llama" ),"other" )): 80p .write_bytes (gguf_header (** kw )) 81self .assertEqual (drafting .file_fit (["--native" ,str (p )]),want ,kw ) 82 83def test_the_pack_says_what_it_was_made_for (self ): 84with tempfile .TemporaryDirectory ()as tmp : 85data = Path (tmp ) 86self .assertEqual (drafting .pack_target (data ),drafting .PACK_TARGET ,"no pack here: what the code knows" ) 87pack = drafting .target_path (data ) 88pack .parent .mkdir (parents = True ) 89pack .write_bytes (pack_with (hidden = 3072 ,vocab = 151936 ,taps = "3,9,15" )+ b"\0" * 64 ) 90self .assertEqual (drafting .pack_target (data ), {"hidden" :3072 ,"vocab" :151936 ,"taps" : (3 ,9 ,15 )}) 91m = Path (tmp )/ "m.gguf" 92m .write_bytes (gguf_header ()) 93self .assertEqual (drafting .file_fit (["--native" ,str (m )],data ),"family" ,"the pack on this computer decides, not the table in the code" ) 94m .write_bytes (gguf_header (hidden = 3072 ,vocab = 151936 ,layers = 20 )) 95self .assertEqual (drafting .file_fit (["--native" ,str (m )],data ),"fits" ) 96 97 98class ARenamedFileAtStart (unittest .TestCase ): 99HARDWARE = (("cuda" , ["sm_120" ]), ("hip" , ["gfx1151" ]), ("metal" ,None )) 100 101def config (self ,tmp ,name ,header ,mode = None ): 102data = Path (tmp ) 103mtp = data / "mtp" / "rt" 104mtp .mkdir (parents = True ) 105 (mtp / "experts.bin" ).write_bytes (b"e" ) 106 (mtp / "draft_vocab.bin" ).write_bytes (b"v" ) 107pack = drafting .pack_path (data ) 108pack .parent .mkdir (parents = True ) 109pack .write_bytes (b"x" * (2 << 20 )) 110model = data / "my-copy.gguf" 111model .write_bytes (header ) 112args = ["--pack" ,str (data / "packs" / "x" ),"--native" ,str (model ),"--mtp" ,str (mtp ),"--spec" ,"4" ,"--spec-min-p" ,"0.5" ] 113cfg = {"args" :args ,** ({}if name is None else {"model_name" :name }),** ({}if mode is None else {"drafting" :mode })} 114return cfg ,data 115 116def test_a_renamed_flash_next_file_starts_dflash2_with_nothing_said (self ): 117for backend ,archs in self .HARDWARE : 118for name in ("my-copy" ,"Qwen3.8 Flash Next (my copy)" ,"" ,None ,"qwen3.8-flash-next-unslothx-q8_0" ): 119for mode in (None ,"auto" ,"dflash2" ): 120with tempfile .TemporaryDirectory ()as tmp : 121cfg ,data = self .config (tmp ,name ,gguf_header (),mode ) 122decision = drafting .apply (cfg ,data_dir = data ,backend = backend ,archs = archs ) 123self .assertEqual ((decision .drafter ,decision .note ), ("dflash2" ,"" ), (backend ,name ,mode )) 124self .assertEqual (cfg ["args" ][cfg ["args" ].index ("--draft" )+ 1 ],"dflash2" ) 125self .assertNotIn ("--mtp" ,cfg ["args" ]) 126 127def test_the_names_setup_writes_are_decided_as_before (self ): 128"""A supported name never reads the file: a name setup wrote is the answer, as in every release before.""" 129with tempfile .TemporaryDirectory ()as tmp : 130cfg ,data = self .config (tmp ,"qwen3.8-flash-next-iq3_s" ,b"" ) 131with mock .patch .object (drafting ,"file_fit" ,side_effect = AssertionError ("the file is not read" )): 132self .assertEqual (drafting .apply (cfg ,data_dir = data ,backend = "cuda" ,archs = ["sm_120" ]).drafter ,"dflash2" ) 133 134def test_coder_nvfp4_and_swift_stay_out_whatever_the_file_says (self ): 135for name in ("qwen3.8-flash-next-coder-iq1_m" ,"qwen3.8-flash-next-nvfp4-nvfp4" ,"swift-1.5-iq2_xs" ,"My-Coder-copy" ): 136for mode in (None ,"auto" ): 137with tempfile .TemporaryDirectory ()as tmp : 138cfg ,data = self .config (tmp ,name ,gguf_header (),mode ) 139original = list (cfg ["args" ]) 140decision = drafting .apply (cfg ,data_dir = data ,backend = "cuda" ,archs = ["sm_120" ]) 141self .assertEqual ((decision .drafter ,decision .note ), ("mtp" ,"" ),name ) 142self .assertEqual (cfg ["args" ],original ) 143 144def test_a_flash_next_family_file_the_drafter_does_not_fit_starts_the_mtp_and_says_so (self ): 145for header in (gguf_header (hidden = 4096 ),gguf_header (layers = 36 ),gguf_header (vocab = 262144 )): 146for name in ("my-copy" ,None ): 147with tempfile .TemporaryDirectory ()as tmp : 148cfg ,data = self .config (tmp ,name ,header ,"auto" ) 149original = list (cfg ["args" ]) 150decision = drafting .apply (cfg ,data_dir = data ,backend = "cuda" ,archs = ["sm_120" ]) 151self .assertEqual ((decision .drafter ,decision .note ), ("mtp" ,drafting .NOT_SUPPORTED )) 152self .assertEqual (drafting .summary_line (decision ),"Drafting: MTP (DFlash2 is for Qwen3.8-Flash-Next only)" ) 153self .assertEqual (cfg ["args" ],original ,"the MTP's own arguments" ) 154self .assertNotIn ("--draft" ,cfg ["args" ]) 155 156def test_another_model_is_not_this_choices_business (self ): 157"""A Qwen3.6 or Llama file under an unknown name: the MTP as before, no line (the drafter was never an option for it, so nothing is lost).""" 158for arch in ("qwen35moe" ,"llama" ): 159with tempfile .TemporaryDirectory ()as tmp : 160cfg ,data = self .config (tmp ,"my-copy" ,gguf_header (arch = arch ),"auto" ) 161original = list (cfg ["args" ]) 162decision = drafting .apply (cfg ,data_dir = data ,backend = "cuda" ,archs = ["sm_120" ]) 163self .assertEqual ((decision .drafter ,decision .note ), ("mtp" ,"" ),arch ) 164self .assertEqual (cfg ["args" ],original ) 165 166def test_an_unreadable_or_missing_file_is_what_it_was (self ): 167with tempfile .TemporaryDirectory ()as tmp : 168cfg ,data = self .config (tmp ,"my-copy" ,b"junk" ) 169decision = drafting .apply (cfg ,data_dir = data ,backend = "cuda" ,archs = ["sm_120" ]) 170self .assertEqual ((decision .drafter ,decision .note ), ("mtp" ,"" )) 171cfg ["args" ][cfg ["args" ].index ("--native" )+ 1 ]= str (Path (tmp )/ "gone.gguf" ) 172self .assertEqual (drafting .apply (cfg ,data_dir = data ,backend = "cuda" ,archs = ["sm_120" ]).note ,"" ) 173 174def test_dflash2_named_on_another_model_says_it_cannot (self ): 175with tempfile .TemporaryDirectory ()as tmp : 176cfg ,data = self .config (tmp ,"my-copy" ,gguf_header (arch = "llama" ),"dflash2" ) 177decision = drafting .apply (cfg ,data_dir = data ,backend = "cuda" ,archs = ["sm_120" ]) 178self .assertEqual ((decision .drafter ,decision .note ), ("mtp" ,drafting .NOT_SUPPORTED )) 179 180def test_the_terminal_that_knows_the_family_does_not_read_the_file (self ): 181with tempfile .TemporaryDirectory ()as tmp : 182cfg ,data = self .config (tmp ,"my-copy" ,gguf_header (arch = "llama" ),"auto" ) 183with mock .patch .object (drafting ,"file_fit" ,side_effect = AssertionError ("the family is the answer" )): 184self .assertEqual (drafting .apply (cfg ,data_dir = data ,family = "qwen" ,backend = "cuda" ,archs = ["sm_120" ]).drafter ,"dflash2" ) 185self .assertEqual (drafting .apply (dict (cfg ),data_dir = data ,family = "coder" ,backend = "cuda" ,archs = ["sm_120" ]).drafter ,"mtp" ) 186 187 188class AKnownSetUnderAnotherName (unittest .TestCase ): 189"""A renamed file that is EXACTLY one of data/gguf_fingerprints.json's sets (tensor count, payload bytes, expert formats over every shard) is treated under that set's own name, so it gets the set's table entry 190(tuned pack, confidence); anything else keeps the general defaults. The layout guess (a fine-tune that only looks like a set) never counts.""" 191 192ROW = json .loads ((ROOT / "data" / "gguf_fingerprints.json" ).read_text (encoding = "utf-8" ))["qwen/IQ3_S" ] 193 194def shards (self ,tmp ,names = ("copy-00001-of-00002.gguf" ,"copy-00002-of-00002.gguf" )): 195for n in names : 196 (Path (tmp )/ n ).write_bytes (b"x" ) 197return Path (tmp )/ names [0 ] 198 199def fake (self ,tensors ,payload ,experts ,arch = "qwen4exp" ,second_arch = None ): 200"""inspect_metadata of two shards: the totals are split between them; the second shard of a real split set has no architecture key (seen on the real IQ3_S files).""" 201halves = iter (((tensors - tensors // 2 ,payload - payload // 2 ,experts ,arch ), (tensors // 2 ,payload // 2 ,set (),second_arch ))) 202 203def inspect (path ): 204t ,p ,e ,a = next (halves ) 205return {"architecture" :a ,"expert_tensor_types" :sorted (e ),"tensor_count_scanned" :t ,"payload_bytes_required" :p } 206return mock .patch ("strata_control.models.inspect_metadata" ,side_effect = inspect ) 207 208def test_the_header_of_a_set_names_it (self ): 209from strata_control import models 210experts = set (self .ROW ["expert_bytes" ]) 211with tempfile .TemporaryDirectory ()as tmp : 212first = self .shards (tmp ) 213with self .fake (self .ROW ["tensors" ],self .ROW ["bytes" ],experts ): 214self .assertEqual (models .known_set_by_header (first ),"qwen/IQ3_S" ) 215with self .fake (self .ROW ["tensors" ],self .ROW ["bytes" ]+ 1 ,experts ): 216self .assertIsNone (models .known_set_by_header (first ),"one byte of payload more: not that set" ) 217with self .fake (self .ROW ["tensors" ],self .ROW ["bytes" ],experts | {"Q8_0" }): 218self .assertIsNone (models .known_set_by_header (first ),"another expert format: not that set" ) 219with self .fake (self .ROW ["tensors" ]- 1 ,self .ROW ["bytes" ],experts ): 220self .assertIsNone (models .known_set_by_header (first )) 221with self .fake (self .ROW ["tensors" ],self .ROW ["bytes" ],experts ,arch = "llama" ): 222self .assertIsNone (models .known_set_by_header (first )) 223with self .fake (self .ROW ["tensors" ],self .ROW ["bytes" ],experts ,second_arch = "qwen4exp" ): 224self .assertEqual (models .known_set_by_header (first ),"qwen/IQ3_S" ,"a later shard may name the architecture too" ) 225with self .fake (self .ROW ["tensors" ],self .ROW ["bytes" ],experts ,second_arch = "llama" ): 226self .assertIsNone (models .known_set_by_header (first ),"a later shard of another architecture" ) 227with mock .patch .object (models ,"_candidate_by_layout" ,side_effect = AssertionError ("the layout guess is never used" )),self .fake (self .ROW ["tensors" ],self .ROW ["bytes" ]// 2 ,experts ): 228self .assertIsNone (models .known_set_by_header (first ),"a file with the layout of a set is not that set" ) 229 (Path (tmp )/ "copy-00002-of-00002.gguf" ).unlink () 230with self .fake (self .ROW ["tensors" ],self .ROW ["bytes" ],experts ): 231self .assertIsNone (models .known_set_by_header (first ),"a shard missing" ) 232with mock .patch ("strata_control.models.inspect_metadata" ,side_effect = OSError ("unreadable" )): 233self .assertIsNone (models .known_set_by_header (first )) 234self .assertIsNone (models .known_set_by_header ("/no/such/file.gguf" )) 235 236def test_the_name_setup_would_have_written (self ): 237for found ,want in (("qwen/IQ3_S" ,"qwen3.8-flash-next-iq3_s" ), ("unsloth/UD-Q4_K_XL" ,"qwen3.8-flash-next-unsloth-ud-q4_k_xl" ), ("gyro/Gyro-S" ,"qwen3.8-flash-next-gyro-gyro-s" ), 238 ("unsloth/UD-IQ4_XS-v31" ,"qwen3.8-flash-next-unsloth-ud-iq4_xs-v31" ), ("coder/IQ1_M" ,None ), ("swift/IQ3_S" ,None ), (None ,None )): 239drafting ._known_names .clear () 240with tempfile .TemporaryDirectory ()as tmp : 241model = Path (tmp )/ "m.gguf" 242model .write_bytes (b"x" ) 243with mock .patch ("strata_control.models.known_set_by_header" ,return_value = found )as call : 244self .assertEqual (drafting .known_name_of_file (["--native" ,str (model )]),want ,found ) 245self .assertEqual (drafting .known_name_of_file (["--native" ,str (model )]),want ) 246self .assertEqual (call .call_count ,1 ,"read once per file, size and time" ) 247self .assertIsNone (drafting .known_name_of_file ([])) 248self .assertIsNone (drafting .known_name_of_file (["--native" ,"/no/such/file.gguf" ])) 249 250def test_a_renamed_known_set_is_decided_under_its_own_name_and_any_other_under_the_general_one (self ): 251for known ,want in ("qwen3.8-flash-next-iq3_s" ,"qwen3.8-flash-next-iq3_s" ), (None ,drafting .FILE_FITS_AS ): 252with tempfile .TemporaryDirectory ()as tmp : 253cfg ,data = ARenamedFileAtStart ("test_a_renamed_flash_next_file_starts_dflash2_with_nothing_said" ).config (tmp ,"my-copy" ,gguf_header (),"auto" ) 254seen = [] 255real = drafting .tuned_applies 256with mock .patch .object (drafting ,"known_name_of_file" ,return_value = known ),mock .patch .object (drafting ,"tuned_applies" ,side_effect = lambda backend ,name ,* a ,** k : (seen .append (name ),real (backend ,name ,* a ,** k ))[1 ]): 257decision = drafting .apply (cfg ,data_dir = data ,backend = "cuda" ,archs = ["sm_120" ],vram_mib = 73728 ) 258self .assertEqual ((decision .drafter ,decision .note ), ("dflash2" ,"" )) 259self .assertEqual (seen , [want ]) 260 261def test_a_name_setup_wrote_never_reads_the_file_for_its_set (self ): 262with tempfile .TemporaryDirectory ()as tmp : 263cfg ,data = ARenamedFileAtStart ("test_a_renamed_flash_next_file_starts_dflash2_with_nothing_said" ).config (tmp ,"qwen3.8-flash-next-iq3_s" ,gguf_header ()) 264with mock .patch .object (drafting ,"known_name_of_file" ,side_effect = AssertionError ("not read" )): 265self .assertEqual (drafting .apply (cfg ,data_dir = data ,backend = "cuda" ,archs = ["sm_120" ]).drafter ,"dflash2" ) 266 267 268if __name__ == "__main__" : 269unittest .main ()