okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
2503b206b
main
1"""Measure a configuration through the API the agent actually uses. 2 3`tune_engine.EngineHarness` measures the engine's own serve protocol, which is fast and precise and 4answers "how fast can this configuration decode". It does **not** answer "is this configuration 5better for a user", because the user's requests arrive over HTTP, go through the worker's queueing, 6prompt handling and streaming, and it is that whole path whose latency matters. 7 8Checklist T04 asks for the full API/Harness workload and for memory, so this module provides it. The 9two modes are deliberately separate rather than one replacing the other: 10 11* ``protocol`` is cheap enough to run for every candidate in a sweep; 12* ``api`` is the confirmation, run against the finalists and against the exported configuration. 13 14Reporting one as the other would be the same class of error as a fixture result standing in for real 15inference, so every measurement carries the mode that produced it and the report shows the mode. 16 17What this measures, per request: time to first token (from the first streamed content frame, which is 18what a user waits for), end-to-end duration, token counts taken from the server's own usage block 19rather than counted here, and the peak resident memory of the server process tree. The prompt and the 20expectation are supplied by the caller, and the response is checked against the expectation, because 21a configuration that answers faster and wrongly is not an improvement. 22""" 23 24from __future__import annotations 25 26import json 27import re 28import subprocess 29import time 30import urllib .error 31import urllib .request 32from pathlib import Path 33from typing import Any 34 35from strata_control import loopback 36from strata_control .childenv import quiet_crash_env 37from strata_control .tune_engine import EngineMeasurement ,MeasurementError ,process_tree_peak_mib 38 39 40class ApiHarness : 41"""Start the worker with one configuration and measure a real chat completion. 42 43The server is started as a child process and stopped afterwards: a configuration that changes the 44KV layout or the expert cache cannot be assumed to take effect in a running server, and reusing 45one would silently measure the previous candidate. 46""" 47 48def __init__ (self ,* ,python :Path | str ,serve_dir :Path ,config_path :Path , 49port :int = 8123 ,host :str = "127.0.0.1" ,boot_timeout_s :float = 900.0 , 50request_timeout_s :float = 900.0 ,env :dict [str ,str ]| None = None , 51engine :str = "strata" )-> None : 52self .python = str (python ) 53# `strata` is the real engine; `mock` is the scripted one, and a measurement taken against it 54# is a test of this harness and never a performance result. 55self .engine = engine 56self .serve_dir = Path (serve_dir ) 57self .config_path = Path (config_path ) 58self .port = int (port ) 59self .host = host 60self .boot_timeout_s = boot_timeout_s 61self .request_timeout_s = request_timeout_s 62self .env = env 63self ._proc :subprocess .Popen | None = None 64self ._log = None 65 66# ------------------------------------------------------------------ lifecycle 67 68@property 69def url (self )-> str : 70return f"http:// { self . host } : { self . port } " 71 72def _argv (self )-> list [str ]: 73# The worker's own spelling. `--profile` is the terminal launcher's flag, not this one, and 74# passing it made the worker exit 2 with a usage message before it ever bound a port. 75return [self .python ,"-m" ,"serve.server" ,"--engine" ,self .engine , 76"--config" ,str (self .config_path ), 77"--host" ,self .host ,"--port" ,str (self .port )] 78 79def start (self )-> None : 80import tempfile 81self ._log = tempfile .NamedTemporaryFile (prefix = "strata-api-harness-" ,suffix = ".log" , 82delete = False ) 83try : 84from serve import lifeline # the worker (and the engine under it) end with this process 85self ._proc = lifeline .popen (self ._argv (),"worker" ,cwd = str (self .serve_dir ), 86env = None if self .env is None else quiet_crash_env (dict (self .env )), 87stdout = self ._log ,stderr = subprocess .STDOUT ) 88except OSError as e : 89raise MeasurementError (f"the worker could not be started: { e } " )from e 90 91deadline = time .monotonic ()+ self .boot_timeout_s 92while time .monotonic ()< deadline : 93if self ._proc .poll ()is not None : 94raise MeasurementError ( 95f"the worker exited with code { self . _proc . returncode } before becoming ready" 96+ self ._log_tail ()) 97try : 98with loopback .urlopen (f" { self . url } /health" ,timeout = 2 )as response : 99if response .status == 200 : 100return 101except (urllib .error .URLError ,OSError ): 102time .sleep (0.2 ) 103raise MeasurementError (f"the worker did not answer /health within { self . boot_timeout_s :.0f } s" 104+ self ._log_tail ()) 105 106def _log_tail (self ,limit :int = 500 )-> str : 107if self ._log is None : 108return "" 109try : 110text = Path (self ._log .name ).read_text (encoding = "utf-8" ,errors = "replace" ) 111if not text .strip (): 112return "" 113# The engine prints its reason first and a usage dump after it, so the last 500 characters of a 114# rejected flag are the middle of the usage text. Name the reason line(s) before the tail. 115reasons = [line .strip ()for line in text .splitlines () 116if re .search (r"unknown argument|unrecognized|invalid value|error|refus|is required|cannot|failed" , 117line ,re .IGNORECASE )][:3 ] 118lead = f"; reason: { ' | ' . join ( reasons )[: 300 ] } " if reasons else "" 119return f" { lead } ; log: { text [ - limit :]. strip () } " 120except OSError : 121return "" 122 123def close (self )-> None : 124if self ._proc is not None and self ._proc .poll ()is None : 125self ._proc .terminate () 126try : 127self ._proc .wait (timeout = 20 ) 128except subprocess .TimeoutExpired : 129self ._proc .kill () 130self ._proc = None 131if self ._log is not None : 132try : 133self ._log .close () 134except OSError : 135pass 136 137def __enter__ (self )-> "ApiHarness" : 138self .start () 139return self 140 141def __exit__ (self ,* exc :object )-> None : 142self .close () 143 144# ------------------------------------------------------------------ measuring 145 146def measure (self ,* ,prompt :str ,max_new :int ,expect :str | None = None , 147temperature :float = 0.0 ,seed :int = 1 , 148model :str = "strata-local" )-> EngineMeasurement : 149"""One streamed chat completion, measured end to end. 150 151`expect` is a regular expression the answer must match for the run to count as correct. A 152configuration that is fast and wrong must not be able to win a sweep, so a mismatch raises 153rather than being recorded as a fast result. 154""" 155body = json .dumps ({ 156"model" :model ,"stream" :True ,"max_tokens" :max_new , 157"temperature" :temperature ,"seed" :seed , 158"messages" : [{"role" :"user" ,"content" :prompt }], 159 }).encode ("utf-8" ) 160request = urllib .request .Request ( 161f" { self . url } /v1/chat/completions" ,data = body , 162headers = {"content-type" :"application/json" ,"authorization" :"Bearer strata-local" }, 163method = "POST" ) 164 165started = time .monotonic () 166# Reasoning models stream their thinking into `reasoning_content` and the answer into 167# `content`. Measuring only `content` reports "no content" for a reasoning model and, worse, 168# moves the first-token time to whenever the thinking finished -- so a configuration that 169# thinks longer would look faster. Both are output, and the first of either is the wait. 170text_parts :list [str ]= [] 171reasoning_parts :list [str ]= [] 172first_token_at :float | None = None 173usage :dict [str ,Any ]= {} 174finish :str | None = None 175try : 176with loopback .urlopen (request ,timeout = self .request_timeout_s )as response : 177for raw in response : 178line = raw .decode ("utf-8" ,errors = "replace" ).strip () 179if not line .startswith ("data:" ): 180continue 181payload = line [5 :].strip () 182if payload == "[DONE]" : 183break 184try : 185frame = json .loads (payload ) 186except json .JSONDecodeError : 187continue 188if frame .get ("error" ): 189raise MeasurementError ( 190f"the worker reported an error: { frame [ 'error' ]. get ( 'message' ) } " ) 191if frame .get ("usage" ): 192usage = frame ["usage" ] 193choice = (frame .get ("choices" )or [{}])[0 ] 194delta = choice .get ("delta" )or {} 195piece = delta .get ("content" )or delta .get ("reasoning_content" ) 196if piece : 197if first_token_at is None : 198first_token_at = time .monotonic () 199if delta .get ("content" ): 200text_parts .append (delta ["content" ]) 201else : 202reasoning_parts .append (delta ["reasoning_content" ]) 203if choice .get ("finish_reason" ): 204finish = choice ["finish_reason" ] 205except urllib .error .HTTPError as e : 206detail = e .read ().decode ("utf-8" ,errors = "replace" )[:400 ] 207raise MeasurementError (f"the worker refused the request ( { e . code } ): { detail } " )from None 208except (urllib .error .URLError ,OSError )as e : 209raise MeasurementError (f"the request failed: { e } " + self ._log_tail ())from None 210 211duration_ms = (time .monotonic ()- started )* 1000.0 212answer = "" .join (text_parts ) 213reasoning = "" .join (reasoning_parts ) 214if not answer and not reasoning : 215raise MeasurementError ("the worker streamed no content and no reasoning" ) 216# The expectation is checked against the answer when there is one, and against the reasoning 217# otherwise: an engine that only streams reasoning is still producing checkable output. 218checked = answer or reasoning 219if expect is not None and not re .search (expect ,checked ,re .IGNORECASE | re .DOTALL ): 220raise MeasurementError ( 221f"the output did not match the expectation { expect !r } , so this configuration is not " 222f"correct: { checked [: 200 ]!r } " ) 223if not answer : 224raise MeasurementError ( 225"the worker streamed reasoning but no answer, so its rate is not a generation rate: " 226f" { reasoning [: 120 ]!r } " ) 227 228out_tokens = usage .get ("completion_tokens" ) 229if not isinstance (out_tokens ,int )or out_tokens <= 0 : 230# The server reports usage; counting frames here would be an estimate, and reporting an 231# estimate as a token count is how chunk counts get mistaken for tokens. 232raise MeasurementError ("the worker reported no completion_tokens, so the rate is unknown" ) 233prompt_tokens = usage .get ("prompt_tokens" ) 234decode_ms = duration_ms - ((first_token_at - started )* 1000.0 if first_token_at else 0.0 ) 235decode_ms = max (decode_ms ,0.001 ) 236 237parts = usage .get ("prompt_tokens_details" )or {} 238measurement = EngineMeasurement ( 239tokens_per_s = round (out_tokens * 1000.0 / decode_ms ,4 ), 240decode_tokens_per_s = round (out_tokens * 1000.0 / decode_ms ,4 ), 241prompt_tokens_per_s = (round (prompt_tokens * 1000.0 / max ( 242 (first_token_at - started )* 1000.0 ,0.001 ),4 ) 243if isinstance (prompt_tokens ,int )and prompt_tokens and first_token_at else None ), 244ttft_ms = round ((first_token_at - started )* 1000.0 ,2 )if first_token_at else None , 245client_ttft_ms = round ((first_token_at - started )* 1000.0 ,2 )if first_token_at else None , 246produced = out_tokens , 247prompt_tokens = prompt_tokens if isinstance (prompt_tokens ,int )else 0 , 248finish = finish or "unknown" , 249source = "worker-http-api" , 250mode = "api" , 251raw = {"usage" :usage ,"cached_tokens" :parts .get ("cached_tokens" ), 252"duration_ms" :round (duration_ms ,2 ),"answer_chars" :len (answer ), 253"reasoning_chars" :len (reasoning )}) 254if self ._proc is not None : 255measurement .peak_memory_mib = process_tree_peak_mib (self ._proc .pid ) 256return measurement 257 258 259def make_api_measure (* ,python :Path | str ,serve_dir :Path ,config_path :Path ,prompt :str , 260max_new :int ,expect :str | None = None ,port :int = 8123 , 261boot_timeout_s :float = 900.0 , 262request_timeout_s :float = 900.0 ): 263"""Build a `measure` callable for the tuning job that uses the HTTP API. 264 265Unlike the protocol harness, the configuration is already in a file, so the candidate's flags are 266written to a *copy* of it and the worker is pointed at the copy. The caller's file is never 267touched: a sweep must not be able to change the active configuration even by accident. 268""" 269import tempfile 270 271from strata_control .tune_apply import apply_args_to_config ,args_to_argv 272 273base = json .loads (Path (config_path ).read_text (encoding = "utf-8" )) 274 275def measure (candidate )-> dict [str ,float ]: 276args = getattr (candidate ,"args" ,candidate ) 277candidate_cfg = apply_args_to_config (base ,args_to_argv (args )if isinstance (args ,dict )else list (args )) 278with tempfile .NamedTemporaryFile ("w" ,prefix = "strata-tune-candidate-" ,suffix = ".json" , 279delete = False ,encoding = "utf-8" )as fh : 280json .dump (candidate_cfg ,fh ,indent = 1 ) 281path = Path (fh .name ) 282harness = ApiHarness (python = python ,serve_dir = serve_dir ,config_path = path ,port = port , 283boot_timeout_s = boot_timeout_s ,request_timeout_s = request_timeout_s ) 284try : 285harness .start () 286return harness .measure (prompt = prompt ,max_new = max_new ,expect = expect ).to_metrics () 287finally : 288harness .close () 289try : 290path .unlink () 291except OSError : 292pass 293 294return measure