gpu-head-to-head
aien-dev/gpu-head-to-head
Brought by drakestapleton
gpu-head-to-head / bench / bench.py
| 1 | #!/usr/bin/env python3 |
| 2 | """End-to-end OpenAI-chat streaming client for the gpu-head-to-head protocol. |
| 3 | |
| 4 | Host measurement tool (Python 3 stdlib only). It is not product code; see README "Host tools". |
| 5 | Every request goes over HTTP to /v1/chat/completions with stream=true, temperature=0, thinking off. |
| 6 | One JSON row per request is appended to --out. Nothing is aggregated here; aggregation is done in |
| 7 | Wolfram (see PROTOCOL.md section 7) so that the raw rows stay the evidence. |
| 8 | """ |
| 9 | import argparse |
| 10 | import hashlib |
| 11 | import http.client |
| 12 | import json |
| 13 | import os |
| 14 | import sys |
| 15 | import threading |
| 16 | import time |
| 17 | import uuid |
| 18 | |
| 19 | |
| 20 | def load1(): |
| 21 | with open("/proc/loadavg") as f: |
| 22 | return float(f.read().split()[0]) |
| 23 | |
| 24 | |
| 25 | def one_request(host, port, model, prompt, max_tokens, timeout=1800, messages=None): |
| 26 | body = { |
| 27 | "model": model, |
| 28 | "messages": messages if messages is not None else [{"role": "user", "content": prompt}], |
| 29 | "stream": True, |
| 30 | "stream_options": {"include_usage": True}, |
| 31 | "temperature": 0, |
| 32 | "top_p": 1, |
| 33 | "max_tokens": max_tokens, |
| 34 | "seed": 0, |
| 35 | "chat_template_kwargs": {"enable_thinking": False}, |
| 36 | } |
| 37 | data = json.dumps(body).encode() |
| 38 | row = {"t_send": None, "t_first": None, "t_last": None, "chunks": 0, "text": "", |
| 39 | "usage": None, "finish_reason": None, "error": None, "http_status": None, |
| 40 | "busy_retries": 0} |
| 41 | conn = None |
| 42 | done = False |
| 43 | try: |
| 44 | row["t_send"] = time.monotonic() |
| 45 | while True: |
| 46 | # PROTOCOL amendment A1: a server that refuses with "busy" (HTTP 429/503) is retried |
| 47 | # every 50 ms; the clock keeps running from the first send. |
| 48 | conn = http.client.HTTPConnection(host, port, timeout=timeout) |
| 49 | conn.request("POST", "/v1/chat/completions", body=data, |
| 50 | headers={"Content-Type": "application/json", "Accept": "text/event-stream"}) |
| 51 | resp = conn.getresponse() |
| 52 | row["http_status"] = resp.status |
| 53 | if resp.status in (429, 503) and time.monotonic() - row["t_send"] < timeout: |
| 54 | resp.read() |
| 55 | conn.close() |
| 56 | row["busy_retries"] += 1 |
| 57 | time.sleep(0.05) |
| 58 | continue |
| 59 | break |
| 60 | if resp.status != 200: |
| 61 | row["error"] = resp.read().decode(errors="replace")[:2000] |
| 62 | return row |
| 63 | while True: |
| 64 | line = resp.readline() |
| 65 | if not line: |
| 66 | break |
| 67 | line = line.strip() |
| 68 | if not line.startswith(b"data:"): |
| 69 | continue |
| 70 | payload = line[5:].strip() |
| 71 | if payload == b"[DONE]": |
| 72 | done = True |
| 73 | break |
| 74 | try: |
| 75 | ev = json.loads(payload) |
| 76 | except json.JSONDecodeError: |
| 77 | row["error"] = "bad json chunk: " + payload[:200].decode(errors="replace") |
| 78 | continue |
| 79 | if ev.get("error"): |
| 80 | row["error"] = "server error event: " + str(ev["error"])[:1000] |
| 81 | continue |
| 82 | now = time.monotonic() |
| 83 | if ev.get("usage"): |
| 84 | row["usage"] = ev["usage"] |
| 85 | for ch in ev.get("choices") or []: |
| 86 | d = ch.get("delta") or {} |
| 87 | piece = (d.get("content") or "") + (d.get("reasoning_content") or "") |
| 88 | if piece: |
| 89 | if row["t_first"] is None: |
| 90 | row["t_first"] = now |
| 91 | row["t_last"] = now |
| 92 | row["chunks"] += 1 |
| 93 | row["text"] += piece |
| 94 | if ch.get("finish_reason"): |
| 95 | row["finish_reason"] = ch["finish_reason"] |
| 96 | except Exception as e: # recorded, never hidden |
| 97 | row["error"] = repr(e) |
| 98 | finally: |
| 99 | if conn is not None: |
| 100 | conn.close() |
| 101 | if row["error"] is None: |
| 102 | if not done: |
| 103 | row["error"] = "stream ended without DONE" |
| 104 | elif not row["text"] or row["t_first"] is None or row["t_last"] is None: |
| 105 | row["error"] = "no content received" |
| 106 | elif not row["finish_reason"]: |
| 107 | row["error"] = "missing finish reason" |
| 108 | return row |
| 109 | |
| 110 | |
| 111 | # PROTOCOL A10 TTFT rows. The nonce depends only on the prompt id, the repetition and whether the |
| 112 | # request is a warmup, never on the arm or the clock: every arm receives byte-identical requests, |
| 113 | # and no prefix cache can carry one repetition into the next. |
| 114 | NONCE_LINE = "Request id %s. Ignore this line.\n" |
| 115 | |
| 116 | |
| 117 | def ttft_nonce(prompt_id, rep, warm): |
| 118 | key = "h2h-ttft|%s|%s%d" % (prompt_id, "w" if warm else "r", rep) |
| 119 | return hashlib.sha256(key.encode()).hexdigest()[:16] |
| 120 | |
| 121 | |
| 122 | def ttft_requests(kind, byid, prompt_id, nonce): |
| 123 | """[(phase, messages)] for one repetition: fresh -> one request; turn2 -> prime, then turn 2.""" |
| 124 | first = {"role": "user", "content": NONCE_LINE % nonce + byid[prompt_id]["text"]} |
| 125 | if kind == "fresh": |
| 126 | return [("fresh", [first])] |
| 127 | full = [dict(first), {"role": "assistant", "content": byid["turn2-assistant"]["text"]}, |
| 128 | {"role": "user", "content": byid["turn2-new"]["text"]}] |
| 129 | return [("prime", [first]), ("turn2", full)] |
| 130 | |
| 131 | |
| 132 | def messages_sha256(messages): |
| 133 | return hashlib.sha256(json.dumps(messages, sort_keys=True).encode()).hexdigest() |
| 134 | |
| 135 | |
| 136 | def prefix_cache_lines(host, port): |
| 137 | """vLLM /metrics prefix-cache counter lines (raw text; deltas are taken in Wolfram).""" |
| 138 | try: |
| 139 | conn = http.client.HTTPConnection(host, port, timeout=10) |
| 140 | conn.request("GET", "/metrics") |
| 141 | resp = conn.getresponse() |
| 142 | text = resp.read().decode(errors="replace") |
| 143 | conn.close() |
| 144 | if resp.status != 200: |
| 145 | return {"error": "HTTP %d" % resp.status} |
| 146 | return {"lines": [l for l in text.splitlines() if "prefix_cache" in l and not l.startswith("#")]} |
| 147 | except Exception as e: # recorded, never hidden |
| 148 | return {"error": repr(e)} |
| 149 | |
| 150 | |
| 151 | def run_ttft(args, byid, f): |
| 152 | """One request at a time; rows carry phase, nonce and the sha256 of the exact message list.""" |
| 153 | failed = False |
| 154 | for k in range(args.warmup + args.reps): |
| 155 | warm = k < args.warmup |
| 156 | rep = args.rep_base + (k if warm else k - args.warmup) |
| 157 | # a warmup may use a cheaper prompt (--warm-select) and is always a single fresh request |
| 158 | pid = (args.warm_select or args.select) if warm else args.select |
| 159 | nonce = ttft_nonce(pid, rep, warm) |
| 160 | for phase, messages in ttft_requests("fresh" if warm else args.ttft, byid, pid, nonce): |
| 161 | before = prefix_cache_lines(args.host, args.port) if args.ttft == "turn2" else None |
| 162 | l1 = load1() |
| 163 | ts = time.time() |
| 164 | r = one_request(args.host, args.port, args.model, None, args.max_tokens, messages=messages) |
| 165 | r.update({"arm": args.arm, "round": args.round, |
| 166 | "metric": args.metric + ("-prime" if phase == "prime" else ""), "rep": rep, |
| 167 | "warmup": warm, "concurrency": 1, "stream_index": 0, |
| 168 | "batch_id": uuid.uuid4().hex[:12], "load1_start": l1, "load1_end": load1(), |
| 169 | "wall_utc": ts, "max_tokens": args.max_tokens, "prompt_id": pid, |
| 170 | "cell_run": args.cell_run, "ttft_phase": phase, "nonce": nonce, |
| 171 | "messages_sha256": messages_sha256(messages), |
| 172 | "prefix_sha256": messages_sha256(messages[:1]), |
| 173 | "server_cpus": os.environ.get("H2H_SRV_CPUS"), |
| 174 | "client_cpus": os.environ.get("H2H_CLI_CPUS")}) |
| 175 | if before is not None: |
| 176 | r["prefix_cache_before"] = before |
| 177 | r["prefix_cache_after"] = prefix_cache_lines(args.host, args.port) |
| 178 | f.write(json.dumps(r) + "\n") |
| 179 | f.flush() |
| 180 | failed = failed or bool(r["error"]) |
| 181 | u = r["usage"] or {} |
| 182 | print("%s %s %s %s rep=%d warm=%s pt=%s ct=%s err=%s" % ( |
| 183 | args.arm, args.round, r["metric"], phase, rep, warm, u.get("prompt_tokens"), |
| 184 | u.get("completion_tokens"), (r["error"] or "")[:120]), file=sys.stderr) |
| 185 | return failed |
| 186 | |
| 187 | |
| 188 | def run_batch(args, prompts, rep, warm): |
| 189 | rows = [None] * len(prompts) |
| 190 | barrier = threading.Barrier(len(prompts)) |
| 191 | |
| 192 | def worker(i): |
| 193 | barrier.wait() |
| 194 | rows[i] = one_request(args.host, args.port, args.model, prompts[i], args.max_tokens) |
| 195 | |
| 196 | l1 = load1() |
| 197 | ts = time.time() |
| 198 | th = [threading.Thread(target=worker, args=(i,)) for i in range(len(prompts))] |
| 199 | for t in th: |
| 200 | t.start() |
| 201 | for t in th: |
| 202 | t.join() |
| 203 | batch_id = uuid.uuid4().hex[:12] |
| 204 | out = [] |
| 205 | for i, r in enumerate(rows): |
| 206 | r.update({"arm": args.arm, "round": args.round, "metric": args.metric, "rep": rep, |
| 207 | "warmup": warm, "concurrency": len(prompts), "stream_index": i, |
| 208 | "batch_id": batch_id, "load1_start": l1, "load1_end": load1(), |
| 209 | "wall_utc": ts, "max_tokens": args.max_tokens, |
| 210 | "prompt_id": args.prompt_ids[i] if args.prompt_ids else None, |
| 211 | "cell_run": args.cell_run, |
| 212 | "server_cpus": os.environ.get("H2H_SRV_CPUS"), |
| 213 | "client_cpus": os.environ.get("H2H_CLI_CPUS")}) |
| 214 | out.append(r) |
| 215 | return out |
| 216 | |
| 217 | |
| 218 | def main(): |
| 219 | ap = argparse.ArgumentParser() |
| 220 | ap.add_argument("--host", default="127.0.0.1") |
| 221 | ap.add_argument("--port", type=int, required=True) |
| 222 | ap.add_argument("--model", required=True) |
| 223 | ap.add_argument("--arm", required=True) |
| 224 | ap.add_argument("--round", required=True) |
| 225 | ap.add_argument("--metric", required=True) |
| 226 | ap.add_argument("--prompts", required=True, help="JSONL with {id, text}") |
| 227 | ap.add_argument("--select", default="", help="comma-separated prompt ids (default: all, in order)") |
| 228 | ap.add_argument("--concurrency", type=int, default=1) |
| 229 | ap.add_argument("--max-tokens", type=int, required=True) |
| 230 | ap.add_argument("--warmup", type=int, default=2) |
| 231 | ap.add_argument("--reps", type=int, default=3) |
| 232 | ap.add_argument("--nonce", action="store_true", |
| 233 | help="prefix each prompt with a unique nonce line so no prefix cache can hit") |
| 234 | ap.add_argument("--ttft", choices=["fresh", "turn2"], |
| 235 | help="A10 TTFT rows: one --select id, deterministic per-rep nonce, concurrency 1") |
| 236 | ap.add_argument("--rep-base", type=int, default=0, help="first repetition number (--ttft only)") |
| 237 | ap.add_argument("--warm-select", default="", help="prompt id for --ttft warmup requests") |
| 238 | ap.add_argument("--out", required=True) |
| 239 | ap.add_argument("--cell-run", default="", help="id of this cell invocation (voiding unit, A2)") |
| 240 | args = ap.parse_args() |
| 241 | if args.concurrency < 1 or args.reps < 1 or args.warmup < 0 or args.max_tokens < 1: |
| 242 | ap.error("concurrency, reps and max-tokens must be positive; warmup must be nonnegative") |
| 243 | if args.ttft: |
| 244 | byid = {p["id"]: p for p in (json.loads(l) for l in open(args.prompts) if l.strip())} |
| 245 | need = [args.select] + (["turn2-assistant", "turn2-new"] if args.ttft == "turn2" else []) |
| 246 | need += [args.warm_select] if args.warm_select else [] |
| 247 | if (args.nonce or args.concurrency != 1 or args.rep_base < 0 or "," in args.select |
| 248 | or not all(n in byid for n in need)): |
| 249 | ap.error("--ttft takes exactly one --select id present in --prompts (turn2 also needs " |
| 250 | "turn2-assistant and turn2-new), concurrency 1, no --nonce, rep-base >= 0") |
| 251 | with open(args.out, "a") as f: |
| 252 | return 1 if run_ttft(args, byid, f) else 0 |
| 253 | if args.rep_base or args.warm_select: |
| 254 | ap.error("--rep-base and --warm-select need --ttft") |
| 255 | |
| 256 | allp = [json.loads(l) for l in open(args.prompts) if l.strip()] |
| 257 | if args.select: |
| 258 | want = args.select.split(",") |
| 259 | byid = {p["id"]: p for p in allp} |
| 260 | allp = [byid[w] for w in want] |
| 261 | if not allp: |
| 262 | ap.error("prompt selection is empty") |
| 263 | failed = False |
| 264 | with open(args.out, "a") as f: |
| 265 | total = args.warmup + args.reps |
| 266 | for k in range(total): |
| 267 | warm = k < args.warmup |
| 268 | rep = k if warm else k - args.warmup |
| 269 | # each batch takes `concurrency` prompts, cycling through the list |
| 270 | sel = [allp[(k * args.concurrency + j) % len(allp)] for j in range(args.concurrency)] |
| 271 | texts = [] |
| 272 | for p in sel: |
| 273 | t = p["text"] |
| 274 | if args.nonce: |
| 275 | t = NONCE_LINE % uuid.uuid4().hex + t |
| 276 | texts.append(t) |
| 277 | args.prompt_ids = [p["id"] for p in sel] |
| 278 | for r in run_batch(args, texts, rep, warm): |
| 279 | f.write(json.dumps(r) + "\n") |
| 280 | f.flush() |
| 281 | err = r["error"] |
| 282 | failed = failed or bool(err) |
| 283 | u = r["usage"] or {} |
| 284 | print("%s %s %s rep=%d warm=%s c=%d i=%d pt=%s ct=%s err=%s" % ( |
| 285 | args.arm, args.round, args.metric, rep, warm, r["concurrency"], r["stream_index"], |
| 286 | u.get("prompt_tokens"), u.get("completion_tokens"), (err or "")[:120]), |
| 287 | file=sys.stderr) |
| 288 | return 1 if failed else 0 |
| 289 | |
| 290 | |
| 291 | if __name__ == "__main__": |
| 292 | sys.exit(main()) |