okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
049ae1c67
main
1"""Round 0213 TUICFG, step 6: tuning stays available (#5056 STRATA_API_KEY, #5122 RAM guard, #5078 engine abort shown as a 503). 2Doubles only: a stub session, a tiny HTTP worker, a recorded spawn.""" 3from __future__import annotations 4 5import json 6import os 7import tempfile 8import threading 9import unittest 10from http .server import BaseHTTPRequestHandler ,HTTPServer 11from pathlib import Path 12from unittest import mock 13 14from strata_control import autotune ,tune_session 15from strata_control .tune_session import StartFailed ,WorkerEngine ,WorkerSession ,native_failure 16from tests .tuning .stub_session import FakeClock ,StubSession ,flag 17from tests .tuning .test_autotune import BASE ,make_ctx ,speed_with 18 19 20class WorkerKey (unittest .TestCase ): 21"""#5056: the worker must answer to the key the tuner made, whatever STRATA_API_KEY says.""" 22 23def spawned (self ,env ): 24seen = {} 25 26def popen (argv ,name ,** kw ): 27seen ["env" ],seen ["argv" ]= dict (kw ["env" ]),argv 28raise OSError ("not started in this test" ) 29with tempfile .TemporaryDirectory ()as tmp ,mock .patch .dict (os .environ ,env ,clear = False ), \ 30mock .patch ("serve.lifeline.popen" ,popen ),mock .patch .object (tune_session .tune_machine ,"gpu_used_mib" ,return_value = None ): 31if "STRATA_API_KEY" not in env : 32os .environ .pop ("STRATA_API_KEY" ,None ) 33s = WorkerSession (base_config = {"args" : [],"api_key" :"from-the-preset" },serve_dir = tmp ,workdir = tmp ) 34with self .assertRaises (StartFailed ): 35with s .engine ([], {}): 36pass 37cfg = json .loads ((Path (tmp )/ "run-1.json" ).read_text ()) 38return seen ,cfg 39 40def test_the_variable_is_not_passed_to_the_worker_and_the_config_key_is_the_tuners_own (self ): 41for env in ({"STRATA_API_KEY" :"client-shared-key" }, {"STRATA_API_KEY" :"" }, {}): 42with self .subTest (env = env ): 43seen ,cfg = self .spawned (env ) 44self .assertNotIn ("STRATA_API_KEY" ,seen ["env" ]) 45self .assertEqual (len (cfg ["api_key" ]),32 ) 46self .assertNotEqual (cfg ["api_key" ],"from-the-preset" ) 47self .assertNotIn (cfg ["api_key" ]," " .join (seen ["argv" ]),"the key is not on the command line" ) 48 49 50class FailingWorker (BaseHTTPRequestHandler ): 51def log_message (self ,* a ):# noqa: ANN002 52pass 53 54def do_GET (self ):# noqa: N802 55body = json .dumps ({"data" : [{"id" :"m" }]}).encode () 56self .send_response (200 ) 57self .send_header ("content-length" ,str (len (body ))) 58self .end_headers () 59self .wfile .write (body ) 60 61def do_POST (self ):# noqa: N802 62self .rfile .read (int (self .headers ["content-length" ])) 63body = json .dumps ({"error" : {"message" :"the engine stopped unexpectedly (exit code -6); the next request restarts it" }}).encode () 64self .send_response (503 ) 65self .send_header ("content-length" ,str (len (body ))) 66self .end_headers () 67self .wfile .write (body ) 68 69 70class FakeProc : 71pid = 0 72 73def poll (self ): 74return None 75 76 77class EngineAbort (unittest .TestCase ): 78"""#5078: a generic 503 from the worker must carry the engine's own last error line, and a memory failure is an OOM.""" 79 80def engine (self ,log_text ): 81srv = HTTPServer (("127.0.0.1" ,0 ),FailingWorker ) 82threading .Thread (target = srv .serve_forever ,daemon = True ).start () 83self .addCleanup (srv .shutdown ) 84tmp = tempfile .TemporaryDirectory () 85self .addCleanup (tmp .cleanup ) 86log = Path (tmp .name )/ "engine.log" 87log .write_text (log_text ) 88session = WorkerSession (base_config = {"args" : []},serve_dir = "." ,workdir = tmp .name ) 89return WorkerEngine (session ,FakeProc (),srv .server_address [1 ],"k" , [log ],1.0 ,None ,lambda x :None ) 90 91def test_a_cuda_oom_in_prefill_is_reported_as_an_oom_with_the_native_line (self ): 92eng = self .engine ("strata serve: 687 MiB of VRAM free with everything loaded\n" 93"ggml-cuda (strata mmq): out of memory: cudaMalloc(&p, size)\n in alloc at ggml_cuda_host.cu:127\n" ) 94with self .assertRaises (StartFailed )as cm : 95eng .chat ("hello" ,8 ) 96self .assertEqual (cm .exception .status ,"OOM" ) 97self .assertIn ("the worker refused the request (503)" ,cm .exception .reason ) 98self .assertIn ("out of memory: cudaMalloc" ,cm .exception .reason ) 99 100def test_another_abort_keeps_its_line_and_is_not_an_oom (self ): 101eng = self .engine ("loading\nterminate called after throwing an instance of 'std::runtime_error'\n" ) 102with self .assertRaises (StartFailed )as cm : 103eng .chat ("hello" ,8 ) 104self .assertEqual (cm .exception .status ,"NO_TOKENS" ) 105self .assertIn ("terminate called" ,cm .exception .reason ) 106 107def test_a_quiet_log_keeps_the_old_message (self ): 108eng = self .engine ("loading\nready\n" ) 109with self .assertRaises (StartFailed )as cm : 110eng .chat ("hello" ,8 ) 111self .assertEqual ((cm .exception .status ,"engine:" in cm .exception .reason ), ("NO_TOKENS" ,False )) 112 113def test_the_memory_guards_information_line_is_not_an_error (self ): 114self .assertEqual (native_failure ("memory guard: limit 20 GiB, available 30 GiB\nready\n" ),"" ) 115 116def test_a_crashing_candidate_is_failed_alone_and_the_baseline_is_kept (self ): 117def fail (args ,env ): 118if flag (args ,"--kv-resident" )== "65536" : 119return StartFailed ("NO_TOKENS" ,"the worker refused the request (503) | engine: terminate called" ) 120return None 121clock = FakeClock () 122session = StubSession (model = speed_with ({("--kv-resident" ,"65536" ):1.10 }),clock = clock ,fail = fail ) 123t = autotune .Tuner (session ,BASE , {},make_ctx (),autotune .Options (),clock = clock ,sleep = clock .sleep ,system = session .system , 124total_ram_mib = 64000 ,total_vram_mib = 12000 ,quiet = lambda :None ) 125r = t .run () 126failed = [a for a in r .arms if a ["status" ]== "failed" ] 127self .assertTrue (failed and "terminate called" in failed [0 ]["reason" ]) 128self .assertNotEqual (r .outcome ,"base_failed" ) 129self .assertNotIn ("--kv-resident" ,r .settings ["args" ],"the crashed candidate is never applied" ) 130self .assertIn (r .outcome , ("default_confirmed" ,"inconclusive" ),"the tune ends with a result, not as a failure" ) 131 132def test_a_base_that_aborts_names_the_native_failure (self ): 133def fail (args ,env ): 134return StartFailed ("OOM" ,"the worker refused the request (503): b'..' | engine: ggml-cuda: out of memory: cudaMalloc" ) 135clock = FakeClock () 136session = StubSession (model = speed_with ({}),clock = clock ,fail = fail ) 137t = autotune .Tuner (session ,BASE , {},make_ctx (),autotune .Options (),clock = clock ,sleep = clock .sleep ,system = session .system , 138total_ram_mib = 64000 ,total_vram_mib = 12000 ,quiet = lambda :None ) 139r = t .run () 140self .assertEqual (r .outcome ,"base_failed" ) 141self .assertIn ("cudaMalloc" ,r .message ) 142 143 144class RamGuard (unittest .TestCase ): 145"""#5122: the restart candidate needs what the base run had, not the base's peak RSS plus the floor.""" 146 147def tuner (self ,free_before ,free_after ,rss = 23429.0 ,wait_ram_s = 30 ,big_card = False ,gain = 1.10 ): 148clock = FakeClock () 149session = StubSession (model = speed_with ({("--kv-resident" ,"65536" ):gain }),clock = clock ,avail = free_before ,rss = lambda a ,e :rss ) 150real = session .system 151 152def system (): 153out = real () 154out ["memory" ]["available_mib" ]= free_before if not session .runs else free_after 155return out 156ctx = make_ctx () 157if big_card :# a 24 GB card also plans the 32K prompt chunk, which asks for 4 GiB more RAM than the base 158ctx .vram_mib = 24000 159t = autotune .Tuner (session ,BASE , {},ctx ,autotune .Options (wait_ram_s = wait_ram_s ,per_request = False ),clock = clock ,sleep = clock .sleep , 160system = system ,total_ram_mib = 32000 ,quiet = lambda :None ) 161return t ,session 162 163def test_a_candidate_that_adds_nothing_is_tried_when_the_base_started_with_the_same_free_memory (self ): 164t ,session = self .tuner (free_before = 23654 ,free_after = 24680 )# 23.1 GiB at the base start, 24.1 GiB free later (the report) 165r = t .run () 166self .assertTrue (any (flag (a ,"--kv-resident" )== "65536" for a ,_ in session .runs ),"the 64K resident-KV candidate (no extra RAM) was started" ) 167self .assertFalse ([a for a in r .arms if a ["status" ]== "skipped" ],r .arms ) 168 169def test_less_free_memory_than_the_base_had_is_still_skipped (self ): 170t ,session = self .tuner (free_before = 23654 ,free_after = 18000 ) 171r = t .run () 172self .assertFalse (any (flag (a ,"--kv-resident" )== "65536" for a ,_ in session .runs )) 173self .assertTrue (any (a ["status" ]== "skipped" and "memory" in a ["reason" ]for a in r .arms )) 174 175def test_a_candidate_that_needs_more_than_the_base_asks_for_the_difference (self ): 176t ,_ = self .tuner (free_before = 23654 ,free_after = 24680 ) 177t .base_runs .append (tune_session .RunResult (status = "PASS" ,rss_peak_mib = 23429.0 )) 178t ._base_start_avail = 23654.0 179t .system = lambda : {"memory" : {"available_mib" :24680 ,"total_mib" :32000 }} 180self .assertIsNone (t ._ram_guard (0 ,"x" ,wait_s = 0 )) 181self .assertIn ("not enough free memory" ,t ._ram_guard (4096 ,"x" ,wait_s = 0 )or "" )# 23.1 + 4 GiB needed, 24.1 free 182 183def test_skipped_for_memory_is_said_instead_of_already_the_fastest (self ): 184"""Owner 11-04: 'N settings could not be tried: not enough free memory', only when some were skipped for memory, in place of 'already the fastest'.""" 185t ,session = self .tuner (free_before = 23654 ,free_after = 24680 ,big_card = True ,gain = 1.0 ) 186r = t .run () 187self .assertEqual ([(a ["id" ],a ["status" ])for a in r .arms if a ["status" ]== "skipped" ], [("prefill_32k" ,"skipped" )],r .arms ) 188self .assertEqual (r .outcome ,"default_confirmed" ) 189self .assertEqual (r .not_tried ,1 ) 190self .assertEqual (r .message ,"1 setting could not be tried: not enough free memory" ) 191self .assertNotIn ("fastest" ,r .message ) 192self .assertEqual (r .values ["not_tried" ],1 ) 193from strata_cli .launch .runner import tune_words 194word ,sentence = tune_words (r .to_dict ()) 195self .assertEqual (sentence ,"1 setting could not be tried: not enough free memory" ) 196self .assertNotEqual (word ,"already fastest" ) 197 198def test_the_plural (self ): 199from strata_cli .launch .runner import tune_words 200self .assertEqual (tune_words ({"outcome" :"default_confirmed" ,"not_tried" :2 })[1 ],"2 settings could not be tried: not enough free memory" ) 201 202def test_nothing_skipped_keeps_the_old_sentences (self ): 203t ,session = self .tuner (free_before = 23654 ,free_after = 24680 ,gain = 1.0 ) 204r = t .run () 205self .assertEqual (r .not_tried ,0 ) 206self .assertEqual (r .message ,"Your current settings are already the fastest we found. Nothing was changed." ) 207from strata_cli .launch .runner import tune_words 208self .assertEqual (tune_words (r .to_dict ())[0 ],"already fastest" ) 209 210def test_the_old_rule_still_holds_when_the_base_had_plenty (self ): 211t ,session = self .tuner (free_before = 40000 ,free_after = 9000 ) 212t .run () 213self .assertEqual (len (session .runs ),1 ,"only the base was started" ) 214 215 216if __name__ == "__main__" : 217unittest .main ()