okami.mom/strata

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

Niko1221Merge f-clean-3 (321794636): docs and history (cleanup step 3, items 3.0-3.10); release manifest and capability table with checks, history/ with pointers, link check, tools/ split, bench index; owner OK'd the wording 11-082b36e8a02

main
7.6 KiB159 linesraw
1#!/usr/bin/env python3
2"""Aggregate output: N concurrent clients against one server, measuring tokens per second summed over the clients. Run the
3same N against a second configuration to compare.
4
5    python research/tools/dgx-spark-2026-10/dgx_concurrent.py CONFIG OUT.json --clients 8 [--clients 16] [--prompt 2000] [--max-new 128]
6                                   [--parallel 4] [--distinct]
7
8--parallel N runs the server with "parallel": N (the engine's batch slots: up to N requests decode together; the run config of setup has
9none, one request at a time). --distinct gives every client its own prompt with its own hidden code and checks the answer: every request
10must finish without an error, and its answer must name ITS code and no other client's (a batch that mixed two requests' state would fail
11that), so the aggregate figure comes with a correctness check. Without --distinct all clients send the same prompt, as the
122026-10-26 handover's numbers were measured.
13"""
14from __future__ import annotations
15
16import argparse
17import json
18import statistics
19import subprocess
20import sys
21import threading
22import time
23import urllib.request
24from pathlib import Path
25
26ROOT = Path(__file__).resolve().parents[3]
27WORDS = ("river stone market lantern copper winter garden signal harbor needle orbit velvet canyon ember ledger quartz "
28         "meadow anchor violet thunder cedar marble piston ribbon cobalt falcon glacier hollow ivory juniper kernel").split()
29
30
31def make_prompt(tokens: int) -> str:
32    body = []
33    n = int(tokens / 1.35)
34    for i in range(n):
35        body.append(WORDS[i % len(WORDS)])
36    return "Summarise the following log in two sentences.\n\n" + " ".join(body)
37
38
39def distinct_prompt(tokens: int, idx: int) -> tuple[str, str]:
40    """(prompt, code): about `tokens` tokens of a log that is different for every client, with one code in the middle."""
41    code = f"{(idx * 7919 + 1357) % 9000 + 1000}-{WORDS[(idx * 5) % len(WORDS)]}"
42    n = int(tokens / 1.35)
43    body = [WORDS[(i * (idx % 7 + 1) + idx) % len(WORDS)] for i in range(n)]
44    body.insert(n // 2, f"(the access code of this log is {code})")
45    return ("Read the following log. First give the access code of this log, then describe in about 80 words what the log looks like.\n\n" + " ".join(body), code)
46
47
48def serve(cfg_path: str, port: int, parallel: int | None = None):
49    cfg = json.loads(Path(cfg_path).read_text())
50    if parallel:
51        cfg["parallel"] = parallel
52    cfg["port"] = port
53    cfg["log"] = f"/tmp/dgx-conc-{port}.log"
54    tmp = Path(f"/tmp/dgx-conc-{port}.json")
55    tmp.write_text(json.dumps(cfg, indent=1))
56    proc = subprocess.Popen([sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config",
57                             str(tmp), "--port", str(port)], cwd=str(ROOT),
58                            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
59    t0 = time.time()
60    while time.time() - t0 < 1800:
61        if proc.poll() is not None:
62            raise SystemExit(f"server exited {proc.returncode}")
63        try:
64            with urllib.request.urlopen(f"http://127.0.0.1:{port}/v1/models", timeout=5) as r:
65                if r.status == 200:
66                    return proc
67        except Exception:
68            pass
69        time.sleep(3)
70    raise SystemExit("server did not come up")
71
72
73def one(port: int, prompt: str, max_new: int, out: list, idx: int):
74    t0 = time.time()
75    try:
76        out[idx] = _one(port, prompt, max_new)
77    except Exception as e:                                   # a request that errors or times out is a finding, not a crash of the run
78        out[idx] = {"error": f"{type(e).__name__}: {e}", "latency": time.time() - t0, "n": 0, "text": "", "finish": None}
79
80
81def _one(port: int, prompt: str, max_new: int) -> dict:
82    body = json.dumps({"messages": [{"role": "user", "content": prompt}], "max_tokens": max_new, "temperature": 0,
83                       "chat_template_kwargs": {"enable_thinking": False}}).encode()
84    req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", data=body,
85                                 headers={"Content-Type": "application/json"})
86    t0 = time.time()
87    with urllib.request.urlopen(req, timeout=3600) as r:
88        res = json.loads(r.read())
89    choice = (res.get("choices") or [{}])[0]
90    return {"latency": time.time() - t0, "n": res.get("timings", {}).get("predicted_n", 0),
91            "text": (choice.get("message") or {}).get("content") or "", "finish": choice.get("finish_reason"), "error": None}
92
93
94def coherent(text: str) -> bool:
95    """A readable answer: not empty, not one repeated token or a wall of the same few words."""
96    words = text.split()
97    return len(words) >= 3 and len(set(words)) / len(words) > 0.35
98
99
100def run(cfg_path: str, port: int, clients: int, prompt: str, max_new: int, parallel: int | None = None,
101        distinct: int | None = None) -> dict:
102    proc = serve(cfg_path, port, parallel)
103    try:
104        with urllib.request.urlopen(urllib.request.Request(
105                f"http://127.0.0.1:{port}/v1/chat/completions",
106                data=json.dumps({"messages": [{"role": "user", "content": "hi"}], "max_tokens": 8}).encode(),
107                headers={"Content-Type": "application/json"}), timeout=1800) as r:
108            r.read()
109        out: list = [None] * clients
110        prompts = [distinct_prompt(distinct, i) for i in range(clients)] if distinct else [(prompt, None)] * clients
111        t0 = time.time()
112        threads = [threading.Thread(target=one, args=(port, prompts[i][0], max_new, out, i)) for i in range(clients)]
113        for t in threads:
114            t.start()
115        for t in threads:
116            t.join()
117        wall = time.time() - t0
118        tokens = sum(r["n"] for r in out if r["n"])
119        times = [r["latency"] for r in out if not r["error"]]
120        row = {"clients": clients, "parallel": parallel, "wall_s": round(wall, 2), "tokens": tokens,
121               "aggregate_tok_s": round(tokens / wall, 2) if wall > 0 else None,
122               "median_latency_s": round(statistics.median(times), 2) if times else None,
123               "errors": [r["error"] for r in out if r["error"]], "finish": sorted({str(r["finish"]) for r in out}),
124               "all_coherent": all(coherent(r["text"]) for r in out if not r["error"])}
125        if distinct:
126            right = [(prompts[i][1] in r["text"]) and not any(prompts[j][1] in r["text"] for j in range(clients) if j != i)
127                     for i, r in enumerate(out) if not r["error"]]
128            row["own_code_named"] = f"{sum(right)} of {clients}"
129            row["answers"] = [r["text"][:100] for r in out]
130        return row
131    finally:
132        proc.terminate()
133        try:
134            proc.wait(180)
135        except subprocess.TimeoutExpired:
136            proc.kill()
137
138
139def main() -> int:
140    ap = argparse.ArgumentParser()
141    ap.add_argument("config")
142    ap.add_argument("out")
143    ap.add_argument("--clients", type=int, nargs="+", default=[8, 16])
144    ap.add_argument("--prompt", type=int, default=2000)
145    ap.add_argument("--max-new", type=int, default=128)
146    ap.add_argument("--port", type=int, default=8091)
147    ap.add_argument("--parallel", type=int, default=None, help='run the server with "parallel": N (batch slots)')
148    ap.add_argument("--distinct", action="store_true", help="a prompt of its own with a hidden code for every client, and check the answers")
149    a = ap.parse_args()
150    prompt = make_prompt(a.prompt)
151    rows = [run(a.config, a.port, c, prompt, a.max_new, a.parallel, a.prompt if a.distinct else None) for c in a.clients]
152    Path(a.out).write_text(json.dumps(rows, indent=1))
153    for r in rows:
154        print(json.dumps(r))
155    return 0
156
157
158if __name__ == "__main__":
159    sys.exit(main())