okami.mom/strata

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

homeofebench: community results, RTX 2080 Ti 11 GB + Threadripper 3960X, IQ3_S at 262K with KV streaming (#469)707fd49eb

main
5.7 KiB139 linesraw
1"""Shared helpers for the scripts in this folder: talk to a running Strata server, wait until it is idle,
2follow its logs, parse the engine's per-request timing lines and strip private details from what is saved.
3
4The API key is read at run time from the STRATA_API_KEY environment variable or from the server's config
5file (--key-config, its "api_key"); it is never written to any output."""
6from __future__ import annotations
7
8import json
9import os
10import re
11import socket
12import time
13import urllib.request
14from pathlib import Path
15
16PROMPT_RE = re.compile(r"strata serve: prompt (\d+) tokens = (\d+) reused \+ (\d+) read in (\d+) ms \(([\d.]+) tok/s\), "
17                       r"(\d+) generated in (\d+) ms \(([\d.]+) tok/s\), drafts accepted (\d+) of (\d+), (\d+) checkpoints")
18HIT_RE = re.compile(r"decode expert cache hit rate: ([\d.]+)% \((\d+) hits / (\d+) lookups\)")
19KV_RE = re.compile(r"KV streaming: ([\d.]+)% of (\d+) block reads hit VRAM, ([\d.]+) MiB read from RAM")
20SUFFIX_RE = re.compile(r"suffix drafts: (\d+) windows, (\d+) of (\d+) drafts accepted")
21
22
23def api_key(key_config: str | None) -> str:
24    key = os.environ.get("STRATA_API_KEY", "")
25    if not key and key_config:
26        key = json.loads(Path(key_config).read_text()).get("api_key") or ""
27    return key
28
29
30class Server:
31    def __init__(self, url: str, key: str):
32        self.url = url.rstrip("/")
33        self.key = key
34
35    def headers(self) -> dict:
36        h = {"Content-Type": "application/json"}
37        if self.key:
38            h["Authorization"] = "Bearer " + self.key
39        return h
40
41    def get(self, path: str, timeout: float = 30) -> dict:
42        req = urllib.request.Request(self.url + path, headers=self.headers())
43        with urllib.request.urlopen(req, timeout=timeout) as r:
44            return json.loads(r.read())
45
46    def totals(self) -> int:
47        """Requests finished since the server started (GET /metrics): a jump of more than one around a measured
48        request means someone else's request ran in between."""
49        return int(self.get("/metrics")["totals"]["requests"])
50
51    def wait_idle(self, settle_s: float = 3.0, poll_s: float = 1.0) -> dict:
52        """Block until GET /status reports busy=false and queued=0 for `settle_s` seconds in a row."""
53        quiet_since = None
54        while True:
55            s = self.get("/status")
56            if not s.get("busy") and not s.get("queued"):
57                quiet_since = quiet_since or time.time()
58                if time.time() - quiet_since >= settle_s:
59                    return s
60            else:
61                if quiet_since is not None:
62                    print("  server busy (foreign request?), waiting ...", flush=True)
63                quiet_since = None
64            time.sleep(poll_s)
65
66    def loaded(self) -> bool:
67        return bool(self.get("/health").get("loaded"))
68
69
70class LogTail:
71    """Byte offset into a log file; `since()` returns the lines appended after `mark()`."""
72
73    def __init__(self, path: str):
74        self.path = Path(path)
75        self.offset = 0
76
77    def mark(self):
78        self.offset = self.path.stat().st_size
79
80    def since(self) -> list[str]:
81        with self.path.open("rb") as f:
82            f.seek(self.offset)
83            data = f.read()
84        return data.decode("utf-8", errors="replace").splitlines()
85
86
87def parse_engine(lines: list[str]) -> list[dict]:
88    """One dict per 'strata serve: prompt ...' line, with the hit-rate / KV-streaming / suffix lines after it."""
89    out = []
90    for line in lines:
91        m = PROMPT_RE.search(line)
92        if m:
93            g = m.groups()
94            out.append({"prompt_tokens": int(g[0]), "reused": int(g[1]), "read": int(g[2]), "prompt_ms_log": int(g[3]),
95                        "prompt_tok_s_log": float(g[4]), "generated": int(g[5]), "decode_ms_log": int(g[6]),
96                        "decode_tok_s_log": float(g[7]), "drafts_accepted": int(g[8]), "drafts_proposed": int(g[9]),
97                        "checkpoints": int(g[10]), "cancelled": "(cancelled)" in line, "line": line.strip()})
98            continue
99        if not out:
100            continue
101        for key, rx in (("hit", HIT_RE), ("kv", KV_RE), ("suffix", SUFFIX_RE)):
102            m = rx.search(line)
103            if m:
104                if key == "hit":
105                    out[-1].update(hit_rate_pct=float(m[1]), hit_line=line.strip())
106                elif key == "kv":
107                    out[-1].update(kv_vram_pct=float(m[1]), kv_block_reads=int(m[2]), kv_ram_mib=float(m[3]),
108                                   kv_line=line.strip())
109                else:
110                    out[-1].update(suffix_windows=int(m[1]), suffix_accepted=int(m[2]), suffix_proposed=int(m[3]))
111    return out
112
113
114_HOST = socket.gethostname()
115_HOME = str(Path.home())
116
117
118def scrub(text: str) -> str:
119    """Remove the install directory (STRATA_SCRUB_PREFIX, shown as <workspace>), the home directory, user name,
120    a host name and LAN addresses from a log excerpt."""
121    prefix = os.environ.get("STRATA_SCRUB_PREFIX")    # the directory that holds Strata and Strata-data
122    if prefix:
123        text = text.replace(prefix.rstrip("/") + "/", "<workspace>/")
124    text = text.replace(_HOME, "<home>")
125    text = text.replace(os.environ.get("USER", "\0"), "<user>")
126    if _HOST and len(_HOST) > 8:                     # a short host name can be an ordinary word in the log
127        text = text.replace(_HOST, "<host>")
128    text = re.sub(r"\b(?:192\.168|10\.\d+|172\.(?:1[6-9]|2\d|3[01]))\.\d+\.\d+\b", "<lan-ip>", text)
129    return text
130
131
132def scrub_lines(lines: list[str]) -> list[str]:
133    return [scrub(l) for l in lines if "from other devices" not in l]
134
135
136def sse_lines(resp):
137    """Yield (t_seconds, raw_line) for each SSE line of an HTTP response."""
138    for raw in resp:
139        yield time.perf_counter(), raw.decode("utf-8", errors="replace").rstrip("\r\n")