okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
747642c2c
main
1"""A GPU picture reader whose start failed in its CUDA context ("CUDA error: out of memory ... in function ggml_cuda_init") on a Linux Arm machine with shared 2CPU / GPU memory (DGX Spark) is started again before the CPU reader takes over: a new spawn may start only while less than 18 s have passed since the first one 3started, and at most 12 times. Every other failure goes the way it went. 4 5python -m serve.test_vision_ctx_retry 6""" 7import tempfile 8import threading 9import time 10import unittest 11from pathlib import Path 12from unittest import mock 13 14import serve .server as server 15from strata_control import vision_reader as VR 16 17CTX = ("CUDA error: out of memory\n current device: 0, in function ggml_cuda_init at ggml/src/ggml-cuda/ggml-cuda.cu:367\n" 18"ggml/src/ggml-cuda/ggml-cuda.cu:108: CUDA error\n" ) 19ALLOC = "ggml_backend_cuda_buffer_type_alloc_buffer: allocating 865.48 MiB on device 0: cudaMalloc failed: out of memory\n" 20DIED = "the vision encoder did not start (killed by signal 6)" 21 22 23def rule (text = CTX ,retries_done = 0 ,next_start_s = 0.0 ,** kw ): 24args = dict (linux = True ,arm = True ,hip = False ) 25args .update (kw ) 26return VR .retry_gpu_start (text = text ,retries_done = retries_done ,next_start_s = next_start_s ,** args ) 27 28 29class Rule (unittest .TestCase ): 30def test_the_constants (self ): 31self .assertEqual ((VR .CONTEXT_RETRIES ,VR .CONTEXT_RETRY_WAIT_S ,VR .CONTEXT_RETRY_BUDGET_S ), (12 ,1.0 ,18.0 )) 32 33def test_the_count_cap_ends_it (self ): 34for done in range (12 ): 35self .assertTrue (rule (retries_done = done )) 36self .assertFalse (rule (retries_done = 12 )) 37self .assertFalse (rule (retries_done = 20 )) 38 39def test_the_time_bound_is_the_start_of_the_next_spawn (self ): 40self .assertTrue (rule (next_start_s = 0.0 )) 41self .assertTrue (rule (next_start_s = 17.9 )) 42self .assertFalse (rule (next_start_s = 18.0 )) 43self .assertFalse (rule (next_start_s = 40.0 )) 44 45def test_the_own_tower_wording_counts_too (self ): 46self .assertTrue (rule ("strata-vision: Strata's picture reader did not start (cannot use GPU 0: out of memory)" )) 47 48def test_other_platforms_never_retry (self ): 49self .assertFalse (rule (linux = False ))# Windows, Mac 50self .assertFalse (rule (arm = False ))# a PC with a card of its own 51self .assertFalse (rule (hip = True ))# the AMD reader 52 53def test_other_errors_never_retry (self ): 54for text in (ALLOC ,# a card another program filled: no retry helps (reader_room reports it) 55CTX + ALLOC , 56"failed to allocate CUDA0 buffer of size 1048576 out of memory" , 57"CUDA error: device kernel image is invalid\n in function ggml_cuda_init" , 58"CUDA error: CUDA-capable device(s) is/are busy or unavailable\n in function ggml_cuda_init" , 59"ggml_cuda_init: failed to initialize CUDA: no CUDA-capable device is detected" , 60"the vision encoder did not start: it said nothing for 300 s" , 61"out of memory" ):# no sign of the context 62with self .subTest (text = text [:50 ]): 63self .assertFalse (rule (text )) 64 65 66def make_vision (args = ("/engine/strata-vision" ,"--gpu" ),log_text = "" ): 67f = tempfile .NamedTemporaryFile ("w+" ,suffix = ".log" ,delete = False ) 68f .write (log_text ) 69f .flush () 70v = server .Vision .__new__ (server .Vision ) 71v .spawn = (list (args ),f ,None ) 72return v ,f 73 74 75class Clock : 76"""A fake monotonic clock: `sleep` and every spawn (`attempt_s` long) move it. It belongs to the thread that made it (the test's): `server.time` is the 77process-wide `time` module, so while it is patched any other thread of the pytest process that sleeps or reads the clock (on Windows a watcher or job thread 78that an earlier test left running) would call these. Those threads get the real `time.sleep` / `time.monotonic` and are neither counted nor allowed to move the clock. 79Make it before patching, so the real functions it keeps are the unpatched ones.""" 80 81def __init__ (self ): 82self .now = 0.0 83self .sleeps = [] 84self .owner = threading .get_ident () 85self ._real_sleep ,self ._real_monotonic = time .sleep ,time .monotonic 86 87def monotonic (self ): 88return self .now if threading .get_ident ()== self .owner else self ._real_monotonic () 89 90def sleep (self ,s ): 91if threading .get_ident ()!= self .owner : 92return self ._real_sleep (s ) 93self .sleeps .append (s ) 94self .now += s 95 96 97class Spawn (unittest .TestCase ): 98def run_start (self ,outcomes ,args = ("/engine/strata-vision" ,"--gpu" ),system = "linux" ,machine = "aarch64" ,logged = CTX ,attempt_s = 1.4 ,hook = None ): 99"""_start_gpu_reader with `_start_reader` giving `outcomes` in turn (the last one repeats; an exception is raised, anything else returned) and taking `attempt_s` 100on a fake clock; returns (clock, calls, result or error).""" 101v ,f = make_vision (args ) 102self .addCleanup (lambda : (f .close (),Path (f .name ).unlink ())) 103clock ,calls = Clock (), [] 104 105def start_reader (): 106calls .append (clock .now )# when this spawn started 107if hook is not None : 108hook () 109clock .now += attempt_s 110o = outcomes [min (len (calls )- 1 ,len (outcomes )- 1 )] 111if isinstance (o ,Exception ): 112f .write (logged ) 113f .flush () 114raise o 115return o 116 117v ._start_reader = start_reader 118with mock .patch .object (server .sys ,"platform" ,system ),mock .patch .object (server .platform ,"machine" ,return_value = machine ), \ 119mock .patch .object (server .time ,"sleep" ,clock .sleep ),mock .patch .object (server .time ,"monotonic" ,clock .monotonic ): 120try : 121res = v ._start_gpu_reader () 122except RuntimeError as e : 123res = e 124return clock ,calls ,res 125 126def test_a_start_that_works_the_first_time_is_not_delayed (self ): 127clock ,calls ,res = self .run_start ([None ]) 128self .assertEqual ((len (calls ),clock .sleeps ), (1 , [])) 129 130def test_a_success_ends_it_at_once (self ): 131clock ,calls ,res = self .run_start ([RuntimeError (DIED )]* 3 + [None ])# the measured case: 3 failures, the 4th spawn works 132self .assertEqual ((len (calls ),clock .sleeps ,res ), (4 , [1.0 ,1.0 ,1.0 ],None )) 133for got ,want in zip (calls , [0.0 ,2.4 ,4.8 ,7.2 ]): 134self .assertAlmostEqual (got ,want ) 135 136def test_the_five_measured_failures_are_covered (self ): 137clock ,calls ,res = self .run_start ([RuntimeError (DIED )]* 5 + [None ]) 138self .assertEqual ((len (calls ),res ), (6 ,None )) 139self .assertLess (calls [- 1 ],18.0 ) 140 141def test_a_context_that_never_works_ends_by_the_time_bound_and_raises_as_before (self ): 142err = RuntimeError (DIED ) 143clock ,calls ,res = self .run_start ([err ]) 144self .assertIs (res ,err ) 145self .assertEqual (len (calls ),8 )# spawns start at 0, 2.4, ... 16.8 s; the next would start at 19.2 s 146self .assertLess (calls [- 1 ],18.0 ) 147self .assertLess (clock .now ,20.0 )# the worst wait before the CPU reader takes over 148 149def test_fast_attempts_end_by_the_count_cap (self ): 150err = RuntimeError (DIED ) 151clock ,calls ,res = self .run_start ([err ],attempt_s = 0.1 ) 152self .assertIs (res ,err ) 153self .assertEqual ((len (calls ),len (clock .sleeps )), (13 ,12 ))# 1 spawn + 12 retries, 13.3 s: the cap, not the clock 154self .assertLess (clock .now ,18.0 ) 155 156def test_another_thread_that_sleeps_meanwhile_is_not_counted_and_does_not_move_the_clock (self ): 157"""`server.time` is the process-wide module: a thread of another part of the process that sleeps while the test has it patched (a winjob / watcher thread left 158by an earlier test on Windows counted 232,838 sleeps) must get the real sleep. Here a thread sleeps in a loop and every spawn waits until it has slept once more.""" 159stop ,slept = threading .Event (),threading .Event () 160 161def other (): 162while not stop .is_set (): 163time .sleep (0.0002 )# the fake one when it is patched, and it must not count 164slept .set () 165 166def hook (): 167slept .clear () 168slept .wait (2 ) 169 170t = threading .Thread (target = other ,daemon = True ) 171t .start () 172try : 173clock ,calls ,res = self .run_start ([RuntimeError (DIED )],attempt_s = 0.1 ,hook = hook ) 174finally : 175stop .set () 176t .join (2 ) 177self .assertEqual ((len (calls ),len (clock .sleeps )), (13 ,12 )) 178self .assertAlmostEqual (clock .now ,13 * 0.1 + 12 * 1.0 )# only this thread's pauses and spawns moved it 179 180def test_a_spawn_that_would_start_at_17_9_s_is_allowed_and_one_at_18_0_s_is_not (self ): 181clock ,calls ,res = self .run_start ([RuntimeError (DIED ),None ],attempt_s = 16.9 )# fails at 16.9, next starts at 17.9 182self .assertEqual ((len (calls ),res ), (2 ,None )) 183self .assertAlmostEqual (calls [1 ],17.9 ) 184clock ,calls ,res = self .run_start ([RuntimeError (DIED ),None ],attempt_s = 17.0 )# fails at 17.0, next would start at 18.0 185self .assertEqual (len (calls ),1 ) 186self .assertIsInstance (res ,RuntimeError ) 187 188def test_the_diagnostic_line_only_with_STRATA_VIT_PROF_and_only_after_a_retry (self ): 189for env ,outcomes ,expect in (({"STRATA_VIT_PROF" :"1" }, [RuntimeError (DIED )]* 3 + [None ], ["vit-prof: GPU reader started after 3 retries, 8.60 s" ]), 190 ({"STRATA_VIT_PROF" :"1" }, [None ], []), 191 ({}, [RuntimeError (DIED )]* 3 + [None ], []), 192 ({"STRATA_VIT_PROF" :"1" }, [RuntimeError (DIED )], ["vit-prof: GPU reader did not start after 7 retries, 18.20 s" ])): 193with self .subTest (env = env ,n = len (outcomes )),mock .patch .dict (server .os .environ ,env ),mock .patch ("builtins.print" )as pr : 194server .os .environ .pop ("STRATA_VIT_PROF" ,None )if not env else None 195self .run_start (outcomes ) 196# (print is patched for the whole process: only this module's diagnostic lines count, whatever another thread prints meanwhile) 197self .assertEqual ([c .args [0 ]for c in pr .call_args_list if c .args and str (c .args [0 ]).startswith ("vit-prof" )],expect ) 198 199def test_no_room_is_not_retried (self ): 200err = server .VisionNoRoom ("the vision encoder did not start: the graphics card has no room for it" ,None ) 201clock ,calls ,res = self .run_start ([err ],logged = ALLOC ) 202self .assertEqual ((len (calls ),clock .sleeps ), (1 , [])) 203self .assertIs (res ,err ) 204 205def test_a_failure_that_is_not_the_context_is_not_retried (self ): 206err = RuntimeError ("the vision encoder did not start: ERR cannot open the model" ) 207clock ,calls ,res = self .run_start ([err ],logged = "ERR cannot open the model\n" ) 208self .assertEqual ((len (calls ),clock .sleeps ), (1 , [])) 209 210def test_other_systems_are_not_retried (self ): 211err = RuntimeError ("the vision encoder did not start" ) 212for kw in ({"system" :"win32" }, {"system" :"darwin" }, {"machine" :"x86_64" }, {"machine" :"AMD64" }, 213 {"args" : ("/engine/strata-vision-hip" ,"--gpu" )}): 214with self .subTest (kw = kw ): 215clock ,calls ,res = self .run_start ([err ],** kw ) 216self .assertEqual ((len (calls ),clock .sleeps ), (1 , [])) 217 218def test_an_old_failure_in_a_shared_log_does_not_count (self ): 219v ,f = make_vision (log_text = CTX )# an earlier start's lines are in the file already 220self .addCleanup (lambda : (f .close (),Path (f .name ).unlink ())) 221v ._start_reader = mock .Mock (side_effect = RuntimeError ("the vision encoder did not start: ERR cannot open the model" )) 222clock = Clock () 223with mock .patch .object (server .sys ,"platform" ,"linux" ),mock .patch .object (server .platform ,"machine" ,return_value = "aarch64" ), \ 224mock .patch .object (server .time ,"sleep" ,clock .sleep ),mock .patch .object (server .time ,"monotonic" ,clock .monotonic ): 225with self .assertRaises (RuntimeError ): 226v ._start_gpu_reader () 227self .assertEqual (v ._start_reader .call_count ,1 ) 228self .assertEqual (clock .sleeps , [])# no retry: this thread never slept 229 230def test_start_falls_back_to_the_cpu_reader_after_the_last_retry (self ): 231v ,f = make_vision () 232self .addCleanup (lambda : (f .close (),Path (f .name ).unlink ())) 233v .fallback = (["/engine/strata-vision" ],f ,None ) 234v .on_cpu ,v .elastic = False ,False 235starts = [] 236clock = Clock () 237 238def start_reader (): 239starts .append (v .on_cpu ) 240if not v .on_cpu : 241f .write (CTX ) 242f .flush () 243raise RuntimeError (DIED ) 244 245v ._start_reader = start_reader 246v .not_started_note = lambda :"note" 247with mock .patch .object (server .sys ,"platform" ,"linux" ),mock .patch .object (server .platform ,"machine" ,return_value = "aarch64" ), \ 248mock .patch .object (server .time ,"sleep" ,clock .sleep ),mock .patch .object (server .time ,"monotonic" ,clock .monotonic ),mock .patch ("builtins.print" ): 249v ._start () 250self .assertEqual (starts , [False ]* 13 + [True ])# fast attempts (the clock moves only by the pauses): the count cap 251self .assertTrue (v .on_cpu ) 252 253 254if __name__ == "__main__" : 255unittest .main ()