prototypes/model-bench — throwaway PROTOTYPE harness (bench.py + merge.py) and measured outputs grounding map #125's model-per-surface decisions: essay + Pass 1/Pass 2 across GLM-5.3 efforts (low/high/max), flash, flashx, GPT-6-Sol x2, grok-4.7, gemini-4-argon, claude-opus/sonnet-5.5. Merged report at results/final/REPORT.md. tps computed over content tokens only — reasoning tokens live in completion_tokens and inflated earlier readings (#131 probe).
378 lines
17 KiB
Python
378 lines
17 KiB
Python
#!/usr/bin/env python3
|
||
# PROTOTYPE — throwaway model benchmark for Museion (writing + mentor passes).
|
||
# Answers: which chat model should Museion use, and does GLM-5.3's thinking
|
||
# level matter? Not production code. Delete freely.
|
||
#
|
||
# Run from repo root:
|
||
# python3 prototypes/model-bench/bench.py # everything
|
||
# python3 prototypes/model-bench/bench.py --smoke # one cheap call
|
||
# python3 prototypes/model-bench/bench.py --tasks essay --models glm-5.3-flash
|
||
#
|
||
# Reads API keys from ./.secrets at runtime (labels → provider). Never prints them.
|
||
|
||
import argparse
|
||
import json
|
||
import re
|
||
import statistics
|
||
import sys
|
||
import time
|
||
import urllib.error
|
||
import urllib.request
|
||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||
from pathlib import Path
|
||
|
||
REPO = Path(__file__).resolve().parents[2]
|
||
OUT = REPO / "prototypes" / "model-bench" / "results"
|
||
SECRETS = REPO / ".secrets"
|
||
PIECE = REPO / "spike" / "prose" / "standing-desk.md"
|
||
PERSONA = REPO / "ref" / "writing skills" / "pass-persona" / "SKILL.md"
|
||
|
||
PROVIDERS = {
|
||
"zai": "https://api.z.ai/api/coding/paas/v4/chat/completions",
|
||
"openai": "https://api.openai.com/v1/chat/completions",
|
||
"xai": "https://api.x.ai/v1/chat/completions",
|
||
"mistral": "https://api.mistral.ai/v1/chat/completions",
|
||
"google": "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
|
||
"anthropic": "https://api.anthropic.com/v1/messages",
|
||
}
|
||
|
||
# label prefix in .secrets (lowercased) -> provider
|
||
LABELS = {
|
||
"z.ai api key": "zai",
|
||
"openai api key": "openai",
|
||
"grok api key": "xai",
|
||
"mistral api key": "mistral",
|
||
"google api key": "google",
|
||
"anthropic api key": "anthropic",
|
||
}
|
||
|
||
MODELS = [
|
||
{"slug": "glm-5.3-low", "model": "glm-5.3", "provider": "zai", "extra": {"thinking": {"type": "enabled"}, "reasoning_effort": "low"}, "note": "effort low"},
|
||
{"slug": "glm-5.3-high", "model": "glm-5.3", "provider": "zai", "extra": {"thinking": {"type": "enabled"}, "reasoning_effort": "high"}, "note": "effort high"},
|
||
{"slug": "glm-5.3-max", "model": "glm-5.3", "provider": "zai", "extra": {"thinking": {"type": "enabled"}, "reasoning_effort": "max"}, "note": "effort max (= Museion today)"},
|
||
{"slug": "glm-5.3-flash", "model": "glm-5.3-flash", "provider": "zai", "extra": {}, "note": "default effort"},
|
||
{"slug": "glm-5.3-flashx", "model": "glm-5.3-flashx", "provider": "zai", "extra": {}, "note": "default effort"},
|
||
{"slug": "gpt-6-sol", "model": "gpt-6-sol", "provider": "openai", "extra": {}},
|
||
{"slug": "gpt-6.1-sol", "model": "gpt-6.1-sol", "provider": "openai", "extra": {}},
|
||
{"slug": "grok-4.7", "model": "grok-4.7", "provider": "xai", "extra": {}},
|
||
{"slug": "mistral-small-2603", "model": "mistral-small-2603", "provider": "mistral", "extra": {}},
|
||
{"slug": "mistral-large-2512", "model": "mistral-large-2512", "provider": "mistral", "extra": {}},
|
||
{"slug": "gemini-4-argon", "model": "gemini-4-argon", "provider": "google", "extra": {}},
|
||
{"slug": "claude-opus-5-5", "model": "claude-opus-5-5", "provider": "anthropic", "extra": {}},
|
||
{"slug": "claude-sonnet-5-5", "model": "claude-sonnet-5-5", "provider": "anthropic", "extra": {}},
|
||
]
|
||
|
||
MAX_TOKENS = {"essay": 2000, "pass1": 24000, "pass2": 24000}
|
||
|
||
|
||
def load_keys():
|
||
keys = {}
|
||
for line in SECRETS.read_text().splitlines():
|
||
line = line.strip()
|
||
if not line:
|
||
continue
|
||
label, _, key = line.rpartition(" ")
|
||
p = LABELS.get(label.lower())
|
||
if p and key and "«" not in key:
|
||
keys[p] = key
|
||
missing = {p for p in ("zai", "openai", "xai", "mistral", "google", "anthropic")} - keys.keys()
|
||
if missing:
|
||
sys.exit(f"missing keys in .secrets for: {sorted(missing)}")
|
||
return keys
|
||
|
||
|
||
# ---------------------------------------------------------------- tasks
|
||
|
||
def pass_prompt(kind, level):
|
||
# PassContext.stub (Pass.swift) verbatim, hasResearch: false.
|
||
stub = (
|
||
f"Pass {kind} — {level}.\n"
|
||
f"Piece: {PIECE}\n"
|
||
"Critique the piece for this pass. Fact-check claims where needed — research findings "
|
||
"travel as candidate source-note tool calls (submit_research_notes), never written to disk. "
|
||
"Deliver the verdict in your reply — findings travel as fix-card tool calls (submit_fix_cards). "
|
||
"Do not write to the piece folder."
|
||
)
|
||
body = PIECE.read_text()
|
||
return stub + "\n\nYou have no file access and no tools in this harness — the piece body follows.\n\n" \
|
||
+ "-----BEGIN PIECE-----\n" + body + "\n-----END PIECE-----\n"
|
||
|
||
|
||
def task_defs():
|
||
persona = PERSONA.read_text()
|
||
adaptation = (
|
||
"\n\n## Harness adaptation (benchmark, not the app)\n\n"
|
||
"No tools are available in this exchange — never emit tool calls. No Learnings exist yet; "
|
||
"no voice anchor is provided. Instead of one ranked submit_fix_cards call, end your reply "
|
||
"with the Fix Cards as a ranked numbered list (max 10), one card per line:\n"
|
||
"**Pattern title** — problem · fix · anchor quote. Verdict prose above the list names each "
|
||
"finding by pattern title only. A pass may emit zero cards. Skip the research rail; flag "
|
||
"unverifiable claims in the verdict.\n"
|
||
)
|
||
system = persona + adaptation
|
||
return {
|
||
"essay": {"system": None, "user": "Write a short essay about making pizza."},
|
||
"pass1": {"system": system, "user": pass_prompt(1, "paragraph level and up")},
|
||
"pass2": {"system": system, "user": pass_prompt(2, "sentence level and below")},
|
||
}
|
||
|
||
|
||
# ---------------------------------------------------------------- DraftStats (port of Museion DraftStats.swift)
|
||
|
||
def tokens_of(text):
|
||
return re.findall(r"[^\W_]+", text.lower())
|
||
|
||
|
||
def draft_stats(body):
|
||
toks = tokens_of(body)
|
||
if not toks:
|
||
return {"burstiness": 0, "ttr": 0, "sentvar": 0, "trigram": 0}
|
||
sents = [tokens_of(s) for s in re.split(r"[.!?]", body)]
|
||
counts = [len(s) for s in sents if s]
|
||
tris = [tuple(toks[i:i + 3]) for i in range(len(toks) - 2)]
|
||
out = {}
|
||
if len(counts) < 2:
|
||
out["burstiness"] = -1
|
||
out["sentvar"] = -1 # ponytail: single-sentence σ/μ is 0/μ=0; flag undefined as -1
|
||
else:
|
||
mu = statistics.fmean(counts)
|
||
sig = statistics.pstdev(counts)
|
||
out["burstiness"] = round((sig - mu) / (sig + mu), 3) if (sig + mu) else 0
|
||
out["sentvar"] = round(sig / mu, 3) if mu else 0
|
||
out["ttr"] = round(len(set(toks)) / len(toks), 3)
|
||
out["trigram"] = round((len(tris) - len(set(tris))) / len(tris), 3) if tris else 0
|
||
return out
|
||
|
||
|
||
# ---------------------------------------------------------------- clients
|
||
|
||
def _post(url, payload, headers, timeout=900):
|
||
req = urllib.request.Request(url, data=json.dumps(payload).encode(),
|
||
headers={"Content-Type": "application/json", **headers})
|
||
t0 = time.monotonic()
|
||
resp = urllib.request.urlopen(req, timeout=timeout)
|
||
return resp, t0
|
||
|
||
|
||
def stream_openai(url, key, payload):
|
||
"""OpenAI-compatible SSE streaming. Returns result dict."""
|
||
headers = {"Authorization": f"Bearer {key}"}
|
||
body = dict(payload)
|
||
body["stream"] = True
|
||
body.setdefault("stream_options", {"include_usage": True})
|
||
fixes = 0
|
||
while True:
|
||
try:
|
||
resp, t0 = _post(url, body, headers)
|
||
break
|
||
except urllib.error.HTTPError as e:
|
||
err = e.read().decode(errors="replace")[:400]
|
||
if fixes < 3 and e.code == 400:
|
||
# param-fix ladder: drop stream_options, rename max_tokens, drop zai extras
|
||
if "stream_options" in err and "stream_options" in body:
|
||
body.pop("stream_options"); fixes += 1; continue
|
||
if "max_completion_tokens" in err and "max_tokens" in body:
|
||
body["max_completion_tokens"] = body.pop("max_tokens"); fixes += 1; continue
|
||
if "thinking" in body:
|
||
body.pop("thinking"); body.pop("reasoning_effort", None); fixes += 1; continue
|
||
raise RuntimeError(f"HTTP {e.code}: {err}") from e
|
||
text, think, usage, finish, ttft = [], [], {}, None, None
|
||
with resp:
|
||
for raw in resp:
|
||
line = raw.decode(errors="replace").strip()
|
||
if not line.startswith("data:"):
|
||
continue
|
||
data = line[5:].strip()
|
||
if data == "[DONE]":
|
||
break
|
||
try:
|
||
chunk = json.loads(data)
|
||
except json.JSONDecodeError:
|
||
continue
|
||
if chunk.get("usage"):
|
||
usage = chunk["usage"]
|
||
for ch in chunk.get("choices", []):
|
||
d = ch.get("delta", {}) or {}
|
||
if d.get("content"):
|
||
if ttft is None:
|
||
ttft = time.monotonic() - t0
|
||
text.append(d["content"])
|
||
if d.get("reasoning_content"):
|
||
think.append(d["reasoning_content"])
|
||
if ch.get("finish_reason"):
|
||
finish = ch["finish_reason"]
|
||
total = time.monotonic() - t0
|
||
return {"text": "".join(text), "thinking": "".join(think), "usage": usage,
|
||
"finish": finish, "ttft": ttft, "total": total}
|
||
|
||
|
||
def stream_anthropic(url, key, payload):
|
||
"""Native /v1/messages SSE streaming."""
|
||
headers = {"x-api-key": key, "anthropic-version": "2023-06-01"}
|
||
body = dict(payload)
|
||
body["stream"] = True
|
||
resp, t0 = _post(url, body, headers)
|
||
text, think = [], []
|
||
usage, finish, ttft = {}, None, None
|
||
with resp:
|
||
for raw in resp:
|
||
line = raw.decode(errors="replace").strip()
|
||
if not line.startswith("data:"):
|
||
continue
|
||
try:
|
||
ev = json.loads(line[5:].strip())
|
||
except json.JSONDecodeError:
|
||
continue
|
||
t = ev.get("type")
|
||
if t == "content_block_delta":
|
||
d = ev.get("delta", {})
|
||
if d.get("type") == "text_delta":
|
||
if ttft is None:
|
||
ttft = time.monotonic() - t0
|
||
text.append(d.get("text", ""))
|
||
elif d.get("type") == "thinking_delta":
|
||
think.append(d.get("thinking", ""))
|
||
elif t == "message_start":
|
||
usage = ev.get("message", {}).get("usage", {})
|
||
elif t == "message_delta":
|
||
usage.update(ev.get("usage", {}))
|
||
finish = ev.get("delta", {}).get("stop_reason", finish)
|
||
total = time.monotonic() - t0
|
||
return {"text": "".join(text), "thinking": "".join(think), "usage": usage,
|
||
"finish": finish, "ttft": ttft, "total": total}
|
||
|
||
|
||
def call_model(m, task, keys, defs):
|
||
url = PROVIDERS[m["provider"]]
|
||
payload = {"model": m["model"], "max_tokens": MAX_TOKENS[task]}
|
||
payload.update(m.get("extra") or {})
|
||
if m["provider"] == "anthropic":
|
||
if defs[task]["system"]:
|
||
payload["system"] = defs[task]["system"]
|
||
payload["messages"] = [{"role": "user", "content": defs[task]["user"]}]
|
||
r = stream_anthropic(url, keys["anthropic"], payload)
|
||
u = r["usage"]
|
||
r["in_tok"] = u.get("input_tokens")
|
||
r["out_tok"] = u.get("output_tokens")
|
||
r["think_tok"] = None
|
||
else:
|
||
msgs = []
|
||
if defs[task]["system"]:
|
||
msgs.append({"role": "system", "content": defs[task]["system"]})
|
||
msgs.append({"role": "user", "content": defs[task]["user"]})
|
||
payload["messages"] = msgs
|
||
r = stream_openai(url, keys[m["provider"]], payload)
|
||
u = r["usage"]
|
||
r["in_tok"] = u.get("prompt_tokens")
|
||
r["out_tok"] = u.get("completion_tokens")
|
||
det = (u.get("completion_tokens_details") or {})
|
||
r["think_tok"] = det.get("reasoning_tokens") or det.get("thinking_tokens")
|
||
gen = r["total"] - (r["ttft"] or 0)
|
||
# tps over CONTENT tokens only — out_tok includes reasoning tokens, which are
|
||
# generated during the (silent) thinking window, not the content window; dividing
|
||
# total-out by content-window inflated GLM to a fake 800-1100 tok/s "flush".
|
||
content_tok = (r["out_tok"] or 0) - (r["think_tok"] or 0)
|
||
r["tps"] = round(content_tok / gen, 1) if content_tok and gen > 0 else None
|
||
r["task"] = task
|
||
r["slug"] = m["slug"]
|
||
return r
|
||
|
||
|
||
def run_one(m, task, keys, defs, attempt=1):
|
||
try:
|
||
return call_model(m, task, keys, defs)
|
||
except Exception as e: # noqa: BLE001 — benchmark reports everything
|
||
msg = str(e)[:300]
|
||
if attempt < 3 and ("429" in msg or "5xx" in msg or "timed out" in msg.lower() or "HTTP 5" in msg):
|
||
time.sleep(5 * attempt)
|
||
return run_one(m, task, keys, defs, attempt + 1)
|
||
return {"slug": m["slug"], "task": task, "error": msg, "text": "", "thinking": "",
|
||
"usage": {}, "ttft": None, "total": None, "in_tok": None, "out_tok": None,
|
||
"think_tok": None, "tps": None, "finish": None}
|
||
|
||
|
||
# ---------------------------------------------------------------- report
|
||
|
||
def fmt(x, nd=1):
|
||
return f"{x:.{nd}f}" if isinstance(x, (int, float)) else "—"
|
||
|
||
|
||
def main():
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--tasks", default="essay,pass1,pass2")
|
||
ap.add_argument("--models", default=",".join(m["slug"] for m in MODELS))
|
||
ap.add_argument("--smoke", action="store_true", help="one cheap call, no report")
|
||
args = ap.parse_args()
|
||
|
||
keys = load_keys()
|
||
defs = task_defs()
|
||
tasks = args.tasks.split(",")
|
||
slugs = set(args.models.split(","))
|
||
jobs = [(m, t) for m in MODELS if m["slug"] in slugs for t in tasks]
|
||
if args.smoke:
|
||
jobs = [(MODELS[3], "essay")] # glm-5.3-flash
|
||
|
||
stamp = time.strftime("%Y%m%d-%H%M%S")
|
||
outdir = OUT / (stamp if not args.smoke else "smoke")
|
||
outdir.mkdir(parents=True, exist_ok=True)
|
||
results = []
|
||
|
||
def worker(job):
|
||
m, t = job
|
||
r = run_one(m, t, keys, defs)
|
||
d = outdir / m["slug"]
|
||
d.mkdir(exist_ok=True)
|
||
head = (f"<!-- PROTOTYPE benchmark output — model: {m['model']} ({m.get('note', '')}) "
|
||
f"task: {t} provider: {m['provider']}\n wall {r.get('total')}s ttft {r.get('ttft')}s "
|
||
f"in {r.get('in_tok')} out {r.get('out_tok')} think {r.get('think_tok')} "
|
||
f"tps {r.get('tps')} finish {r.get('finish')} error {r.get('error')} -->\n\n")
|
||
(d / f"{t}.md").write_text(head + r.get("text", ""))
|
||
if r.get("thinking"):
|
||
(d / f"{t}.thinking.md").write_text(r["thinking"])
|
||
status = f"ERR {str(r.get('error'))[:80]}" if r.get("error") else \
|
||
f"{fmt(r.get('total'))}s {fmt(r.get('tps'))} tok/s out={r.get('out_tok')}"
|
||
print(f"[{time.strftime('%H:%M:%S')}] {m['slug']:<20} {t:<6} {status}")
|
||
return r
|
||
|
||
with ThreadPoolExecutor(max_workers=4) as ex:
|
||
futs = [ex.submit(worker, j) for j in jobs]
|
||
for f in as_completed(futs):
|
||
results.append(f.result())
|
||
|
||
if args.smoke:
|
||
print("\nSMOKE RESULT:")
|
||
r = results[0]
|
||
print(r.get("text", r.get("error"))[:600])
|
||
return
|
||
|
||
results.sort(key=lambda r: (r["task"], r["slug"]))
|
||
cols = ["slug", "task", "total", "ttft", "tps", "in_tok", "out_tok", "think_tok", "finish", "error"]
|
||
with open(outdir / "summary.csv", "w") as f:
|
||
f.write(",".join(cols) + "\n")
|
||
for r in results:
|
||
f.write(",".join(str(r.get(c) or "") for c in cols) + "\n")
|
||
|
||
lines = [f"# Model benchmark — {stamp}", "",
|
||
"Museion mentor-model bake-off. GLM on z.ai coding-plan endpoint; "
|
||
"`reasoning_effort` per docs (coding plan maps low/medium→…, max=default).",
|
||
"Museion today = glm-5.3-max. Outputs in `<slug>/<task>.md`.", ""]
|
||
for t in tasks:
|
||
lines += [f"## {t}", "", "| model | wall s | ttft s | tok/s | in | out | think | finish |",
|
||
"|---|---|---|---|---|---|---|---|"]
|
||
for r in [x for x in results if x["task"] == t]:
|
||
lines.append(f"| {r['slug']} | {fmt(r.get('total'))} | {fmt(r.get('ttft'), 2)} | "
|
||
f"{fmt(r.get('tps'))} | {r.get('in_tok') or '—'} | {r.get('out_tok') or '—'} | "
|
||
f"{r.get('think_tok') or '—'} | {r.get('finish') or r.get('error', 'ERR')[:40]} |")
|
||
lines.append("")
|
||
for r in results:
|
||
if r["task"] == "essay" and r.get("text"):
|
||
ds = draft_stats(r["text"])
|
||
lines.append(f"- essay DraftStats {r['slug']}: burstiness {ds['burstiness']}, ttr {ds['ttr']}, "
|
||
f"sentvar {ds['sentvar']}, trigram-rep {ds['trigram']}")
|
||
(outdir / "summary.md").write_text("\n".join(lines) + "\n")
|
||
print(f"\nReport: {outdir / 'summary.md'}")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|