okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ccf18ea14
main
1"""Split serving (serve/split.py): the config, the decision, the hand-over with two fake engines, and every fallback. 2The engine-side proof (the continuation after a hand-over equals a single engine's) is tests/split_serve_exact.py.""" 3import os 4import tempfile 5import threading 6import unittest 7 8from serve import split as sp 9from serve .server import EngineDied ,SessionRefused 10from serve .split import SplitConfigError ,SplitEngine ,check_cfg ,common_prefix ,role_cfg ,split_spec 11 12 13class Config (unittest .TestCase ): 14def test_off_without_the_key (self ): 15self .assertIsNone (split_spec ({})) 16self .assertIsNone (split_spec ({"split_serve" :False })) 17self .assertIsNone (split_spec ({"split_serve" :None })) 18 19def test_cards_and_defaults (self ): 20s = split_spec ({"split_serve" : {"prefill_gpu" :0 ,"decode_gpu" :"1" }}) 21self .assertEqual ((s ["prefill_gpu" ],s ["decode_gpu" ]), (0 ,1 )) 22self .assertEqual (s ["min_prompt_tokens" ],sp .MIN_TOKENS ) 23self .assertIs (s ["shared_arena" ],True ) 24self .assertEqual ((s ["prefill_args" ],s ["decode_args" ]), ([], [])) 25 26def test_mistakes_are_said (self ): 27bad = [{"split_serve" :1 }, {"split_serve" : {"prefill_gpu" :0 }}, {"split_serve" : {"prefill_gpu" :1 ,"decode_gpu" :1 }}, 28 {"split_serve" : {"prefill_gpu" :0 ,"decode_gpu" :- 1 }}, {"split_serve" : {"prefill_gpu" :True ,"decode_gpu" :1 }}, 29 {"split_serve" : {"prefill_gpu" :0 ,"decode_gpu" :1 ,"x" :1 }}, 30 {"split_serve" : {"prefill_gpu" :0 ,"decode_gpu" :1 ,"min_prompt_tokens" :"9" }}, 31 {"split_serve" : {"prefill_gpu" :0 ,"decode_gpu" :1 ,"prefill_args" :"--x" }}, 32 {"split_serve" : {"prefill_gpu" :0 ,"decode_gpu" :1 ,"shared_arena" :3 }}] 33for cfg in bad : 34with self .assertRaises (SplitConfigError ,msg = cfg ): 35split_spec (cfg ) 36 37def test_check_cfg_refuses_what_cannot_run (self ): 38spec = split_spec ({"split_serve" : {"prefill_gpu" :0 ,"decode_gpu" :1 }}) 39check_cfg ({"args" : ["--serve" ,"--prompt-cache" ,"3" ]},spec ) 40for cfg in ({"args" : ["--layer-split" ,"24" ]}, {"args" : ["--batch" ,"2" ]}, {"args" : ["--prompt-cache" ,"0" ]}, 41 {"args" : [],"replicas" :2 }, {"args" : [],"parallel" :2 }, {"args" : ["--peer-device" ,"1" ]}): 42with self .assertRaises (SplitConfigError ,msg = cfg ): 43check_cfg (cfg ,spec ) 44spec2 = split_spec ({"split_serve" : {"prefill_gpu" :0 ,"decode_gpu" :1 ,"decode_args" : ["--batch" ,"2" ]}}) 45with self .assertRaises (SplitConfigError ): 46check_cfg ({"args" : []},spec2 ) 47 48def test_role_cfg (self ): 49cfg = {"gpu" : [0 ,1 ],"args" : ["--x" ],"log" :"/l/strata.log" ,"hip_ordinal" :1 ,"gpu_roles" : {"0" :"main" }, 50"expert_profile_save" :"/p/prof.bin" , 51"split_serve" : {"prefill_gpu" :2 ,"decode_gpu" :3 ,"decode_args" : ["--expert-cache" ,"auto" ]}} 52spec = split_spec (cfg ) 53p ,d = role_cfg (cfg ,spec ,"prefill" ),role_cfg (cfg ,spec ,"decode" ) 54self .assertEqual ((p ["gpu" ],d ["gpu" ]), (2 ,3 )) 55self .assertEqual ((p ["log" ],d ["log" ]), ("/l/strata.prefill.log" ,"/l/strata.decode.log" )) 56self .assertEqual (p ["args" ], ["--x" ]) 57self .assertEqual (d ["args" ], ["--x" ,"--expert-cache" ,"auto" ]) 58self .assertEqual (d ["expert_profile_save" ],"/p/prof.decode.bin" ) 59for c in (p ,d ): 60self .assertNotIn ("split_serve" ,c ) 61self .assertNotIn ("hip_ordinal" ,c ) 62self .assertNotIn ("gpu_roles" ,c ) 63self .assertEqual (cfg ["args" ], ["--x" ])# the original is untouched 64 65def test_arena_choice (self ): 66spec = split_spec ({"split_serve" : {"prefill_gpu" :0 ,"decode_gpu" :1 }}) 67off = split_spec ({"split_serve" : {"prefill_gpu" :0 ,"decode_gpu" :1 ,"shared_arena" :False }}) 68named = split_spec ({"split_serve" : {"prefill_gpu" :0 ,"decode_gpu" :1 ,"shared_arena" :"/data/a.bin" }}) 69self .assertIsNone (sp .arena_path ({"args" : ["--shared-expert-arena" ,"/x" ]},spec )[0 ]) 70self .assertIsNone (sp .arena_path ({"args" : []},off )[0 ]) 71if os .name != "nt" : 72self .assertEqual (sp .arena_path ({"args" : []},named )[0 ],os .path .abspath ("/data/a.bin" )) 73path ,note = sp .arena_path ({"args" : ["--pack" ,"/no/such/pack" ]},spec )# nothing to size it from 74self .assertIsNone (path ) 75self .assertIn ("experts.bin" ,note ) 76 77def test_common_prefix (self ): 78self .assertEqual (common_prefix ([1 ,2 ,3 ], [1 ,2 ,9 ,4 ]),2 ) 79self .assertEqual (common_prefix ([], [1 ]),0 ) 80self .assertEqual (common_prefix ([1 ,2 ], [1 ,2 ]),2 ) 81 82 83class FakeEngine : 84"""The part of StrataEngine the SplitEngine uses. `session` is the token list its session holds (a file is a json-free 85list in a dict keyed by path, shared between the two fakes).""" 86files = {} 87 88def __init__ (self ,name ,tokens_per_answer = 3 ): 89self .name ,self .up ,self .max_context ,self .info ,self .last = name ,True ,4096 , {}, {} 90self .session ,self .log ,self .progress ,self .prefill_tok_s_mean = [], [],None ,None 91self .answer = tokens_per_answer 92self .fail_save = self .fail_restore = self .fail_prefill = None 93self .unloaded = False 94 95def alive (self ): 96return self .up 97 98def restart (self ,tries = 3 ): 99self .up = True 100 101def exit_code (self ): 102return None 103 104def death_note (self ): 105return "" 106 107def unload (self ): 108self .up = False 109 110def close (self ): 111self .up = False 112 113def generate (self ,ids ,max_new ,sampling ,cancel ,embeddings = None ,prefill_only = False ): 114if not self .up : 115raise EngineDied ("down" ) 116if prefill_only : 117if self .fail_prefill : 118raise self .fail_prefill 119have = common_prefix (self .session ,ids [:- 1 ]) 120self .log .append (("prefill" ,len (ids ))) 121self .session = list (ids [:- 1 ]) 122self .last = {"generated" :0 ,"prompt_tokens" :len (ids ),"prompt_ms" :1000.0 ,"decode_ms" :0.0 , 123"finish" :"length" ,"reused" :have ,"prompt_read" :len (ids )- have } 124yield None 125return 126have = common_prefix (self .session ,ids [:- 1 ]) 127out = [100 + i for i in range (min (max_new ,self .answer ))] 128self .log .append (("generate" ,len (ids ),have )) 129self .session = list (ids )+ out [:- 1 ] 130self .last = {"generated" :len (out ),"prompt_tokens" :len (ids ),"prompt_ms" :50.0 ,"decode_ms" :200.0 , 131"finish" :"length" ,"reused" :have ,"prompt_read" :len (ids )- have } 132for t in out : 133yield t 134 135def session_file (self ,action ,path ): 136if action == "save" : 137if self .fail_save : 138raise self .fail_save 139FakeEngine .files [path ]= list (self .session ) 140with open (path ,"wb" )as f : 141f .write (b"x" * 1000 ) 142return {"tokens" :len (self .session ),"bytes" :1000 ,"ms" :12.0 } 143if self .fail_restore : 144raise self .fail_restore 145self .session = list (FakeEngine .files [path ]) 146return {"tokens" :len (self .session ),"bytes" :1000 ,"ms" :7.0 } 147 148 149class Handover (unittest .TestCase ): 150def setUp (self ): 151FakeEngine .files = {} 152self .dir = tempfile .mkdtemp (prefix = "split-test-" ) 153self .p ,self .d = FakeEngine ("p" ),FakeEngine ("d" ) 154self .said = [] 155self .e = SplitEngine (self .p ,self .d ,min_tokens = 100 ,work_dir = self .dir ,say = self .said .append ) 156self .cancel = threading .Event () 157 158def run_one (self ,ids ,max_new = 5 ): 159return [t for t in self .e .generate (ids ,max_new , {},self .cancel )if t is not None ] 160 161def test_a_long_prompt_is_handed_over (self ): 162ids = list (range (500 )) 163out = self .run_one (ids ) 164self .assertEqual (out , [100 ,101 ,102 ]) 165self .assertEqual (self .p .log , [("prefill" ,500 )]) 166self .assertEqual (self .d .log , [("generate" ,500 ,499 )])# the decode engine read one token itself 167self .assertEqual (self .e .stats ["handed_over" ],1 ) 168self .assertEqual (os .listdir (self .dir ), [])# the session file is gone 169last = self .e .last 170self .assertEqual (last ["reused" ],0 ) 171self .assertEqual (last ["prompt_read" ],500 )# 499 read by the prefill engine, 1 by the decode one... 500 172self .assertGreaterEqual (last ["prompt_ms" ],12.0 + 7.0 + 50.0 )# the file steps and the decode engine's start 173self .assertLess (last ["prompt_ms" ],12.0 + 7.0 + 50.0 + 1000.0 ) 174self .assertEqual (last ["split_bytes" ],1000 ) 175 176def test_a_short_prompt_stays_on_the_decode_engine (self ): 177self .run_one (list (range (50 ))) 178self .assertEqual (self .p .log , []) 179self .assertEqual (self .e .stats ["short" ],1 ) 180 181def test_the_next_turn_is_not_handed_over_when_the_decode_engine_holds_it (self ): 182ids = list (range (500 )) 183out = self .run_one (ids ) 184turn2 = ids + out + list (range (7000 ,7040 ))# the answer and a short question 185self .run_one (turn2 ) 186self .assertEqual (len (self .p .log ),1 )# only the first turn went through the prefill engine 187self .assertEqual (self .d .log [- 1 ][0 ],"generate" ) 188self .assertGreater (self .d .log [- 1 ][2 ],490 )# and the decode engine continued its own session 189 190def test_a_big_new_part_is_handed_over_again (self ): 191ids = list (range (500 )) 192out = self .run_one (ids ) 193self .run_one (ids + out + list (range (9000 ,9400 ))) 194self .assertEqual (len (self .p .log ),2 ) 195 196def test_pictures_go_to_the_decode_engine (self ): 197list (self .e .generate (list (range (500 )),3 , {},self .cancel ,embeddings = "/tmp/x" )) 198self .assertEqual (self .p .log , []) 199 200def test_a_dead_prefill_engine_is_not_an_error (self ): 201self .p .up = False 202self .e .heal = lambda :None 203out = self .run_one (list (range (500 ))) 204self .assertEqual (out , [100 ,101 ,102 ]) 205self .assertEqual (self .d .log , [("generate" ,500 ,0 )])# the decode engine read all of it 206 207def test_a_prefill_engine_that_dies_midway_falls_back (self ): 208self .p .fail_prefill = EngineDied ("gone" ) 209self .e .heal = lambda :None 210out = self .run_one (list (range (500 ))) 211self .assertEqual (out , [100 ,101 ,102 ]) 212self .assertEqual (self .d .log , [("generate" ,500 ,0 )]) 213self .assertTrue (any ("failed" in s for s in self .said )) 214 215def test_a_refused_file_falls_back (self ): 216for which in ("fail_save" ,"fail_restore" ): 217FakeEngine .files = {} 218self .p .session ,self .d .session = [], [] 219setattr (self .p if which == "fail_save" else self .d ,which ,SessionRefused ("invalid" ,"other model" ,False )) 220self .d .log .clear () 221ids = list (range (500 ))if which == "fail_save" else list (range (1000 ,1500 )) 222out = self .run_one (ids ) 223self .assertEqual (out , [100 ,101 ,102 ]) 224self .assertEqual (self .d .log , [("generate" ,500 ,0 )],which ) 225setattr (self .p if which == "fail_save" else self .d ,which ,None ) 226self .assertEqual (self .e .stats ["fallbacks" ],2 ) 227self .assertEqual (os .listdir (self .dir ), []) 228 229def test_a_decode_engine_that_dies_in_the_restore_is_an_error (self ): 230def boom (* a ): 231self .d .up = False 232raise EngineDied ("transfer failed" ) 233self .d .fail_restore = None 234orig = self .d .session_file 235self .d .session_file = lambda action ,path :boom ()if action == "restore" else orig (action ,path ) 236with self .assertRaises (EngineDied ): 237self .run_one (list (range (500 ))) 238self .assertEqual (os .listdir (self .dir ), []) 239 240def test_cancel_during_the_prefill_ends_quietly (self ): 241self .cancel .set () 242orig = self .p .generate 243 244def gen (* a ,** k ): 245for t in orig (* a ,** k ): 246yield t 247self .p .generate = gen 248out = self .run_one (list (range (500 ))) 249self .assertEqual (out , []) 250self .assertEqual (self .d .log , []) 251self .assertEqual (self .e .held , []) 252 253def test_attributes_come_from_the_decode_engine (self ): 254self .assertEqual (self .e .max_context ,4096 ) 255self .assertEqual (self .e .batch ,0 ) 256self .assertFalse (hasattr (self .e ,"session_file" )) 257self .assertTrue (self .e .alive ()) 258self .d .up = False 259self .assertFalse (self .e .alive ()) 260self .assertTrue (self .e .info ["split_serve" ]) 261self .e .silence_s = 5 262self .assertEqual ((self .p .silence_s ,self .d .silence_s ), (5 ,5 )) 263 264def test_close_removes_the_work_dir (self ): 265self .e .close () 266self .assertFalse (os .path .exists (self .dir )) 267self .assertFalse (self .p .up or self .d .up ) 268 269 270if __name__ == "__main__" : 271unittest .main ()