#!/usr/bin/env python3 """Same-prompt streaming chat benchmark for one OpenAI-compatible server. stdlib only. Decode tok/s per request = (completion_tokens - 1) / (last token - first token). Aggregate tok/s = all completion tokens / wall time of the batch. Token counts come from the server's usage field. Every request starts with a unique line so prompts never share a prefix across runs. temperature 0, max_tokens 512, ignore_eos off, reasoning left at the model's default. CONCS (env) picks the concurrency levels (default 1 4 16); RUNS the repeats (default 3). Below 16 a level sends the 12 prompts; from 16 up it sends 2 x concurrency requests. """ import json, sys, time, threading, http.client, statistics as st, os model, label, out = sys.argv[1:4] extra = json.loads(sys.argv[4]) if len(sys.argv) > 4 and sys.argv[4] else {} PROMPTS = [ ("code", "Write a Python class implementing an LRU cache with get, put and a TTL per entry. Include type hints and pytest unit tests."), ("code", "Write a Go HTTP handler that streams a large CSV export from PostgreSQL row by row with context cancellation."), ("code", "Refactor this into idiomatic Rust with error handling: fn f(s:&str)->i32{let v:Vec<&str>=s.split(',').collect();let mut t=0;for x in v{t+=x.parse::().unwrap();}t} Explain each change."), ("code", "Write a SQL migration and queries for a double-entry ledger: accounts, entries, and a view that shows balances per account per day."), ("prose", "Write a 450-word story about a lighthouse keeper who finds a letter addressed to a ship that never arrived."), ("prose", "Explain to a homeowner, in about 450 words, how a heat pump works in winter and when it stops being economical."), ("prose", "Write a travel essay of about 450 words on taking a night train through the Alps in January."), ("prose", "Summarise the causes of the 1929 stock market crash for a general reader in about 450 words."), ("json", "Invent 12 realistic customer support tickets and return them as a JSON array with id, customer, product, severity, summary and next_action. Output only JSON."), ("json", "Produce a JSON schema for a hotel booking API with guests, rooms, rates, taxes and cancellation rules, then one valid example document."), ("reason", "A tank fills through pipe A in 6 hours and pipe B in 9 hours, and drains through C in 12 hours. All open for 2 hours, then C closes. How long in total until full? Show the steps."), ("reason", "Three people share a taxi and leave at different stops, 4 km, 9 km and 15 km. The fare is 2 euro base plus 1.5 euro per km. Propose two fair ways to split it and compute both."), ] def one(tag, prompt, mt=512): body = {"model": model, "messages": [{"role": "user", "content": f"[request {label}-{tag}]\n{prompt}"}], "max_tokens": mt, "temperature": 0, "stream": True, "stream_options": {"include_usage": True}} body.update(extra) c = http.client.HTTPConnection("127.0.0.1", 8000, timeout=900) t0 = time.perf_counter() tf = tl = u = fr = None try: c.request("POST", "/v1/chat/completions", json.dumps(body), {"Content-Type": "application/json"}) r = c.getresponse() if r.status != 200: return {"tag": tag, "error": f"{r.status} {r.read()[:300]!r}"} for line in r: line = line.strip() if not line.startswith(b"data:") or line.endswith(b"[DONE]"): continue d = json.loads(line[5:]) if d.get("usage"): u = d["usage"] for ch in d.get("choices", []): de = ch.get("delta", {}) if any(de.get(k) for k in ("content", "reasoning", "reasoning_content")): tl = time.perf_counter() tf = tf or tl fr = ch.get("finish_reason") or fr except Exception as e: return {"tag": tag, "error": repr(e)[:300]} n = u["completion_tokens"] if u else 0 return {"tag": tag, "ptok": u and u["prompt_tokens"], "ctok": n, "ttft": tf and tf - t0, "e2e": time.perf_counter() - t0, "finish": fr, "decode": (n - 1) / (tl - tf) if tf and tl > tf and n > 1 else None} def batch(conc, jobs): res = [None] * len(jobs) it = iter(enumerate(jobs)) lk = threading.Lock() def w(): while True: with lk: x = next(it, None) if x is None: return i, (kind, tag, p) = x res[i] = one(tag, p) res[i]["kind"] = kind t = time.perf_counter() th = [threading.Thread(target=w) for _ in range(conc)] [x.start() for x in th] [x.join() for x in th] return res, time.perf_counter() - t def avg(v): v = [x for x in v if x] return round(st.mean(v), 1) if v else None print("warmup", one("w1", "Say hello and count to fifty.", 128), one("w2", "Write a haiku, then count to fifty.", 128)) for conc in [int(x) for x in os.environ.get('CONCS', '1 4 16').split()]: for run in range(1, int(os.environ.get('RUNS', '3')) + 1): base = PROMPTS if conc < 16 else (PROMPTS * 8)[:2 * conc] res, wall = batch(conc, [(k, f"c{conc}r{run}n{i}", p) for i, (k, p) in enumerate(base)]) ok = [x for x in res if "error" not in x and x["ctok"]] s = {"label": label, "conc": conc, "run": run, "n": len(res), "failed": len(res) - len(ok), "wall_s": round(wall, 2), "ctok": sum(x["ctok"] for x in ok), "agg_tok_s": round(sum(x["ctok"] for x in ok) / wall, 1), "decode_mean": avg([x["decode"] for x in ok]), "ttft_median_ms": round(1000 * st.median([x["ttft"] for x in ok if x["ttft"]] or [0])), "ttft_p95_ms": round(1000 * sorted([x["ttft"] for x in ok if x["ttft"]] or [0])[int(0.95 * (len([x for x in ok if x["ttft"]]) - 1))]), "decode_p10": round(sorted([x["decode"] for x in ok if x["decode"]] or [0])[int(0.10 * (len([x for x in ok if x["decode"]]) - 1))], 1)} for k in ("code", "prose", "json", "reason"): s["decode_" + k] = avg([x["decode"] for x in ok if x["kind"] == k]) print(json.dumps(s), flush=True) for x in res: if "error" in x: print("ERR", x["error"], flush=True) break with open(out, "a") as f: for x in res: f.write(json.dumps({"label": label, "run": run, "conc": conc, **x}) + "\n")