okami.mom/strata

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

Niko1221Merge branch 'f-1402-w' into f-140253623e56f

main
4.5 KiB91 linesraw
1#!/usr/bin/env python3
2"""Strata community-report runs (PREREG_STRATA_194 addendum). Runs ON .194 against a running Strata server.
3Builds ~N-token prompts from Strata's own docs (MIT, at the installed commit), sends each request with a unique nonce
4first line (no prefix reuse), streams, and records client TTFT / total. The engine's own timing line for each request
5is read from Strata's log afterwards (by order). Python stdlib only.
6usage: strata_bench.py --url http://127.0.0.1:8080 --repo ~/strata --lengths 4096,32768 --runs 3 --out bench.jsonl"""
7import argparse, json, os, secrets, time, urllib.request
8from pathlib import Path
9
10QUESTION = ("\n\nThe text above is documentation for an inference engine. In a few short paragraphs, explain what "
11            "the engine does and how it keeps a large mixture-of-experts model fast on a consumer PC.")
12
13
14def corpus(repo: Path) -> str:
15    parts = []
16    for p in sorted((repo / "docs").glob("*.md")) + [repo / "README.md"]:
17        parts.append(f"===== {p.name} =====\n" + p.read_text(errors="replace"))
18    return "\n\n".join(parts)
19
20
21def tokenize_count(url: str, text: str) -> int:
22    for path in ("/tokenize", "/v1/tokenize"):
23        try:
24            req = urllib.request.Request(url + path, json.dumps({"content": text}).encode(), {"Content-Type": "application/json"})
25            with urllib.request.urlopen(req, timeout=120) as r:
26                return len(json.load(r).get("tokens", []))
27        except Exception:
28            continue
29    return int(len(text) / 3.6)            # fallback estimate, flagged in the output
30
31
32def build(url: str, text: str, target: int) -> tuple[str, int]:
33    lo, hi = 1000, len(text)
34    best = text[:lo]
35    while hi - lo > 2000:                  # binary search on characters for ~target tokens
36        mid = (lo + hi) // 2
37        if tokenize_count(url, text[:mid] + QUESTION) <= target:
38            lo, best = mid, text[:mid]
39        else:
40            hi = mid
41    p = best + QUESTION
42    return p, tokenize_count(url, p)
43
44
45def run(url: str, prompt: str) -> dict:
46    nonce = secrets.token_hex(16)
47    body = {"model": "strata", "messages": [{"role": "user", "content": f"[bench nonce: {nonce}]\n" + prompt}],
48            "max_tokens": 256, "temperature": 0, "stream": True, "reasoning_effort": "none",
49            "stream_options": {"include_usage": True}}
50    req = urllib.request.Request(url + "/v1/chat/completions", json.dumps(body).encode(), {"Content-Type": "application/json"})
51    t0 = time.monotonic(); first = last = None; text = []; usage = None; reasoning = 0
52    with urllib.request.urlopen(req, timeout=3600) as r:
53        for raw in r:
54            line = raw.decode(errors="replace").strip()
55            if not line.startswith("data: ") or line == "data: [DONE]":
56                continue
57            ev = json.loads(line[6:])
58            for ch in ev.get("choices") or []:
59                d = ch.get("delta") or {}
60                if d.get("content") or d.get("reasoning_content"):
61                    now = time.monotonic() - t0
62                    first = now if first is None else first
63                    last = now
64                    text.append(d.get("content") or "")
65                    reasoning += len(d.get("reasoning_content") or "")
66            usage = ev.get("usage") or usage
67    total = time.monotonic() - t0
68    return {"nonce": nonce, "ttft_s": round(first, 3) if first else None, "total_s": round(total, 3),
69            "first_to_last_s": round(last - first, 3) if first is not None else None,
70            "usage": usage, "content_chars": len("".join(text)), "reasoning_chars": reasoning,
71            "content_head": "".join(text)[:200]}
72
73
74def main():
75    ap = argparse.ArgumentParser()
76    ap.add_argument("--url", default="http://127.0.0.1:8080"); ap.add_argument("--repo", default=os.path.expanduser("~/strata"))
77    ap.add_argument("--lengths", default="4096,32768"); ap.add_argument("--runs", type=int, default=3)
78    ap.add_argument("--out", required=True)
79    a = ap.parse_args()
80    text = corpus(Path(a.repo))
81    with open(a.out, "a") as f:
82        for L in [int(x) for x in a.lengths.split(",")]:
83            prompt, n = build(a.url, text, L - 40)
84            for i in range(a.runs):
85                rec = {"target_tokens": L, "prompt_tokens_tokenized": n, "run": i + 1, **run(a.url, prompt)}
86                f.write(json.dumps(rec) + "\n"); f.flush(); os.fsync(f.fileno())
87                print(json.dumps({k: rec[k] for k in ("target_tokens", "run", "ttft_s", "total_s", "content_chars", "reasoning_chars")}), flush=True)
88
89
90if __name__ == "__main__":
91    main()