okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
2503b206b
main
1"""Measure one engine configuration, for the tuning job. 2 3The tuning job (`strata_control/tuning.py`) searches configurations and decides from numbers. This 4module is where those numbers come from: it boots the engine with one candidate's flags, sends the 5declared workload, reads the engine's own output, and returns measurements. 6 7It is deliberately separate from the job, and it is deliberately paranoid: 8 9* **It never invents a number.** If the engine does not start, produces no tokens, or finishes for a 10reason other than a stop or a length, this raises with the engine's own words. The job records 11that as a failed candidate — which is a real result — rather than as a slow one. 12* **It measures what the engine reports, not what the wall clock suggests.** The engine prints its 13own prompt and decode milliseconds, so a measurement does not include this process's scheduling. 14Client-observed timings are recorded separately and labelled, because they answer a different 15question. 16* **It runs the declared workload every time**, with a fixed seed, so two candidates are compared on 17the same work. A "faster" configuration that quietly did less is the classic tuning failure. 18 19The production engine protocol this reads (see `src/program/generate.cpp`): 20 21READY <max_context> stop 22PP <processed> <total> <ms> [<tok_s>] prompt progress 23T <token_id> one generated token 24DONE <produced> <prompt_tokens> <prompt_ms> <decode_ms> <finish> <drafts_acc> <drafts_off> ... 25 26`finish` is `stop`, `length`, `cancel` or `nonfinite`. A `cancel` or `nonfinite` finish is not a 27measurement, and neither is a run whose `produced` is zero. 28""" 29 30from __future__import annotations 31 32import os 33import re 34import subprocess 35import time 36from dataclasses import dataclass ,field 37from pathlib import Path 38from typing import Any ,Sequence 39 40from strata_control .childenv import quiet_crash_env 41 42#: A workload is fixed for the whole sweep: the same prompt, the same number of tokens to generate, 43#: the same sampling. Changing any of these between candidates invalidates the comparison. 44DEFAULT_WORKLOAD = { 45"prompt_tokens" :512 , 46"max_new" :128 , 47"seed" :1 , 48"temperature" :0.0 ,# greedy, so the work is deterministic 49} 50 51 52class MeasurementError (RuntimeError ): 53"""The candidate could not be measured. The message is the engine's own reason.""" 54 55 56@dataclass 57class EngineMeasurement : 58"""One candidate's measurements, with the units and the source of each. 59 60`source` distinguishes what the engine reported from what this process observed, because they 61are not interchangeable: the engine's `prompt_ms`/`decode_ms` exclude process startup and 62scheduling, while `client_ttft_ms` includes everything a user would wait for. 63""" 64 65tokens_per_s :float 66#: Peak resident memory of the measured process tree, in MiB. Tuning that gets faster by 67#: spilling or by thrashing is not an improvement, and the checklist asks for memory to travel 68#: with the speed number so the trade is visible rather than hidden. 69peak_memory_mib :float | None = None 70prompt_tokens_per_s :float | None = None 71decode_tokens_per_s :float | None = None 72ttft_ms :float | None = None # engine-reported: prompt_ms + the first decode step 73client_ttft_ms :float | None = None # observed here, includes process scheduling 74produced :int = 0 75prompt_tokens :int = 0 76finish :str = "" 77memory_mib :float | None = None 78source :str = "engine-serve-protocol" 79#: `protocol` measures the engine's own serve protocol; `api` drives the real HTTP API the agent 80#: uses. They answer different questions, so the report must not present one as the other. 81mode :str = "protocol" 82raw :dict [str ,Any ]= field (default_factory = dict ) 83 84def to_metrics (self )-> dict [str ,float ]: 85"""The dict the job's `measure` callable must return. 86 87Only finite numbers are emitted, so a missing measurement stays missing rather than becoming 88a zero that a comparison might treat as a very slow result. 89""" 90out :dict [str ,float ]= {"tokens_per_s" :self .tokens_per_s } 91for key in ("prompt_tokens_per_s" ,"decode_tokens_per_s" ,"ttft_ms" ,"client_ttft_ms" , 92"memory_mib" ,"peak_memory_mib" ): 93value = getattr (self ,key ) 94if isinstance (value , (int ,float )): 95out [key ]= float (value ) 96return out 97 98 99# --------------------------------------------------------------------------- parsing 100 101_READY = re .compile (r"^READY\s+(\d+)\s+(\S+)\s*$" ) 102_PP = re .compile (r"^PP\s+(\d+)\s+(\d+)\s+([\d.]+)(?:\s+([\d.]+))?\s*$" ) 103_DONE = re .compile (r"^DONE\s+(.*)$" ) 104_TOKEN = re .compile (r"^T\s+(\d+)\s*$" ) 105 106 107def parse_done (line :str )-> dict [str ,Any ]: 108"""Parse a `DONE` line. 109 110The line's tail is variable — the engine appends lookup-chain counters only when that option is 111on — so the leading fields are read positionally and the rest is kept, never required. 112""" 113m = _DONE .match (line .strip ()) 114if not m : 115raise MeasurementError (f"not a DONE line: { line [: 120 ]!r } " ) 116parts = m .group (1 ).split () 117if len (parts )< 5 : 118raise MeasurementError (f"a DONE line with fewer than 5 fields: { line [: 120 ]!r } " ) 119try : 120produced = int (parts [0 ]) 121prompt_tokens = int (parts [1 ]) 122prompt_ms = float (parts [2 ]) 123decode_ms = float (parts [3 ]) 124except ValueError as e : 125raise MeasurementError (f"a DONE line with an unreadable number: { line [: 120 ]!r } " )from e 126return { 127"produced" :produced , 128"prompt_tokens" :prompt_tokens , 129"prompt_ms" :prompt_ms , 130"decode_ms" :decode_ms , 131"finish" :parts [4 ], 132"drafts_accepted" :_int (parts [5 ])if len (parts )> 5 else None , 133"drafts_offered" :_int (parts [6 ])if len (parts )> 6 else None , 134"tail" :parts [7 :], 135 } 136 137 138def _int (text :str )-> int | None : 139try : 140return int (text ) 141except ValueError : 142return None 143 144 145def parse_ready (line :str )-> int : 146m = _READY .match (line .strip ()) 147if not m : 148raise MeasurementError (f"not a READY line: { line [: 120 ]!r } " ) 149return int (m .group (1 )) 150 151 152def parse_pp (line :str )-> dict [str ,float ]: 153m = _PP .match (line .strip ()) 154if not m : 155raise MeasurementError (f"not a PP line: { line [: 120 ]!r } " ) 156out = {"processed" :float (m .group (1 )),"total" :float (m .group (2 )),"ms" :float (m .group (3 ))} 157if m .group (4 ): 158out ["tok_s" ]= float (m .group (4 )) 159return out 160 161 162def measurement_from_protocol (done :dict [str ,Any ],* ,tokens_seen :int , 163client_ttft_ms :float | None = None , 164ready_ms :float | None = None )-> EngineMeasurement : 165"""Turn the engine's own report into measurements. 166 167Rejects a run that did not actually generate: a `cancel`, a `nonfinite`, a zero-token run and a 168disagreement between the token count and the DONE line are all errors, not slow results. 169""" 170finish = str (done .get ("finish" ,"" )) 171produced = int (done .get ("produced" ,0 )) 172if finish in ("cancel" ,"nonfinite" ): 173raise MeasurementError (f"the engine finished with ' { finish } ', which is not a measurement" ) 174if produced <= 0 : 175raise MeasurementError ("the engine produced no tokens" ) 176if tokens_seen and tokens_seen != produced : 177# The stream and the summary disagree, so neither can be trusted for a rate. 178raise MeasurementError ( 179f"the engine reported { produced } tokens but streamed { tokens_seen } ; refusing to score it" ) 180 181decode_ms = float (done .get ("decode_ms" )or 0.0 ) 182prompt_ms = float (done .get ("prompt_ms" )or 0.0 ) 183prompt_tokens = int (done .get ("prompt_tokens" )or 0 ) 184 185decode_per_s = (produced * 1000.0 / decode_ms )if decode_ms > 0 else None 186prompt_per_s = (prompt_tokens * 1000.0 / prompt_ms )if prompt_ms > 0 and prompt_tokens else None 187 188# What "tokens per second" means for the objective: the whole request's decoding rate. Prompt 189# processing is reported separately because a candidate can move one without the other, and 190# averaging them would hide exactly the trade the tuner is searching for. 191total_ms = prompt_ms + decode_ms 192overall = (produced * 1000.0 / total_ms )if total_ms > 0 else (decode_per_s or 0.0 ) 193 194# The engine's own TTFT: reading the prompt plus the first decode step. 195per_token_ms = (decode_ms / produced )if produced else None 196ttft = (prompt_ms + per_token_ms )if per_token_ms is not None else (prompt_ms or None ) 197 198return EngineMeasurement ( 199tokens_per_s = overall , 200prompt_tokens_per_s = prompt_per_s , 201decode_tokens_per_s = decode_per_s , 202ttft_ms = ttft , 203client_ttft_ms = client_ttft_ms , 204produced = produced , 205prompt_tokens = prompt_tokens , 206finish = finish , 207raw = dict (done ), 208 ) 209 210 211# --------------------------------------------------------------------------- running 212 213class LineReader : 214"""Read lines from a pipe without ever blocking the caller. 215 216`readline()` on a pipe has no timeout, so a `while time.monotonic() < deadline` loop around it 217does not bound anything: an engine that starts and then says nothing hangs the measurement 218forever. That is a real defect, not a hypothetical — it made the boot-timeout path unreachable 219and hung this module's own tests. 220 221A daemon reader thread moves the blocking read off the caller's thread, and the caller polls a 222queue with a deadline it actually enforces. 223""" 224 225def __init__ (self ,stream ,name :str = "engine" )-> None : 226import queue 227import threading 228self ._queue :"queue.Queue[str | None]" = queue .Queue () 229self ._stream = stream 230self .name = name 231self ._thread = threading .Thread (target = self ._pump ,daemon = True , 232name = f"strata- { name } -reader" ) 233self ._thread .start () 234 235def _pump (self )-> None : 236try : 237for line in self ._stream : 238self ._queue .put (line ) 239except (OSError ,ValueError ): 240pass 241finally : 242# A sentinel so a reader knows the stream ended rather than that it is merely quiet. 243self ._queue .put (None ) 244 245def read_line (self ,deadline :float )-> str | None : 246"""One line, or None if the deadline passed or the stream ended. 247 248Raises `EOFError` when the stream has ended, so a caller can distinguish "nothing yet" from 249"the engine is gone". 250""" 251import queue 252remaining = deadline - time .monotonic () 253if remaining <= 0 : 254return None 255try : 256line = self ._queue .get (timeout = remaining ) 257except queue .Empty : 258return None 259if line is None : 260raise EOFError (f"the { self . name } stream ended" ) 261return line 262 263def drain_available (self )-> list [str ]: 264"""Everything already buffered, without waiting.""" 265import queue 266out :list [str ]= [] 267while True : 268try : 269line = self ._queue .get_nowait () 270except queue .Empty : 271return out 272if line is None : 273return out 274out .append (line ) 275 276 277 278def _windows_tree_peak_mib (pid :int )-> float | None : 279"""The same measurement on Windows: peak working set summed over the process and its children. 280 281``ps`` does not exist there, so the process list comes from a Toolhelp snapshot and each 282process's peak from ``GetProcessMemoryInfo``. A process that cannot be opened (another 283session, already gone) is skipped; if none can be read the answer is absent, not zero. 284""" 285import ctypes 286from ctypes import wintypes 287 288class ProcessEntry (ctypes .Structure ): 289_fields_ = [("dwSize" ,wintypes .DWORD ), ("cntUsage" ,wintypes .DWORD ), ("th32ProcessID" ,wintypes .DWORD ), 290 ("th32DefaultHeapID" ,ctypes .c_size_t ), ("th32ModuleID" ,wintypes .DWORD ), 291 ("cntThreads" ,wintypes .DWORD ), ("th32ParentProcessID" ,wintypes .DWORD ), 292 ("pcPriClassBase" ,ctypes .c_long ), ("dwFlags" ,wintypes .DWORD ), ("szExeFile" ,ctypes .c_wchar * 260 )] 293 294class MemoryCounters (ctypes .Structure ): 295_fields_ = [("cb" ,wintypes .DWORD ), ("PageFaultCount" ,wintypes .DWORD ), ("PeakWorkingSetSize" ,ctypes .c_size_t ), 296 ("WorkingSetSize" ,ctypes .c_size_t ), ("QuotaPeakPagedPoolUsage" ,ctypes .c_size_t ), 297 ("QuotaPagedPoolUsage" ,ctypes .c_size_t ), ("QuotaPeakNonPagedPoolUsage" ,ctypes .c_size_t ), 298 ("QuotaNonPagedPoolUsage" ,ctypes .c_size_t ), ("PagefileUsage" ,ctypes .c_size_t ), 299 ("PeakPagefileUsage" ,ctypes .c_size_t )] 300 301kernel = ctypes .WinDLL ("kernel32" ,use_last_error = True ) 302psapi = ctypes .WinDLL ("psapi" ,use_last_error = True ) 303kernel .CreateToolhelp32Snapshot .restype = wintypes .HANDLE 304kernel .CreateToolhelp32Snapshot .argtypes = [wintypes .DWORD ,wintypes .DWORD ] 305kernel .Process32FirstW .argtypes = [wintypes .HANDLE ,ctypes .POINTER (ProcessEntry )] 306kernel .Process32NextW .argtypes = [wintypes .HANDLE ,ctypes .POINTER (ProcessEntry )] 307kernel .OpenProcess .restype = wintypes .HANDLE 308kernel .OpenProcess .argtypes = [wintypes .DWORD ,wintypes .BOOL ,wintypes .DWORD ] 309kernel .CloseHandle .argtypes = [wintypes .HANDLE ] 310psapi .GetProcessMemoryInfo .argtypes = [wintypes .HANDLE ,ctypes .POINTER (MemoryCounters ),wintypes .DWORD ] 311 312snapshot = kernel .CreateToolhelp32Snapshot (0x2 ,0 )# TH32CS_SNAPPROCESS 313if snapshot in (None ,wintypes .HANDLE (- 1 ).value ): 314return None 315rows :list [tuple [int ,int ]]= [] 316try : 317entry = ProcessEntry () 318entry .dwSize = ctypes .sizeof (ProcessEntry ) 319more = kernel .Process32FirstW (snapshot ,ctypes .byref (entry )) 320while more : 321rows .append ((entry .th32ProcessID ,entry .th32ParentProcessID )) 322more = kernel .Process32NextW (snapshot ,ctypes .byref (entry )) 323finally : 324kernel .CloseHandle (snapshot ) 325if pid not in {child for child ,_ in rows }: 326return None 327wanted = {pid } 328changed = True 329while changed : 330changed = False 331for child ,parent in rows : 332if parent in wanted and child not in wanted : 333wanted .add (child ) 334changed = True 335total = 0 336for member in wanted : 337handle = kernel .OpenProcess (0x1000 | 0x0010 ,False ,member )# QUERY_LIMITED_INFORMATION | VM_READ 338if not handle : 339handle = kernel .OpenProcess (0x0400 | 0x0010 ,False ,member )# QUERY_INFORMATION | VM_READ 340if not handle : 341continue 342try : 343counters = MemoryCounters () 344counters .cb = ctypes .sizeof (MemoryCounters ) 345if psapi .GetProcessMemoryInfo (handle ,ctypes .byref (counters ),counters .cb ): 346total += counters .PeakWorkingSetSize 347finally : 348kernel .CloseHandle (handle ) 349return round (total / (1024.0 * 1024.0 ),1 )if total else None 350 351 352def process_tree_peak_mib (pid :int )-> float | None : 353"""Peak resident memory of a process and its children, in MiB. 354 355The engine is one process today, but a backend may spawn workers, so the tree is summed rather 356than the root alone. `ps` is used because it reports each process's own peak (`rss` is current, 357`vsz` is address space); when it is unavailable the memory is simply absent, which is the honest 358answer and not a zero. 359""" 360if os .name == "nt" : 361return _windows_tree_peak_mib (pid ) 362try : 363out = subprocess .run (["ps" ,"-o" ,"rss=,pid=,ppid=" ,"-ax" ],capture_output = True ,text = True , 364timeout = 5 ).stdout 365except (OSError ,subprocess .SubprocessError ): 366return None 367rows :list [tuple [int ,int ,int ]]= [] 368for line in out .splitlines (): 369parts = line .split () 370if len (parts )!= 3 : 371continue 372try : 373rows .append ((int (parts [1 ]),int (parts [2 ]),int (parts [0 ]))) 374except ValueError : 375continue 376wanted = {pid } 377changed = True 378while changed :# transitive closure over ppid 379changed = False 380for child ,parent ,_ in rows : 381if parent in wanted and child not in wanted : 382wanted .add (child ) 383changed = True 384total = sum (rss for child ,_ ,rss in rows if child in wanted ) 385return round (total / 1024.0 ,1 )if total else None 386 387 388class EngineHarness : 389"""Boot the engine once per candidate and measure the declared workload. 390 391The engine is a subprocess speaking line protocol over stdout, exactly as `serve/server.py` 392drives it. One harness is created per candidate: a configuration that changes the expert cache 393or the KV layout cannot be assumed to take effect in a running engine. 394""" 395 396def __init__ (self ,engine :Path ,args :dict [str ,str ],* ,workload :dict [str ,Any ]| None = None , 397cwd :Path | None = None ,env :dict [str ,str ]| None = None , 398boot_timeout_s :float = 600.0 ,request_timeout_s :float = 600.0 )-> None : 399self .engine = Path (engine ) 400self .args = dict (args ) 401self .workload = {** DEFAULT_WORKLOAD ,** (workload or {})} 402self .cwd = Path (cwd )if cwd else Path .cwd () 403if env is None : 404from strata_control .tuning import engine_env 405env = engine_env (self .engine )# an engine package's own folder first on the library path 406self .env = env 407self .boot_timeout_s = boot_timeout_s 408self .request_timeout_s = request_timeout_s 409self ._proc :subprocess .Popen | None = None 410self ._reader :LineReader | None = None 411self .last_measurement :EngineMeasurement | None = None 412self ._ready_ms :float | None = None 413self ._context :int | None = None 414 415def _argv (self )-> list [str ]: 416from strata_control .tuning import engine_command ,flag_argv 417argv = [* engine_command (self .engine ),"--serve" ] 418for flag ,value in self .args .items (): 419argv .extend (flag_argv (flag ,value )) 420return argv 421 422def __enter__ (self )-> "EngineHarness" : 423self .start () 424return self 425 426def __exit__ (self ,* exc :object )-> None : 427self .close () 428 429def start (self )-> None : 430if not self .engine .exists (): 431raise MeasurementError (f"the engine binary is not at { self . engine } " ) 432started = time .monotonic () 433try : 434from serve import lifeline # the engine ends with this process, however this process ends 435self ._proc = lifeline .popen ( 436self ._argv (),"engine" ,cwd = str (self .cwd ),env = None if self .env is None else quiet_crash_env (dict (self .env )), 437stdin = subprocess .PIPE ,stdout = subprocess .PIPE ,stderr = subprocess .PIPE , 438text = True ,errors = "replace" ,bufsize = 1 ) 439except OSError as e : 440raise MeasurementError (f"the engine could not be started: { e } " )from e 441 442self ._reader = LineReader (self ._proc .stdout ,"engine" ) 443deadline = time .monotonic ()+ self .boot_timeout_s 444while True : 445if time .monotonic ()>= deadline : 446if self ._proc .poll ()is not None : 447raise MeasurementError ( 448f"the engine exited with code { self . _exit_code () } before it was ready" 449+ self ._stderr_tail ()) 450raise MeasurementError ( 451f"the engine did not report READY within { self . boot_timeout_s :.0f } s" ) 452try : 453line = self ._reader .read_line (deadline ) 454except EOFError : 455raise MeasurementError ( 456f"the engine exited with code { self . _exit_code () } before it was ready" 457+ self ._stderr_tail ())from None 458if line is None : 459# Nothing yet. Only a *finished* process means failure; a slow boot does not. 460if self ._proc .poll ()is not None : 461raise MeasurementError ( 462f"the engine exited with code { self . _exit_code () } before it was ready" 463+ self ._stderr_tail ()) 464continue 465line = line .strip () 466if line .startswith ("READY" ): 467self ._context = parse_ready (line ) 468self ._ready_ms = (time .monotonic ()- started )* 1000.0 469return 470if line .startswith ("ERR" ): 471raise MeasurementError (f"the engine refused to start: { line } " ) 472 473def _exit_code (self )-> int | None : 474"""The engine's exit code, reaped if necessary. 475 476`poll()` returns None until the process has been waited on, and a reader thread can observe 477end-of-stream *before* that happens. Reporting "exited with code None" is useless in exactly 478the case where the code matters most, so this waits briefly for the status. 479""" 480if self ._proc is None : 481return None 482if self ._proc .poll ()is None : 483try : 484self ._proc .wait (timeout = 5 ) 485except subprocess .TimeoutExpired : 486return None 487return self ._proc .returncode 488 489def _stderr_tail (self ,limit :int = 400 )-> str : 490if self ._proc is None or self ._proc .stderr is None : 491return "" 492try : 493# Only meaningful once the process has ended; a running engine's stderr is still open. 494if self ._proc .poll ()is None : 495return "" 496text = self ._proc .stderr .read ()or "" 497return f"; stderr: { text [ - limit :]. strip () } " 498except OSError : 499return "" 500 501def measure (self )-> EngineMeasurement : 502"""Send the workload and read one result. Raises `MeasurementError` on anything unusable.""" 503if self ._proc is None or self ._proc .poll ()is not None : 504raise MeasurementError ("the engine is not running" ) 505if self ._proc .stdin is None or self ._proc .stdout is None : 506raise MeasurementError ("the engine has no input/output pipe" ) 507 508tokens = self ._prompt_tokens () 509flags = (f" temperature= { self . workload [ 'temperature' ] } seed= { self . workload [ 'seed' ] } " ) 510request = f"GEN { int ( self . workload [ 'max_new' ]) } { flags } { ',' . join ( str ( t ) for t in tokens ) } \n" 511 512client_start = time .monotonic () 513try : 514self ._proc .stdin .write (request ) 515self ._proc .stdin .flush () 516except (OSError ,BrokenPipeError )as e : 517raise MeasurementError (f"the engine stopped accepting work: { e } " + self ._stderr_tail ())from e 518 519deadline = time .monotonic ()+ self .request_timeout_s 520seen = 0 521client_ttft :float | None = None 522done :dict [str ,Any ]| None = None 523while True : 524if time .monotonic ()>= deadline : 525break 526try : 527raw = self ._reader .read_line (deadline ) 528except EOFError : 529raise MeasurementError ( 530f"the engine exited with code { self . _exit_code () } during the request" 531+ self ._stderr_tail ())from None 532if raw is None : 533if self ._proc .poll ()is not None : 534raise MeasurementError ( 535f"the engine exited with code { self . _exit_code () } during the request" 536+ self ._stderr_tail ()) 537continue 538line = raw .strip () 539if _TOKEN .match (line ): 540seen += 1 541if client_ttft is None : 542client_ttft = (time .monotonic ()- client_start )* 1000.0 543elif line .startswith ("DONE" ): 544done = parse_done (line ) 545break 546elif line .startswith ("ERR" ): 547raise MeasurementError (f"the engine reported an error: { line } " ) 548if done is None : 549raise MeasurementError ( 550f"the engine produced no DONE line within { self . request_timeout_s :.0f } s" ) 551 552result = measurement_from_protocol (done ,tokens_seen = seen ,client_ttft_ms = client_ttft , 553ready_ms = self ._ready_ms ) 554if self ._proc is not None : 555result .peak_memory_mib = process_tree_peak_mib (self ._proc .pid ) 556result .mode = "protocol" 557self .last_measurement = result 558return result 559 560def _prompt_tokens (self )-> Sequence [int ]: 561"""The workload's token ids. 562 563A real sweep substitutes the tokenizer's ids here. The default is a fixed, deterministic 564sequence of the declared length: it exercises the same code path for every candidate, which 565is what makes the comparison valid, and it cannot be accused of silently changing the work. 566""" 567n = max (1 ,int (self .workload ["prompt_tokens" ])) 568return [1000 + (i % 97 )for i in range (n )] 569 570def close (self )-> None : 571if self ._proc is None : 572return 573try : 574if self ._proc .poll ()is None and self ._proc .stdin is not None : 575self ._proc .stdin .write ("QUIT\n" ) 576self ._proc .stdin .flush () 577try : 578self ._proc .wait (timeout = 10 ) 579except subprocess .TimeoutExpired : 580self ._proc .kill () 581except (OSError ,ValueError ): 582try : 583self ._proc .kill () 584except OSError : 585pass 586finally : 587for stream in (self ._proc .stdin ,self ._proc .stdout ,self ._proc .stderr ): 588try : 589if stream is not None : 590stream .close () 591except OSError : 592pass 593self ._proc = None 594 595 596def make_measure (engine :Path ,workload :dict [str ,Any ]| None = None , 597cwd :Path | None = None )-> "callable" : 598"""Build the `measure` callable the tuning job expects. 599 600The returned function boots the engine with the candidate's args, measures once, and returns the 601metrics. It raises on anything unusable, which the job records as that candidate's status. 602""" 603def measure (candidate )-> dict [str ,float ]: 604harness = EngineHarness (engine ,candidate .args if hasattr (candidate ,"args" )else candidate , 605workload = workload ,cwd = cwd ) 606try : 607harness .start () 608return harness .measure ().to_metrics () 609finally : 610harness .close () 611 612return measure