okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ccf18ea14
main
1"""Split serving: one engine reads the prompt, another makes the answer (issue #4000, idea and manual setup by @MarcoTool). 2 3Two engines on the same PC, one card each, the same model files and the same session settings. A long prompt is read by 4the prefill engine, which saves the session (the engine's own session file: SAVE <path>) into RAM; the decode engine 5restores it (RESTORE <path>) and makes the answer. The server keeps its one HTTP front, its one Service and its one set of 6endpoints; `SplitEngine` stands in for the engine, as `ReplicaEngine` does for replicas. 7 8Opt-in, in the run config (nothing changes without it): 9 10"split_serve": {"prefill_gpu": 0, "decode_gpu": 1} 11 12prefill_gpu / decode_gpu the card of each engine, numbered as nvidia-smi numbers them (required, different) 13min_prompt_tokens hand a request over only when the decode engine would read at least this many new tokens 14itself (default 2048); a shorter tail is read by the decode engine in place 15dir where the session files go (default /dev/shm when it has room, else the temp folder) 16shared_arena true (default): one copy of the experts in RAM for both engines (Linux, a file in /dev/shm 17when the experts fit there); false: each engine keeps its own copy; a path: that file 18prefill_args / decode_args extra engine arguments for one role (a bigger expert cache for the decode engine, say) 19 20What must match between the two engines is what the session file checks (docs/SPLIT_SERVE.md): the model files, the engine 21version, the backend, --kv, --max-context, --kv-resident, --mtp-window, the rope settings and the arithmetic switches. They 22start from one config, so they do. Every failure on the way (a prefill engine that died, a refused file) is not an error 23for the client: the decode engine reads the prompt itself, as it would without the option. 24 25Honest limit of this first version: one request at a time (the Service's FIFO), one conversation resident on the decode 26engine (a restore replaces what it held), no parallel slots (--batch), no layer split in an engine, no pictures (a request 27with pictures goes to the decode engine alone). 28""" 29from __future__import annotations 30 31import os 32import shutil 33import tempfile 34import threading 35import time 36 37MIN_TOKENS = 2048 # the decode engine's own tail below this is read in place 38KNOWN_KEYS = {"prefill_gpu" ,"decode_gpu" ,"min_prompt_tokens" ,"dir" ,"shared_arena" ,"prefill_args" ,"decode_args" } 39FORBIDDEN_ARGS = {# engine arguments that cannot be used in a split-serve engine, and why 40"--layer-split" :"an engine of the split runs on one card" , 41"--split-device" :"an engine of the split runs on one card" , 42"--peer-device" :"session files do not support --peer-device" , 43"--batch" :"session files do not support --batch (parallel requests)" , 44"--slots" :"session files do not support parallel slots" , 45} 46HEAL_COOLDOWN_S = 60.0 # a prefill engine that died is started again at most this often 47HEARTBEAT_S = 5.0 # a long file step sends a keep-alive this often 48 49 50class SplitConfigError (ValueError ): 51pass 52 53 54def split_spec (cfg :dict )-> dict | None : 55"""The checked "split_serve" section of the run config, or None when the option is off.""" 56raw = cfg .get ("split_serve" ) 57if raw is None or raw is False : 58return None 59if not isinstance (raw ,dict ): 60raise SplitConfigError ('"split_serve" must be {"prefill_gpu": N, "decode_gpu": M}, not ' + repr (raw )) 61unknown = sorted (set (raw )- KNOWN_KEYS ) 62if unknown : 63raise SplitConfigError (f'"split_serve" has no key { unknown [ 0 ]!r } (keys: { ", " . join ( sorted ( KNOWN_KEYS )) } )' ) 64cards = [] 65for k in ("prefill_gpu" ,"decode_gpu" ): 66v = raw .get (k ) 67if isinstance (v ,str )and v .strip ().isdigit (): 68v = int (v .strip ()) 69if isinstance (v ,bool )or not isinstance (v ,int )or v < 0 : 70raise SplitConfigError (f'"split_serve" needs " { k } ": the number of a card (0, 1, ...), not { v !r } ' ) 71cards .append (v ) 72if cards [0 ]== cards [1 ]: 73raise SplitConfigError (f'"split_serve": prefill_gpu and decode_gpu are both card { cards [ 0 ] } ; each engine needs a ' 74"card of its own" ) 75out = {"prefill_gpu" :cards [0 ],"decode_gpu" :cards [1 ]} 76n = raw .get ("min_prompt_tokens" ,MIN_TOKENS ) 77if isinstance (n ,bool )or not isinstance (n ,int )or n < 0 : 78raise SplitConfigError (f'"split_serve": "min_prompt_tokens" must be a number of tokens (0 or more), not { n !r } ' ) 79out ["min_prompt_tokens" ]= n 80d = raw .get ("dir" ) 81if d is not None and (not isinstance (d ,str )or not d .strip ()): 82raise SplitConfigError (f'"split_serve": "dir" must be a folder name, not { d !r } ' ) 83out ["dir" ]= d 84sa = raw .get ("shared_arena" ,True ) 85if not (isinstance (sa ,bool )or (isinstance (sa ,str )and sa .strip ())): 86raise SplitConfigError (f'"split_serve": "shared_arena" must be true, false or a file name, not { sa !r } ' ) 87out ["shared_arena" ]= sa 88for k in ("prefill_args" ,"decode_args" ): 89a = raw .get (k , []) 90if not isinstance (a ,list )or not all (isinstance (x , (str ,int ,float ))and not isinstance (x ,bool )for x in a ): 91raise SplitConfigError (f'"split_serve": " { k } " must be a list of engine arguments' ) 92out [k ]= [str (x )for x in a ] 93return out 94 95 96def check_cfg (cfg :dict ,spec :dict )-> None : 97"""Refuse (with the reason, in plain words) a config the split cannot run.""" 98if cfg .get ("replicas" )not in (None ,False ): 99raise SplitConfigError ('"split_serve" and "replicas" cannot be used together: both start engines on the cards' ) 100args = [str (a )for a in cfg .get ("args" )or []]+ spec ["prefill_args" ]+ spec ["decode_args" ] 101for flag ,why in FORBIDDEN_ARGS .items (): 102if flag in args : 103raise SplitConfigError (f'"split_serve" cannot be used with { flag } in the engine arguments: { why } ' ) 104for i ,a in enumerate (args ): 105if a == "--prompt-cache" and i + 1 < len (args )and args [i + 1 ].strip ()== "0" : 106raise SplitConfigError ('"split_serve" needs the conversation cache (--prompt-cache 1 or more): the session ' 107"file is made from it" ) 108if cfg .get ("batch" )or cfg .get ("parallel" ): 109raise SplitConfigError ('"split_serve" does not run parallel requests ("parallel"/"batch"): remove it' ) 110 111 112def _suffixed (path ,tag :str ): 113if not isinstance (path ,str )or not path : 114return path 115root ,ext = os .path .splitext (path ) 116return f" { root } . { tag } { ext } " 117 118 119def role_cfg (cfg :dict ,spec :dict ,role :str )-> dict : 120"""The config of one engine of the split: its own card, log and learned-profile file; its role's extra arguments.""" 121import copy 122c = copy .deepcopy (cfg ) 123c .pop ("split_serve" ,None ) 124c ["gpu" ]= spec [f" { role } _gpu" ] 125c .pop ("hip_ordinal" ,None ) 126c .pop ("gpu_roles" ,None )# the roles were for a layer split over several cards 127c ["log" ]= _suffixed (cfg .get ("log" ),role ) 128if cfg .get ("expert_profile_save" ): 129c ["expert_profile_save" ]= _suffixed (cfg ["expert_profile_save" ],role ) 130extra = spec [f" { role } _args" ] 131if extra : 132c ["args" ]= list (c ["args" ])+ extra 133return c 134 135 136def _arg_value (args :list ,flag :str ): 137for i ,a in enumerate (args ): 138if a == flag and i + 1 < len (args ): 139return args [i + 1 ] 140return None 141 142 143def arena_path (cfg :dict ,spec :dict )-> tuple [str | None ,str ]: 144"""(file for --shared-expert-arena or None, a line for the log). Only Linux can share the arena; the experts 145file must fit /dev/shm (a tmpfs is half of the RAM by default) unless the config names another file.""" 146args = [str (a )for a in cfg .get ("args" )or []] 147if "--shared-expert-arena" in args : 148return None ,"the config already names a shared expert arena" 149sa = spec ["shared_arena" ] 150if sa is False : 151return None ,"shared_arena is off: each engine keeps its own copy of the experts in RAM" 152if os .name == "nt" : 153return None , ("this OS cannot share the expert arena between two engines (Linux only): each engine keeps its own " 154"copy of the experts in RAM, so the PC needs RAM for two" ) 155if isinstance (sa ,str ): 156return os .path .abspath (sa ),f"shared expert arena in { os . path . abspath ( sa ) } " 157pack = _arg_value (args ,"--pack" ) 158experts = os .path .join (pack ,"experts.bin" )if pack else None 159if not experts or not os .path .isfile (experts ): 160return None , ("no experts.bin to size a shared arena from (a pack that reads the GGUF in place): each engine " 161"keeps its own copy of the experts; name a file in \"shared_arena\" to share one" ) 162need = os .path .getsize (experts ) 163try : 164free = shutil .disk_usage ("/dev/shm" ).free 165except OSError : 166free = 0 167if free < need + (1 << 30 ): 168return None , (f"/dev/shm has { free / 2 ** 30 :.1f } GiB free and the experts are { need / 2 ** 30 :.1f } GiB: each engine " 169"keeps its own copy of the experts in RAM (two copies). To share one copy name a file in " 170"\"shared_arena\" (a file on disk works, it is written once) or make /dev/shm bigger" ) 171return "/dev/shm/strata-split-arena.bin" ,f"one shared expert arena in /dev/shm ( { need / 2 ** 30 :.1f } GiB)" 172 173 174def session_dir (spec :dict )-> str : 175d = spec .get ("dir" ) 176if d : 177os .makedirs (d ,exist_ok = True ) 178return d 179shm = "/dev/shm" 180try : 181if os .name != "nt" and os .path .isdir (shm )and os .access (shm ,os .W_OK )and shutil .disk_usage (shm ).free > (6 << 30 ): 182return tempfile .mkdtemp (prefix = "strata-split-" ,dir = shm ) 183except OSError : 184pass 185return tempfile .mkdtemp (prefix = "strata-split-" ) 186 187 188def common_prefix (a ,b )-> int : 189n = min (len (a ),len (b )) 190i = 0 191while i < n and a [i ]== b [i ]: 192i += 1 193return i 194 195 196class SplitEngine : 197"""Stands in for one engine (the interface Service uses), over a prefill engine and a decode engine.""" 198 199NOT_HERE = {"session_file" ,"vram" ,"ctl" ,"slot_cv" }# not offered: one conversation file / VRAM resize / control line 200PROPAGATE = {"silence_s" ,"gpu_busy" } 201 202def __init__ (self ,prefill ,decode ,* ,min_tokens :int = MIN_TOKENS ,work_dir :str | None = None , 203arena_file :str | None = None ,say = d = self .__dict__ 205d ["prefill" ],d ["decode" ]= prefill ,decode 206d ["cur" ]= decode # the engine the request is on now (progress, last) 207d ["min_tokens" ]= int (min_tokens ) 208d ["work_dir" ]= work_dir or tempfile .mkdtemp (prefix = "strata-split-" ) 209d ["arena_file" ]= arena_file 210d ["say" ]= say 211d ["held" ]= []# the tokens the decode engine's session holds (an estimate: ids + answer) 212d ["seq" ]= 0 213d ["heal_at" ]= 0.0 214d ["healing" ]= False 215d ["lock" ]= threading .Lock () 216d ["stats" ]= {"requests" :0 ,"handed_over" :0 ,"fallbacks" :0 ,"short" :0 ,"bytes" :0 ,"prefill_ms" :0.0 , 217"save_ms" :0.0 ,"restore_ms" :0.0 ,"last" :None } 218 219# ---- attribute plumbing 220def __getattr__ (self ,name ): 221if name in self .NOT_HERE or name .startswith ("__" ): 222raise AttributeError (name ) 223return getattr (self .decode ,name ) 224 225def __setattr__ (self ,name ,value ): 226if name in self .PROPAGATE : 227self .prefill .__setattr__ (name ,value ) 228self .decode .__setattr__ (name ,value ) 229else : 230self .__dict__ [name ]= value 231 232@property 233def last (self ): 234return self .decode .last 235 236@ last . setter 237def last (self ,value ): 238self .decode .last = value 239 240@property 241def progress (self ): 242return self .cur .progress 243 244@property 245def prefill_tok_s_mean (self ): 246return self .cur .prefill_tok_s_mean 247 248@property 249def batch (self )-> int : 250return 0 251 252@property 253def max_context (self )-> int : 254v = [e .max_context for e in (self .prefill ,self .decode )if getattr (e ,"max_context" ,0 )and e .alive ()] 255return min (v )if v else 0 256 257@property 258def unloaded (self )-> bool : 259return all (getattr (e ,"unloaded" ,False )for e in (self .prefill ,self .decode )) 260 261@property 262def starting (self )-> bool : 263return not self .alive ()and any (getattr (e ,"starting" ,False )for e in (self .prefill ,self .decode )) 264 265@property 266def info (self )-> dict : 267i = dict (self .decode .info ) 268i ["split_serve" ]= True 269i ["split_prefill_alive" ]= bool (self .prefill .alive ()) 270return i 271 272@ info . setter 273def info (self ,value ): 274pass 275 276def alive (self )-> bool : 277return bool (self .decode .alive ()) 278 279def exit_code (self ): 280return next ((c for c in (e .exit_code ()for e in (self .decode ,self .prefill )if not e .alive ())if c is not None ), 281None ) 282 283def death_note (self )-> str : 284return next ((e .death_note ()for e in (self .decode ,self .prefill )if not e .alive ()),"" ) 285 286def split_view (self )-> dict : 287"""For /metrics: how the two engines are used.""" 288s = dict (self .stats ) 289s .update (prefill_alive = bool (self .prefill .alive ()),decode_alive = bool (self .decode .alive ()), 290min_prompt_tokens = self .min_tokens ) 291return s 292 293# ---- life cycle 294def restart (self ,tries :int = 3 ): 295errors = {} 296for name ,e in (("decode" ,self .decode ), ("prefill" ,self .prefill )):# one at a time: the arena fills once 297if e .alive (): 298continue 299try : 300e .restart (tries ) 301except BaseException as x :# noqa: BLE001 302errors [name ]= x 303if "decode" in errors : 304raise errors ["decode" ] 305for name ,x in errors .items (): 306self .say (f"[strata] the { name } engine of the split did not start ( { x } ); the other one serves" ) 307self .__dict__ ["held" ]= [] 308 309def unload (self ): 310for e in (self .prefill ,self .decode ): 311e .unload () 312self .__dict__ ["held" ]= [] 313 314def close (self ): 315err = None 316for e in (self .prefill ,self .decode ): 317try : 318e .close () 319except BaseException as x :# noqa: BLE001 320err = err or x 321shutil .rmtree (self .work_dir ,ignore_errors = True ) 322if self .arena_file and self .arena_file .startswith ("/dev/shm/strata-split-" ): 323try : 324os .unlink (self .arena_file )# RAM until it is gone 325except OSError : 326pass 327if err : 328raise err 329 330def heal (self )-> None : 331"""Start a prefill engine that died again, in the background (the decode engine serves meanwhile).""" 332e = self .prefill 333now = time .monotonic () 334if e .alive ()or getattr (e ,"unloaded" ,False )or getattr (e ,"starting" ,False )or self .healing or now < self .heal_at : 335return 336self .__dict__ ["heal_at" ]= now + HEAL_COOLDOWN_S 337self .__dict__ ["healing" ]= True 338 339def run (): 340try : 341self .say ("[strata] split: the prefill engine had stopped; starting it again" ) 342e .restart () 343self .say ("[strata] split: the prefill engine is running again" ) 344except BaseException as x :# noqa: BLE001 345self .say (f"[strata] split: the prefill engine did not start again: { x } " ) 346finally : 347self .__dict__ ["healing" ]= False 348threading .Thread (target = run ,daemon = True ).start () 349 350# ---- the request 351def wants_handover (self ,ids )-> tuple [bool ,int ]: 352"""(hand the prompt to the prefill engine?, the tokens the decode engine would read itself).""" 353n = len (ids ) 354if n < 2 : 355return False ,0 356need = (n - 1 )- min (common_prefix (self .held ,ids ),n - 1 ) 357return need >= max (1 ,self .min_tokens )and self .prefill .alive (),need 358 359def _wait (self ,fn ): 360"""Run a blocking engine call on a thread; yields None as a keep-alive while it runs. -> its result.""" 361box = {} 362 363def run (): 364try : 365box ["r" ]= fn () 366except BaseException as e :# noqa: BLE001 367box ["e" ]= e 368th = threading .Thread (target = run ,daemon = True ) 369th .start () 370while th .is_alive (): 371th .join (HEARTBEAT_S ) 372if th .is_alive (): 373yield None 374if "e" in box : 375raise box ["e" ] 376return box .get ("r" ) 377 378def _hand_over (self ,ids ,cancel ,rec :dict ): 379"""Prefill engine reads the prompt, saves the session; the decode engine restores it. Yields keep-alives. 380rec['ok'] is True when the decode engine now holds the prompt's first n-1 tokens.""" 381from serve .server import EngineDied ,SessionRefused 382P ,D = self .prefill ,self .decode 383n = len (ids ) 384self .__dict__ ["seq" ]+= 1 385path = os .path .join (self .work_dir ,f"handover- { os . getpid () } - { self . seq } .session" ) 386rec .update (ok = False ) 387t0 = time .monotonic () 388self .__dict__ ["cur" ]= P 389try : 390try : 391for _ in P .generate (ids ,0 , {},cancel ,prefill_only = True ): 392yield None 393except (EngineDied ,ValueError )as e : 394self .say (f"[strata] split: the prefill engine failed ( { e } ); the decode engine reads the prompt itself" ) 395self .heal () 396return 397if cancel .is_set (): 398return 399p_last = dict (P .last or {}) 400rec ["prefill_ms" ]= (time .monotonic ()- t0 )* 1000.0 401rec ["p_last" ]= p_last 402try : 403saved = yield from self ._wait (lambda :P .session_file ("save" ,path )) 404self .__dict__ ["cur" ]= D 405restored = yield from self ._wait (lambda :D .session_file ("restore" ,path )) 406except SessionRefused as e : 407self .say (f"[strata] split: the session file was refused ( { e } ); the decode engine reads the prompt itself" ) 408return 409except EngineDied as e : 410if not D .alive (): 411raise 412self .say (f"[strata] split: the prefill engine failed while saving ( { e } ); the decode engine reads the prompt " 413"itself" ) 414self .heal () 415return 416rec .update (save_ms = float (saved ["ms" ]),restore_ms = float (restored ["ms" ]),bytes = int (saved ["bytes" ]), 417tokens = int (restored ["tokens" ]),ok = restored ["tokens" ]== n - 1 ) 418if not rec ["ok" ]: 419self .say (f"[strata] split: the decode engine restored { restored [ 'tokens' ] } tokens, not the { n - 1 } the " 420"prompt needs; it reads the rest itself" ) 421rec ["ok" ]= restored ["tokens" ]> 0 422finally : 423self .__dict__ ["cur" ]= D 424try : 425os .unlink (path ) 426except OSError : 427pass 428 429def generate (self ,ids ,max_new ,sampling ,cancel ,embeddings = None ): 430D = self .decode 431ids = list (ids ) 432st = self .stats 433st ["requests" ]+= 1 434rec :dict = {} 435use ,need = (False ,0 )if embeddings is not None else self .wants_handover (ids ) 436if not use : 437st ["short" ]+= 1 438if use : 439if not self .prefill .alive (): 440self .heal () 441yield from self ._hand_over (ids ,cancel ,rec ) 442if cancel .is_set (): 443self .__dict__ ["held" ]= [] 444return 445if rec .get ("ok" ): 446st ["handed_over" ]+= 1 447st ["bytes" ]+= rec ["bytes" ] 448st ["prefill_ms" ]+= rec ["prefill_ms" ] 449st ["save_ms" ]+= rec ["save_ms" ] 450st ["restore_ms" ]+= rec ["restore_ms" ] 451self .__dict__ ["held" ]= ids [:len (ids )- 1 ] 452else : 453st ["fallbacks" ]+= 1 454self .__dict__ ["cur" ]= D 455produced :list [int ]= [] 456ok = False 457try : 458gen = D .generate (ids ,max_new ,sampling ,cancel ,embeddings = embeddings )if embeddings is not None \ 459else D .generate (ids ,max_new ,sampling ,cancel ) 460for t in gen : 461if t is not None : 462produced .append (t ) 463yield t 464ok = True 465finally : 466self .__dict__ ["held" ]= (ids + produced )if ok else [] 467if rec .get ("ok" )and ok : 468self ._account (ids ,rec ) 469 470def _account (self ,ids ,rec :dict )-> None : 471"""The figures of the engine's last DONE, as the whole request: the prefill engine's read, the file steps and the 472decode engine's own start are the prompt time; what the prefill engine reused is the cached part.""" 473D = self .decode 474last = dict (D .last or {}) 475p = rec .get ("p_last" )or {} 476total_prompt_ms = rec ["prefill_ms" ]+ rec ["save_ms" ]+ rec ["restore_ms" ]+ float (last .get ("prompt_ms" )or 0.0 ) 477p_read = p .get ("prompt_read" ) 478if p_read is None : 479p_read = len (ids )- int (p .get ("reused" )or 0 ) 480last .update (prompt_ms = total_prompt_ms ,reused = int (p .get ("reused" )or 0 ), 481prompt_read = max (0 ,min (len (ids ),int (p_read )+ int (last .get ("prompt_read" )or 0 ))), 482split_prefill_ms = round (rec ["prefill_ms" ],1 ),split_save_ms = round (rec ["save_ms" ],1 ), 483split_restore_ms = round (rec ["restore_ms" ],1 ),split_bytes = rec ["bytes" ]) 484D .last = last 485self .stats ["last" ]= {k :last [k ]for k in last if k .startswith ("split_" )} 486self .say (f"[strata] split: prompt { len ( ids ) } tokens read on the prefill card in { rec [ 'prefill_ms' ] / 1000 :.1f } s, " 487f"session { rec [ 'bytes' ] / 2 ** 20 :.0f } MiB saved in { rec [ 'save_ms' ] / 1000 :.2f } s and restored in " 488f" { rec [ 'restore_ms' ] / 1000 :.2f } s; the decode card makes the answer" )