okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cded60248
main
1"""The elastic image encoder (the vision section's "elastic": true with "vram_elastic"): the first picture makes the 2expert cache keep the encoder's VRAM free and then starts it, later pictures use it as it is, an idle encoder stops and 3the cache takes its VRAM back, a POST /v1/vram reserve stacks on the encoder's share, and the engine's load never starts 4it on its own.""" 5import contextlib 6import io 7import tempfile 8import time 9import unittest 10from pathlib import Path 11from unittest import mock 12 13from serve .frontend import ChatTemplate 14from serve .server import ByteTokenizer ,EngineDied ,Service ,Vision 15from serve .test_vram import VramEngine 16 17ROOT = Path (__file__ ).resolve ().parents [1 ] 18IMAGE = {"type" :"image" ,"source" :"x.png" } 19 20 21class ElasticVision : 22"""An encoder process stand-in: starts, stops, and turns every picture into three image tokens.""" 23def __init__ (self ,d ,elastic = True ): 24self .elastic ,self .elastic_mib ,self .elastic_idle_s = elastic ,2048 ,60.0 25self .up ,self .starts ,self .unloads = False ,0 ,0 26self .dir = Path (d ) 27self .rows = self .dir / "img.sve" 28self .rows .write_bytes (b"rows" ) 29 30def alive (self ): 31return self .up 32 33def restart (self ): 34self .up ,self .starts = True ,self .starts + 1 35 36def unload (self ): 37self .up ,self .unloads = False ,self .unloads + 1 38 39def encode (self ,source ): 40assert self .up ,"a picture reached an encoder that was not started" 41return self .rows ,3 42 43 44class Elastic (unittest .TestCase ): 45def setUp (self ): 46d = tempfile .mkdtemp () 47self .tok = ByteTokenizer () 48self .engine = VramEngine (self .tok ) 49self .engine .loaded = True 50self .vision = ElasticVision (d ) 51self .svc = Service (self .engine ,self .tok ,ChatTemplate (ROOT / "serve/chat_template.jinja" ),vision = self .vision ) 52self .svc .free_vram_mib = lambda :None # (not this PC's card) 53self .addCleanup (self .drop_embeddings ) 54 55def drop_embeddings (self ): 56path = getattr (getattr (self .svc ,"embeddings" ,None ),"path" ,None ) 57if path is not None : 58path .unlink (missing_ok = True ) 59 60def picture (self ): 61self .svc .prepare ([{"role" :"user" ,"content" : [{"type" :"text" ,"text" :"what is it" },IMAGE ]}],None , {}) 62 63def test_the_first_picture_makes_room_then_starts_the_encoder (self ): 64self .picture () 65self .assertEqual (self .engine .calls , [2048 ])# the cache keeps the encoder's share free first 66self .assertEqual (self .vision .starts ,1 ) 67self .assertTrue (self .svc .vision_held ) 68self .picture ()# the next one uses the running encoder 69self .assertEqual (self .engine .calls , [2048 ]) 70self .assertEqual (self .vision .starts ,1 ) 71 72def test_an_idle_encoder_stops_and_the_cache_grows_back_whole (self ): 73self .picture () 74self .assertEqual (self .svc ._vision_idle_down (),"busy" )# a picture came just now 75self .svc .last_image_at = time .time ()- 61 76with self .svc .fifo :# a request holds the turn 77self .assertEqual (self .svc ._vision_idle_down (),"busy" ) 78self .assertEqual (self .svc ._vision_idle_down (),"down" ) 79self .assertFalse (self .vision .up ) 80self .assertFalse (self .svc .vision_held ) 81self .assertEqual (self .engine .calls , [2048 ,0 ])# 0, not None: the full size, not the start's reserve 82self .assertEqual (self .svc ._vision_idle_down (),"nothing" ) 83self .picture ()# and the next picture starts it again 84self .assertEqual (self .vision .starts ,2 ) 85self .assertEqual (self .engine .calls , [2048 ,0 ,2048 ]) 86 87def test_a_vram_reserve_stacks_on_the_encoders_share (self ): 88self .svc .vram (4000 ) 89self .picture () 90self .assertEqual (self .engine .calls , [4000 ,6048 ]) 91self .svc .vram (1000 )# asked while the encoder runs 92self .assertEqual (self .engine .calls [- 1 ],3048 ) 93self .svc .last_image_at = 0 94self .svc ._vision_idle_down () 95self .assertEqual (self .engine .calls [- 1 ],1000 )# back to the asked reserve, not to 0 96 97def test_an_engine_that_cannot_shrink_still_gets_its_encoder (self ): 98self .engine .elastic = False 99self .picture () 100self .assertEqual (self .vision .starts ,1 ) 101self .assertFalse (self .svc .vision_held ) 102self .svc .last_image_at = 0 103self .assertEqual (self .svc ._vision_idle_down (),"down" ) 104self .assertEqual (self .engine .calls , [2048 ])# the refused shrink only: nothing to give back 105 106def test_an_encoder_that_fails_to_start_is_a_503_not_a_dropped_connection (self ): 107def fail (): 108raise RuntimeError ("the vision encoder did not start: cudaMalloc failed: out of memory" ) 109self .vision .restart = fail 110with self .assertRaises (EngineDied )as e :# the handlers answer EngineDied with a 503 111self .picture () 112self .assertIn ("the image encoder failed to start" ,str (e .exception )) 113self .svc .last_image_at = 0 114self .assertEqual (self .svc ._vision_idle_down (),"down" ) 115self .assertEqual (self .engine .calls , [2048 ,0 ])# the share made for it goes back 116 117def test_the_stop_is_logged_when_the_cache_never_made_room (self ): 118self .engine .elastic = False # a layer split: the engine refuses --vram-elastic 119self .picture () 120self .svc .last_image_at = 0 121out = io .StringIO () 122with contextlib .redirect_stdout (out ): 123self .assertEqual (self .svc ._vision_idle_down (),"down" ) 124self .assertIn ("the image encoder stopped after 60 s without a picture" ,out .getvalue ()) 125self .assertNotIn ("expert cache" ,out .getvalue ()) 126 127def test_the_load_never_starts_an_elastic_encoder (self ): 128self .assertFalse (self .svc ._vision_down ()) 129self .svc .vision = ElasticVision (tempfile .mkdtemp (),elastic = False ) 130self .assertTrue (self .svc ._vision_down ())# a non-elastic encoder that is down is started again 131 132def test_an_unload_lets_go_of_the_share (self ): 133self .picture () 134self .assertEqual (self .svc .unload (),"unloaded" ) 135self .assertFalse (self .svc .vision_held ) 136self .assertFalse (self .vision .up ) 137 138def test_the_config_keys (self ): 139v = Vision ({"exe" :"e" ,"mmproj" :"m" ,"model" :"t" ,"elastic" :True ,"elastic_mib" :3000 , 140"elastic_idle_s" :30 },lazy = False )# elastic: nothing starts with the server 141self .assertTrue (v .elastic and v .elastic_mib == 3000 and v .elastic_idle_s == 30 and not v .alive ()) 142v = Vision ({"exe" :"e" ,"mmproj" :"m" ,"model" :"t" },lazy = True ) 143self .assertFalse (v .elastic ) 144self .assertEqual ((v .elastic_mib ,v .elastic_idle_s ), (2048 ,120.0 )) 145 146def test_the_ask_follows_the_image_limit (self ): 147"""Without the person's own elastic_mib the cache keeps the reader's need at its image limit free, never less than 2,048 MiB.""" 148base = {"exe" :"e" ,"mmproj" :"m" ,"model" :"t" ,"gpu" :True ,"elastic" :True } 149for limit ,ask in ((None ,2048 ), (1024 ,2048 ), (4096 ,2048 ), (16384 ,3674 ), (0 ,3674 )): 150cfg = dict (base )if limit is None else {** base ,"max_tokens" :limit } 151self .assertEqual (Vision (cfg ,lazy = True ).elastic_mib ,ask ,limit ) 152self .assertEqual (Vision ({** base ,"max_tokens" :16384 ,"elastic_mib" :2500 },lazy = True ).elastic_mib ,2500 ) 153self .assertEqual (Vision ({** base ,"max_tokens" :1024 ,"elastic_mib" :5000 },lazy = True ).elastic_mib ,5000 ) 154 155 156class OnDemandReader (unittest .TestCase ): 157"""The reader that starts with the first picture: no room on the card -> the CPU reader reads it, the cache grows back at once, 158and the next start tries the card again; pictures already encoded start nothing.""" 159 160def vision (self ,d ): 161v = Vision ({"exe" :"gpu-reader" ,"mmproj" :"m" ,"model" :"t" ,"gpu" :True ,"cpu_exe" :"cpu-reader" ,"elastic" :True },lazy = True ) 162v .started = [] 163 164def start_reader (): 165exe = v .spawn [0 ][0 ] 166v .started .append (exe ) 167if exe .endswith ("gpu-reader" )and v .gpu_fails : 168raise RuntimeError ("cudaMalloc failed: out of memory" ) 169v .proc = mock .Mock () 170v .proc .poll .return_value = None 171v .stopped = False 172v .gpu_fails = False 173v ._start_reader = start_reader 174v .close = lambda :None 175return v 176 177def service (self ,v ,elastic_engine = True ): 178tok = ByteTokenizer () 179engine = VramEngine (tok ,elastic = elastic_engine ) 180engine .loaded = True 181svc = Service (engine ,tok ,ChatTemplate (ROOT / "serve/chat_template.jinja" ),vision = v ) 182return svc ,engine 183 184def test_a_gpu_reader_that_does_not_start_is_the_cpu_reader_for_this_start_only (self ): 185v = self .vision (tempfile .mkdtemp ()) 186v .gpu_fails = True 187svc ,engine = self .service (v ) 188svc ._vision_up () 189self .assertEqual ([x .split ("-" )[0 ]for x in v .started ], ["gpu" ,"cpu" ]) 190self .assertTrue (v .on_cpu ) 191self .assertEqual (engine .calls , [2048 ,0 ])# the cache made room, then took it back: the CPU reader needs none 192self .assertFalse (svc .vision_held ) 193svc .last_image_at = 0 194self .assertEqual (svc ._vision_idle_down (),"down" )# the idle stop ends the CPU reader too ... 195self .assertEqual (engine .calls , [2048 ,0 ])# ... and has no VRAM to give back 196self .assertFalse (v .on_cpu )# the next start tries the card again 197v .gpu_fails = False 198svc ._vision_up ()# the card is tried again, and works now 199self .assertEqual (v .started [- 1 ].split ("-" )[0 ],"gpu" ) 200self .assertFalse (v .on_cpu ) 201self .assertTrue (svc .vision_held ) 202 203def test_no_room_and_a_cache_that_cannot_shrink_goes_straight_to_the_cpu_reader (self ): 204v = self .vision (tempfile .mkdtemp ()) 205svc ,engine = self .service (v ,elastic_engine = False ) 206svc .free_vram_mib = lambda :900 207out = io .StringIO () 208with contextlib .redirect_stdout (out ): 209svc ._vision_up () 210self .assertEqual ([x .split ("-" )[0 ]for x in v .started ], ["cpu" ])# the card was not tried 211self .assertIn ("this picture is read on the CPU" ,out .getvalue ()) 212self .assertFalse (svc .vision_held ) 213 214def test_room_enough_and_a_cache_that_cannot_shrink_still_tries_the_card (self ): 215v = self .vision (tempfile .mkdtemp ()) 216svc ,engine = self .service (v ,elastic_engine = False ) 217svc .free_vram_mib = lambda :5000 218svc ._vision_up () 219self .assertEqual ([x .split ("-" )[0 ]for x in v .started ], ["gpu" ]) 220svc2 ,_ = self .service (self .vision (tempfile .mkdtemp ()),elastic_engine = False ) 221svc2 .free_vram_mib = lambda :None # unknown: the card is tried (and the CPU reader is there if it fails) 222svc2 ._vision_up () 223self .assertEqual ([x .split ("-" )[0 ]for x in svc2 .vision .started ], ["gpu" ]) 224 225def test_a_non_elastic_gpu_reader_keeps_the_cpu_reader_for_good (self ): 226v = Vision ({"exe" :"gpu-reader" ,"mmproj" :"m" ,"model" :"t" ,"gpu" :True ,"cpu_exe" :"cpu-reader" },lazy = True ) 227started = [] 228 229def start_reader (): 230started .append (v .spawn [0 ][0 ]) 231if started [- 1 ].endswith ("gpu-reader" ): 232raise RuntimeError ("no kernel image" ) 233v ._start_reader = start_reader 234v ._start () 235v .unload () 236self .assertEqual ([x .split ("-" )[0 ]for x in started ], ["gpu" ,"cpu" ]) 237self .assertTrue (v .on_cpu )# as before: the card is not tried again 238 239def test_pictures_already_encoded_start_no_reader (self ): 240d = Path (tempfile .mkdtemp ()) 241v = self .vision (d ) 242png = bytes ([0x89 ])+ b"PNG" + bytes ([13 ,10 ,26 ,10 ])+ b"rest" 243v .dir = d 244v .cache ["k" ]= (d / "x.sve" ,3 ) 245import hashlib 246v .cache [hashlib .sha256 (png ).hexdigest ()[:32 ]]= (d / "x.sve" ,3 ) 247self .assertTrue (v .all_cached ([png ])) 248self .assertFalse (v .all_cached ([png + b"x" ])) 249self .assertFalse (v .all_cached (["/no/such/file.png" ]))# an error is encode()'s to report 250 251 252class OnDemandByDefault (unittest .TestCase ): 253"""An NVIDIA GPU reader on one GPU starts on demand without the config saying so; everything else keeps its reader as it was.""" 254BASE = {"args" : ["--max-context" ,"8192" ,"--vision" ],"gpu" :0 , 255"vision" : {"exe" :"/e/strata-vision" ,"mmproj" :"m" ,"model" :"t" ,"gpu" :True ,"max_tokens" :1024 }} 256 257def setUp (self ): 258# these tests describe a PC (x86); the Spark class (Linux on Arm) has its own tests below, so a test run on a Spark does not change them 259p = mock .patch ("platform.machine" ,return_value = "x86_64" ) 260p .start () 261self .addCleanup (p .stop ) 262 263def cfg (self ,** over ): 264import copy 265c = copy .deepcopy (self .BASE ) 266for k ,v in over .items (): 267if k == "vision" : 268c ["vision" ].update (v ) 269else : 270c [k ]= v 271return c 272 273def test_the_spark_class_keeps_the_reader_loaded_by_default (self ): 274"""Linux on Arm with an NVIDIA GPU reader on one GPU (a DGX Spark): resident, as the AMD reader and the Mac's are (owner 2026-11-11).""" 275import sys 276from serve .server import apply_vision_defaults ,vision_on_demand_by_default as f 277for machine in ("aarch64" ,"arm64" ,"AARCH64" ): 278with self .subTest (machine = machine ),mock .patch ("platform.machine" ,return_value = machine ),mock .patch .object (sys ,"platform" ,"linux" ): 279self .assertFalse (f (self .cfg ())) 280c = apply_vision_defaults (self .cfg (args = ["--vision" ,"--vram-reserve-mib" ,"700" ])) 281self .assertNotIn ("elastic" ,c ["vision" ])# no key written: the reader starts with the server 282self .assertEqual (c ["args" ][c ["args" ].index ("--vram-reserve-mib" )+ 1 ],"700" )# the resident path's reserve, not 2,048 283self .assertFalse (f (self .cfg (vision = {"exe" :"component:engine/strata-vision" }))) 284self .assertFalse (f (self .cfg (backend = "cuda" ))) 285 286def test_the_spark_class_still_takes_an_explicit_elastic_key_either_way (self ): 287import sys 288from serve .server import apply_vision_defaults 289with mock .patch ("platform.machine" ,return_value = "aarch64" ),mock .patch .object (sys ,"platform" ,"linux" ): 290c = apply_vision_defaults (self .cfg (vision = {"elastic" :True })) 291self .assertIs (c ["vision" ]["elastic" ],True )# the old behaviour is still reachable 292self .assertEqual (c ["args" ],self .BASE ["args" ]) 293c = apply_vision_defaults (self .cfg (vision = {"elastic" :False })) 294self .assertIs (c ["vision" ]["elastic" ],False ) 295 296def test_other_hosts_keep_the_on_demand_default (self ): 297import sys 298from serve .server import vision_on_demand_by_default as f 299for system ,machine in (("linux" ,"x86_64" ), ("linux" ,"AMD64" ), ("win32" ,"AMD64" ), ("win32" ,"ARM64" )):# a PC, and Windows on Arm (not this rule) 300with self .subTest (system = system ,machine = machine ),mock .patch ("platform.machine" ,return_value = machine ),mock .patch .object (sys ,"platform" ,system ): 301self .assertTrue (f (self .cfg ())) 302with mock .patch ("platform.machine" ,return_value = "arm64" ),mock .patch .object (sys ,"platform" ,"darwin" ): 303self .assertFalse (f (self .cfg ()))# a Mac was never on demand 304 305def test_the_spark_class_does_not_change_the_amd_rule (self ): 306import sys 307import serve .server as S 308with mock .patch ("platform.machine" ,return_value = "aarch64" ),mock .patch .object (sys ,"platform" ,"linux" ), \ 309mock .patch .object (S ,"VISION_ON_DEMAND_AMD_BY_DEFAULT" ,True ): 310self .assertTrue (S .vision_on_demand_by_default (self .cfg (vision = {"exe" :"/e/strata-vision-hip" ,"cpu_exe" :"/e/strata-vision" },backend = "hip" ))) 311 312def test_the_plain_nvidia_config_is_on_demand (self ): 313from serve .server import apply_vision_defaults ,vision_on_demand_by_default 314c = apply_vision_defaults (self .cfg ()) 315self .assertTrue (c ["vision" ]["elastic" ]) 316self .assertIs (c ["vram_elastic" ],True )# owner 11-11: the cache makes the room when a picture comes 317self .assertEqual (c ["args" ],self .BASE ["args" ])# ... and nothing is held back before it 318c = apply_vision_defaults (self .cfg (args = ["--vision" ,"--vram-reserve-mib" ,"700" ])) 319self .assertEqual (c ["args" ][c ["args" ].index ("--vram-reserve-mib" )+ 1 ],"700" )# setup's reserve stays as written 320c = apply_vision_defaults (self .cfg (args = ["--vision" ,"--vram-reserve-mib" ,"1536" ])) 321self .assertEqual (c ["args" ][c ["args" ].index ("--vram-reserve-mib" )+ 1 ],"1536" )# a chosen reserve is kept 322# a config that names the shrinking cache itself keeps the old rule: the reader's room in the reserve 323c = apply_vision_defaults (self .cfg (vram_elastic = False ,args = ["--vision" ,"--vram-reserve-mib" ,"700" ])) 324self .assertIs (c ["vram_elastic" ],False ) 325self .assertEqual (c ["args" ][c ["args" ].index ("--vram-reserve-mib" )+ 1 ],"2048" ) 326c = apply_vision_defaults (self .cfg (vram_elastic = False )) 327self .assertEqual (c ["args" ][- 2 :], ["--vram-reserve-mib" ,"2048" ]) 328import serve .server as S 329with mock .patch .object (S ,"VISION_NO_RESERVE_BY_DEFAULT" ,False ):# the switch back: the old rule everywhere 330c = apply_vision_defaults (self .cfg (args = ["--vision" ,"--vram-reserve-mib" ,"700" ])) 331self .assertNotIn ("vram_elastic" ,c ) 332self .assertEqual (c ["args" ][c ["args" ].index ("--vram-reserve-mib" )+ 1 ],"2048" ) 333self .assertTrue (vision_on_demand_by_default (self .cfg (vision = {"exe" :"component:engine/strata-vision.exe" }))) 334self .assertTrue (vision_on_demand_by_default (self .cfg (vision = {"exe" :"C:/e/strata-vision.exe" }))) 335bs = chr (92 ) 336self .assertTrue (vision_on_demand_by_default (self .cfg (vision = {"exe" :"C:" + bs + "e" + bs + "strata-vision.exe" }))) 337 338def test_the_amd_reader_with_its_cpu_reader_is_on_demand_when_asked (self ): 339import serve .server as S 340f = S .vision_on_demand_by_default 341amd = self .cfg (vision = {"exe" :"/e/strata-vision-hip" ,"cpu_exe" :"/e/strata-vision" },backend = "hip" ) 342self .assertFalse (f (amd ))# off by default on AMD (no slots gained: see the constant's note) 343with mock .patch .object (S ,"VISION_ON_DEMAND_AMD_BY_DEFAULT" ,True ): 344self .assertTrue (f (amd )) 345got = S .apply_vision_defaults (amd ) 346self .assertTrue (got ["vision" ]["elastic" ]) 347self .assertNotIn ("vram_elastic" ,got )# AMD: no shrinking cache, the room stays in the reserve 348self .assertEqual (got ["args" ][- 2 :], ["--vram-reserve-mib" ,"2048" ]) 349with mock .patch .object (__import__ ("serve.server" ).server ,"VISION_ON_DEMAND_AMD_BY_DEFAULT" ,True ): 350self .assertFalse (f (self .cfg (vision = {"exe" :"/e/strata-vision-hip" ,"cpu_exe" :"/e/strata-vision" },backend = "hip" ,gpu = [0 ,1 ]))) 351self .assertFalse (f (self .cfg (vision = {"exe" :"/e/strata-vision-sycl" ,"cpu_exe" :"/e/strata-vision" },backend = "sycl" ))) 352 353def test_what_stays_as_it_was (self ): 354from serve .server import vision_on_demand_by_default as f 355self .assertFalse (f (self .cfg (vision = {"gpu" :False })))# the CPU reader 356self .assertFalse (f (self .cfg (vision = {"elastic" :False })))# the person said no 357self .assertFalse (f (self .cfg (vision = {"cuda_device" :1 })))# a reader on its own card 358self .assertFalse (f (self .cfg (vision = {"exe" :"/e/strata-vision-hip" },backend = "hip" )))# AMD without its CPU reader 359self .assertFalse (f (self .cfg (vision = {"exe" :"/e/strata-vision" },backend = "hip" ))) 360self .assertFalse (f (self .cfg (backend = "sycl" ,vision = {"exe" :"/e/strata-vision-sycl" }))) 361self .assertFalse (f (self .cfg (gpu = [0 ,1 ])))# a layer split 362self .assertFalse (f (self .cfg (args = ["--vision" ,"--kv-grow" ]))) 363self .assertTrue (f (self .cfg (args = ["--vision" ,"--resident-budget-gib" ,"30" ])))# no cache to shrink is needed 364self .assertFalse (f (self .cfg (parallel = 4 ))) 365self .assertFalse (f (self .cfg (arch = "deepseek41" ))) 366c = self .cfg () 367c .pop ("vision" ) 368self .assertFalse (f (c )) 369c = self .cfg (vision = {"elastic" :True })# already asked for: untouched 370from serve .server import apply_vision_defaults 371self .assertEqual (apply_vision_defaults (c )["args" ],self .BASE ["args" ])# already asked for: untouched 372 373 374if __name__ == "__main__" : 375unittest .main ()