okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge main dbb2d168c (picture-reader fix, GGML_NO_BACKTRACE) into f-own-int2503b206b

main
25.1 KiB545 linesraw
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
43    def __init__(self, status: str, reason: str) -> None:
44        super().__init__(reason)
45        self.status = status
46        self.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
53    warmups: int = 1
54    decodes: int = 3
55    decode_tokens: int = 200
56    pp_tokens: int = 4096
57    long_tokens: int = 0              # 0 = no long prompt
58
59
60@dataclass
61class RunResult:
62    status: str = "PASS"              # PASS | FAIL_BOOT | OOM | UNSUPPORTED | TIMEOUT | NO_TOKENS
63    reason: str = ""
64    load_s: float | None = None
65    decode_tok_s: float | None = None          # median of the measured decodes
66    decode_runs: list[float] = field(default_factory=list)
67    pp_tok_s: float | None = None              # the warm prompt (the second one; the first is cold)
68    pp_cold_tok_s: float | None = None
69    ttft_s: float | None = None
70    pp_long_tok_s: float | None = None
71    rss_peak_mib: float | None = None
72    vram_used_mib: float | None = None         # this run's total graphics memory in use (all cards, absolute)
73    vram_added_mib: float | None = None        # ... minus what was in use before the engine started
74    min_avail_mib: float | None = None         # lowest free system RAM seen while the engine ran
75    facts: dict[str, Any] = field(default_factory=dict)
76    wall_s: float = 0.0
77
78    def to_dict(self) -> dict[str, Any]:
79        return dict(self.__dict__)
80
81
82class Engine(Protocol):
83    facts: dict[str, Any]
84
85    def measure(self, spec: RequestSet) -> RunResult: ...
86
87    def decode_once(self, tune: dict[str, Any] | None = None, tokens: int = 200) -> float | None: ...
88
89
90class Session(Protocol):
91    def engine(self, args: list[str], env: dict[str, str | None], pre_start: Callable[[], None] | None = None) -> contextlib.AbstractContextManager[Engine]: ...
92
93    def 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)."""
112    facts: dict[str, Any] = {}
113    for key, rx, cast in _FACTS:
114        found = rx.findall(text)
115        if found:
116            try:
117                facts[key] = cast(found[-1])
118            except ValueError:
119                pass
120    if "workers" not in facts and "cpu_threads" in facts:
121        facts["workers"] = facts["cpu_threads"]
122    low = 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
124    facts["resident_ram"] = bool(re.search(r"resident ram mode|resident complement|resident [\d.]+ gib, pinned|low-ram mode", low))
125    facts["hybrid_experts"] = "hybrid experts" in low or "hybrid:" in low
126    facts["unknown_argument"] = bool(re.search(r"unknown argument|unrecognized (?:argument|option)", low))
127    return facts
128
129
130_CUDA_BUSY = re.compile(r"failed to initialize cuda|no cuda-capable device|cuda-capable device\(s\) is/are busy|"
131                        r"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|"
135                           r"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).
141    The engine's informational `memory guard: limit ... available ...` line is not an error. Empty when the log says nothing."""
142    lines = [ln.strip() for ln in text.splitlines()
143             if _NATIVE_ERROR.search(ln) and not re.search(r"memory guard: (?:limit|the available)", ln, re.I)]
144    return " | ".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)."""
150    low = text.lower()
151    lines = [ln.strip() for ln in text.splitlines()
152             if re.search(r"unknown argument|unrecognized|invalid value|out of memory|cannot|failed|error|refus|killed", ln, re.I)
153             and not re.search(r"memory guard: (?:limit|the available)", ln, re.I)]
154    reason = " | ".join(lines[:3])[:300]
155    if re.search(r"unknown argument|unrecognized (argument|option)", low):
156        return "UNSUPPORTED", reason or "the engine does not accept one of the settings"
157    if _CUDA_BUSY.search(text):
158        return "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]
160    if 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):
161        return "OOM", reason or "the engine ran out of memory"
162    return "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
189    never reused, and the rest is shuffled prose."""
190    rng = random.Random(salt)
191    target = int(tokens * chars_per_token)
192    parts = [f"Reference {salt}."]
193    size = len(parts[0])
194    while size < target:
195        s = rng.choice(_SENTENCES)
196        parts.append(s)
197        size += len(s) + 1
198    parts.append("Now answer in one short sentence: what is the main subject of the text above?")
199    return " ".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
213    def __init__(self, path: str | os.PathLike[str], wait_s: float = 5400.0, log: Callable[[str], None] = lambda s: None) -> None:
214        self.path = str(path)
215        self.wait_s = wait_s
216        self.log = log
217        self._fh = None
218
219    def __enter__(self) -> "FileLock":
220        Path(self.path).parent.mkdir(parents=True, exist_ok=True)
221        self._fh = open(self.path, "a+")
222        if os.name != "nt" and threading.current_thread() is threading.main_thread():
223            return self._blocking()
224        return self._polling()
225
226    def _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
228        a polling tuner is not starved). The wait limit is a timer, not a loop."""
229        import fcntl
230        import signal
231
232        def on_alarm(signum, frame):  # noqa: ANN001
233            raise TimeoutError
234
235        try:
236            fcntl.flock(self._fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
237            return self
238        except OSError:
239            self.log(f"waiting for the lock {self.path}")
240        old = signal.signal(signal.SIGALRM, on_alarm)
241        signal.setitimer(signal.ITIMER_REAL, self.wait_s)
242        try:
243            fcntl.flock(self._fh.fileno(), fcntl.LOCK_EX)
244            return self
245        except TimeoutError:
246            self._fh.close()
247            raise StartFailed("TIMEOUT", f"the lock {self.path} was not free within {int(self.wait_s)} s") from None
248        finally:
249            signal.setitimer(signal.ITIMER_REAL, 0)
250            signal.signal(signal.SIGALRM, old)
251
252    def _polling(self) -> "FileLock":
253        deadline = time.time() + self.wait_s
254        told = False
255        while True:
256            try:
257                if os.name == "nt":
258                    import msvcrt
259                    self._fh.seek(0)
260                    msvcrt.locking(self._fh.fileno(), msvcrt.LK_NBLCK, 1)
261                else:
262                    import fcntl
263                    fcntl.flock(self._fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
264                return self
265            except OSError:
266                if time.time() > deadline:
267                    self._fh.close()
268                    raise StartFailed("TIMEOUT", f"the lock {self.path} was not free within {int(self.wait_s)} s")
269                if not told:
270                    self.log(f"waiting for the lock {self.path}")
271                    told = True
272                time.sleep(2.0)
273
274    def __exit__(self, *exc: object) -> None:
275        try:
276            if os.name == "nt":
277                import msvcrt
278                self._fh.seek(0)
279                msvcrt.locking(self._fh.fileno(), msvcrt.LK_UNLCK, 1)
280            else:
281                import fcntl
282                fcntl.flock(self._fh.fileno(), fcntl.LOCK_UN)
283        except OSError:
284            pass
285        finally:
286            if self._fh:
287                self._fh.close()
288
289
290# --------------------------------------------------------------------------- the real session
291
292def _free_port() -> int:
293    with socket.socket() as s:
294        s.bind(("127.0.0.1", 0))
295        return s.getsockname()[1]
296
297
298class WorkerEngine:
299    """One running worker and the requests that measure it."""
300
301    def __init__(self, session: "WorkerSession", proc: subprocess.Popen, port: int, key: str, log_files: list[Path],
302                 load_s: float, vram_before: int | None, log: Callable[[str], None]) -> None:
303        self.s = session
304        self.proc = proc
305        self.port = port
306        self.key = key
307        self.log_files = log_files
308        self.load_s = load_s
309        self.vram_before = vram_before
310        self.log = log
311        self.model = "strata-local"
312        self.min_avail: float | None = None
313        self.facts: dict[str, Any] = parse_facts(self.log_text())
314        self.salt_n = 0
315        self._model_id()
316
317    # ---- helpers
318    def log_text(self) -> str:
319        out = []
320        for f in self.log_files:
321            try:
322                out.append(f.read_text(encoding="utf-8", errors="replace"))
323            except OSError:
324                pass
325        return "\n".join(out)
326
327    def _model_id(self) -> None:
328        try:
329            req = urllib.request.Request(f"http://127.0.0.1:{self.port}/v1/models", headers=self._h())
330            with loopback.urlopen(req, timeout=10) as r:
331                data = json.loads(r.read())
332            self.model = ((data.get("data") or [{}])[0]).get("id") or self.model
333        except Exception:  # noqa: BLE001
334            pass
335
336    def _h(self) -> dict[str, str]:
337        return {"content-type": "application/json", "authorization": f"Bearer {self.key}"}
338
339    def _sample_mem(self) -> None:
340        a = tune_machine.memory().get("available_mib")
341        if a is not None:
342            self.min_avail = a if self.min_avail is None else min(self.min_avail, a)
343
344    def chat(self, prompt: str, max_tokens: int, tune: dict[str, Any] | None = None, timeout: float = 1800.0) -> dict[str, Any]:
345        body: dict[str, Any] = {"model": self.model, "stream": False, "max_tokens": max_tokens, "temperature": 0.0,
346                                "messages": [{"role": "user", "content": prompt}], "strata_checkpoint": False}
347        if tune:
348            body["strata_tune"] = tune
349        req = urllib.request.Request(f"http://127.0.0.1:{self.port}/v1/chat/completions",
350                                     data=json.dumps(body).encode(), headers=self._h(), method="POST")
351        try:
352            with loopback.urlopen(req, timeout=timeout) as r:
353                data = json.loads(r.read())
354        except urllib.error.HTTPError as e:
355            reason = f"the worker refused the request ({e.code}): {e.read()[:200]!r}"
356            status = "NO_TOKENS"
357            if 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)
358                native = native_failure(self.log_text()[-8000:])
359                if native:
360                    reason += f" | engine: {native}"
361                    if _NATIVE_OOM.search(native):
362                        status = "OOM"
363            raise StartFailed(status, reason) from None
364        except (urllib.error.URLError, OSError, ValueError) as e:
365            code = self.proc.poll()
366            status, why = failure_kind(self.log_text()[-4000:], code) if code is not None else ("TIMEOUT", str(e))
367            raise StartFailed(status, f"the engine did not answer: {why}") from None
368        self._sample_mem()
369        return data
370
371    # ---- measurements
372    def decode_once(self, tune: dict[str, Any] | None = None, tokens: int = 200) -> float | None:
373        for prompt in DECODE_PROMPTS:
374            data = self.chat(prompt, tokens, tune)
375            t = data.get("timings") or {}
376            n, rate = t.get("predicted_n"), t.get("predicted_per_second")
377            if n and rate and n >= max(32, tokens // 2):
378                return float(rate)
379        return None
380
381    def prompt_once(self, tokens: int) -> dict[str, float | None]:
382        self.salt_n += 1
383        salt = secrets.token_hex(6)
384        text = make_prompt(tokens, salt, self.s.chars_per_token)
385        data = self.chat(text, 8)
386        t = data.get("timings") or {}
387        usage = data.get("usage") or {}
388        pt = usage.get("prompt_tokens")
389        if isinstance(pt, int) and pt > 64 and not self.s.calibrated:
390            self.s.chars_per_token = max(2.0, min(8.0, self.s.chars_per_token * tokens / pt))
391            self.s.calibrated = True
392        rate = t.get("prompt_per_second")
393        # a prompt that was partly cached is not a prompt-speed measurement
394        if t.get("cache_n") and t.get("prompt_n") and t["cache_n"] > 0.1 * (t["prompt_n"] + t["cache_n"]):
395            rate = None
396        ms = t.get("prompt_ms")
397        return {"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
400    def measure(self, spec: RequestSet) -> RunResult:
401        t0 = time.time()
402        res = RunResult(load_s=self.load_s, facts=dict(self.facts))
403        for _ in range(spec.warmups):
404            self.decode_once(None, 64)
405        runs: list[float] = []
406        for _ in range(spec.decodes):
407            r = self.decode_once(None, spec.decode_tokens)
408            if r:
409                runs.append(r)
410        res.decode_runs = [round(x, 3) for x in runs]
411        if not runs:
412            res.status, res.reason = "NO_TOKENS", "the engine produced no measurable decode"
413        else:
414            res.decode_tok_s = round(statistics.median(runs), 3)
415        if spec.pp_tokens:
416            cold = self.prompt_once(spec.pp_tokens)
417            warm = self.prompt_once(spec.pp_tokens)
418            res.pp_cold_tok_s = cold["rate"]
419            res.pp_tok_s, res.ttft_s = warm["rate"], warm["ttft_s"]
420        if spec.long_tokens:
421            res.pp_long_tok_s = self.prompt_once(spec.long_tokens)["rate"]
422        res.rss_peak_mib = tune_engine_peak(self.proc.pid)
423        used = tune_machine.gpu_used_mib()
424        if used is not None:
425            res.vram_used_mib = used
426            if self.vram_before is not None:
427                res.vram_added_mib = used - self.vram_before
428        res.min_avail_mib = self.min_avail
429        res.facts = dict(parse_facts(self.log_text()))
430        res.wall_s = round(time.time() - t0, 1)
431        return res
432
433
434def tune_engine_peak(pid: int) -> float | None:
435    try:
436        from strata_control.tune_engine import process_tree_peak_mib
437        return process_tree_peak_mib(pid)
438    except Exception:  # noqa: BLE001
439        return None
440
441
442class WorkerSession:
443    """Starts ``serve.server`` on a copy of the run configuration for each configuration the tuner asks for."""
444
445    def __init__(self, *, base_config: dict[str, Any], python: str | os.PathLike[str] | None = None,
446                 serve_dir: str | os.PathLike[str], workdir: str | os.PathLike[str] | None = None,
447                 boot_timeout_s: float = 900.0, lock: Callable[[], contextlib.AbstractContextManager] | None = None,
448                 log: Callable[[str], None] = lambda s: None, extra_env: dict[str, str] | None = None) -> None:
449        self.base = json.loads(json.dumps(base_config))
450        self.python = str(python or sys.executable)
451        self.serve_dir = Path(serve_dir)
452        self.workdir = Path(workdir) if workdir else Path(tempfile.mkdtemp(prefix="strata-tune-"))
453        self.workdir.mkdir(parents=True, exist_ok=True)
454        self.boot_timeout_s = boot_timeout_s
455        self.lock = lock
456        self.log = log
457        self.extra_env = dict(extra_env or {})
458        self.chars_per_token = 4.4
459        self.calibrated = False
460        self.runs = 0
461
462    def system(self) -> dict[str, Any]:
463        return {"memory": tune_machine.memory(), "gpus": tune_machine.gpus(), "cpu": tune_machine.cpu()}
464
465    @contextlib.contextmanager
466    def engine(self, args: list[str], env: dict[str, str | None], pre_start: Callable[[], None] | None = None) -> Iterator[WorkerEngine]:
467        with contextlib.ExitStack() as stack:
468            if self.lock is not None:
469                stack.enter_context(self.lock())
470            if pre_start is not None:
471                pre_start()                      # the memory and quiet checks run once the lock is ours, right before the start
472            self.runs += 1
473            n = self.runs
474            cfg = json.loads(json.dumps(self.base))
475            cfg["args"] = list(args)
476            cenv = dict(cfg.get("env") or {})
477            for k, v in env.items():
478                if v is None:
479                    cenv.pop(k, None)
480                else:
481                    cenv[k] = str(v)
482            cfg["env"] = cenv
483            key = secrets.token_hex(16)
484            port = _free_port()
485            engine_log = self.workdir / f"engine-{n}.log"
486            worker_log = self.workdir / f"worker-{n}.log"
487            engine_log.write_text("")
488            cfg.update({"api_key": key, "port": port, "host": "127.0.0.1", "open_browser": False, "log": str(engine_log)})
489            cfg_path = self.workdir / f"run-{n}.json"
490            cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8")
491            spawn_env = quiet_crash_env(dict(os.environ))      # no debugger on a user's machine (strata_control/childenv.py)
492            spawn_env.update(self.extra_env)
493            spawn_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)
494            for k, v in env.items():
495                if v is None:
496                    spawn_env.pop(k, None)
497            spawn_env["PYTHONUNBUFFERED"] = "1"
498            spawn_env["STRATA_NO_PRESET"] = "1"          # measure the configuration as given, not a saved tuning on top
499            before = tune_machine.gpu_used_mib()
500            wl = open(worker_log, "w")
501            argv = [self.python, "-m", "serve.server", "--engine", "strata", "--config", str(cfg_path),
502                    "--host", "127.0.0.1", "--port", str(port)]
503            t0 = time.time()
504            try:
505                from serve import lifeline
506                proc = lifeline.popen(argv, "worker", cwd=str(self.serve_dir), env=spawn_env, stdout=wl,
507                                      stderr=subprocess.STDOUT)
508            except OSError as e:
509                wl.close()
510                raise StartFailed("FAIL_BOOT", f"the worker could not be started: {e}") from None
511            try:
512                deadline = t0 + self.boot_timeout_s
513                ready = False
514                while time.time() < deadline:
515                    if proc.poll() is not None:
516                        text = (engine_log.read_text(errors="replace") if engine_log.exists() else "") + "\n" + \
517                               worker_log.read_text(errors="replace")
518                        status, why = failure_kind(text, proc.returncode)
519                        raise StartFailed(status, why)
520                    try:
521                        req = urllib.request.Request(f"http://127.0.0.1:{port}/health",
522                                                     headers={"authorization": f"Bearer {key}"})
523                        with loopback.urlopen(req, timeout=2) as r:
524                            if r.status == 200:
525                                ready = True
526                                break
527                    except (urllib.error.URLError, OSError):
528                        time.sleep(0.5)
529                if not ready:
530                    raise StartFailed("TIMEOUT", f"the engine was not ready within {int(self.boot_timeout_s)} s")
531                eng = WorkerEngine(self, proc, port, key, [engine_log, worker_log], time.time() - t0, before, self.log)
532                yield eng
533            finally:
534                try:
535                    if proc.poll() is None:
536                        proc.terminate()
537                        try:
538                            proc.wait(timeout=60)
539                        except subprocess.TimeoutExpired:
540                            proc.kill()
541                            proc.wait(timeout=30)
542                finally:
543                    wl.close()
544                    # the engine gives its graphics memory back a moment after it exits
545                    time.sleep(3.0)