okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
2503b206b
main
1"""Running one engine configuration and measuring it, for the tuner. 2 3A *session* is what the tuner needs from the outside world: start an engine with these arguments and environment, run the 4fixed request set, report numbers, stop. The real session (`WorkerSession`) starts Strata's own worker (``serve.server``) 5on a **copy** of the user's run configuration and talks to it over HTTP, so the engine, the queueing and the prompt 6handling are exactly the ones the user gets. The numbers come from the engine's own clock (the ``timings`` block of the 7reply), not from this process's stopwatch. The stub session in the tests implements the same two methods. 8 9Never invents a number: an engine that does not start, answers nothing or answers too little raises `StartFailed` or 10returns a result whose ``status`` says why, and the tuner records that as the candidate's result. 11""" 12 13from __future__import annotations 14 15import contextlib 16import json 17import os 18import random 19import re 20import secrets 21import socket 22import statistics 23import subprocess 24import sys 25import tempfile 26import threading 27import time 28import urllib .error 29import urllib .request 30from dataclasses import dataclass ,field 31from pathlib import Path 32from typing import Any ,Callable ,Iterator ,Protocol 33 34from strata_control import loopback ,tune_machine 35from strata_control .childenv import quiet_crash_env 36 37# --------------------------------------------------------------------------- the contract 38 39 40class StartFailed (RuntimeError ): 41"""The engine did not come up. ``status``: FAIL_BOOT | OOM | UNSUPPORTED | TIMEOUT.""" 42 43def __init__ (self ,status :str ,reason :str )-> None : 44super ().__init__ (reason ) 45self .status = status 46self .reason = reason 47 48 49@dataclass 50class RequestSet : 51"""The fixed work every run does, so two configurations are compared on the same requests.""" 52 53warmups :int = 1 54decodes :int = 3 55decode_tokens :int = 200 56pp_tokens :int = 4096 57long_tokens :int = 0 # 0 = no long prompt 58 59 60@dataclass 61class RunResult : 62status :str = "PASS" # PASS | FAIL_BOOT | OOM | UNSUPPORTED | TIMEOUT | NO_TOKENS 63reason :str = "" 64load_s :float | None = None 65decode_tok_s :float | None = None # median of the measured decodes 66decode_runs :list [float ]= field (default_factory = list ) 67pp_tok_s :float | None = None # the warm prompt (the second one; the first is cold) 68pp_cold_tok_s :float | None = None 69ttft_s :float | None = None 70pp_long_tok_s :float | None = None 71rss_peak_mib :float | None = None 72vram_used_mib :float | None = None # this run's total graphics memory in use (all cards, absolute) 73vram_added_mib :float | None = None # ... minus what was in use before the engine started 74min_avail_mib :float | None = None # lowest free system RAM seen while the engine ran 75facts :dict [str ,Any ]= field (default_factory = dict ) 76wall_s :float = 0.0 77 78def to_dict (self )-> dict [str ,Any ]: 79return dict (self .__dict__ ) 80 81 82class Engine (Protocol ): 83facts :dict [str ,Any ] 84 85def measure (self ,spec :RequestSet )-> RunResult : ... 86 87def decode_once (self ,tune :dict [str ,Any ]| None = None ,tokens :int = 200 )-> float | None : ... 88 89 90class Session (Protocol ): 91def engine (self ,args :list [str ],env :dict [str ,str | None ],pre_start :Callable [[],None ]| None = None )-> contextlib .AbstractContextManager [Engine ]: ... 92 93def system (self )-> dict [str ,Any ]: ... 94 95 96# --------------------------------------------------------------------------- the engine log 97 98_FACTS = [ 99 ("slots" ,re .compile (r"expert cache (\d+) slots" ),int ), 100 ("workers" ,re .compile (r"(\d+) (?:expert-)?pool workers" ),int ), 101 ("cpu_threads" ,re .compile (r"(\d+) CPU threads" ),int ), 102 ("pcie_gbs" ,re .compile (r"PCIe probe: ([\d.]+) GB/s" ),float ), 103 ("pcie_frac" ,re .compile (r"-> pcie_frac ([\d.]+)" ),float ), 104 ("chunk" ,re .compile (r"prompt chunk auto: (\d+) tokens" ),int ), 105 ("avail_gib" ,re .compile (r"available ([\d.]+) GiB \(MemAvailable" ),float ), 106 ("loaded_gib" ,re .compile (r"loaded ([\d.]+) GiB at" ),float ), 107] 108 109 110def parse_facts (text :str )-> dict [str ,Any ]: 111"""What the engine's own log says about the setup it chose (the last value of each fact wins).""" 112facts :dict [str ,Any ]= {} 113for key ,rx ,cast in _FACTS : 114found = rx .findall (text ) 115if found : 116try : 117facts [key ]= cast (found [- 1 ]) 118except ValueError : 119pass 120if "workers" not in facts and "cpu_threads" in facts : 121facts ["workers" ]= facts ["cpu_threads" ] 122low = text .lower () 123# the engine's low-RAM resident mode (--resident-experts) says so in its log; "resident experts" alone is the GPU cache's own wording 124facts ["resident_ram" ]= bool (re .search (r"resident ram mode|resident complement|resident [\d.]+ gib, pinned|low-ram mode" ,low )) 125facts ["hybrid_experts" ]= "hybrid experts" in low or "hybrid:" in low 126facts ["unknown_argument" ]= bool (re .search (r"unknown argument|unrecognized (?:argument|option)" ,low )) 127return facts 128 129 130_CUDA_BUSY = re .compile (r"failed to initialize cuda|no cuda-capable device|cuda-capable device\(s\) is/are busy|" 131r"cuda driver version is insufficient|hipinit.{0,40}(?:fail|error)|no hip-capable device" ,re .I ) 132 133 134_NATIVE_ERROR = re .compile (r"out of memory|cuda(?:malloc|error)|hip(?:malloc|error)|cublas|ze_result|std::bad_alloc|terminate called|assert|abort|" 135r"segmentation|fatal|failed|error" ,re .I ) 136_NATIVE_OOM = re .compile (r"out of memory|cudamalloc|hipmalloc|bad_alloc|cannot allocate" ,re .I ) 137 138 139def native_failure (text :str )-> str : 140"""The engine's own last error line(s) from its log (the first native failure is what a person needs; a generic 503 from the worker hides it, #5078). 141The engine's informational `memory guard: limit ... available ...` line is not an error. Empty when the log says nothing.""" 142lines = [ln .strip ()for ln in text .splitlines () 143if _NATIVE_ERROR .search (ln )and not re .search (r"memory guard: (?:limit|the available)" ,ln ,re .I )] 144return " | " .join (lines [- 2 :])[:300 ] 145 146 147def failure_kind (text :str ,returncode :int | None )-> tuple [str ,str ]: 148"""Classify an engine that ended before it was ready: (status, one plain line). The engine's informational 149`memory guard: limit ... available ...` line is not a failure and never decides the status (#3502).""" 150low = text .lower () 151lines = [ln .strip ()for ln in text .splitlines () 152if re .search (r"unknown argument|unrecognized|invalid value|out of memory|cannot|failed|error|refus|killed" ,ln ,re .I ) 153and not re .search (r"memory guard: (?:limit|the available)" ,ln ,re .I )] 154reason = " | " .join (lines [:3 ])[:300 ] 155if re .search (r"unknown argument|unrecognized (argument|option)" ,low ): 156return "UNSUPPORTED" ,reason or "the engine does not accept one of the settings" 157if _CUDA_BUSY .search (text ): 158return "FAIL_BOOT" , ("the graphics card could not be opened by the measuring engine; it is probably in use by the " 159"loaded model. Unload the model and tune again (" + reason + ")" )[:400 ] 160if re .search (r"out of memory|memory guard: (?:refus|not enough|too)|cannot allocate|std::bad_alloc|\boom\b|(?:^|\n)killed(?:\r?\n|$)" ,low )or returncode in (- 9 ,137 ,3221226505 ): 161return "OOM" ,reason or "the engine ran out of memory" 162return "FAIL_BOOT" ,reason or f"the engine stopped while starting (exit { returncode } )" 163 164 165# --------------------------------------------------------------------------- prompts 166 167_SENTENCES = ( 168"The harbour town woke slowly, with fishing boats knocking against the wooden piers." , 169"A small team measured how long each step of the process took and wrote the numbers in a notebook." , 170"Rain fell on the old railway station while a clerk sorted letters by hand." , 171"The recipe asked for two cups of flour, a pinch of salt and patience." , 172"In the library, a quiet reader turned pages while the clock in the hall struck three." , 173"Engineers compared the two bridges and noted how each handled wind and weight." , 174"The orchard produced more apples than the village could eat, so the surplus went to the city market." , 175"She packed a map, a flask of tea and a spare pair of boots for the long walk north." , 176"Each morning the baker lit the oven before dawn and left the shop door unlocked for the milkman." , 177"A careful gardener keeps a record of when each seed is planted and when it first sprouts." , 178"The museum's new wing displayed instruments that once guided ships across open water." , 179"Traffic slowed near the tunnel entrance, and the radio suggested taking the coast road instead." , 180"Two neighbours argued kindly over whose tomato plants had grown taller that summer." , 181"The orchestra tuned together, a single note spreading through the hall until the conductor raised a hand." , 182"He wrote down every question he had about the machine before opening its case." , 183"A river of lanterns floated past the bridge as the festival reached its final evening." , 184) 185 186 187def make_prompt (tokens :int ,salt :str ,chars_per_token :float = 4.4 )-> str : 188"""A prompt of about ``tokens`` tokens that no earlier run has seen: its first line is the salt, so a cached prefix is 189never reused, and the rest is shuffled prose.""" 190rng = random .Random (salt ) 191target = int (tokens * chars_per_token ) 192parts = [f"Reference { salt } ." ] 193size = len (parts [0 ]) 194while size < target : 195s = rng .choice (_SENTENCES ) 196parts .append (s ) 197size += len (s )+ 1 198parts .append ("Now answer in one short sentence: what is the main subject of the text above?" ) 199return " " .join (parts ) 200 201 202DECODE_PROMPTS = ( 203"Write a long, detailed story about a lighthouse keeper who finds a message in a bottle. Keep going without stopping." , 204"Explain step by step how a bicycle works, covering the frame, wheels, gears, chain and brakes in depth." , 205) 206 207 208# --------------------------------------------------------------------------- a flock for the box locks 209 210class FileLock : 211"""An exclusive advisory lock on a file, held around each engine run (the lent boxes' /data/gpu.lock rule).""" 212 213def __init__ (self ,path :str | os .PathLike [str ],wait_s :float = 5400.0 ,log :Callable [[str ],None ]= lambda s :None )-> None : 214self .path = str (path ) 215self .wait_s = wait_s 216self .log = log 217self ._fh = None 218 219def __enter__ (self )-> "FileLock" : 220Path (self .path ).parent .mkdir (parents = True ,exist_ok = True ) 221self ._fh = open (self .path ,"a+" ) 222if os .name != "nt" and threading .current_thread ()is threading .main_thread (): 223return self ._blocking () 224return self ._polling () 225 226def _blocking (self )-> "FileLock" : 227"""A blocking flock(2), queued in the kernel like `flock -x` (so the other streams' waiters are served in order and 228a polling tuner is not starved). The wait limit is a timer, not a loop.""" 229import fcntl 230import signal 231 232def on_alarm (signum ,frame ):# noqa: ANN001 233raise TimeoutError 234 235try : 236fcntl .flock (self ._fh .fileno (),fcntl .LOCK_EX | fcntl .LOCK_NB ) 237return self 238except OSError : 239self .log (f"waiting for the lock { self . path } " ) 240old = signal .signal (signal .SIGALRM ,on_alarm ) 241signal .setitimer (signal .ITIMER_REAL ,self .wait_s ) 242try : 243fcntl .flock (self ._fh .fileno (),fcntl .LOCK_EX ) 244return self 245except TimeoutError : 246self ._fh .close () 247raise StartFailed ("TIMEOUT" ,f"the lock { self . path } was not free within { int ( self . wait_s ) } s" )from None 248finally : 249signal .setitimer (signal .ITIMER_REAL ,0 ) 250signal .signal (signal .SIGALRM ,old ) 251 252def _polling (self )-> "FileLock" : 253deadline = time .time ()+ self .wait_s 254told = False 255while True : 256try : 257if os .name == "nt" : 258import msvcrt 259self ._fh .seek (0 ) 260msvcrt .locking (self ._fh .fileno (),msvcrt .LK_NBLCK ,1 ) 261else : 262import fcntl 263fcntl .flock (self ._fh .fileno (),fcntl .LOCK_EX | fcntl .LOCK_NB ) 264return self 265except OSError : 266if time .time ()> deadline : 267self ._fh .close () 268raise StartFailed ("TIMEOUT" ,f"the lock { self . path } was not free within { int ( self . wait_s ) } s" ) 269if not told : 270self .log (f"waiting for the lock { self . path } " ) 271told = True 272time .sleep (2.0 ) 273 274def __exit__ (self ,* exc :object )-> None : 275try : 276if os .name == "nt" : 277import msvcrt 278self ._fh .seek (0 ) 279msvcrt .locking (self ._fh .fileno (),msvcrt .LK_UNLCK ,1 ) 280else : 281import fcntl 282fcntl .flock (self ._fh .fileno (),fcntl .LOCK_UN ) 283except OSError : 284pass 285finally : 286if self ._fh : 287self ._fh .close () 288 289 290# --------------------------------------------------------------------------- the real session 291 292def _free_port ()-> int : 293with socket .socket ()as s : 294s .bind (("127.0.0.1" ,0 )) 295return s .getsockname ()[1 ] 296 297 298class WorkerEngine : 299"""One running worker and the requests that measure it.""" 300 301def __init__ (self ,session :"WorkerSession" ,proc :subprocess .Popen ,port :int ,key :str ,log_files :list [Path ], 302load_s :float ,vram_before :int | None ,log :Callable [[str ],None ])-> None : 303self .s = session 304self .proc = proc 305self .port = port 306self .key = key 307self .log_files = log_files 308self .load_s = load_s 309self .vram_before = vram_before 310self .log = log 311self .model = "strata-local" 312self .min_avail :float | None = None 313self .facts :dict [str ,Any ]= parse_facts (self .log_text ()) 314self .salt_n = 0 315self ._model_id () 316 317# ---- helpers 318def log_text (self )-> str : 319out = [] 320for f in self .log_files : 321try : 322out .append (f .read_text (encoding = "utf-8" ,errors = "replace" )) 323except OSError : 324pass 325return "\n" .join (out ) 326 327def _model_id (self )-> None : 328try : 329req = urllib .request .Request (f"http://127.0.0.1: { self . port } /v1/models" ,headers = self ._h ()) 330with loopback .urlopen (req ,timeout = 10 )as r : 331data = json .loads (r .read ()) 332self .model = ((data .get ("data" )or [{}])[0 ]).get ("id" )or self .model 333except Exception :# noqa: BLE001 334pass 335 336def _h (self )-> dict [str ,str ]: 337return {"content-type" :"application/json" ,"authorization" :f"Bearer { self . key } " } 338 339def _sample_mem (self )-> None : 340a = tune_machine .memory ().get ("available_mib" ) 341if a is not None : 342self .min_avail = a if self .min_avail is None else min (self .min_avail ,a ) 343 344def chat (self ,prompt :str ,max_tokens :int ,tune :dict [str ,Any ]| None = None ,timeout :float = 1800.0 )-> dict [str ,Any ]: 345body :dict [str ,Any ]= {"model" :self .model ,"stream" :False ,"max_tokens" :max_tokens ,"temperature" :0.0 , 346"messages" : [{"role" :"user" ,"content" :prompt }],"strata_checkpoint" :False } 347if tune : 348body ["strata_tune" ]= tune 349req = urllib .request .Request (f"http://127.0.0.1: { self . port } /v1/chat/completions" , 350data = json .dumps (body ).encode (),headers = self ._h (),method = "POST" ) 351try : 352with loopback .urlopen (req ,timeout = timeout )as r : 353data = json .loads (r .read ()) 354except urllib .error .HTTPError as e : 355reason = f"the worker refused the request ( { e . code } ): { e . read ()[: 200 ]!r } " 356status = "NO_TOKENS" 357if e .code >= 500 :# the engine stopped under this request: its own last error line is the cause, and an allocation failure is an OOM (#5078) 358native = native_failure (self .log_text ()[- 8000 :]) 359if native : 360reason += f" | engine: { native } " 361if _NATIVE_OOM .search (native ): 362status = "OOM" 363raise StartFailed (status ,reason )from None 364except (urllib .error .URLError ,OSError ,ValueError )as e : 365code = self .proc .poll () 366status ,why = failure_kind (self .log_text ()[- 4000 :],code )if code is not None else ("TIMEOUT" ,str (e )) 367raise StartFailed (status ,f"the engine did not answer: { why } " )from None 368self ._sample_mem () 369return data 370 371# ---- measurements 372def decode_once (self ,tune :dict [str ,Any ]| None = None ,tokens :int = 200 )-> float | None : 373for prompt in DECODE_PROMPTS : 374data = self .chat (prompt ,tokens ,tune ) 375t = data .get ("timings" )or {} 376n ,rate = t .get ("predicted_n" ),t .get ("predicted_per_second" ) 377if n and rate and n >= max (32 ,tokens // 2 ): 378return float (rate ) 379return None 380 381def prompt_once (self ,tokens :int )-> dict [str ,float | None ]: 382self .salt_n += 1 383salt = secrets .token_hex (6 ) 384text = make_prompt (tokens ,salt ,self .s .chars_per_token ) 385data = self .chat (text ,8 ) 386t = data .get ("timings" )or {} 387usage = data .get ("usage" )or {} 388pt = usage .get ("prompt_tokens" ) 389if isinstance (pt ,int )and pt > 64 and not self .s .calibrated : 390self .s .chars_per_token = max (2.0 ,min (8.0 ,self .s .chars_per_token * tokens / pt )) 391self .s .calibrated = True 392rate = t .get ("prompt_per_second" ) 393# a prompt that was partly cached is not a prompt-speed measurement 394if t .get ("cache_n" )and t .get ("prompt_n" )and t ["cache_n" ]> 0.1 * (t ["prompt_n" ]+ t ["cache_n" ]): 395rate = None 396ms = t .get ("prompt_ms" ) 397return {"rate" :float (rate )if rate else None ,"ttft_s" :float (ms )/ 1000.0 if ms else None , 398"tokens" :pt if isinstance (pt ,int )else None } 399 400def measure (self ,spec :RequestSet )-> RunResult : 401t0 = time .time () 402res = RunResult (load_s = self .load_s ,facts = dict (self .facts )) 403for _ in range (spec .warmups ): 404self .decode_once (None ,64 ) 405runs :list [float ]= [] 406for _ in range (spec .decodes ): 407r = self .decode_once (None ,spec .decode_tokens ) 408if r : 409runs .append (r ) 410res .decode_runs = [round (x ,3 )for x in runs ] 411if not runs : 412res .status ,res .reason = "NO_TOKENS" ,"the engine produced no measurable decode" 413else : 414res .decode_tok_s = round (statistics .median (runs ),3 ) 415if spec .pp_tokens : 416cold = self .prompt_once (spec .pp_tokens ) 417warm = self .prompt_once (spec .pp_tokens ) 418res .pp_cold_tok_s = cold ["rate" ] 419res .pp_tok_s ,res .ttft_s = warm ["rate" ],warm ["ttft_s" ] 420if spec .long_tokens : 421res .pp_long_tok_s = self .prompt_once (spec .long_tokens )["rate" ] 422res .rss_peak_mib = tune_engine_peak (self .proc .pid ) 423used = tune_machine .gpu_used_mib () 424if used is not None : 425res .vram_used_mib = used 426if self .vram_before is not None : 427res .vram_added_mib = used - self .vram_before 428res .min_avail_mib = self .min_avail 429res .facts = dict (parse_facts (self .log_text ())) 430res .wall_s = round (time .time ()- t0 ,1 ) 431return res 432 433 434def tune_engine_peak (pid :int )-> float | None : 435try : 436from strata_control .tune_engine import process_tree_peak_mib 437return process_tree_peak_mib (pid ) 438except Exception :# noqa: BLE001 439return None 440 441 442class WorkerSession : 443"""Starts ``serve.server`` on a copy of the run configuration for each configuration the tuner asks for.""" 444 445def __init__ (self ,* ,base_config :dict [str ,Any ],python :str | os .PathLike [str ]| None = None , 446serve_dir :str | os .PathLike [str ],workdir :str | os .PathLike [str ]| None = None , 447boot_timeout_s :float = 900.0 ,lock :Callable [[],contextlib .AbstractContextManager ]| None = None , 448log :Callable [[str ],None ]= lambda s :None ,extra_env :dict [str ,str ]| None = None )-> None : 449self .base = json .loads (json .dumps (base_config )) 450self .python = str (python or sys .executable ) 451self .serve_dir = Path (serve_dir ) 452self .workdir = Path (workdir )if workdir else Path (tempfile .mkdtemp (prefix = "strata-tune-" )) 453self .workdir .mkdir (parents = True ,exist_ok = True ) 454self .boot_timeout_s = boot_timeout_s 455self .lock = lock 456self .log = log 457self .extra_env = dict (extra_env or {}) 458self .chars_per_token = 4.4 459self .calibrated = False 460self .runs = 0 461 462def system (self )-> dict [str ,Any ]: 463return {"memory" :tune_machine .memory (),"gpus" :tune_machine .gpus (),"cpu" :tune_machine .cpu ()} 464 465@ contextlib . contextmanager 466def engine (self ,args :list [str ],env :dict [str ,str | None ],pre_start :Callable [[],None ]| None = None )-> Iterator [WorkerEngine ]: 467with contextlib .ExitStack ()as stack : 468if self .lock is not None : 469stack .enter_context (self .lock ()) 470if pre_start is not None : 471pre_start ()# the memory and quiet checks run once the lock is ours, right before the start 472self .runs += 1 473n = self .runs 474cfg = json .loads (json .dumps (self .base )) 475cfg ["args" ]= list (args ) 476cenv = dict (cfg .get ("env" )or {}) 477for k ,v in env .items (): 478if v is None : 479cenv .pop (k ,None ) 480else : 481cenv [k ]= str (v ) 482cfg ["env" ]= cenv 483key = secrets .token_hex (16 ) 484port = _free_port () 485engine_log = self .workdir / f"engine- { n } .log" 486worker_log = self .workdir / f"worker- { n } .log" 487engine_log .write_text ("" ) 488cfg .update ({"api_key" :key ,"port" :port ,"host" :"127.0.0.1" ,"open_browser" :False ,"log" :str (engine_log )}) 489cfg_path = self .workdir / f"run- { n } .json" 490cfg_path .write_text (json .dumps (cfg ,indent = 1 ),encoding = "utf-8" ) 491spawn_env = quiet_crash_env (dict (os .environ ))# no debugger on a user's machine (strata_control/childenv.py) 492spawn_env .update (self .extra_env ) 493spawn_env .pop ("STRATA_API_KEY" ,None )# the server reads this variable before the config's "api_key": the worker answers only to the key made for it (#5056) 494for k ,v in env .items (): 495if v is None : 496spawn_env .pop (k ,None ) 497spawn_env ["PYTHONUNBUFFERED" ]= "1" 498spawn_env ["STRATA_NO_PRESET" ]= "1" # measure the configuration as given, not a saved tuning on top 499before = tune_machine .gpu_used_mib () 500wl = open (worker_log ,"w" ) 501argv = [self .python ,"-m" ,"serve.server" ,"--engine" ,"strata" ,"--config" ,str (cfg_path ), 502"--host" ,"127.0.0.1" ,"--port" ,str (port )] 503t0 = time .time () 504try : 505from serve import lifeline 506proc = lifeline .popen (argv ,"worker" ,cwd = str (self .serve_dir ),env = spawn_env ,stdout = wl , 507stderr = subprocess .STDOUT ) 508except OSError as e : 509wl .close () 510raise StartFailed ("FAIL_BOOT" ,f"the worker could not be started: { e } " )from None 511try : 512deadline = t0 + self .boot_timeout_s 513ready = False 514while time .time ()< deadline : 515if proc .poll ()is not None : 516text = (engine_log .read_text (errors = "replace" )if engine_log .exists ()else "" )+ "\n" + \ 517worker_log .read_text (errors = "replace" ) 518status ,why = failure_kind (text ,proc .returncode ) 519raise StartFailed (status ,why ) 520try : 521req = urllib .request .Request (f"http://127.0.0.1: { port } /health" , 522headers = {"authorization" :f"Bearer { key } " }) 523with loopback .urlopen (req ,timeout = 2 )as r : 524if r .status == 200 : 525ready = True 526break 527except (urllib .error .URLError ,OSError ): 528time .sleep (0.5 ) 529if not ready : 530raise StartFailed ("TIMEOUT" ,f"the engine was not ready within { int ( self . boot_timeout_s ) } s" ) 531eng = WorkerEngine (self ,proc ,port ,key , [engine_log ,worker_log ],time .time ()- t0 ,before ,self .log ) 532yield eng 533finally : 534try : 535if proc .poll ()is None : 536proc .terminate () 537try : 538proc .wait (timeout = 60 ) 539except subprocess .TimeoutExpired : 540proc .kill () 541proc .wait (timeout = 30 ) 542finally : 543wl .close () 544# the engine gives its graphics memory back a moment after it exits 545time .sleep (3.0 )