okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ba8745e13
main
1"""Data-parallel replicas: N independent engines, each on its own group of cards, behind one server. 2 3A model that fits two cards (IQ3_S on two R9700s) runs better as two 2-card engines than as one 4-card layer split: 4the split runs one pipeline whose stages wait on each other, two replicas run two pipelines. The server keeps its one 5HTTP front, its one Service and its one set of endpoints; `ReplicaEngine` stands in for the engine and spreads the 6requests over the replicas. 7 8Opt-in, in the run config: 9 10"replicas": 2 the "gpu" list cut into 2 equal groups ([0,1] and [2,3]) 11"replicas": [{"gpus": [0, 1]}, {"gpus": [2, 3]}] the groups named; an entry may add "env" and "args" 12 13or `serve/server.py --replicas 2`. Nothing changes without it. 14 15Routing. Each request goes to the replica with the lowest cost, cost = prompt tokens the replica would have to read 16again (it holds the start of a conversation in its cache) + LOAD_TOKENS for every request already running there. A 17conversation's next turn therefore goes back to its replica, until that replica is so much busier than another that 18reading the prompt again is cheaper than waiting. What each replica holds is tracked as hashes of 64-token blocks of 19the prompts and answers it served (the engine itself checks the real prefix, as it always does). 20 21Host RAM. Every engine keeps its own copy of the experts in RAM (about 47 GiB for Qwen3.8-Flash-Next IQ3_S), so two 22replicas need two copies and four need four. "replica_shared_arena": true (or STRATA_REPLICA_SHARED_ARENA=1; opt-in) 23backs the experts' arena of all replicas with ONE shared memory object (the engine's --shared-expert-arena, MAP_SHARED): 24the experts are in RAM once, whatever the number of replicas. On Linux the object is a memfd the server creates 25(os.memfd_create): it is not a file on a mount, so the size of /dev/shm does not limit it; the engines open it as 26/proc/<server pid>/fd/<n>. On Windows it is a named section (CreateFileMapping) the engines open by name. Without memfd (an old kernel, a sandbox that refuses it) a file in /dev/shm is used instead. 27The pack hash in the header refuses another model; the first engine to start reads the experts into it and the others 28wait for it and skip the read (a state word in the header: nobody / a pid reading / filled; an engine whose reader died 29takes the read over); the server closes the memfd (or unlinks the file) when it ends - an engine that still maps it 30keeps its pages, the kernel frees them with the last mapping - and a /dev/shm file whose server is gone is removed at 31the next start. See shared_arena_plan. 32 33CPU cores. On Linux the replicas get disjoint physical cores (serve/cpu_affinity.py, from PR #1436 by agorevski), so 34the host threads of the engines (the expert workers) do not compete. "replica_cpus": false turns it off. 35""" 36from __future__import annotations 37 38import collections 39import copy 40import os 41import sys 42import threading 43import time 44 45BLOCK = 64 # tokens per hashed block of a prompt 46LOAD_TOKENS = 3000 # the cost of one request already running on a replica, in prompt tokens 47INDEX_MAX = 262144 # block hashes kept (about 17M tokens of prompts) 48HEAL_COOLDOWN_S = 60.0 # a replica that died is started again at most this often 49 50 51class ReplicaConfigError (ValueError ): 52pass 53 54 55def gpu_groups (cfg :dict )-> list [list [int ]]: 56"""The cards of each replica, from the config's "replicas" (see the module doc); [] when there are none or one.""" 57spec = cfg .get ("replicas" ) 58if spec is None or spec is False : 59return [] 60cards = _cards (cfg .get ("gpu" )) 61if isinstance (spec ,bool )or (not isinstance (spec , (int ,list ))): 62raise ReplicaConfigError (f'"replicas" must be a number or a list of {{"gpus": [...]}}, not { spec !r } ' ) 63if isinstance (spec ,int ): 64if spec <= 1 : 65return [] 66if not cards : 67raise ReplicaConfigError (f'"replicas": { spec } needs the "gpu" list to cut into groups (e.g. "gpu": [0, 1, 2, 3])' ) 68if len (cards )% spec : 69raise ReplicaConfigError (f'"replicas": { spec } does not divide the { len ( cards ) } cards { cards } evenly: name the ' 70f'groups ("replicas": [{{"gpus": [0, 1]}}, ...]) or change the count' ) 71n = len (cards )// spec 72return [cards [i * n :(i + 1 )* n ]for i in range (spec )] 73groups = [] 74for e in spec : 75g = e .get ("gpus" )if isinstance (e ,dict )else e 76groups .append (_cards (g )) 77if any (not g for g in groups ): 78raise ReplicaConfigError ('every replica needs its cards: {"gpus": [0, 1]}' ) 79flat = [c for g in groups for c in g ] 80if len (set (flat ))!= len (flat ): 81raise ReplicaConfigError (f"a card is in two replicas: { groups } " ) 82if len (groups )< 2 : 83return [] 84return groups 85 86 87def _cards (g )-> list [int ]: 88if g is None or g == "" : 89return [] 90items = g if isinstance (g , (list ,tuple ))else str (g ).split ("," ) 91try : 92return [int (str (x ).strip ())for x in items if str (x ).strip ()!= "" ] 93except ValueError : 94raise ReplicaConfigError (f"cards must be numbers, not { g !r } " )from None 95 96 97ARENA_PREFIX = "strata-replicas-" 98_MEMFDS :dict = {}# the memfds this server created: path (/proc/<pid>/fd/<n>) -> fd 99ARENA_MIN_RAM = 8 << 30 # a memfd arena: at least this much free RAM to try (the engine reserves the real size) 100ARENA_MIN_FREE = 8 << 30 # /dev/shm must have at least this much free to try (the engine reserves the real size) 101ARENA_INCOMPATIBLE = ("--mmap-experts" ,"--resident-experts" ,"--shared-expert-arena" ,"--resident-budget-gib" ) 102 103 104def _pid_alive (pid :int )-> bool : 105try : 106os .kill (pid ,0 ) 107except ProcessLookupError : 108return False 109except PermissionError : 110return True 111return True 112 113 114def sweep_stale_arenas (shm :str = "/dev/shm" ,uid :int | None = None )-> list [str ]: 115"""Remove the arena files of servers that no longer run (a killed server cannot unlink its own). A file of a living 116server, or of another user, is never touched; a mapping an engine still holds stays valid either way.""" 117if uid is None : 118uid = os .getuid ()if hasattr (os ,"getuid" )else 0 119gone = [] 120try : 121names = os .listdir (shm ) 122except OSError : 123return gone 124head = f" { ARENA_PREFIX } { uid } -" 125for n in names : 126if not (n .startswith (head )and n .endswith (".bin" )): 127continue 128try : 129pid = int (n [len (head ):- 4 ]) 130except ValueError : 131continue 132if _pid_alive (pid ): 133continue 134try : 135os .unlink (os .path .join (shm ,n )) 136gone .append (n ) 137except OSError : 138pass 139return gone 140 141 142def _free (path :str )-> int : 143try : 144st = os .statvfs (path ) 145return st .f_bavail * st .f_frsize 146except OSError : 147return 0 148 149 150def _mem_available ()-> int : 151try : 152with open ("/proc/meminfo" )as f : 153for line in f : 154if line .startswith ("MemAvailable:" ): 155return int (line .split ()[1 ])* 1024 156except (OSError ,ValueError ,IndexError ): 157pass 158return 0 159 160 161def shared_arena_plan (cfg :dict ,n_replicas :int ,* ,shm :str = "/dev/shm" ,platform :str | None = None , 162environ = None ,free_bytes = None ,use_memfd :bool | None = None )-> tuple [str | None ,str ]: 163"""(the file for --shared-expert-arena or None, a line for the log). Opt-in: "replica_shared_arena": true (or 164STRATA_REPLICA_SHARED_ARENA=1). Only on Linux (the engine's MAP_SHARED backing), for Qwen's arena (not DeepSeek, 165not the mapped or budgeted RAM modes, which have no arena), and with room in /dev/shm. The engine checks the real 166size and reserves it before it loads (a tmpfs that is too small is an error at start, not a bus error later).""" 167environ = os .environ if environ is None else environ 168platform = sys .platform if platform is None else platform 169want = cfg .get ("replica_shared_arena" ) 170if want is None : 171want = str (environ .get ("STRATA_REPLICA_SHARED_ARENA" ,"" )).strip ().lower ()in ("1" ,"true" ,"on" ,"yes" ) 172if not want or n_replicas < 2 : 173return None ,"" 174if platform .startswith ("win" ): 175# a named pagefile-backed section the engines open by name (src/core/pinned.cu); it lives while any engine holds it 176name = f"Local { chr ( 92 ) } strata-replicas- { os . getpid () } " 177return f"win: { name } " , (f"one shared expert arena for { n_replicas } replicas (a Windows section, { name } ): " 178"the experts are in RAM once" ) 179if not platform .startswith ("linux" ): 180return None ,"shared expert arena: Linux and Windows only; each replica keeps its own copy of the experts in RAM" 181args = [str (a )for a in cfg .get ("args" )or []] 182if isinstance (cfg .get ("replicas" ),list ): 183for e in cfg ["replicas" ]: 184if isinstance (e ,dict ): 185args += [str (a )for a in e .get ("args" )or []] 186if cfg .get ("arch" )== "deepseek41" or any (a in args for a in ARENA_INCOMPATIBLE ): 187return None ,"shared expert arena: this model/config has no private expert arena to share; each replica as before" 188if use_memfd is None : 189use_memfd = hasattr (os ,"memfd_create" )and str (cfg .get ("replica_shared_arena" )).lower ()!= "devshm" 190if use_memfd : 191avail = free_bytes if free_bytes is not None else _mem_available () 192if avail < ARENA_MIN_RAM : 193return None , (f"shared expert arena: only { avail / 2 ** 30 :.1f } GiB of RAM is free; each replica keeps its own " 194"copy of the experts in RAM" ) 195try : 196fd = os .memfd_create ("strata-replicas-arena" ,os .MFD_CLOEXEC ) 197except OSError : 198fd = - 1 199if fd >= 0 : 200path = f"/proc/ { os . getpid () } /fd/ { fd } " 201_MEMFDS [path ]= fd 202warn = "" 203try :# the arena once plus about 7 GB of private RAM per engine (measured); a warning, never a refusal 204from strata_control import replica_profile as _rp 205q = _rp .quant_of (cfg ) 206if q : 207need = _rp .ARENA_GB [q ]+ n_replicas * _rp .PER_REPLICA_GB 208if avail / 2 ** 30 < need + 4 : 209warn = (f" WARNING: about { need :.0f } GB are needed for { n_replicas } engines and { avail / 2 ** 30 :.0f } GB " 210"are free: the last engine may not fit (fewer replicas, or the layer split, is safer)" ) 211except Exception :# noqa: BLE001 212pass 213return path , (f"one shared expert arena for { n_replicas } replicas (memory object of the server, not limited by " 214f"the size of /dev/shm): the experts are in RAM once. { warn } " ) 215if not (os .path .isdir (shm )and os .access (shm ,os .W_OK )): 216return None ,f"shared expert arena: { shm } is not usable; each replica keeps its own copy of the experts in RAM" 217free = free_bytes if free_bytes is not None else _free (shm ) 218if free < ARENA_MIN_FREE : 219return None , (f"shared expert arena: { shm } has only { free / 2 ** 30 :.1f } GiB free (a tmpfs is half the RAM by " 220"default); each replica keeps its own copy of the experts in RAM" ) 221sweep_stale_arenas (shm ) 222uid = os .getuid ()if hasattr (os ,"getuid" )else 0 223path = os .path .join (shm ,f" { ARENA_PREFIX } { uid } - { os . getpid () } .bin" ) 224return path ,f"one shared expert arena for { n_replicas } replicas ( { path } ): the experts are in RAM once" 225 226 227def remove_arena (path :str | None )-> None : 228"""Close the memfd / unlink the arena file (the server's end, or a start that fell back): engines that map it keep 229their pages.""" 230if not path or path .startswith ("win:" ):# (a Windows section goes with its last handle) 231return 232fd = _MEMFDS .pop (path ,None ) 233if fd is not None : 234try : 235os .close (fd ) 236except OSError : 237pass 238return 239try : 240os .unlink (path ) 241except OSError : 242pass 243 244 245def _suffixed (path ,i :int ): 246if not isinstance (path ,str )or not path : 247return path 248root ,ext = os .path .splitext (path ) 249return f" { root } .r { i } { ext } " 250 251 252def replica_cfg (cfg :dict ,i :int ,gpus :list [int ])-> dict : 253"""The config of replica i: its own cards, log and learned-profile file; the entry's "env" and "args" added.""" 254c = copy .deepcopy (cfg ) 255spec = cfg .get ("replicas" ) 256entry = spec [i ]if isinstance (spec ,list )and isinstance (spec [i ],dict )else {} 257c .pop ("replicas" ,None ) 258c ["gpu" ]= gpus if len (gpus )> 1 else gpus [0 ] 259c .pop ("hip_ordinal" ,None )# a one-card config's Windows ordinal: not for a group 260c ["log" ]= _suffixed (cfg .get ("log" ),i ) 261if cfg .get ("expert_profile_save" ): 262c ["expert_profile_save" ]= _suffixed (cfg ["expert_profile_save" ],i ) 263if entry .get ("env" ): 264c ["env" ]= {** (c .get ("env" )or {}),** {str (k ):str (v )for k ,v in entry ["env" ].items ()}} 265if entry .get ("args" ): 266c ["args" ]= list (c ["args" ])+ [str (x )for x in entry ["args" ]] 267return c 268 269 270def cpu_sets (n :int ,enabled :bool = True ): 271"""n disjoint sets of CPUs (whole physical cores, SMT siblings together), or None (off, not Linux, or the topology 272cannot be read: the engines then share the cores as they would without replicas).""" 273if not enabled or n < 2 or not hasattr (os ,"sched_getaffinity" ): 274return None 275try : 276from serve .cpu_affinity import partition_cpu_sets 277return partition_cpu_sets (n ,set (os .sched_getaffinity (0 ))) 278except (ValueError ,OSError ,ImportError )as e : 279f"[strata] replicas: no separate CPU cores ( { e } )" ,flush = True ) 280return None 281 282 283class Router : 284"""Which replica holds the start of a prompt: chained hashes of its 64-token blocks, each with the set of replicas 285that served it (a bit mask).""" 286 287def __init__ (self ,n :int ,cap :int = INDEX_MAX ): 288self .n ,self .cap = n ,cap 289self .blocks :collections .OrderedDict [int ,int ]= collections .OrderedDict () 290self .lock = threading .Lock () 291 292@staticmethod 293def chain (ids )-> list [int ]: 294out ,h = [],0 295for k in range (len (ids )// BLOCK ): 296h = hash ((h ,tuple (ids [k * BLOCK :(k + 1 )* BLOCK ]))) 297out .append (h ) 298return out 299 300def matched (self ,ids )-> list [int ]: 301"""Per replica: how many leading tokens of `ids` it holds (a multiple of BLOCK).""" 302got = [0 ]* self .n 303alive = (1 << self .n )- 1 304with self .lock : 305for k ,h in enumerate (self .chain (ids )): 306m = self .blocks .get (h ,0 )& alive 307if not m : 308break 309alive = m 310for r in range (self .n ): 311if m >> r & 1 : 312got [r ]= (k + 1 )* BLOCK 313return got 314 315def note (self ,r :int ,ids )-> None : 316with self .lock : 317for h in self .chain (ids ): 318self .blocks [h ]= self .blocks .pop (h ,0 )| (1 << r ) 319while len (self .blocks )> self .cap : 320self .blocks .popitem (last = False ) 321 322def forget (self ,r :int )-> None : 323"""Replica r lost its cache (it restarted).""" 324with self .lock : 325bit = ~ (1 << r ) 326for h in [h for h ,m in self .blocks .items ()if m >> r & 1 ]: 327m = self .blocks [h ]& bit 328if m : 329self .blocks [h ]= m 330else : 331del self .blocks [h ] 332 333 334class ReplicaEngine : 335"""Stands in for one engine (the interface Service uses), over several.""" 336 337NOT_HERE = {"session_file" ,"vram" ,"ctl" ,"slot_cv" }# not offered: one conversation file / VRAM resize / control line 338PROPAGATE = {"silence_s" ,"gpu_busy" } 339 340def __init__ (self ,engines :list ,load_tokens :int = LOAD_TOKENS ): 341if len (engines )< 2 : 342raise ValueError ("ReplicaEngine needs two or more engines" ) 343d = self .__dict__ 344d ["engines" ]= list (engines ) 345d ["router" ]= Router (len (engines )) 346d ["load_tokens" ]= load_tokens 347d ["inflight" ]= [0 ]* len (engines ) 348d ["run_locks" ]= [threading .Lock ()for _ in engines ]# an engine without batch slots: one request at a time 349d ["lock" ]= threading .Lock () 350d ["tl" ]= threading .local () 351d ["healing" ]= {} 352d ["heal_at" ]= [0.0 ]* len (engines ) 353d ["routed" ]= [0 ]* len (engines ) 354d ["gen_seen" ]= [getattr (e ,"gen" ,0 )for e in engines ] 355 356# ---- attribute plumbing 357@property 358def current (self ): 359return getattr (self .tl ,"cur" ,None )or self .engines [0 ] 360 361def __getattr__ (self ,name ): 362if name in self .NOT_HERE or name .startswith ("__" ): 363raise AttributeError (name ) 364return getattr (self .current ,name ) 365 366def __setattr__ (self ,name ,value ): 367if name in self .PROPAGATE : 368for e in self .engines : 369setattr (e ,name ,value ) 370else : 371self .__dict__ [name ]= value 372 373@property 374def last (self ): 375"""The DONE figures of the calling thread's own request (#2892). An unbatched engine has one shared `last` 376that the next request overwrites the moment the replica's lock is free, so generate() copies the figures of 377this caller's DONE while it still owns the replica; until the thread has had one, the engine's own object.""" 378tl = self .tl 379if not hasattr (tl ,"last" ): 380tl .last = self .current .last 381return tl .last 382 383@ last . setter 384def last (self ,value ): 385self .current .last = value 386self .tl .last = value 387 388@property 389def batch (self )-> int : 390"""Parallel slots, in total: the Service lets this many requests run at once (it holds no FIFO). An engine 391without slots counts one.""" 392return sum (max (1 ,int (getattr (e ,"batch" ,0 )or 0 ))for e in self .engines ) 393 394@property 395def waiting (self )-> int : 396return sum (int (getattr (e ,"waiting" ,0 )or 0 )for e in self .engines ) 397 398@property 399def max_context (self )-> int : 400v = [e .max_context for e in self .engines if getattr (e ,"max_context" ,0 )and e .alive ()] 401return min (v )if v else 0 402 403@property 404def known_ctx (self )-> int : 405v = [getattr (e ,"known_ctx" ,0 )for e in self .engines ] 406return min (x for x in v if x )if any (v )else 0 407 408@property 409def unloaded (self )-> bool : 410return all (getattr (e ,"unloaded" ,False )for e in self .engines ) 411 412@property 413def starting (self )-> bool : 414return not self .alive ()and any (getattr (e ,"starting" ,False )for e in self .engines ) 415 416@property 417def info (self )-> dict : 418i = dict (self .engines [0 ].info ) 419i ["replicas" ]= len (self .engines ) 420i ["replicas_alive" ]= sum (1 for e in self .engines if e .alive ()) 421return i 422 423@ info . setter 424def info (self ,value ): 425pass 426 427@property 428def spawn (self ): 429return self .engines [0 ].spawn 430 431@property 432def log_path (self ): 433return self .engines [0 ].log_path 434 435@property 436def progress (self ): 437c = getattr (self .tl ,"cur" ,None ) 438if c is not None : 439return c .progress 440return next ((e .progress for e in self .engines if getattr (e ,"progress" ,None )),None ) 441 442@property 443def prefill_tok_s_mean (self ): 444c = getattr (self .tl ,"cur" ,None ) 445if c is not None : 446return c .prefill_tok_s_mean 447return next ((e .prefill_tok_s_mean for e in self .engines if getattr (e ,"prefill_tok_s_mean" ,None )),None ) 448 449def alive (self )-> bool : 450return any (e .alive ()for e in self .engines ) 451 452def exit_code (self ): 453return next ((c for c in (e .exit_code ()for e in self .engines if not e .alive ())if c is not None ),None ) 454 455def death_note (self )-> str : 456return next ((e .death_note ()for e in self .engines if not e .alive ()),"" ) 457 458def slots_view (self )-> list [dict ]: 459out ,base = [],0 460for k ,e in enumerate (self .engines ): 461n = int (getattr (e ,"batch" ,0 )or 0 ) 462view = e .slots_view ()if n and hasattr (e ,"slots_view" )else \ 463 [{"slot" :0 ,"state" :"busy" if self .inflight [k ]else "idle" ,"held_tokens" :0 }] 464for s in view : 465out .append ({** s ,"slot" :base + s ["slot" ],"replica" :k }) 466base += max (1 ,n ) 467return out 468 469def replica_view (self )-> list [dict ]: 470"""For /metrics: each replica's state, requests running, and requests routed to it so far.""" 471return [{"replica" :k ,"alive" :e .alive (),"running" :self .inflight [k ],"routed" :self .routed [k ], 472"batch" :int (getattr (e ,"batch" ,0 )or 0 )}for k ,e in enumerate (self .engines )] 473 474# ---- life cycle 475def restart (self ,tries :int = 3 ): 476dead = [k for k ,e in enumerate (self .engines )if not e .alive ()] 477errors :dict [int ,BaseException ]= {} 478 479def one (k ): 480try : 481self .engines [k ].restart (tries ) 482self .router .forget (k ) 483except BaseException as e :# noqa: BLE001 484errors [k ]= e 485ts = [threading .Thread (target = one ,args = (k ,),daemon = True )for k in dead ] 486for t in ts : 487t .start () 488for t in ts : 489t .join () 490if errors and not self .alive (): 491raise next (iter (errors .values ())) 492for k ,e in errors .items (): 493f"[strata] replica { k } did not start ( { e } ); the others serve" ,flush = True ) 494 495def unload (self ): 496for e in self .engines : 497e .unload () 498for k in range (len (self .engines )): 499self .router .forget (k ) 500 501def close (self ): 502err = None 503for e in self .engines : 504try : 505e .close () 506except BaseException as x :# noqa: BLE001 507err = err or x 508remove_arena (self .__dict__ .get ("arena_file" ))# (an engine that still maps it keeps its pages) 509if err : 510raise err 511 512# ---- routing 513def route (self ,ids )-> int : 514"""The replica for this prompt (and its running count raised): lowest cost among the living ones.""" 515got = self .router .matched (ids ) 516with self .lock : 517alive = [k for k ,e in enumerate (self .engines )if e .alive ()] 518if not alive : 519return - 1 520cost = {k : (len (ids )- got [k ])+ self .load_tokens * self .inflight [k ]for k in alive } 521# the least loaded wins a tie of cost (equal cards, nothing cached): spread, do not pile on replica 0 522k = min (alive ,key = lambda k : (cost [k ],self .inflight [k ],self .routed [k ])) 523self .inflight [k ]+= 1 524self .routed [k ]+= 1 525if len (alive )< len (self .engines ): 526self .heal () 527return k 528 529def heal (self )-> None : 530"""Start a replica that died again, in the background (the others keep serving).""" 531now = time .monotonic () 532for k ,e in enumerate (self .engines ): 533if e .alive ()or getattr (e ,"unloaded" ,False )or getattr (e ,"starting" ,False )or self .healing .get (k ): 534continue 535if now < self .heal_at [k ]: 536continue 537self .heal_at [k ]= now + HEAL_COOLDOWN_S 538self .healing [k ]= True 539 540def run (k = k ): 541try : 542f"[strata] replica { k } had stopped; starting it again" ,flush = True ) 543self .engines [k ].restart () 544self .router .forget (k ) 545f"[strata] replica { k } is running again" ,flush = True ) 546except BaseException as x :# noqa: BLE001 547f"[strata] replica { k } did not start again: { x } " ,flush = True ) 548finally : 549self .healing [k ]= False 550threading .Thread (target = run ,daemon = True ).start () 551 552def generate (self ,ids ,max_new ,sampling ,cancel ,embeddings = None ): 553# imported here: serve.server imports this module 554from serve .server import EngineDied ,EngineNonFinite 555k = self .route (ids ) 556if k < 0 : 557raise EngineDied ("no replica is running; this request was not sent" ) 558e = self .engines [k ] 559self .tl .cur = e 560_ = self .last # the caller's figures exist before this request (#2892) 561produced :list [int ]= [] 562held = False 563gen = None 564native_before = None 565nonfinite = False 566try : 567selected = getattr (cancel ,"_strata_replica_selected" ,None ) 568if selected is not None : 569selected (k ) 570self .router .note (k ,ids ) 571if not int (getattr (e ,"batch" ,0 )or 0 ):# no slots: this replica takes one request at a time 572lock = self .run_locks [k ] 573while not lock .acquire (timeout = 0.25 ): 574if cancel is not None and cancel .is_set (): 575return 576held = True 577native_before = e .last 578if embeddings is not None : 579gen = e .generate (ids ,max_new ,sampling ,cancel ,embeddings = embeddings ) 580else : 581gen = e .generate (ids ,max_new ,sampling ,cancel ) 582for t in gen : 583if t is not None : 584produced .append (t ) 585yield t 586except EngineNonFinite : 587nonfinite = True 588raise 589finally : 590# #2892: the replica's pipe belongs to this request until its native exchange is over. The child 591# generator sends STOP and reads to its DONE when it is closed; that has to happen HERE, before the lock is 592# given back - left to the garbage collector it ran after the next request had sent its GEN, and the two 593# read each other's tokens and DONE. A close that fails (the engine never answered its STOP) ends the 594# replica: it is not handed on (heal() starts it again), and the error is not lost. 595try : 596if gen is not None : 597try : 598gen .close () 599except BaseException :# noqa: BLE001 - the pipe cannot be trusted any more 600self .quarantine (k ) 601raise 602finally : 603try : 604# the figures of the DONE this caller's request read, copied while it still owns the replica; with 605# no new DONE the caller's earlier object stays, so Service does not record an old result as new 606if gen is not None and e .last is not native_before : 607self .tl .last = dict (e .last ) 608finally : 609if held : 610self .run_locks [k ].release () 611with self .lock : 612self .inflight [k ]-= 1 613if nonfinite :# #879: the engine dropped every cached conversation 614self .router .forget (k ) 615elif produced : 616self .router .note (k ,list (ids )+ produced ) 617 618def quarantine (self ,k :int )-> None : 619"""A replica whose pipe could not be drained is out of the routing until it has been started again: its process 620is ended (nothing it still prints can reach a later request) and heal() restarts it.""" 621e = self .engines [k ] 622try : 623e .ended = True 624except AttributeError : 625pass 626proc = getattr (e ,"proc" ,None ) 627try : 628if proc is not None and proc .poll ()is None : 629proc .kill () 630except (OSError ,AttributeError ,ValueError ): 631pass 632self .router .forget (k )