okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
707fd49eb
main
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\), " 17r"(\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 : 24key = os .environ .get ("STRATA_API_KEY" ,"" ) 25if not key and key_config : 26key = json .loads (Path (key_config ).read_text ()).get ("api_key" )or "" 27return key 28 29 30class Server : 31def __init__ (self ,url :str ,key :str ): 32self .url = url .rstrip ("/" ) 33self .key = key 34 35def headers (self )-> dict : 36h = {"Content-Type" :"application/json" } 37if self .key : 38h ["Authorization" ]= "Bearer " + self .key 39return h 40 41def get (self ,path :str ,timeout :float = 30 )-> dict : 42req = urllib .request .Request (self .url + path ,headers = self .headers ()) 43with urllib .request .urlopen (req ,timeout = timeout )as r : 44return json .loads (r .read ()) 45 46def totals (self )-> int : 47"""Requests finished since the server started (GET /metrics): a jump of more than one around a measured 48request means someone else's request ran in between.""" 49return int (self .get ("/metrics" )["totals" ]["requests" ]) 50 51def 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.""" 53quiet_since = None 54while True : 55s = self .get ("/status" ) 56if not s .get ("busy" )and not s .get ("queued" ): 57quiet_since = quiet_since or time .time () 58if time .time ()- quiet_since >= settle_s : 59return s 60else : 61if quiet_since is not None : 62" server busy (foreign request?), waiting ..." ,flush = True ) 63quiet_since = None 64time .sleep (poll_s ) 65 66def loaded (self )-> bool : 67return 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 73def __init__ (self ,path :str ): 74self .path = Path (path ) 75self .offset = 0 76 77def mark (self ): 78self .offset = self .path .stat ().st_size 79 80def since (self )-> list [str ]: 81with self .path .open ("rb" )as f : 82f .seek (self .offset ) 83data = f .read () 84return 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.""" 89out = [] 90for line in lines : 91m = PROMPT_RE .search (line ) 92if m : 93g = m .groups () 94out .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 ()}) 98continue 99if not out : 100continue 101for key ,rx in (("hit" ,HIT_RE ), ("kv" ,KV_RE ), ("suffix" ,SUFFIX_RE )): 102m = rx .search (line ) 103if m : 104if key == "hit" : 105out [- 1 ].update (hit_rate_pct = float (m [1 ]),hit_line = line .strip ()) 106elif key == "kv" : 107out [- 1 ].update (kv_vram_pct = float (m [1 ]),kv_block_reads = int (m [2 ]),kv_ram_mib = float (m [3 ]), 108kv_line = line .strip ()) 109else : 110out [- 1 ].update (suffix_windows = int (m [1 ]),suffix_accepted = int (m [2 ]),suffix_proposed = int (m [3 ])) 111return 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, 120a host name and LAN addresses from a log excerpt.""" 121prefix = os .environ .get ("STRATA_SCRUB_PREFIX" )# the directory that holds Strata and Strata-data 122if prefix : 123text = text .replace (prefix .rstrip ("/" )+ "/" ,"<workspace>/" ) 124text = text .replace (_HOME ,"<home>" ) 125text = text .replace (os .environ .get ("USER" ,"\0" ),"<user>" ) 126if _HOST and len (_HOST )> 8 :# a short host name can be an ordinary word in the log 127text = text .replace (_HOST ,"<host>" ) 128text = re .sub (r"\b(?:192\.168|10\.\d+|172\.(?:1[6-9]|2\d|3[01]))\.\d+\.\d+\b" ,"<lan-ip>" ,text ) 129return text 130 131 132def scrub_lines (lines :list [str ])-> list [str ]: 133return [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.""" 138for raw in resp : 139yield time .perf_counter (),raw .decode ("utf-8" ,errors = "replace" ).rstrip ("\r\n" )