okami.mom/strata

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

qni-livebench: community entry, 2x RTX PRO 4500, Swift IQ3_XXS, engine 0.1.30 and 0.1.36 (#418)c69872aa2

main
4.6 KiB82 linesraw
1#!/usr/bin/env python3
2"""Spec-Sweep fuer Strata: pro N den Server neu starten, 3 Laeufe je Prompt, 256 Token, greedy.
3Liest tok/s aus dem Serverlog ("generated in X ms")."""
4import json, os, re, signal, subprocess, sys, time, urllib.request, random, pathlib, statistics
5ROOT = pathlib.Path.home() / "ai/Strata"
6OUT = pathlib.Path.home() / "messungen/2026-10-01-strata-spec-sweep"
7BASE = json.load(open(ROOT / "strata-swift-iq3_xxs.json.bak-20261001-vorsweep"))
8NS = [int(x) for x in sys.argv[1].split(",")]
9RUNS = 3
10def corpus(tokens):
11    files = sorted((ROOT/"src").rglob("*.cpp")) + sorted((ROOT/"serve").glob("*.py")) + sorted((ROOT/"docs").glob("*.md"))
12    txt = ""
13    for f in files:
14        txt += f"\n### {f.name}\n" + f.read_text(errors="ignore")
15        if len(txt) > tokens * 3.2: break
16    return txt[: int(tokens * 3.2)]
17PROMPTS = {
18  "kurz-code": ("Write a Python class LRUCache with get/put, type hints and unit tests using pytest.", 0),
19  "4k-code": ("Here is source code:\n" + corpus(4000) + "\n\nExplain what this code does and propose three concrete refactorings with code.", 4000),
20  "32k-code": ("Here is source code:\n" + corpus(32000) + "\n\nExplain what this code does and propose three concrete refactorings with code.", 32000),
21}
22def stop():
23    me = os.getpid()
24    for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGKILL):
25        for d in os.listdir("/proc"):
26            if d.isdigit() and int(d) != me:
27                try: cmd = open(f"/proc/{d}/cmdline").read().replace(chr(0), " ")
28                except OSError: continue
29                if "serve/server.py --engine strata" in cmd or "engine/strata" in cmd and "python3 sweep" not in cmd:
30                    try: os.kill(int(d), sig)
31                    except OSError: pass
32        time.sleep(8)
33    for _ in range(60):
34        port = subprocess.run("ss -ltn | grep -q ':8080 '", shell=True).returncode == 0
35        mem = max(int(x) for x in subprocess.run("nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits", shell=True, capture_output=True, text=True).stdout.split())
36        if not port and mem < 1000: return
37        time.sleep(3)
38    raise SystemExit("Port/GPU wurde nicht frei")
39def start(n):
40    cfg = json.loads(json.dumps(BASE))
41    a = cfg["args"]; a[a.index("--spec")+1] = str(n)
42    cfg["log"] = str(OUT / f"server-spec{n}.log")
43    p = OUT / f"cfg-spec{n}.json"; json.dump(cfg, open(p, "w"), indent=1)
44    proc = subprocess.Popen(["setsid", str(ROOT/".venv/bin/python"), str(ROOT/"serve/server.py"), "--engine", "strata", "--config", str(p), "--port", "8080", "--open"],
45        cwd=ROOT, stdout=open(OUT/f"stdout-spec{n}.txt","w"), stderr=subprocess.STDOUT)
46    for _ in range(300):
47        time.sleep(3)
48        if proc.poll() is not None: raise SystemExit(f"Server fuer spec={n} sofort beendet, siehe stdout-spec{n}.txt")
49        try:
50            urllib.request.urlopen("http://127.0.0.1:8080/v1/models", timeout=3).read(); return cfg["log"]
51        except Exception: pass
52    raise SystemExit(f"Server fuer spec={n} nicht hochgekommen")
53def ask(text, nonce):
54    body = {"model": BASE["model_name"], "messages": [{"role":"user","content": f"[{nonce}]\n"+text}],
55            "max_tokens": 256, "temperature": 0, "stream": False}
56    r = urllib.request.Request("http://127.0.0.1:8080/v1/chat/completions", json.dumps(body).encode(), {"Content-Type":"application/json"})
57    return json.load(urllib.request.urlopen(r, timeout=900))
58res = []
59for n in NS:
60    stop(); log = start(n)
61    for name, (text, _) in PROMPTS.items():
62        ask(text, f"warm{n}{name}{random.random()}")   # Aufwaermung, zaehlt nicht
63        for i in range(RUNS):
64            before = open(log).read()
65            ask(text, f"r{n}{name}{i}{random.random()}")
66            time.sleep(1)
67            new = open(log).read()[len(before):]
68            m = re.findall(r"prompt (\d+) tokens = .*?, (\d+) generated in (\d+) ms \(([\d.]+) tok/s\), drafts accepted (\d+) of (\d+)", new)
69            if not m: print("kein Logtreffer", n, name, i); continue
70            pt, gen, ms, tps, acc, tot = m[-1]
71            res.append(dict(spec=n, prompt=name, run=i, prompt_tokens=int(pt), generated=int(gen), tok_s=float(tps), accepted=int(acc), drafted=int(tot)))
72            print(n, name, i, tps, f"{acc}/{tot}", flush=True)
73    json.dump(res, open(OUT/"sweep.json","w"), indent=1)
74print("\nspec  prompt      median  min-max   accept")
75for n in NS:
76    for name in PROMPTS:
77        r = [x for x in res if x["spec"]==n and x["prompt"]==name]
78        if r:
79            t = [x["tok_s"] for x in r]
80            print(f"{n:>4}  {name:<10} {statistics.median(t):7.1f}  {min(t):.0f}-{max(t):.0f}   {sum(x['accepted'] for x in r)/max(1,sum(x['drafted'] for x in r)):.0%}")
81
82stop()