okami.mom/strata

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

did-technomancerbench: community results for an RX 6800 on Windows (0.1.39 against 0.1.38) (#815)0b65d593c

main
12.2 KiB259 linesraw
1"""bench-local/run_all.py - the full local benchmark: quality suites, speed per configuration, the longest contexts.
2
3Runs detached; restarts the Strata server with other settings between phases and restores 128K / 2048 MiB at the
4end.  Progress: run_all.log; numbers: run_all.json.
5"""
6from __future__ import annotations
7
8import base64
9import io
10import json
11import random
12import re
13import statistics
14import subprocess
15import sys
16import time
17import uuid
18from pathlib import Path
19
20import psutil
21import requests
22
23HERE = Path(__file__).parent
24ROOT = HERE.parent
25PY = sys.executable
26BASE = "http://127.0.0.1:8080"
27CFG = ROOT / "strata-iq2_xs.json"
28LOG = HERE / "run_all.log"
29RES: dict = {"speed": [], "longctx": [], "vision": [], "config": [], "suites": []}
30
31
32def log(msg):
33    line = f"{time.strftime('%H:%M:%S')} {msg}"
34    with LOG.open("a", encoding="utf-8") as f:
35        f.write(line + "\n")
36    (HERE / "run_all.json").write_text(json.dumps(RES, ensure_ascii=False, indent=1), encoding="utf-8")
37
38
39# ------------------------------------------------------------------------------------------------ the server
40def stop_server():
41    for p in psutil.process_iter(["name", "cmdline"]):
42        try:
43            cl = " ".join(p.info["cmdline"] or [])
44            if p.info["name"] in ("strata.exe", "strata-vision.exe") or ("serve" in cl and "server.py" in cl):
45                p.kill()
46        except (psutil.NoSuchProcess, psutil.AccessDenied):
47            pass
48    time.sleep(5)
49
50
51def health():
52    try:
53        return requests.get(BASE + "/health", timeout=5).json()
54    except Exception:
55        return {}
56
57
58def start_server():
59    out = open(ROOT / "server.out", "w")
60    err = open(ROOT / "server.err", "w")
61    proc = subprocess.Popen([PY, "serve/server.py", "--engine", "strata", "--config", str(CFG), "--port", "8080"],
62                            cwd=ROOT, stdout=out, stderr=err, creationflags=subprocess.CREATE_NO_WINDOW)
63    t = time.time()
64    while time.time() - t < 1200:
65        if health().get("loaded"):
66            return round(time.time() - t)
67        if proc.poll() is not None:
68            return None
69        time.sleep(3)
70    return None
71
72
73def engine_facts():
74    text = (ROOT / "strata-iq2_xs.log").read_text(encoding="utf-8", errors="replace")[-200000:]
75    slots = re.findall(r"expert cache (\d+) slots, ([\d.]+) GiB", text)
76    free = re.findall(r"(\d+) MiB of VRAM free with everything loaded", text)
77    return {"expert_slots": int(slots[-1][0]) if slots else None, "cache_gib": float(slots[-1][1]) if slots else None,
78            "vram_free_mib": int(free[-1]) if free else None}
79
80
81def configure(ctx, reserve, vision_tokens=None):
82    stop_server()
83    p = subprocess.run([PY, "setup.py", "--setup", "--yes", "--family", "qwen", "--model", "IQ2_XS", "--context",
84                        str(ctx), "--vram-reserve-mib", str(reserve), "--vision", "cpu", "--data-dir",
85                        r"D:\Strata-data", "--no-start"], cwd=ROOT, stdin=subprocess.DEVNULL, capture_output=True,
86                       text=True, encoding="utf-8", errors="replace")
87    notes = [ln.strip()[:220] for ln in p.stdout.splitlines() if "[!]" in ln or "context" in ln.lower() or "rope" in ln.lower()]
88    if vision_tokens:
89        cfg = json.loads(CFG.read_text(encoding="utf-8"))
90        cfg["vision"]["max_tokens"] = vision_tokens
91        CFG.write_text(json.dumps(cfg, indent=1), encoding="utf-8")
92    secs = start_server()
93    h = health()
94    rec = {"asked_context": ctx, "reserve_mib": reserve, "vision_tokens": vision_tokens, "start_s": secs,
95           "max_context": h.get("max_context"), "setup_exit": p.returncode, "notes": notes[-8:], **engine_facts()}
96    RES["config"].append(rec)
97    log(f"CONFIG ctx {ctx} reserve {reserve}: started in {secs} s, max_context {h.get('max_context')}, {engine_facts()}")
98    for n in notes[-8:]:
99        log("   setup: " + n)
100    return secs is not None
101
102
103# ------------------------------------------------------------------------------------------------ requests
104def ask(content, max_tokens=300, effort="none", timeout=7200):
105    t = time.time()
106    try:
107        r = requests.post(BASE + "/v1/chat/completions", timeout=timeout, json={
108            "model": "strata", "messages": [{"role": "user", "content": content}], "max_tokens": max_tokens,
109            "reasoning_effort": effort, "temperature": 0}).json()
110    except Exception as e:
111        return {"error": f"{type(e).__name__}: {e}"[:300]}
112    if "choices" not in r:
113        return {"error": json.dumps(r)[:300]}
114    tm = r.get("timings", {})
115    return {"content": r["choices"][0]["message"].get("content") or "", "wall": round(time.time() - t, 1),
116            "prompt_n": tm.get("prompt_n"), "prompt_s": round(tm.get("prompt_ms", 0) / 1000, 1),
117            "prompt_tok_s": tm.get("prompt_per_second"), "out_n": tm.get("predicted_n"),
118            "tok_s": tm.get("predicted_per_second")}
119
120
121def speed(label):
122    dec = [ask(f"[{uuid.uuid4().hex[:8]}] Explain in detail how a hash map works: hashing, collisions, resizing, "
123               "complexity. About 300 words.", 420) for _ in range(3)]
124    src = (ROOT / "serve" / "server.py").read_text(encoding="utf-8")
125    reads = {}
126    for name, kb in (("2K", 8), ("8K", 30), ("32K", 125)):
127        mc = health().get("max_context") or 0
128        if kb * 280 > mc - 2000:      # ~280 tokens per KB of this file
129            continue
130        r = ask(f"Run {uuid.uuid4().hex}.\n\n" + src[:kb * 1000] + "\n\nIn one sentence: what is this code?", 60)
131        reads[name] = {k: r.get(k) for k in ("prompt_n", "prompt_s", "prompt_tok_s", "tok_s", "error")}
132    ok = [d["tok_s"] for d in dec if d.get("tok_s")]
133    rec = {"label": label, "decode_tok_s": ok, "decode_median": statistics.median(ok) if ok else None, "read": reads,
134           **engine_facts()}
135    RES["speed"].append(rec)
136    log(f"SPEED {label}: decode {ok} tok/s; read " +
137        ", ".join(f"{k} {v.get('prompt_n')} tok at {v.get('prompt_tok_s')} tok/s" for k, v in reads.items()))
138
139
140# ------------------------------------------------------------------------------------------------ long context
141WORDS = ("river mountain engine garden window bridge market signal harbor library forest station valley mirror "
142         "ladder castle meadow tunnel beacon anchor copper marble velvet thunder lantern compass orchard glacier "
143         "pepper cotton ribbon basket candle feather hammer island jacket kettle lemon magnet needle ocean pillow "
144         "quartz rocket saddle timber violet walnut yarn zipper").split()
145COLORS = ["red", "green", "blue", "amber", "violet"]
146
147
148def filler(rng, n_chars):
149    out, size, i = [], 0, 0
150    while size < n_chars:
151        i += 1
152        s = f"Section {i}. " + " ".join(
153            f"The {rng.choice(WORDS)} near the {rng.choice(WORDS)} was moved to the {rng.choice(WORDS)} on day "
154            f"{rng.randint(1, 365)}." for _ in range(6)) + "\n"
155        out.append(s)
156        size += len(s)
157    return out
158
159
160def longctx(target_tokens, label):
161    rng = random.Random(target_tokens)
162    cal = ask("".join(filler(rng, 40000)) + "\nReply OK.", 5)
163    if cal.get("error"):
164        log(f"LONGCTX {label}: calibration failed {cal['error']}")
165        return
166    per_tok = 40000 / cal["prompt_n"]
167    paras = filler(rng, int(target_tokens * per_tok))
168    codes = {c: str(rng.randint(100000, 999999)) for c in COLORS}
169    for c, depth in zip(COLORS, (0.1, 0.3, 0.5, 0.7, 0.9)):
170        paras.insert(int(len(paras) * depth), f"Important: the secret code for {c} is {codes[c]}.\n")
171    q = ("\nQuestion: the text above contains five secret codes, one each for red, green, blue, amber and violet. "
172         "Reply with only JSON like {\"red\": \"...\", \"green\": \"...\", \"blue\": \"...\", \"amber\": \"...\", "
173         "\"violet\": \"...\"}.")
174    r = ask(f"Document {uuid.uuid4().hex}:\n\n" + "".join(paras) + q, 200, timeout=14400)
175    found = {c: (codes[c] in r.get("content", "")) for c in COLORS}
176    rec = {"label": label, "target": target_tokens, "found": sum(found.values()), "by_depth": found,
177           **{k: r.get(k) for k in ("prompt_n", "prompt_s", "prompt_tok_s", "tok_s", "wall", "error")},
178           "answer": r.get("content", "")[:200]}
179    RES["longctx"].append(rec)
180    log(f"LONGCTX {label}: {r.get('prompt_n')} tok read in {r.get('prompt_s')} s ({r.get('prompt_tok_s')} tok/s), "
181        f"found {sum(found.values())}/5 {found}, decode {r.get('tok_s')} tok/s {r.get('error', '')}")
182    if not r.get("error"):          # a follow-up in the same conversation is not possible through ask(); a new short
183        r2 = ask("What is 12 * 12? Number only.", 20)   # request shows the server still answers after the long one
184        log(f"   after it, a short request: {r2.get('content', r2.get('error'))!r} in {r2.get('wall')} s")
185
186
187# ------------------------------------------------------------------------------------------------ pictures
188def vision(label):
189    from PIL import Image, ImageDraw, ImageFont
190    for name, size, px, rows in (("1600x900 16px", (1600, 900), 16, 40), ("3840x2160 16px", (3840, 2160), 16, 95),
191                                 ("3840x2160 28px", (3840, 2160), 28, 60)):
192        rng = random.Random(px + size[0])
193        font = ImageFont.truetype("consola.ttf", px)
194        lines = [f"{i:02d}  cfg.{rng.choice(['port', 'retries', 'timeout', 'workers', 'limit', 'depth'])}_{i} = "
195                 f"{rng.randint(1000, 9999)}" for i in range(1, rows + 1)]
196        img = Image.new("RGB", size, (30, 30, 30))
197        d = ImageDraw.Draw(img)
198        for i, s in enumerate(lines):
199            d.text((40, 20 + i * int(px * 1.35)), s, font=font, fill=(220, 220, 220))
200        buf = io.BytesIO()
201        img.save(buf, "PNG")
202        b64 = base64.b64encode(buf.getvalue()).decode()
203        hits, walls, ptoks = 0, [], None
204        picks = [3, rows // 3, rows // 2, (2 * rows) // 3, rows - 2]
205        for ln in picks:
206            r = ask([{"type": "text", "text": f"This is a screenshot of code. Copy line {ln:02d} exactly."},
207                     {"type": "image_url", "image_url": {"url": "data:image/png;base64," + b64}}], 80)
208            want = lines[ln - 1].split("  ", 1)[1]
209            hits += want in r.get("content", "")
210            walls.append(r.get("wall"))
211            ptoks = r.get("prompt_n") or ptoks
212        RES["vision"].append({"label": label, "image": name, "exact": hits, "of": len(picks), "prompt_tokens": ptoks,
213                              "wall": walls})
214        log(f"VISION {label} {name}: {hits}/{len(picks)} lines exact, {ptoks} prompt tokens, {walls} s")
215
216
217def suite(script, tag, args=()):
218    t = time.time()
219    with (HERE / f"{tag}.log").open("w", encoding="utf-8") as f:
220        p = subprocess.run([PY, str(HERE / script), *args], cwd=ROOT, stdout=f, stderr=subprocess.STDOUT,
221                           env={**__import__("os").environ, "PYTHONIOENCODING": "utf-8"})
222    RES["suites"].append({"tag": tag, "exit": p.returncode, "minutes": round((time.time() - t) / 60, 1)})
223    log(f"SUITE {tag} finished in {(time.time() - t) / 60:.1f} min (exit {p.returncode})")
224
225
226def main():
227    log("=== run_all started")
228    try:
229        if not health().get("loaded"):
230            configure(131072, 2048)
231        # 1. the everyday configuration: 128K, 2048 MiB kept free
232        # (the 128K speed test and the round-1 suites were measured before; only what is still missing runs here)
233        vision("300 image tokens")
234        suite("strata_eval2.py", "eval2-qa", ["qa"])
235        suite("strata_eval2.py", "eval2-hard", ["hard"])
236        longctx(118000, "128K config")
237        # 2. the upper speed limit: a small context and the smallest VRAM reserve
238        if configure(8192, 700):
239            speed("8K reserve 700")
240        # 3. the trained maximum, and pictures with more tokens
241        if configure(262144, 2048, vision_tokens=1024):
242            speed("256K reserve 2048")
243            vision("1024 image tokens")
244            longctx(248000, "256K config")
245        # 4. past the trained range (experimental rope scaling)
246        if configure(524288, 2048):
247            mc = health().get("max_context") or 0
248            speed(f"{mc // 1024}K (asked 512K) reserve 2048")
249            if mc > 270000:
250                longctx(mc - 14000, f"{mc // 1024}K config")
251    except Exception as e:
252        log(f"CRASHED {type(e).__name__}: {e}")
253    finally:
254        configure(131072, 2048)
255        log("=== run_all finished; server restored to 128K / 2048 MiB")
256
257
258if __name__ == "__main__":
259    main()