okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
45c71cf9c
main
1"""The DFlash2 pack with the Q4_0 selector (174 MiB less graphics memory): made on this computer from the checked Q4_0 pack, used only when it verifies and the engine reads it. 2 3The idea and the bytes are nazeshinjite's (https://huggingface.co/nazeshinjite/Qwen3.8-Flash-Next-DFlash2-GGUF, Apache-2.0): the community GGUF stores the selector's two 4codebooks as Q4_0, and tools/dflash2_pack.py --q4_0-selector writes exactly those bytes (checked against the GGUF with the real checkpoint: RESULTS-DF2MEM.md section 15). 5These tests use the small synthetic checkpoint of tools/test_dflash2_pack.py: the real pins cannot be exercised without the 1.2 GB download, so the pinned numbers are 6checked for consistency and the mechanism with pins of the synthetic pack. 7""" 8 9from __future__import annotations 10 11import hashlib 12import importlib .util 13import json 14import os 15import sys 16import tempfile 17import unittest 18from pathlib import Path 19from unittest import mock 20 21from strata_control import drafting ,drafting_fetch 22 23ROOT = Path (__file__ ).resolve ().parents [2 ] 24VOCAB_REAL ,RANK_REAL = 248320 ,256 25 26 27def _load (name ,rel ): 28spec = importlib .util .spec_from_file_location (name ,ROOT / rel ) 29module = importlib .util .module_from_spec (spec ) 30sys .modules .setdefault (name ,module ) 31spec .loader .exec_module (module ) 32return module 33 34 35class PinnedNumbers (unittest .TestCase ): 36def test_the_converted_pack_is_the_q4_pack_less_the_codebooks_difference (self ): 37"""CONVERTED_BYTES follows from PACK_BYTES by arithmetic alone: two codebooks of 248,320 x 256 go from bf16 (2 bytes a value) to Q4_0 (18 bytes per 32 values).""" 38bf16 = 2 * VOCAB_REAL * RANK_REAL * 2 39q4 = 2 * VOCAB_REAL * (RANK_REAL // 32 )* 18 40self .assertEqual (drafting .PACK_BYTES - drafting .CONVERTED_BYTES ,bf16 - q4 ) 41self .assertEqual (bf16 - q4 ,182763520 ) 42self .assertEqual (len (drafting .CONVERTED_SHA256 ),64 ) 43self .assertNotEqual (drafting .CONVERTED_SHA256 ,drafting .PACK_SHA256 ) 44 45 46class SmallPacks (unittest .TestCase ): 47"""A synthetic checkpoint packed as the Q4_0 pack, then converted.""" 48 49@classmethod 50def setUpClass (cls ): 51cls .synth = _load ("t_pack_sel" ,"tools/test_dflash2_pack.py" ) 52cls .packer = _load ("strata_dflash2_pack_sel" ,"tools/dflash2_pack.py" ) 53 54def setUp (self ): 55self .tmp = tempfile .TemporaryDirectory () 56self .addCleanup (self .tmp .cleanup ) 57self .dir = Path (self .tmp .name ) 58self .synth .write_safetensors (self .dir / "m.safetensors" ,self .synth .tensors ()) 59 (self .dir / "c.json" ).write_text (json .dumps (self .synth .CFG )) 60self .data = self .dir / "data" 61self .q4 = drafting .target_path (self .data ) 62self .q4 .parent .mkdir (parents = True ) 63self .packer .pack (str (self .dir / "m.safetensors" ),str (self .dir / "c.json" ),str (self .q4 ),say = lambda * _ :None ,q4 = True ) 64self .src_pins = {"source_bytes" :self .q4 .stat ().st_size ,"source_sha256" :hashlib .sha256 (self .q4 .read_bytes ()).hexdigest ()} 65direct = self .dir / "direct.pack" 66self .packer .pack (str (self .dir / "m.safetensors" ),str (self .dir / "c.json" ),str (direct ),say = lambda * _ :None ,q4 = True ,q4_selector = True ) 67self .pins = {"size" :direct .stat ().st_size ,"sha256" :hashlib .sha256 (direct .read_bytes ()).hexdigest (),** self .src_pins } 68self .direct = direct 69 70def convert (self ,** extra ): 71return drafting_fetch .convert_selector (self .data ,** {** self .pins ,** extra }) 72 73def test_the_conversion_reproduces_the_pinned_bytes (self ): 74"""The pack converted from the finished Q4_0 pack is byte-identical to the one packed straight from the checkpoint with --q4_0-selector (the pinned hash).""" 75out = self .convert () 76self .assertEqual (out ,drafting .converted_path (self .data )) 77self .assertEqual (out .read_bytes (),self .direct .read_bytes ()) 78self .assertLess (out .stat ().st_size ,self .q4 .stat ().st_size ) 79self .assertTrue (drafting .converted_ok (self .data ,size = self .pins ["size" ],sha256 = self .pins ["sha256" ])) 80self .assertTrue (self .q4 .is_file (),"the Q4_0 pack stays: it is the fallback" ) 81 82def test_every_tensor_but_the_two_codebooks_is_carried_over_unchanged (self ): 83out = self .convert () 84a ,b = self .q4 .read_bytes (),out .read_bytes () 85 86def table (blob ): 87n = int .from_bytes (blob [8 :12 ],"little" ) 88rows = {} 89for line in blob [12 :12 + n ].decode ().split ("\n" ): 90w = line .split () 91if w and w [0 ]== "t" : 92rows [w [1 ]]= (w [2 ],int (w [5 ]),int (w [6 ])) 93return rows ,12 + n 94ta ,base_a = table (a ) 95tb ,base_b = table (b ) 96self .assertEqual (set (ta ),set (tb )) 97books = {"candidate_selector.predecessor_codebook" ,"candidate_selector.successor_codebook" } 98for name in ta : 99ba = a [base_a + ta [name ][1 ]:base_a + ta [name ][1 ]+ ta [name ][2 ]] 100bb = b [base_b + tb [name ][1 ]:base_b + tb [name ][1 ]+ tb [name ][2 ]] 101if name in books : 102self .assertEqual ((ta [name ][0 ],tb [name ][0 ]), ("bf16" ,"q4_0" )) 103self .assertEqual (len (bb )* 32 ,len (ba )* 9 ,name )# 18 bytes per 32 values against 2 bytes a value 104else : 105self .assertEqual (ba ,bb ,name ) 106 107def test_a_missing_corrupt_or_short_converted_pack_falls_back_to_the_q4_pack (self ): 108eng = self .dir / "engine" 109eng .write_bytes (b"\0" * 64 + drafting ._MARK_SELQ4 + b"\0" * 64 ) 110self .assertEqual (drafting .pack_path (self .data ,eng ),self .q4 ,"not made yet" ) 111out = self .convert () 112with mock .patch .object (drafting ,"CONVERTED_BYTES" ,self .pins ["size" ]),mock .patch .object (drafting ,"CONVERTED_SHA256" ,self .pins ["sha256" ]): 113self .assertEqual (drafting .pack_path (self .data ,eng ),out ) 114blob = bytearray (out .read_bytes ()) 115blob [len (blob )// 2 ]^= 0xFF # one flipped byte, the same size, and the marker still describes the old file 116before = out .stat () 117out .write_bytes (bytes (blob )) 118# (a real corruption happens long after the marker was written; on Linux the kernel's file clock ticks in ~4 ms steps, so a rewrite right away can keep the 119# same mtime_ns and the marker would still describe the file: let the clock move on, as it does in real life) 120os .utime (out ,ns = (before .st_atime_ns ,before .st_mtime_ns + 1_000_000_000 )) 121self .assertEqual (drafting .pack_path (self .data ,eng ),self .q4 ,"a corrupt file (the marker no longer matches it) is not used" ) 122out .write_bytes (bytes (blob )[:- 1000 ]) 123self .assertEqual (drafting .pack_path (self .data ,eng ),self .q4 ,"a short file is not used" ) 124out .unlink () 125self .assertEqual (drafting .pack_path (self .data ,eng ),self .q4 ,"a missing file is not used" ) 126 127def test_a_q4_pack_that_is_not_the_pinned_one_is_left_alone (self ): 128self .assertIsNone (self .convert (source_sha256 = "0" * 64 )) 129self .assertFalse (drafting .converted_path (self .data ).exists ()) 130self .assertTrue (self .q4 .is_file ()) 131 132def test_a_result_that_does_not_match_the_pin_is_deleted (self ): 133self .assertIsNone (self .convert (sha256 = "f" * 64 )) 134self .assertFalse (drafting .converted_path (self .data ).exists ()) 135self .assertFalse (drafting .converted_path (self .data ).with_suffix (".tmp" ).exists ()) 136 137def test_a_failing_conversion_is_never_an_error_for_the_caller (self ): 138with mock .patch .object (drafting_fetch ,"_packer" ,side_effect = RuntimeError ("no numpy" )): 139self .assertIsNone (self .convert ()) 140self .assertFalse (drafting .converted_path (self .data ).exists ()) 141 142def test_the_engine_must_read_the_pack_before_it_is_used (self ): 143out = self .convert () 144old = self .dir / "old-engine" 145old .write_bytes (b"\0" * 256 ) 146new = self .dir / "new-engine" 147new .write_bytes (b"\0" * 64 + drafting ._MARK_SELQ4 + b"\0" * 64 ) 148with mock .patch .object (drafting ,"CONVERTED_BYTES" ,self .pins ["size" ]),mock .patch .object (drafting ,"CONVERTED_SHA256" ,self .pins ["sha256" ]): 149self .assertEqual (drafting .pack_path (self .data ),self .q4 ,"no engine named: the pack every engine reads" ) 150self .assertEqual (drafting .pack_path (self .data ,old ),self .q4 ,"an engine without the text would read the rows as garbage" ) 151self .assertEqual (drafting .pack_path (self .data ,self .dir / "none" ),self .q4 ) 152self .assertEqual (drafting .pack_path (self .data ,new ),out ) 153 154def test_auto_arguments_point_at_the_converted_pack (self ): 155self .convert () 156new = self .dir / "new-engine" 157new .write_bytes (b"\0" * 64 + drafting ._MARK_SELQ4 + b"\0" * 64 + b"--draft-fallback" + b"--mtp-draft-vocab FILE (or --mtp DIR" ) 158vocab = self .data / drafting .FOLDER / drafting .VOCAB_NAME 159vocab .write_bytes (b"\1\0\0\0" * 8 ) 160cfg = {"model_name" :"qwen3.8-flash-next-iq3_s" ,"drafting" :"dflash2" ,"args" : ["--spec" ,"4" ,"--expert-cache" ,"1000" ]} 161with mock .patch .object (drafting ,"CONVERTED_BYTES" ,self .pins ["size" ]),mock .patch .object (drafting ,"CONVERTED_SHA256" ,self .pins ["sha256" ]), \ 162mock .patch .object (drafting ,"ENGINE_SERVES_DFLASH2" ,True ),mock .patch .object (drafting ,"pack_ready" ,return_value = True ): 163drafting .apply (cfg ,klass = "blackwell" ,data_dir = self .data ,backend = "cuda" ,archs = ["sm_120" ],engine = new ) 164args = cfg ["args" ] 165self .assertEqual (args [args .index ("--draft-model" )+ 1 ],str (drafting .converted_path (self .data ))) 166cfg2 = {"model_name" :"qwen3.8-flash-next-iq3_s" ,"drafting" :"dflash2" ,"args" : ["--spec" ,"4" ,"--expert-cache" ,"1000" ]} 167drafting .apply (cfg2 ,klass = "blackwell" ,data_dir = self .data ,backend = "cuda" ,archs = ["sm_120" ],engine = None ) 168self .assertEqual (cfg2 ["args" ][cfg2 ["args" ].index ("--draft-model" )+ 1 ],str (self .q4 ),"an engine that is not known gets the pack every engine reads" ) 169 170def test_needs_conversion_only_when_dflash2_is_chosen_and_the_q4_pack_is_here (self ): 171want = dict (mode = "dflash2" ,model_name = "qwen3.8-flash-next-iq3_s" ,data_dir = self .data ,backend = "cuda" ,archs = ["sm_120" ]) 172with mock .patch .object (drafting ,"ENGINE_SERVES_DFLASH2" ,True ),mock .patch .object (drafting ,"_here" ,lambda p :Path (p ).is_file ()): 173self .assertTrue (drafting .needs_conversion (** want )) 174self .assertFalse (drafting .needs_conversion (** {** want ,"mode" :"mtp" })) 175self .assertFalse (drafting .needs_conversion (** {** want ,"data_dir" :self .dir / "empty" })) 176self .convert () 177with mock .patch .object (drafting ,"CONVERTED_BYTES" ,self .pins ["size" ]),mock .patch .object (drafting ,"CONVERTED_SHA256" ,self .pins ["sha256" ]): 178self .assertFalse (drafting .needs_conversion (** want ),"already made" ) 179 180def test_setup_and_load_convert_a_start_does_not (self ): 181"""ensure() (strata drafting fetch, setup) converts a pack that is already here, with no network; the serving side only reads.""" 182with mock .patch .object (drafting_fetch ,"convert_selector" )as convert ,mock .patch .object (drafting ,"pack_ready" ,return_value = True ),mock .patch .object (drafting ,"engine_has_selector_q4" ,return_value = True ): 183drafting_fetch .ensure (self .data ) 184convert .assert_called_once () 185with mock .patch .object (drafting_fetch ,"convert_selector" )as convert ,mock .patch .object (drafting ,"pack_ready" ,return_value = True ),mock .patch .object (drafting ,"engine_has_selector_q4" ,return_value = False ): 186drafting_fetch .ensure (self .data ) 187convert .assert_not_called ()# an engine that cannot read the Q4_0 selector (the SYCL one) or none installed yet: the 340 MB file would never be used 188source = (ROOT / "serve" / "server.py" ).read_text (encoding = "utf-8" ) 189self .assertNotIn ("convert_selector" ,source ) 190self .assertNotIn ("convert_selector" , (ROOT / "strata_cli" / "launch" / "plan.py" ).read_text (encoding = "utf-8" )if (ROOT / "strata_cli" / "launch" / "plan.py" ).exists ()else "" ) 191 192 193class TheTrueGraphicsMemory (unittest .TestCase ): 194"""drafting.vram_gb: 0.72 GB with the converted pack (an engine that reads it), 0.89 GB otherwise; the plan and its text say the same number.""" 195 196def setUp (self ): 197self .tmp = tempfile .TemporaryDirectory () 198self .addCleanup (self .tmp .cleanup ) 199self .dir = Path (self .tmp .name ) 200self .new = self .dir / "new-engine" 201self .new .write_bytes (b"\0" * 64 + drafting ._MARK_SELQ4 + b"\0" * 64 ) 202self .old = self .dir / "old-engine" 203self .old .write_bytes (b"\0" * 256 ) 204self .data = self .dir / "data" 205 (self .data / drafting .FOLDER ).mkdir (parents = True ) 206 207def pack (self ,name ): 208 (self .data / drafting .FOLDER / name ).write_bytes (b"x" * ((1 << 20 )+ 1 )) 209 210def test_the_table (self ): 211self .assertEqual ((drafting .DRAFTER_MIB ["dflash2" ],drafting .DRAFTER_MIB ["dflash2_selq4" ],drafting .DRAFTER_MIB ["mtp" ]), (890 ,715 ,1082 )) 212self .assertEqual ((drafting .DRAFTER_GB ["dflash2" ],drafting .DRAFTER_GB ["dflash2_selq4" ],drafting .DRAFTER_GB ["mtp" ],drafting .DRAFTER_GB ["off" ]), (0.89 ,0.72 ,1.08 ,0.0 )) 213self .assertEqual (drafting .VRAM_GB ,0.89 ,"the bf16-selector figure stays the module constant" ) 214 215def test_the_figure_follows_the_engine_and_the_pack (self ): 216self .pack (drafting .PACK_NAME ) 217self .assertEqual (drafting .vram_gb (self .data ,self .new ),0.72 ) 218self .assertEqual (drafting .vram_gb (self .data ,self .old ),0.89 ,"an engine without the text keeps the bf16 selector" ) 219self .assertEqual (drafting .vram_gb (self .data ,None ),0.89 ,"an engine that is not known: the larger figure" ) 220self .assertEqual (drafting .vram_gb (None ,self .new ),0.72 ,"no data folder yet: the pack will be the Q4_0 one" ) 221 222def test_a_q8_pack_of_an_earlier_strata_is_never_converted_so_the_figure_stays (self ): 223self .pack (drafting .LEGACY_PACK_NAME ) 224self .assertEqual (drafting .vram_gb (self .data ,self .new ),0.89 ) 225self .pack (drafting .PACK_NAME )# the Q4_0 pack beside it wins (pack_path): the converted figure 226self .assertEqual (drafting .vram_gb (self .data ,self .new ),0.72 ) 227 228def test_the_plan_says_the_same_number_in_words_and_in_the_fields (self ): 229plan = drafting_fetch .plan (self .data ,self .new ) 230self .assertEqual ((plan ["vram_gb" ],plan ["selq4" ]), (0.72 ,True )) 231self .assertIn ("about 0.7 GB of graphics memory" ,plan ["text" ]) 232plan = drafting_fetch .plan (self .data ,self .old ) 233self .assertEqual ((plan ["vram_gb" ],plan ["selq4" ]), (0.89 ,False )) 234self .assertIn ("about 0.9 GB of graphics memory" ,plan ["text" ]) 235plan = drafting_fetch .plan (self .data ) 236self .assertEqual ((plan ["vram_gb" ],plan ["selq4" ]), (0.89 ,False )) 237 238 239if __name__ == "__main__" : 240unittest .main ()