okami.mom/strata

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

Niko1221Merge f-141-conc: --batch-groups auto for layer-split batches, #857 fix, listen backlogb0bc4a70f

main
8.0 KiB160 linesraw
1#!/usr/bin/env python3
2"""Small load generator for the OpenAI-compatible server: C clients at once, each a different prompt.
3
4    python3 tools/serve_load.py http://127.0.0.1:8080 --clients 1,2,4,8 --rounds 3 --max-tokens 256
5
6For every client count it sends C streamed chat requests at the same moment (each prompt starts with its own nonce, so
7the prompt cache cannot help), and reports per round and as medians: total tokens/s (all generated tokens over the
8wall time of the burst), per-request tokens/s, time to first token (p50 / p95 over all requests of that count), and
9the request latency (p50 / p95).  With --save DIR it writes every answer, so a later run can be compared byte for
10byte with `--compare DIR` (greedy answers of a request must not depend on who else ran).
11
12Standard library only.  The prompts are fixed texts, so two runs of the tool send the same requests.
13"""
14import argparse, json, os, statistics, sys, threading, time, urllib.request
15
16TOPICS = [
17    "the history of lighthouses and how their lenses worked",
18    "how a mechanical watch keeps time",
19    "why bridges are built as arches and as suspension spans",
20    "the water cycle and what a drought does to a river valley",
21    "how bread rises, from yeast to crust",
22    "the design of a medieval castle and why walls were stepped",
23    "how a transistor switches, explained for a curious teenager",
24    "the life of a honey bee colony through one year",
25]
26
27
28def prompt_for(i: int, words: int, nonce: str = "") -> str:
29    topic = TOPICS[i % len(TOPICS)]
30    return (f"[request {i}{nonce}] Write a clear, well organised essay of about {words} words on {topic}. "
31            f"Use plain prose, no lists.")
32
33
34def one(url, key, model, i, words, max_tokens, res, extra, think, nonce=""):
35    body = {"model": model, "stream": True, "max_tokens": max_tokens, "temperature": 0,
36            "messages": [{"role": "user", "content": prompt_for(i, words, nonce)}]}
37    if not think:
38        body["reasoning_effort"] = "none"
39        body["chat_template_kwargs"] = {"enable_thinking": False}
40    body.update(extra)
41    req = urllib.request.Request(url + "/v1/chat/completions", data=json.dumps(body).encode(),
42                                 headers={"Content-Type": "application/json",
43                                          **({"Authorization": "Bearer " + key} if key else {})})
44    t0 = time.perf_counter()
45    first, n, text = None, 0, []
46    err = None
47    try:
48        with urllib.request.urlopen(req, timeout=900) as r:
49            for raw in r:
50                line = raw.decode("utf-8", "replace").strip()
51                if not line.startswith("data:"):
52                    continue
53                d = line[5:].strip()
54                if d == "[DONE]":
55                    break
56                try:
57                    j = json.loads(d)
58                except ValueError:
59                    continue
60                for ch in j.get("choices", []):
61                    dl = ch.get("delta", {})
62                    piece = (dl.get("content") or "") + (dl.get("reasoning_content") or "")
63                    if piece:
64                        if first is None:
65                            first = time.perf_counter() - t0
66                        n += 1                      # one SSE chunk = one token (the server flushes per token)
67                        text.append(piece)
68                if j.get("usage"):
69                    n = j["usage"].get("completion_tokens", n)
70    except Exception as e:                          # noqa: BLE001
71        err = repr(e)
72    res[i] = {"first": first, "tokens": n, "total": time.perf_counter() - t0, "text": "".join(text), "err": err}
73
74
75def pct(v, p):
76    v = sorted(v)
77    if not v:
78        return float("nan")
79    k = (len(v) - 1) * p
80    lo, hi = int(k), min(int(k) + 1, len(v) - 1)
81    return v[lo] + (v[hi] - v[lo]) * (k - lo)
82
83
84def main():
85    ap = argparse.ArgumentParser()
86    ap.add_argument("url")
87    ap.add_argument("--clients", default="1,2,4,8")
88    ap.add_argument("--rounds", type=int, default=3)
89    ap.add_argument("--max-tokens", type=int, default=256)
90    ap.add_argument("--words", type=int, default=800, help="the essay length asked for (longer = longer prompt? no: the answer)")
91    ap.add_argument("--model", default="strata")
92    ap.add_argument("--key", default=os.environ.get("STRATA_KEY", ""))
93    ap.add_argument("--nonce", default=str(int(time.time())), help="prefix of the per-request nonce (every round reads fresh prompts); '' = identical prompts every round; fix it to compare two runs")
94    ap.add_argument("--think", action="store_true")
95    ap.add_argument("--stagger", type=float, default=0.0, help="seconds between the starts of the clients of a burst")
96    ap.add_argument("--save", help="write every answer (clients/round/request) here")
97    ap.add_argument("--compare", help="compare every answer with the files a --save run wrote")
98    ap.add_argument("--json", help="write the table as JSON")
99    a = ap.parse_args()
100    extra = {}
101    out = []
102    bad = 0
103    for c in [int(x) for x in a.clients.split(",")]:
104        rows = []
105        for rd in range(a.rounds):
106            res = {}
107            th = []
108            t0 = time.perf_counter()
109            for i in range(c):
110                t = threading.Thread(target=one, args=(a.url, a.key, a.model, i, a.words, a.max_tokens, res, extra, a.think, f" {a.nonce}-{c}-{rd}" if a.nonce else ""))
111                t.start()
112                th.append(t)
113                if a.stagger:
114                    time.sleep(a.stagger)
115            for t in th:
116                t.join()
117            wall = time.perf_counter() - t0
118            toks = sum(r["tokens"] for r in res.values())
119            errs = [r["err"] for r in res.values() if r["err"]]
120            firsts = [r["first"] for r in res.values() if r["first"] is not None]
121            tot = [r["total"] for r in res.values()]
122            per = [r["tokens"] / max(r["total"] - (r["first"] or 0), 1e-6) for r in res.values()]
123            rows.append({"wall": wall, "toks": toks, "tps": toks / wall, "first": firsts, "lat": tot, "per": per, "err": errs})
124            if a.save:
125                d = os.path.join(a.save, f"c{c}", f"r{rd}")
126                os.makedirs(d, exist_ok=True)
127                for i, r in res.items():
128                    open(os.path.join(d, f"{i}.txt"), "w", encoding="utf-8").write(r["text"])
129            if a.compare:
130                for i, r in res.items():
131                    p = os.path.join(a.compare, f"c{c}", f"r{rd}", f"{i}.txt")
132                    if os.path.exists(p):
133                        ref = open(p, encoding="utf-8").read()
134                        if ref != r["text"]:
135                            n = next((k for k, (x, y) in enumerate(zip(ref, r["text"])) if x != y), min(len(ref), len(r["text"])))
136                            print(f"  DIFF c={c} round={rd} req={i}: first difference at char {n}")
137                            bad += 1
138            print(f"c={c} round={rd}: {toks} tokens in {wall:.1f}s = {toks / wall:.1f} tok/s total"
139                  + (f"  ERRORS {errs[:2]}" if errs else ""), flush=True)
140        allf = [x for r in rows for x in r["first"]]
141        alll = [x for r in rows for x in r["lat"]]
142        allp = [x for r in rows for x in r["per"]]
143        s = {"clients": c, "total_tps": statistics.median(r["tps"] for r in rows),
144             "per_req_tps": statistics.median(allp) if allp else float("nan"),
145             "first_p50": pct(allf, .5), "first_p95": pct(allf, .95),
146             "lat_p50": pct(alll, .5), "lat_p95": pct(alll, .95), "errors": sum(len(r["err"]) for r in rows)}
147        out.append(s)
148    print("\nclients  total tok/s  per-req tok/s  first p50/p95 (s)  latency p50/p95 (s)  errors")
149    for s in out:
150        print(f"{s['clients']:>7}  {s['total_tps']:>11.1f}  {s['per_req_tps']:>13.1f}  "
151              f"{s['first_p50']:>7.2f}/{s['first_p95']:<7.2f}  {s['lat_p50']:>8.2f}/{s['lat_p95']:<8.2f}  {s['errors']}")
152    if a.json:
153        json.dump(out, open(a.json, "w"), indent=1)
154    if a.compare:
155        print("compare:", "ALL IDENTICAL" if not bad else f"{bad} DIFFERENT")
156    return 1 if bad else 0
157
158
159if __name__ == "__main__":
160    sys.exit(main())