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
4.3 KiB97 linesraw
1#!/usr/bin/env python3
2"""Multi-turn (agent-style) comparison: one conversation, five turns of ~1,200 new tokens each, cache reuse measured.
3
4    python research/tools/dgx-spark-2026-10/dgx_turns.py CONFIG TAG OUTDIR [--turns 5] [--tokens 1200] [--port 8091]
5
6Per turn it records the engine's prompt_n / cache_n, prompt tok/s and TTFT, so the cache path is compared, not just the
7fresh-prompt path the other tools measure.
8"""
9import argparse
10import json
11import random
12import subprocess
13import sys
14import time
15import urllib.request
16from pathlib import Path
17
18ROOT = Path(__file__).resolve().parents[3]
19WORDS = ("river stone market lantern copper winter garden signal harbor needle orbit velvet canyon ember ledger quartz "
20         "meadow anchor violet thunder cedar marble piston ribbon cobalt falcon glacier hollow ivory juniper kernel "
21         "lattice mirror nectar oasis pepper quarry raven saddle tundra umber vessel willow xenon yellow zephyr").split()
22
23
24def blob(n, seed):
25    rng = random.Random(seed)
26    return " ".join(rng.choice(WORDS) for _ in range(n))
27
28
29def chat(port, messages, max_tokens=64):
30    body = json.dumps({"messages": messages, "max_tokens": max_tokens, "temperature": 0, "stream": False,
31                       "chat_template_kwargs": {"enable_thinking": False}}).encode()
32    req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", data=body,
33                                 headers={"Content-Type": "application/json"})
34    t0 = time.time()
35    with urllib.request.urlopen(req, timeout=3600) as r:
36        out = json.loads(r.read())
37    return out, time.time() - t0
38
39
40def main():
41    ap = argparse.ArgumentParser()
42    ap.add_argument("config")
43    ap.add_argument("tag")
44    ap.add_argument("outdir")
45    ap.add_argument("--turns", type=int, default=5)
46    ap.add_argument("--tokens", type=int, default=1200)
47    ap.add_argument("--port", type=int, default=8091)
48    a = ap.parse_args()
49    out = Path(a.outdir)
50    out.mkdir(parents=True, exist_ok=True)
51    cfg = json.loads(Path(a.config).read_text())
52    cfg["port"] = a.port
53    cfg["log"] = str(out / f"{a.tag}.engine.log")
54    cpath = out / f"{a.tag}.config.json"
55    cpath.write_text(json.dumps(cfg, indent=1))
56    log = open(out / f"{a.tag}.jsonl", "a", encoding="utf-8")
57    proc = subprocess.Popen([sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config",
58                             str(cpath), "--port", str(a.port)], cwd=str(ROOT),
59                            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
60    try:
61        t0 = time.time()
62        while time.time() - t0 < 3600:
63            try:
64                with urllib.request.urlopen(f"http://127.0.0.1:{a.port}/v1/models", timeout=5) as r:
65                    if r.status == 200:
66                        break
67            except Exception:
68                pass
69            time.sleep(3)
70        print(f"{a.tag}: ready in {time.time() - t0:.0f} s", flush=True)
71        msgs = [{"role": "user", "content": "Read this note and answer with one short sentence.\n" + blob(a.tokens, 1)}]
72        outj, wall = chat(a.port, msgs)
73        msgs.append({"role": "assistant", "content": outj["choices"][0]["message"].get("content", "")})
74        for turn in range(a.turns):
75            msgs.append({"role": "user", "content": "More notes.\n" + blob(a.tokens, 100 + turn) +
76                                                   "\nSummarise the last note in one sentence."})
77            outj, wall = chat(a.port, msgs)
78            t = outj.get("timings") or {}
79            msgs.append({"role": "assistant", "content": outj["choices"][0]["message"].get("content", "")})
80            row = {"round": turn, "arm": a.tag, "len": 0, "temp": 0.0, "max_new": 64, "wall_s": round(wall, 2),
81                   "ttft_s": (t.get("prompt_ms") or 0) / 1000.0 or None, **t}
82            log.write(json.dumps(row) + "\n")
83            log.flush()
84            print(f"  turn {turn}: prompt_n {t.get('prompt_n')} cache_n {t.get('cache_n')} "
85                  f"prompt {t.get('prompt_per_second')} tok/s decode {t.get('predicted_per_second')} tok/s "
86                  f"ttft {row['ttft_s']}", flush=True)
87    finally:
88        proc.terminate()
89        try:
90            proc.wait(90)
91        except subprocess.TimeoutExpired:
92            proc.kill()
93        log.close()
94
95
96if __name__ == "__main__":
97    main()