okami.mom/strata

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

Niko1221Merge f-142b-serve into f-1426e1085c1d

main
5.9 KiB126 linesraw
1#!/usr/bin/env python3
2"""benchmark.py - this report's client: one ~1,000-token warm-up (not counted), then three runs each at
34,096 / 32,768 / 128,000 prompt tokens (prompts.json, built by make_prompts.py), one request at a time,
4streamed, temperature 0, 256-token cap, the server's other defaults. Per request: time to the first streamed token
5(reasoning or answer text, whichever comes first; keep-alives and empty deltas ignored), total wall time, the server's
6`timings` (llama.cpp's names, from the engine's own clock: cache_n reused, prompt_n read, prompt_ms, predicted_n,
7predicted_ms, drafts) and memory right after it (MemAvailable, the engine's RSS, each GPU's used VRAM) and what the engine read from the
8drive during it (/proc/PID/io read_bytes). Linux only (it reads /proc).
9
10    python benchmark.py --base http://127.0.0.1:8081 --label NAME --out NAME.json"""
11import argparse
12import json
13import subprocess
14import time
15import urllib.request
16from pathlib import Path
17
18ap = argparse.ArgumentParser()
19ap.add_argument("--base", default="http://127.0.0.1:8081")
20ap.add_argument("--prompts", default="prompts.json")
21ap.add_argument("--label", required=True)
22ap.add_argument("--out", required=True)
23ap.add_argument("--max-tokens", type=int, default=256)
24ap.add_argument("--engine-pattern", default="strata --serve --pack")
25ap.add_argument("--sizes", default="", help="only these sizes (warmup,4096,32768,128000); default all")
26ap.add_argument("--reps", default="", help="only these reps, e.g. 0,1")
27a = ap.parse_args()
28
29
30def engine_pid():
31    """the engine process: matches the pattern and its executable is named strata"""
32    import os
33    for pid in subprocess.run(["pgrep", "-f", a.engine_pattern], capture_output=True, text=True).stdout.split():
34        try:
35            if os.path.basename(os.readlink(f"/proc/{pid}/exe")) == "strata":
36                return pid
37        except OSError:
38            pass
39    return None
40
41
42def memory():
43    m = {}
44    for line in open("/proc/meminfo"):
45        k, v = line.split(":", 1)
46        if k in ("MemAvailable", "SwapFree", "SwapTotal"):
47            m[k] = int(v.split()[0]) // 1024
48    pid = engine_pid()
49    rss = 0
50    if pid:
51        for line in open(f"/proc/{pid}/status"):
52            if line.startswith("VmRSS"):
53                rss = int(line.split()[1]) // 1024
54    g = subprocess.run(["nvidia-smi", "--query-gpu=index,memory.used", "--format=csv,noheader,nounits"],
55                       capture_output=True, text=True).stdout.split("\n")
56    return {"mem_available_mib": m.get("MemAvailable"), "swap_used_mib": m.get("SwapTotal", 0) - m.get("SwapFree", 0),
57            "engine_rss_mib": rss, "gpu_used_mib": {x.split(",")[0].strip(): int(x.split(",")[1]) for x in g if x.strip()}}
58
59
60def engine_read_bytes():
61    """bytes the engine process fetched from storage so far (/proc/PID/io read_bytes: page-cache hits not counted)"""
62    pid = engine_pid()
63    try:
64        for line in open(f"/proc/{pid}/io"):
65            if line.startswith("read_bytes"):
66                return int(line.split()[1])
67    except (OSError, TypeError):
68        return None
69
70
71def ask(msgs):
72    body = json.dumps({"model": "strata", "messages": msgs, "max_tokens": a.max_tokens, "temperature": 0,
73                       "stream": True, "stream_options": {"include_usage": True}}).encode()
74    r = urllib.request.Request(a.base + "/v1/chat/completions", data=body, headers={"Content-Type": "application/json"})
75    t0 = time.time()
76    first, finish, usage, timings, n_content, n_reason, first_kind = None, None, None, None, 0, 0, None
77    with urllib.request.urlopen(r, timeout=1800) as f:
78        for raw in f:
79            line = raw.decode("utf-8", "replace").strip()
80            if not line.startswith("data:"):
81                continue
82            data = line[5:].strip()
83            if data == "[DONE]":
84                break
85            d = json.loads(data)
86            usage = d.get("usage") or usage
87            timings = d.get("timings") or timings
88            for c in d.get("choices", []):
89                delta = c.get("delta", {})
90                txt, rsn = delta.get("content") or "", delta.get("reasoning_content") or ""
91                if (txt or rsn) and first is None:
92                    first, first_kind = time.time() - t0, "reasoning" if rsn else "answer"
93                n_content += len(txt)
94                n_reason += len(rsn)
95                finish = c.get("finish_reason") or finish
96    return {"ttft_s": round(first, 3) if first is not None else None, "first_token_kind": first_kind,
97            "total_s": round(time.time() - t0, 3), "finish": finish, "usage": usage, "timings": timings,
98            "answer_chars": n_content, "reasoning_chars": n_reason}
99
100
101P = json.loads(Path(a.prompts).read_text())
102runs = []
103warm = None
104for p in P:
105    if a.sizes and p["size"] not in a.sizes.split(","):
106        continue
107    if a.reps and p["size"] != "warmup" and str(p["rep"]) not in a.reps.split(","):
108        continue
109    rb0 = engine_read_bytes()
110    rec = {"label": a.label, "size": p["size"], "rep": p["rep"], "target_tokens": p["target"],
111           "started": time.strftime("%Y-%m-%dT%H:%M:%S"), **ask(p["messages"])}
112    rb1 = engine_read_bytes()
113    rec["drive_read_gb"] = round((rb1 - rb0) / 1e9, 2) if rb0 is not None and rb1 is not None else None
114    rec["memory_after"] = memory()
115    t = rec["timings"] or {}
116    print(f"{a.label} {p['size']:>7} r{p['rep']}: prompt {t.get('prompt_n')} read + {t.get('cache_n')} reused in "
117          f"{t.get('prompt_ms')} ms ({t.get('prompt_per_second')} tok/s), {t.get('predicted_n')} generated at "
118          f"{t.get('predicted_per_second')} tok/s, TTFT {rec['ttft_s']} s ({rec['first_token_kind']}), finish {rec['finish']}, "
119          f"drive {rec['drive_read_gb']} GB, MemAvailable {rec['memory_after']['mem_available_mib']} MiB",
120          flush=True)
121    if p["size"] != "warmup":
122        runs.append(rec)
123    else:
124        warm = rec
125Path(a.out).write_text(json.dumps({"label": a.label, "warmup": warm, "runs": runs}, indent=1))
126print("wrote", a.out)