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
14.5 KiB294 linesraw
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
43    The server is started as a child process and stopped afterwards: a configuration that changes the
44    KV layout or the expert cache cannot be assumed to take effect in a running server, and reusing
45    one would silently measure the previous candidate.
46    """
47
48    def __init__(self, *, python: Path | str, serve_dir: Path, config_path: Path,
49                 port: int = 8123, host: str = "127.0.0.1", boot_timeout_s: float = 900.0,
50                 request_timeout_s: float = 900.0, env: dict[str, str] | None = None,
51                 engine: str = "strata") -> None:
52        self.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.
55        self.engine = engine
56        self.serve_dir = Path(serve_dir)
57        self.config_path = Path(config_path)
58        self.port = int(port)
59        self.host = host
60        self.boot_timeout_s = boot_timeout_s
61        self.request_timeout_s = request_timeout_s
62        self.env = env
63        self._proc: subprocess.Popen | None = None
64        self._log = None
65
66    # ------------------------------------------------------------------ lifecycle
67
68    @property
69    def url(self) -> str:
70        return f"http://{self.host}:{self.port}"
71
72    def _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.
75        return [self.python, "-m", "serve.server", "--engine", self.engine,
76                "--config", str(self.config_path),
77                "--host", self.host, "--port", str(self.port)]
78
79    def start(self) -> None:
80        import tempfile
81        self._log = tempfile.NamedTemporaryFile(prefix="strata-api-harness-", suffix=".log",
82                                                delete=False)
83        try:
84            from serve import lifeline       # the worker (and the engine under it) end with this process
85            self._proc = lifeline.popen(self._argv(), "worker", cwd=str(self.serve_dir),
86                                        env=None if self.env is None else quiet_crash_env(dict(self.env)),
87                                        stdout=self._log, stderr=subprocess.STDOUT)
88        except OSError as e:
89            raise MeasurementError(f"the worker could not be started: {e}") from e
90
91        deadline = time.monotonic() + self.boot_timeout_s
92        while time.monotonic() < deadline:
93            if self._proc.poll() is not None:
94                raise MeasurementError(
95                    f"the worker exited with code {self._proc.returncode} before becoming ready"
96                    + self._log_tail())
97            try:
98                with loopback.urlopen(f"{self.url}/health", timeout=2) as response:
99                    if response.status == 200:
100                        return
101            except (urllib.error.URLError, OSError):
102                time.sleep(0.2)
103        raise MeasurementError(f"the worker did not answer /health within {self.boot_timeout_s:.0f}s"
104                               + self._log_tail())
105
106    def _log_tail(self, limit: int = 500) -> str:
107        if self._log is None:
108            return ""
109        try:
110            text = Path(self._log.name).read_text(encoding="utf-8", errors="replace")
111            if not text.strip():
112                return ""
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.
115            reasons = [line.strip() for line in text.splitlines()
116                       if re.search(r"unknown argument|unrecognized|invalid value|error|refus|is required|cannot|failed",
117                                    line, re.IGNORECASE)][:3]
118            lead = f"; reason: {' | '.join(reasons)[:300]}" if reasons else ""
119            return f"{lead}; log: {text[-limit:].strip()}"
120        except OSError:
121            return ""
122
123    def close(self) -> None:
124        if self._proc is not None and self._proc.poll() is None:
125            self._proc.terminate()
126            try:
127                self._proc.wait(timeout=20)
128            except subprocess.TimeoutExpired:
129                self._proc.kill()
130        self._proc = None
131        if self._log is not None:
132            try:
133                self._log.close()
134            except OSError:
135                pass
136
137    def __enter__(self) -> "ApiHarness":
138        self.start()
139        return self
140
141    def __exit__(self, *exc: object) -> None:
142        self.close()
143
144    # ------------------------------------------------------------------ measuring
145
146    def measure(self, *, prompt: str, max_new: int, expect: str | None = None,
147                temperature: float = 0.0, seed: int = 1,
148                model: 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
152        configuration that is fast and wrong must not be able to win a sweep, so a mismatch raises
153        rather than being recorded as a fast result.
154        """
155        body = 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")
160        request = urllib.request.Request(
161            f"{self.url}/v1/chat/completions", data=body,
162            headers={"content-type": "application/json", "authorization": "Bearer strata-local"},
163            method="POST")
164
165        started = 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.
170        text_parts: list[str] = []
171        reasoning_parts: list[str] = []
172        first_token_at: float | None = None
173        usage: dict[str, Any] = {}
174        finish: str | None = None
175        try:
176            with loopback.urlopen(request, timeout=self.request_timeout_s) as response:
177                for raw in response:
178                    line = raw.decode("utf-8", errors="replace").strip()
179                    if not line.startswith("data:"):
180                        continue
181                    payload = line[5:].strip()
182                    if payload == "[DONE]":
183                        break
184                    try:
185                        frame = json.loads(payload)
186                    except json.JSONDecodeError:
187                        continue
188                    if frame.get("error"):
189                        raise MeasurementError(
190                            f"the worker reported an error: {frame['error'].get('message')}")
191                    if frame.get("usage"):
192                        usage = frame["usage"]
193                    choice = (frame.get("choices") or [{}])[0]
194                    delta = choice.get("delta") or {}
195                    piece = delta.get("content") or delta.get("reasoning_content")
196                    if piece:
197                        if first_token_at is None:
198                            first_token_at = time.monotonic()
199                        if delta.get("content"):
200                            text_parts.append(delta["content"])
201                        else:
202                            reasoning_parts.append(delta["reasoning_content"])
203                    if choice.get("finish_reason"):
204                        finish = choice["finish_reason"]
205        except urllib.error.HTTPError as e:
206            detail = e.read().decode("utf-8", errors="replace")[:400]
207            raise MeasurementError(f"the worker refused the request ({e.code}): {detail}") from None
208        except (urllib.error.URLError, OSError) as e:
209            raise MeasurementError(f"the request failed: {e}" + self._log_tail()) from None
210
211        duration_ms = (time.monotonic() - started) * 1000.0
212        answer = "".join(text_parts)
213        reasoning = "".join(reasoning_parts)
214        if not answer and not reasoning:
215            raise 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.
218        checked = answer or reasoning
219        if expect is not None and not re.search(expect, checked, re.IGNORECASE | re.DOTALL):
220            raise MeasurementError(
221                f"the output did not match the expectation {expect!r}, so this configuration is not "
222                f"correct: {checked[:200]!r}")
223        if not answer:
224            raise MeasurementError(
225                "the worker streamed reasoning but no answer, so its rate is not a generation rate: "
226                f"{reasoning[:120]!r}")
227
228        out_tokens = usage.get("completion_tokens")
229        if 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.
232            raise MeasurementError("the worker reported no completion_tokens, so the rate is unknown")
233        prompt_tokens = usage.get("prompt_tokens")
234        decode_ms = duration_ms - ((first_token_at - started) * 1000.0 if first_token_at else 0.0)
235        decode_ms = max(decode_ms, 0.001)
236
237        parts = usage.get("prompt_tokens_details") or {}
238        measurement = EngineMeasurement(
239            tokens_per_s=round(out_tokens * 1000.0 / decode_ms, 4),
240            decode_tokens_per_s=round(out_tokens * 1000.0 / decode_ms, 4),
241            prompt_tokens_per_s=(round(prompt_tokens * 1000.0 / max(
242                (first_token_at - started) * 1000.0, 0.001), 4)
243                if isinstance(prompt_tokens, int) and prompt_tokens and first_token_at else None),
244            ttft_ms=round((first_token_at - started) * 1000.0, 2) if first_token_at else None,
245            client_ttft_ms=round((first_token_at - started) * 1000.0, 2) if first_token_at else None,
246            produced=out_tokens,
247            prompt_tokens=prompt_tokens if isinstance(prompt_tokens, int) else 0,
248            finish=finish or "unknown",
249            source="worker-http-api",
250            mode="api",
251            raw={"usage": usage, "cached_tokens": parts.get("cached_tokens"),
252                 "duration_ms": round(duration_ms, 2), "answer_chars": len(answer),
253                 "reasoning_chars": len(reasoning)})
254        if self._proc is not None:
255            measurement.peak_memory_mib = process_tree_peak_mib(self._proc.pid)
256        return measurement
257
258
259def make_api_measure(*, python: Path | str, serve_dir: Path, config_path: Path, prompt: str,
260                     max_new: int, expect: str | None = None, port: int = 8123,
261                     boot_timeout_s: float = 900.0,
262                     request_timeout_s: float = 900.0):
263    """Build a `measure` callable for the tuning job that uses the HTTP API.
264
265    Unlike the protocol harness, the configuration is already in a file, so the candidate's flags are
266    written to a *copy* of it and the worker is pointed at the copy. The caller's file is never
267    touched: a sweep must not be able to change the active configuration even by accident.
268    """
269    import tempfile
270
271    from strata_control.tune_apply import apply_args_to_config, args_to_argv
272
273    base = json.loads(Path(config_path).read_text(encoding="utf-8"))
274
275    def measure(candidate) -> dict[str, float]:
276        args = getattr(candidate, "args", candidate)
277        candidate_cfg = apply_args_to_config(base, args_to_argv(args) if isinstance(args, dict) else list(args))
278        with tempfile.NamedTemporaryFile("w", prefix="strata-tune-candidate-", suffix=".json",
279                                         delete=False, encoding="utf-8") as fh:
280            json.dump(candidate_cfg, fh, indent=1)
281            path = Path(fh.name)
282        harness = ApiHarness(python=python, serve_dir=serve_dir, config_path=path, port=port,
283                             boot_timeout_s=boot_timeout_s, request_timeout_s=request_timeout_s)
284        try:
285            harness.start()
286            return harness.measure(prompt=prompt, max_new=max_new, expect=expect).to_metrics()
287        finally:
288            harness.close()
289            try:
290                path.unlink()
291            except OSError:
292                pass
293
294    return measure