okami.mom/strata

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

Niko1221Merge f-142b-cuda into f-14254d7f7d7c

main
12.4 KiB216 linesraw
1"""Decode A/B on coding-agent turns over this repository: arms restarted per round, per-turn ratios.
2
3    python tools/agent_turns_bench.py strata-iq2_xs.json base: hcq8:STRATA_HC_Q8=2 [--rounds 2]
4
5The workload is five simulated coding-agent sessions over this repository's own files (README, serve/, setup.py, the
6expert cache, the hyper-connection kernels, the tokenizer): a system prompt, four tools, a task (three in English, two
7in French), then tool calls whose results are the real files, at most 2,000 lines per read as agents' read tools
8return them.  Every point right after a tool result is one turn the model continues - 23 turns from ~2.5K to ~100K
9tokens with the repository as of 0.1.41, consecutive turns sharing their prefix as in a real session.  Nothing
10personal and nothing downloaded: anyone with this checkout gets the same requests.
11
12Arms are given as ab_engine.py takes them (NAME:key=value,...; `exe` replaces the engine, `xargs` appends
13';'-separated engine arguments, any other key goes to the engine's environment).  The rounds mirror the arm order
14(A B, B A, ...), each arm on a fresh server.  Sampling is the agent's (temperature 1, top-p 0.95, top-k 20, a fixed
15seed), 256 new tokens per turn.  The result is the server's own decode tok/s per turn and, per arm, the median of the
16per-turn ratios to the first arm with the number of turns it won: a whole-session median hides which turns moved.
17"""
18from __future__ import annotations
19
20import argparse
21import json
22import os
23import statistics
24import subprocess
25import sys
26import tempfile
27import time
28import urllib.request
29from pathlib import Path
30
31ROOT = Path(__file__).resolve().parents[1]
32sys.path.insert(0, str(Path(__file__).resolve().parent))
33from ab_engine import wait_ready  # noqa: E402
34
35SYSTEM = ("You are an autonomous coding agent working in the user's repository. You can read files, search the code, "
36          "edit files and run commands with the tools below. Work step by step: read the code you need before changing "
37          "it, make small and correct edits, keep the existing style, and explain briefly what you did. Never invent "
38          "file contents: read them. When the task is done, give a short summary of the changes and how to test them.")
39
40TOOLS = [
41    {"type": "function", "function": {
42        "name": "read_file", "description": "Read a file of the repository (UTF-8 text).",
43        "parameters": {"type": "object", "properties": {"path": {"type": "string", "description": "path from the repository root"}},
44                       "required": ["path"]}}},
45    {"type": "function", "function": {
46        "name": "grep", "description": "Search the repository for a regular expression; returns matching lines.",
47        "parameters": {"type": "object", "properties": {"pattern": {"type": "string"}, "path": {"type": "string"}},
48                       "required": ["pattern"]}}},
49    {"type": "function", "function": {
50        "name": "edit_file", "description": "Replace an exact string in a file with a new one.",
51        "parameters": {"type": "object", "properties": {"path": {"type": "string"}, "old": {"type": "string"},
52                                                        "new": {"type": "string"}}, "required": ["path", "old", "new"]}}},
53    {"type": "function", "function": {
54        "name": "run", "description": "Run a shell command in the repository and return its output.",
55        "parameters": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}}},
56]
57
58# (name, task, [(tool, argument, what the assistant says before the call)])
59SESSIONS = [
60    ("server-option",
61     "Add a `--max-queue N` option to the HTTP server that rejects new chat requests with HTTP 503 when N requests are "
62     "already waiting, document it in the README's settings section, and add a test.",
63     [("read_file", "README.md", "I'll start with the README to see how settings are documented."),
64      ("grep", "add_argument", "Now let me find where the server parses its options."),
65      ("read_file", "serve/server.py", "The options are in serve/server.py; reading it."),
66      ("read_file", "serve/frontend.py", "Requests go through the frontend; let me read it too."),
67      ("read_file", "docs/DETAILS.md", "Checking DETAILS.md for the existing API documentation style.")]),
68    ("expert-cache",
69     "Explain precisely how the expert cache decides which experts stay in VRAM during decode, then propose and "
70     "implement a small improvement to its eviction policy with a measurement plan.",
71     [("read_file", "docs/HOW_IT_WORKS.md", "Let me read the design overview first."),
72      ("read_file", "include/strata/core/expert_cache.hpp", "Now the cache's interface."),
73      ("read_file", "src/core/expert_cache.cpp", "And its implementation."),
74      ("grep", "adapt_every", "Searching for the adaptive swap logic."),
75      ("read_file", "src/core/expert_source.cpp", "The dispatch that consults the cache is in expert_source.cpp.")]),
76    ("installer-fr",
77     "Dans l'installateur, la détection de la RAM disponible se trompe parfois sous Windows quand un autre programme "
78     "réserve beaucoup de mémoire. Trouve où elle est faite, corrige-la, ajoute un test et explique la correction en "
79     "français.",
80     [("read_file", "setup.py", "Je commence par lire l'installateur."),
81      ("grep", "def .*ram", "Je cherche les fonctions qui mesurent la RAM."),
82      ("read_file", "docs/INSTALL.md", "Je vérifie ce que la documentation promet sur la RAM."),
83      ("read_file", "docs/MODELS.md", "Le choix du modèle dépend de la RAM ; je lis cette page aussi.")]),
84    ("cuda-kernel",
85     "The hyper-connection read kernels are latency bound on small batches. Read them, explain where the time goes, "
86     "and write a faster variant for 1-4 tokens that keeps the same results bit for bit.",
87     [("read_file", "include/strata/kernels/fused_gr.hpp", "First the kernel interface."),
88      ("read_file", "src/kernels/cuda/fused_gr.cu", "Now the kernels themselves."),
89      ("grep", "fused_gr_read_multi", "Where are they called from?"),
90      ("read_file", "src/core/verify.cpp", "The verify window calls them; reading it.")]),
91    ("tokenizer-fr",
92     "Écris une suite de tests pytest pour le tokenizer Python (encodage, décodage, tokens spéciaux, texte multilingue, "
93     "cas limites), puis corrige les bugs que les tests révèlent. Réponds en français.",
94     [("read_file", "tools/strata_tokenizer.py", "Je lis d'abord le tokenizer."),
95      ("grep", "strata_tokenizer", "Je cherche qui l'utilise."),
96      ("read_file", "serve/frontend.py", "Le frontend l'appelle ; je le lis pour voir les usages réels."),
97      ("read_file", "serve/chat_template.jinja", "Je regarde aussi le modèle de conversation."),
98      ("read_file", "chat.py", "Et le client en ligne de commande.")]),
99]
100
101
102def tool_result(tool: str, arg: str) -> str:
103    if tool == "read_file":
104        lines = (ROOT / arg).read_text(encoding="utf-8", errors="replace").splitlines()
105        text = "\n".join(lines[:2000])
106        return text + (f"\n... (truncated: lines 1-2000 of {len(lines)})" if len(lines) > 2000 else "")
107    if tool == "grep":
108        r = subprocess.run(["git", "-C", str(ROOT), "grep", "-n", "-I", "-E", arg], capture_output=True, text=True,
109                           encoding="utf-8", errors="replace")
110        lines = r.stdout.splitlines()
111        return "\n".join(lines[:200]) + (f"\n... ({len(lines) - 200} more lines)" if len(lines) > 200 else "")
112    raise ValueError(tool)
113
114
115def turns() -> list[tuple[str, list[dict]]]:
116    """[(tag, messages)]: one entry per point right after a tool result."""
117    out = []
118    for name, task, steps in SESSIONS:
119        msgs = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": task}]
120        for i, (tool, arg, before) in enumerate(steps):
121            cid = f"call_{name}_{i}"
122            args = {"path": arg} if tool == "read_file" else {"pattern": arg}
123            msgs.append({"role": "assistant", "content": before,
124                         "tool_calls": [{"id": cid, "type": "function",
125                                         "function": {"name": tool, "arguments": json.dumps(args)}}]})
126            msgs.append({"role": "tool", "tool_call_id": cid, "content": tool_result(tool, arg)})
127            out.append((f"{name}.{i}", [dict(m) for m in msgs]))
128    return out
129
130
131def post(port: int, messages: list[dict], max_tokens: int, seed: int) -> dict:
132    body = {"messages": messages, "tools": TOOLS, "max_tokens": max_tokens, "temperature": 1.0, "top_p": 0.95,
133            "top_k": 20, "seed": seed, "reasoning_effort": "high"}
134    req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", data=json.dumps(body).encode(),
135                                 headers={"Content-Type": "application/json"})
136    with urllib.request.urlopen(req, timeout=3600) as r:
137        return json.loads(r.read())
138
139
140def main() -> int:
141    ap = argparse.ArgumentParser()
142    ap.add_argument("config")
143    ap.add_argument("arms", nargs="+")
144    ap.add_argument("--rounds", type=int, default=2)
145    ap.add_argument("--port", type=int, default=8090)
146    ap.add_argument("--max-new", type=int, default=256)
147    ap.add_argument("--max-turns", type=int, default=0, help="only the first N turns (0: all)")
148    ap.add_argument("--seed", type=int, default=1234)
149    ap.add_argument("--log", default="agent_turns_bench.jsonl")
150    a = ap.parse_args()
151    base = json.loads(Path(a.config).read_text())
152    arms = []
153    for s in a.arms:
154        name, _, kv = s.partition(":")
155        arms.append((name, dict(x.split("=", 1) for x in kv.split(",") if x)))
156    work = turns()
157    if a.max_turns:
158        work = work[:a.max_turns]
159    out = open(a.log, "a")
160    res: dict = {n: {} for n, _ in arms}
161    for rnd in range(a.rounds):
162        for name, env in (arms if rnd % 2 == 0 else arms[::-1]):
163            cfg = dict(base)
164            e = dict(env)
165            if "exe" in e:
166                cfg["exe"] = e.pop("exe")
167            if "xargs" in e:
168                cfg["args"] = list(base["args"]) + e.pop("xargs").split(";")
169            cfg["port"] = a.port
170            cfg["log"] = str(Path(tempfile.gettempdir()) / f"agent_turns_{name}_r{rnd}.log")
171            cpath = Path(tempfile.gettempdir()) / f"agent_turns_{name}.json"
172            cpath.write_text(json.dumps(cfg, indent=1))
173            proc = subprocess.Popen([sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config",
174                                     str(cpath), "--port", str(a.port)], cwd=str(ROOT), env=dict(os.environ, **e),
175                                    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
176            try:
177                t0 = time.time()
178                wait_ready(a.port, proc)
179                print(f"round {rnd} {name}: ready in {time.time() - t0:.0f} s", flush=True)
180                for tag, msgs in work:
181                    r = post(a.port, msgs, a.max_new, a.seed)
182                    t = r.get("timings", {})
183                    row = {"round": rnd, "arm": name, "turn": tag, "decode": t.get("predicted_per_second"),
184                           "prompt_n": t.get("prompt_n"), "prompt": t.get("prompt_per_second"),
185                           "n": r.get("usage", {}).get("completion_tokens")}
186                    out.write(json.dumps(row) + "\n")
187                    out.flush()
188                    res[name].setdefault(tag, []).append(row)
189                    print(f"  {tag:16s} decode {row['decode']} tok/s  prompt {row['prompt_n']} tokens", flush=True)
190            finally:
191                proc.terminate()
192                try:
193                    proc.wait(60)
194                except subprocess.TimeoutExpired:
195                    proc.kill()
196                time.sleep(5)
197    first = arms[0][0]
198
199    def per_turn(name: str, tag: str) -> float:
200        v = [x["decode"] for x in res[name].get(tag, []) if x["decode"]]
201        return statistics.mean(v) if v else float("nan")
202
203    print(f"\nper-turn decode ratio to {first} (mean over rounds per turn, then the median over turns):")
204    for name, _ in arms:
205        med = statistics.median([per_turn(name, t) for t, _ in work])
206        if name == first:
207            print(f"  {name:10s} median decode {med:6.1f} tok/s")
208            continue
209        r = [per_turn(name, t) / per_turn(first, t) for t, _ in work]
210        print(f"  {name:10s} median decode {med:6.1f} tok/s   x{statistics.median(r):.3f} (x{min(r):.2f} to "
211              f"x{max(r):.2f}), {sum(x > 1 for x in r)}/{len(r)} turns faster")
212    return 0
213
214
215if __name__ == "__main__":
216    sys.exit(main())