okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0c165b48b
main
1"""A saved tuning is applied at every start: after an app restart (a new process), after an unload and a load, and it can be seen 2(`presets effective`, `presets status`) and switched off and on again.""" 3 4from __future__import annotations 5 6import json 7import os 8import subprocess 9import sys 10import tempfile 11import unittest 12from pathlib import Path 13 14ROOT = Path (__file__ ).resolve ().parents [2 ] 15 16 17def cli (env ,* args ): 18out = subprocess .run ([sys .executable ,str (ROOT / "strata.py" ),* args ,"--output" ,"json" ],capture_output = True ,text = True , 19env = env ,cwd = str (ROOT ),timeout = 120 ) 20return json .loads (out .stdout [out .stdout .index ("{" ):]),out 21 22 23def fresh_process (env ,code ): 24"""A new Python process: what an app restart or a new server start is.""" 25r = subprocess .run ([sys .executable ,"-c" ,code ],capture_output = True ,text = True ,env = env ,cwd = str (ROOT ),timeout = 120 ) 26assert r .returncode == 0 ,r .stderr 27return json .loads (r .stdout .strip ().splitlines ()[- 1 ]) 28 29 30class PersistenceTest (unittest .TestCase ): 31def setUp (self ): 32self .tmp = tempfile .TemporaryDirectory () 33self .addCleanup (self .tmp .cleanup ) 34t = Path (self .tmp .name ) 35 (t / "model.gguf" ).write_bytes (b"gguf" * 1000 ) 36 (t / "engine.exe" ).write_bytes (b"x" ) 37 (t / "tok" ).mkdir () 38self .cfg_path = t / "strata-model.json" 39self .cfg = {"exe" :str (t / "engine.exe" ),"tokenizer" :str (t / "tok" ),"model_name" :"iq3_s-test" ,"ui_resource_profile" :"work" , 40"args" : ["--native" ,str (t / "model.gguf" ),"--expert-cache" ,"auto" ,"--spec" ,"4" ,"--max-context" ,"65536" , 41"--kv" ,"int8" ,"--kv-resident" ,"32768" ]} 42self .cfg_path .write_text (json .dumps (self .cfg )) 43self .env = dict (os .environ ,STRATA_PRESET_DIR = str (t / "presets" ),PYTHONPATH = str (ROOT ),STRATA_NO_PRESET = "" ) 44self .env .pop ("STRATA_NO_PRESET" ) 45# the tune's result, saved as a preset by the library, the way `strata tune auto` does 46sys .path .insert (0 ,str (ROOT )) 47os .environ ["STRATA_PRESET_DIR" ]= str (t / "presets" ) 48self .addCleanup (lambda :os .environ .pop ("STRATA_PRESET_DIR" ,None )) 49from strata_control import presets 50self .presets = presets 51ident = presets .current_identity (self .cfg ,exe = self .cfg ["exe" ]) 52result = {"outcome" :"improved" ,"seconds" :900 ,"settings" : {"args" : {"--kv-resident" :65536 },"env" : {},"per_request" : {}}, 53"answers" : {"class" :"exact" ,"fields" : []},"base" : {"decode_tok_s" :60.0 },"chosen" : {"decode_tok_s" :64.0 }, 54"gain_pct" :6.6 ,"pairs" :2 ,"faster_pairs" :2 ,"noise" : {}} 55self .preset = presets .create (result ,choices = presets .choices_from_config (self .cfg ),identity = ident ,name = "IQ3_S 64K – Work" ) 56 57CODE = ("import json,sys;sys.path.insert(0,'.');from serve import server;" 58"c=json.load(open(%r));out=server.apply_saved_tuning(c,say=lambda l:None);" 59"print(json.dumps(out['args']))" ) 60 61def args_at_start (self ): 62return fresh_process (self .env ,self .CODE % str (self .cfg_path )) 63 64def test_applied_after_restart_and_after_unload_and_load (self ): 65for _ in range (3 ):# three starts = a restart, an unload, a load: every one is a new server process 66args = self .args_at_start () 67self .assertEqual (args [args .index ("--kv-resident" )+ 1 ],"65536" ) 68self .assertEqual (args [args .index ("--spec" )+ 1 ],"4" )# the user's own flags are untouched 69self .assertEqual (json .loads (self .cfg_path .read_text ())["args" ],self .cfg ["args" ])# the saved run config itself never changes 70 71def test_a_tune_worker_measures_the_configuration_as_given (self ): 72env = dict (self .env ,STRATA_NO_PRESET = "1" ) 73args = fresh_process (env ,self .CODE % str (self .cfg_path )) 74self .assertEqual (args [args .index ("--kv-resident" )+ 1 ],"32768" ) 75 76def test_expert_mode_can_read_what_will_run (self ): 77out ,_ = cli (self .env ,"presets" ,"effective" ,str (self .cfg_path )) 78self .assertTrue (out ["applied" ]) 79self .assertEqual (out ["preset" ]["name" ],"IQ3_S 64K – Work" ) 80self .assertEqual (out ["changed" ], [{"flag" :"--kv-resident" ,"was" :"32768" ,"now" :"65536" }]) 81self .assertEqual (out ["args" ][out ["args" ].index ("--kv-resident" )+ 1 ],"65536" ) 82 83def test_which_tuning_is_in_use_and_switching_it_off_and_on (self ): 84st ,_ = cli (self .env ,"presets" ,"status" ,str (self .cfg_path )) 85self .assertEqual (st ["active" ]["name" ],"IQ3_S 64K – Work" ) 86self .assertFalse (st ["switched_off" ]) 87off ,_ = cli (self .env ,"presets" ,"off" ,str (self .cfg_path )) 88self .assertIsNone (off ["active" ]) 89args = self .args_at_start () 90self .assertEqual (args [args .index ("--kv-resident" )+ 1 ],"32768" )# back to the standard settings 91eff ,_ = cli (self .env ,"presets" ,"effective" ,str (self .cfg_path )) 92self .assertFalse (eff ["applied" ]) 93st ,_ = cli (self .env ,"presets" ,"status" ,str (self .cfg_path )) 94self .assertIsNone (st ["active" ]) 95self .assertTrue (st ["switched_off" ]) 96self .assertEqual (st ["last_active" ]["name" ],"IQ3_S 64K – Work" )# kept, and listed, so it can be switched on again 97on ,_ = cli (self .env ,"presets" ,"apply" ,st ["last_active" ]["id" ]) 98self .assertTrue (on ["ok" ]) 99args = self .args_at_start () 100self .assertEqual (args [args .index ("--kv-resident" )+ 1 ],"65536" ) 101 102def test_a_changed_gpu_is_not_applied_and_says_why (self ): 103p = self .presets .load (self .preset ["id" ]) 104p ["identity" ]["hardware" ]["hard" ]["gpus" ]= [{"name" :"Another GPU" ,"vram_mib" :1 }] 105self .presets ._write_json (self .presets ._path (p ["id" ]),p ) 106out ,_ = cli (self .env ,"presets" ,"effective" ,str (self .cfg_path )) 107self .assertFalse (out ["applied" ]) 108self .assertIn ("graphics card" ,out ["why_not" ]) 109 110 111class OutcomeCodesTest (unittest .TestCase ): 112def test_codes_and_values (self ): 113from strata_control import autotune 114mk = autotune .TuneResult 115r = mk (outcome = "improved" ,gain_pct = 7.2 ,seconds = 1200 ,waited_s = 120 ,pairs = 5 ,faster_pairs = 4 ) 116r .base ,r .chosen = {"decode_tok_s" :50.0 }, {"decode_tok_s" :53.6 } 117autotune .Tuner .finalize (r ) 118self .assertEqual (r .code ,"faster" ) 119self .assertEqual (r .values ["gain_pct" ],7.2 ) 120self .assertEqual (r .values ["minutes" ],18.0 ) 121for outcome ,reason ,code in (("default_confirmed" ,"" ,"already_fastest" ), ("inconclusive" ,"noisy" ,"busy_pc" ), 122 ("inconclusive" ,"drift" ,"busy_pc" ), ("inconclusive" ,"not_tried" ,"busy_pc" ), 123 ("base_failed" ,"start_failed" ,"failed" ), ("cancelled" ,"" ,"stopped" )): 124x = mk (outcome = outcome ,reason_code = reason ) 125autotune .Tuner .finalize (x ) 126self .assertEqual ((x .code ,x .reason_code ), (code ,reason ),outcome ) 127 128 129if __name__ == "__main__" : 130unittest .main ()