okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6ca60e9a0
main
1"""The preset store: save, name, apply on load, stale detection, undo.""" 2 3from __future__import annotations 4 5import copy 6import json 7import os 8import tempfile 9import time 10import unittest 11from pathlib import Path 12 13from strata_control import presets ,tune_knobs 14 15CFG = {"exe" :"strata" ,"model_name" :"swift-iq2_xs" ,"ui_resource_profile" :"work" ,"vram_reserve_mib" :1536 , 16"args" : ["--pack" ,"P" ,"--native" ,"Swift-IQ3_S-00001-of-00002.gguf" ,"--expert-cache" ,"auto" ,"--prefill" ,"auto" , 17"--spec" ,"4" ,"--max-context" ,"131072" ,"--kv" ,"int8" ]} 18 19 20def identity (driver = "610.47" ,sha = "aaa" ,epoch = 0 ,gpu = "RTX 5070" ,ram = 64 ): 21return {"hardware" : {"hard" : {"gpus" : [{"name" :gpu ,"vram_mib" :12227 }],"cpu" :"cpu" ,"logical" :12 ,"physical" :6 , 22"hybrid" :False ,"ram_gib" :ram ,"pcie" :None ,"os" :"Windows" }, 23"soft" : {"driver" : [driver ],"os_release" :"11" }}, 24"engine" : {"version" :"0.1.45" ,"backend" :"cuda" ,"sha256" :"e1" ,"tuning_epoch" :epoch }, 25"model" : {"sha256_shard1" :sha ,"bytes" :1 }} 26 27 28RESULT = {"outcome" :"improved" ,"seconds" :1100 ,"settings" : {"args" : {"--host-core" :"last" },"env" : {},"per_request" : {}}, 29"answers" : {"class" :"exact" ,"fields" : []},"base" : {"decode_tok_s" :60.0 ,"pp_tok_s" :1500.0 }, 30"chosen" : {"decode_tok_s" :65.0 ,"pp_tok_s" :1500.0 ,"rss_peak_mib" :12000 ,"vram_used_mib" :9000 }, 31"gain_pct" :8.3 ,"pairs" :2 ,"faster_pairs" :2 ,"noise" : {"aa_gap" :0.004 }} 32 33 34class StoreTest (unittest .TestCase ): 35def setUp (self ): 36self .tmp = tempfile .TemporaryDirectory () 37os .environ ["STRATA_PRESET_DIR" ]= str (Path (self .tmp .name )/ "presets" ) 38self .addCleanup (lambda :os .environ .pop ("STRATA_PRESET_DIR" ,None )) 39self .addCleanup (self .tmp .cleanup ) 40self .choices = presets .choices_from_config (CFG ) 41 42def make (self ,name = None ,ident = None ,result = None ,choices = None ): 43return presets .create (result or RESULT ,choices = choices or self .choices ,identity = ident or identity (),name = name ) 44 45def test_default_name_is_plain_words (self ): 46self .assertEqual (self .choices ["quant" ],"IQ3_S" ) 47self .assertEqual (presets .default_name (self .choices ),"IQ3_S 128K – Work" ) 48full = dict (self .choices ,goal = "speed" ) 49self .assertEqual (presets .default_name (full ),"IQ3_S 128K – Full speed" ) 50 51def test_create_list_rename_delete (self ): 52p = self .make () 53self .assertTrue (p ["name" ].startswith ("IQ3_S 128K" )) 54self .assertEqual (len (presets .list_presets ()),1 ) 55self .assertTrue (presets .list_presets ()[0 ]["active" ]) 56q = presets .rename (p ["id" ],"My fast one" ) 57self .assertEqual (q ["name" ],"My fast one" ) 58with self .assertRaises (presets .PresetError ): 59presets .rename (p ["id" ],"" ) 60p2 = self .make (name = "My fast one" )# a duplicate name gets a number, never overwrites 61self .assertEqual (p2 ["name" ],"My fast one (2)" ) 62presets .delete ("My fast one (2)" ) 63self .assertEqual ([x ["name" ]for x in presets .list_presets ()], ["My fast one" ]) 64 65def test_activation_keeps_the_previous_one_and_undo_restores_it (self ): 66a = self .make (name = "A" ) 67b = self .make (name = "B" ) 68self .assertEqual (presets .find ("B" )["id" ],b ["id" ]) 69slot = a ["slot" ] 70self .assertEqual (presets ._index ()[slot ]["active" ],b ["id" ]) 71self .assertEqual (presets .load (b ["id" ])["previous" ],a ["id" ]) 72restored = presets .undo (slot ) 73self .assertEqual (restored ["id" ],a ["id" ]) 74self .assertEqual (presets ._index ()[slot ]["active" ],a ["id" ]) 75self .assertIsNone (presets .undo (slot ))# undo once more: back to the standard setup 76self .assertIsNone (presets ._index ()[slot ]["active" ]) 77with self .assertRaises (presets .PresetError ): 78presets .undo (slot ) 79 80def test_unsafe_settings_are_refused (self ): 81bad = copy .deepcopy (RESULT ) 82bad ["settings" ]["args" ]= {"--expert-cache" :0 } 83with self .assertRaises (presets .PresetError ): 84self .make (result = bad ) 85 86def test_a_value_outside_the_tested_range_is_kept_with_a_warning (self ): 87# #3844: --spec 5 is not a value the tuner tries (its safe values are 3 and 4), but nobody measured it as bad on every 88# card; a user who chose it keeps it, and is told once. The never list (--spec 6, --expert-cache 0 ...) still refuses. 89res = copy .deepcopy (RESULT ) 90res ["settings" ]["args" ]= {"--spec" :5 } 91self .make (result = res )# saved, not refused 92out ,info = presets .overlay (CFG ,now = identity ()) 93self .assertTrue (info ["applied" ],info ) 94self .assertEqual (tune_knobs ._current (out ["args" ],"--spec" ),"5" ) 95self .assertEqual (info ["warnings" ], ["--spec 5: not tried by the tuner, kept because it is your setting" ]) 96self .assertNotIn ("why_not" ,info ) 97self .assertEqual (tune_knobs ._current (CFG ["args" ],"--spec" ),"4" )# the input is not modified 98# an in-range preset has no warnings 99presets .delete (presets .list_presets ()[0 ]["id" ]) 100self .make () 101_ ,info2 = presets .overlay (CFG ,now = identity ()) 102self .assertTrue (info2 ["applied" ]) 103self .assertNotIn ("warnings" ,info2 ) 104 105def test_the_never_list_still_refuses_but_a_range_does_not (self ): 106ctx = tune_knobs .Context () 107never ,bounds = tune_knobs .check_setting_parts ({"--spec" :5 ,"--pcie-frac" :0.6 }, {},ctx ) 108self .assertEqual (never , []) 109self .assertEqual (len (bounds ),2 ) 110never ,bounds = tune_knobs .check_setting_parts ({"--spec" :6 }, {},ctx ) 111self .assertTrue (never and bounds )# slower (never list) and outside the values 112# the tuner's own check is the two lists together, in the same order as before 113self .assertEqual (tune_knobs .check_setting ({"--spec" :6 }, {},ctx ),never + bounds ) 114bad = copy .deepcopy (RESULT ) 115bad ["settings" ]["args" ]= {"--spec" :6 } 116with self .assertRaises (presets .PresetError ): 117self .make (result = bad ) 118 119def test_overlay_applies_the_active_preset_without_measuring (self ): 120self .make () 121out ,info = presets .overlay (CFG ,now = identity ()) 122self .assertTrue (info ["applied" ]) 123self .assertEqual (info ["state" ],"fresh" ) 124self .assertEqual (out ["args" ][- 2 :], ["--host-core" ,"last" ]) 125self .assertEqual (out ["args" ][:len (CFG ["args" ])],CFG ["args" ])# the user's own flags are untouched 126self .assertNotIn ("--host-core" ,CFG ["args" ])# the input is not modified 127self .assertIn ("identical" ,info ["notice" ]) 128 129def test_overlay_other_choices_get_no_preset (self ): 130self .make () 131other = copy .deepcopy (CFG ) 132other ["args" ][other ["args" ].index ("--max-context" )+ 1 ]= "32768" 133out ,info = presets .overlay (other ,now = identity ()) 134self .assertFalse (info ["applied" ]) 135self .assertEqual (out ,other ) 136full = copy .deepcopy (CFG ) 137full ["ui_resource_profile" ]= "performance" 138self .assertFalse (presets .overlay (full ,now = identity ())[1 ]["applied" ]) 139 140def test_hard_change_does_not_apply_and_says_why (self ): 141self .make () 142for kw ,word in ((dict (gpu = "RTX 4090" ),"graphics card" ), (dict (sha = "zzz" ),"model file" )): 143out ,info = presets .overlay (CFG ,now = identity (** kw )) 144if "model file" in word : 145self .assertFalse (info ["applied" ])if info .get ("state" )else None 146self .assertFalse (info ["applied" ],kw ) 147 148def test_soft_change_applies_and_asks_for_a_recheck (self ): 149self .make () 150out ,info = presets .overlay (CFG ,now = identity (driver = "620.1" )) 151self .assertTrue (info ["applied" ]) 152self .assertEqual (info ["state" ],"soft" ) 153self .assertTrue (any ("driver" in r for r in info ["reasons" ])) 154out ,info = presets .overlay (CFG ,now = identity (epoch = 1 )) 155self .assertEqual (info ["state" ],"soft" ) 156 157def test_staleness_rules (self ): 158p = self .make () 159self .assertEqual (presets .staleness (p ,identity ())["state" ],"fresh" ) 160self .assertEqual (presets .staleness (p ,identity (ram = 32 ))["state" ],"hard" ) 161self .assertEqual (presets .staleness (p ,identity (ram = 62 ))["state" ],"fresh" )# within 10% 162old = dict (p ,created_epoch = time .time ()- 100 * 86400 ) 163self .assertEqual (presets .staleness (old ,identity ())["state" ],"soft" ) 164 165def test_per_request_defaults_reach_the_sampling_block (self ): 166res = copy .deepcopy (RESULT ) 167res ["settings" ]["per_request" ]= {"spec_min_p" :0.7 } 168self .make (result = res ) 169out ,info = presets .overlay (CFG ,now = identity ()) 170self .assertEqual (out ["sampling" ]["strata_tune" ], {"spec_min_p" :0.7 }) 171 172def test_a_broken_store_never_breaks_a_start (self ): 173self .make () 174for f in Path (os .environ ["STRATA_PRESET_DIR" ]).glob ("*.json" ): 175f .write_text ("{not json" ) 176out ,info = presets .overlay (CFG ,now = identity ()) 177self .assertEqual (out ,CFG ) 178self .assertFalse (info ["applied" ]) 179 180def test_export_import_roundtrip (self ): 181p = self .make (name = "Shared" ) 182data = presets .export_preset (p ["id" ]) 183presets .delete (p ["id" ]) 184q = presets .import_preset (data ) 185self .assertEqual (q ["settings" ],p ["settings" ]) 186self .assertNotEqual (q ["id" ],p ["id" ]) 187data ["settings" ]["args" ]= {"--spec" :6 } 188with self .assertRaises (presets .PresetError ): 189presets .import_preset (data ) 190data ["settings" ]["args" ]= {"--spec" :5 }# #3844: only outside the tuner's range: kept 191self .assertEqual (presets .import_preset (data )["settings" ]["args" ], {"--spec" :5 }) 192 193def test_recheck_keep_refreshes_the_identity (self ): 194p = self .make () 195out = presets .record_recheck (p ["id" ], {"verdict" :"keep" ,"identity" :identity (driver = "620.1" ), 196"measured" : {"decode_tok_s" :70.0 }}) 197self .assertEqual (presets .staleness (out ,identity (driver = "620.1" ))["state" ],"fresh" ) 198self .assertEqual (out ["measured" ]["decode_tok_s" ],70.0 )# better by more than 3%: stored 199self .assertIsNotNone (out ["recheck" ]["last_ok" ]) 200 201def test_trial_history_blocks_a_candidate_that_did_not_start (self ): 202presets .record_trials ([{"label" :"host_core_last" ,"args" : ["--x" ],"env" : {},"status" :"OOM" ,"at" :1 }], 203hw_hash = "h" ,model_digest = "m" ,engine_sha = "e" ) 204self .assertEqual (presets .bad_signatures (hw_hash = "h" ,model_digest = "m" ,engine_sha = "e" ), {"host_core_last" }) 205self .assertEqual (presets .bad_signatures (hw_hash = "h2" ,model_digest = "m" ,engine_sha = "e" ),set ()) 206self .assertEqual (presets .bad_signatures (hw_hash = "h" ,model_digest = "m" ,engine_sha = "e2" ),set ()) 207 208def test_a_command_that_passed_is_not_switched_off_by_a_later_failure (self ): 209# #3502: the plain base command passed four times, then a busy card wrote OOM rows 210for status in ("PASS" ,"OOM" ): 211presets .record_trials ([{"label" :"base" ,"args" : ["--x" ],"env" : {},"status" :status ,"at" :1 }], 212hw_hash = "h" ,model_digest = "m" ,engine_sha = "e" ) 213self .assertEqual (presets .bad_signatures (hw_hash = "h" ,model_digest = "m" ,engine_sha = "e" ),set ()) 214 215 216if __name__ == "__main__" : 217unittest .main ()