diff --git a/benchmarks/README.md b/benchmarks/README.md index 40c0f6de..78e12f71 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -3,3 +3,9 @@ The `fixtures/responses/` directory currently holds a synthetic protocol replay example. It is not a real Codex capture or a performance measurement. Run it through the Rust `replay-responses` binary described in [control-plane/README.md](../control-plane/README.md). Store future benchmark definitions and sanitized fixtures in Git; place generated reports and sensitive captures outside the source tree or under ignored local paths. No baseline has been measured yet. + +## Synthetic paired Chat smoke + +`fixtures/chat/paired-smoke.json` contains public synthetic arithmetic, retrieval, and function-call prompts. Run `scripts/bench-chat-paired.py` from the repository root. It sends one untimed warmup per case and endpoint, then alternates baseline/candidate order over repeated, sequential requests with the same model, prompt, greedy sampling settings, and token cap. It checks each response's terminal `finish_reason` and case-specific text or tool arguments. The report includes per-case pass counts, raw response timings, and paired wall-time ratios. The full response report is written only to a new private path outside Git with mode 0600; API keys are read from private server config files and omitted from the report. + +For the current upstream server, pass its full bound URL as `--baseline-url`, the configured model name as `--model`, and its private JSON config as `--baseline-auth-config`. Once a compressed inference endpoint exists, pass its URL as `--candidate-url`. A baseline-only run is a functional check and cannot establish a speedup. Even a paired run of this small synthetic suite is only a smoke test: the charter's long-context, real-agent, cache-state, and model-quality gates still require separate runs. Record engine/config digests, GPU, driver, CUDA, power settings, and artifact digests in a private `--metadata` JSON for any reported performance result. Never commit the report or private config. diff --git a/benchmarks/fixtures/chat/paired-smoke.json b/benchmarks/fixtures/chat/paired-smoke.json new file mode 100644 index 00000000..a12778bf --- /dev/null +++ b/benchmarks/fixtures/chat/paired-smoke.json @@ -0,0 +1,34 @@ +{ + "schema": 1, + "name": "public-synthetic-chat-smoke", + "cases": [ + { + "id": "arithmetic", + "category": "reasoning", + "messages": [ + {"role": "user", "content": "Compute 17 * 19. Reply with the integer only."} + ], + "expect": {"text_regex": "^323\\s*$"} + }, + { + "id": "retrieval", + "category": "retrieval", + "messages": [ + {"role": "user", "content": "Facts: Ada owns a blue kite. Bruno owns a red cup. Cora owns a green book. Dany owns a yellow lamp. Who owns the green book? Reply with the name only."} + ], + "expect": {"text_regex": "^Cora\\s*$"} + }, + { + "id": "tool-call", + "category": "tool-calling", + "messages": [ + {"role": "user", "content": "Look up the weather for Paris. Use the weather tool."} + ], + "tools": [ + {"type": "function", "function": {"name": "get_weather", "description": "Get weather for a city", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"], "additionalProperties": false}}} + ], + "tool_choice": {"type": "function", "function": {"name": "get_weather"}}, + "expect": {"tool_name": "get_weather", "tool_arguments": {"city": "Paris"}} + } + ] +} diff --git a/scripts/bench-chat-paired.py b/scripts/bench-chat-paired.py new file mode 100755 index 00000000..8435f8d1 --- /dev/null +++ b/scripts/bench-chat-paired.py @@ -0,0 +1,232 @@ +#!/usr/bin/env python3 +"""Private, reproducible Chat Completions smoke for one or two GPU runtimes. + +This is an offline evaluation tool. It does not form part of production serving. +Full responses go only to the requested private output path; stdout is summary-only. +""" + +import argparse +import datetime as dt +import hashlib +import json +import os +import pathlib +import re +import statistics +import sys +import time +import urllib.error +import urllib.request + + +def parse_args(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--suite", type=pathlib.Path, required=True) + parser.add_argument("--baseline-url", required=True, + help="full baseline /v1/chat/completions URL") + parser.add_argument("--candidate-url", + help="full candidate /v1/chat/completions URL") + parser.add_argument("--model", required=True) + parser.add_argument("--output", type=pathlib.Path, required=True) + parser.add_argument("--repeats", type=int, default=3) + parser.add_argument("--max-tokens", type=int, default=128) + parser.add_argument("--timeout-seconds", type=float, default=180.0) + parser.add_argument("--baseline-auth-config", type=pathlib.Path, + help="private JSON config with an api_key field") + parser.add_argument("--candidate-auth-config", type=pathlib.Path, + help="private JSON config with an api_key field") + parser.add_argument("--metadata", type=pathlib.Path, + help="private JSON with engine commits, digests and GPU settings") + args = parser.parse_args() + if args.repeats < 1 or args.repeats > 100 or args.max_tokens < 1 or args.timeout_seconds <= 0: + parser.error("repeats must be 1..100, max-tokens positive and timeout positive") + if args.candidate_auth_config and not args.candidate_url: + parser.error("candidate auth config requires candidate URL") + return args + + +def api_key(config): + if config is None: + return None + key = json.loads(config.read_text())["api_key"] + if not isinstance(key, str) or not key: + raise ValueError("api_key must be a nonempty string") + return key + + +def request(url, key, payload, timeout): + data = json.dumps(payload, separators=(",", ":")).encode() + headers = {"Content-Type": "application/json"} + if key: + headers["Authorization"] = "Bearer " + key + start = time.perf_counter() + try: + with urllib.request.urlopen(urllib.request.Request(url, data, headers), timeout=timeout) as response: + raw = response.read() + status = response.status + except urllib.error.HTTPError as error: + # Server error bodies can contain request material. Keep them private. + raw = error.read(65536) + status = error.code + wall = time.perf_counter() - start + try: + decoded = json.loads(raw) + except (ValueError, UnicodeDecodeError): + decoded = {"raw_body_sha256": hashlib.sha256(raw).hexdigest(), "raw_body_bytes": len(raw)} + return {"http_status": status, "wall_seconds": wall, "response": decoded} + + +def judge(case, observation): + response = observation["response"] + if observation["http_status"] != 200 or not isinstance(response, dict): + return {"passed": False, "reason": "HTTP or JSON failure"} + choices = response.get("choices") + if not isinstance(choices, list) or len(choices) != 1 or not isinstance(choices[0], dict): + return {"passed": False, "reason": "missing single choice"} + choice = choices[0] + if choice.get("finish_reason") not in ("stop", "tool_calls"): + return {"passed": False, "reason": "incomplete finish reason"} + message = choice.get("message") + if not isinstance(message, dict): + return {"passed": False, "reason": "missing message"} + expect = case["expect"] + if "text_regex" in expect: + if choice["finish_reason"] != "stop": + return {"passed": False, "reason": "text finish reason mismatch"} + content = message.get("content") + passed = isinstance(content, str) and re.fullmatch(expect["text_regex"], content) is not None + return {"passed": passed, "reason": "text matched" if passed else "text mismatch"} + calls = message.get("tool_calls") + if choice["finish_reason"] != "tool_calls": + return {"passed": False, "reason": "tool finish reason mismatch"} + if not isinstance(calls, list) or len(calls) != 1 or not isinstance(calls[0], dict): + return {"passed": False, "reason": "missing single tool call"} + function = calls[0].get("function") + if not isinstance(function, dict) or function.get("name") != expect["tool_name"]: + return {"passed": False, "reason": "tool name mismatch"} + try: + arguments = json.loads(function["arguments"]) + except (KeyError, TypeError, ValueError): + return {"passed": False, "reason": "invalid tool JSON"} + passed = arguments == expect["tool_arguments"] + return {"passed": passed, "reason": "tool matched" if passed else "tool arguments mismatch"} + + +def normalized_output(observation): + response = observation["response"] + try: + message = response["choices"][0]["message"] + calls = message.get("tool_calls") or [] + return {"content": message.get("content"), + "tool_calls": [{"name": call["function"]["name"], + "arguments": json.loads(call["function"]["arguments"])} + for call in calls]} + except (KeyError, IndexError, TypeError, ValueError): + return None + + +def summarize(rows, paired): + summary = {} + for arm in ("baseline", "candidate") if paired else ("baseline",): + selected = [row for row in rows if row["arm"] == arm and not row["warmup"]] + good = [row for row in selected if row["quality"]["passed"]] + by_case = {} + for case_id in sorted({row["case_id"] for row in selected}): + case_rows = [row for row in selected if row["case_id"] == case_id] + by_case[case_id] = { + "requests": len(case_rows), + "quality_passed": sum(row["quality"]["passed"] for row in case_rows), + "wall_median_seconds": statistics.median(row["wall_seconds"] for row in case_rows), + } + summary[arm] = { + "requests": len(selected), + "quality_passed": len(good), + "wall_median_seconds": statistics.median(row["wall_seconds"] for row in selected), + "wall_mean_seconds": statistics.mean(row["wall_seconds"] for row in selected), + "cases": by_case, + } + if paired: + pairs = {} + for row in rows: + if not row["warmup"]: + pairs.setdefault((row["case_id"], row["repeat"]), {})[row["arm"]] = row + complete = [pair for pair in pairs.values() if len(pair) == 2] + summary["paired"] = { + "pairs": len(complete), + "candidate_over_baseline_wall_median_ratio": statistics.median( + pair["candidate"]["wall_seconds"] / pair["baseline"]["wall_seconds"] + for pair in complete), + "same_normalized_output": sum( + normalized_output(pair["baseline"]) == normalized_output(pair["candidate"]) + for pair in complete), + "both_quality_passed": sum( + pair["baseline"]["quality"]["passed"] and + pair["candidate"]["quality"]["passed"] for pair in complete), + } + return summary + + +def main(): + args = parse_args() + repository = pathlib.Path(__file__).resolve().parent.parent + output = args.output.resolve() + if output == repository or repository in output.parents: + raise ValueError("output must be outside the repository") + suite_bytes = args.suite.read_bytes() + suite = json.loads(suite_bytes) + if suite.get("schema") != 1 or not isinstance(suite.get("cases"), list) or not suite["cases"]: + raise ValueError("invalid benchmark suite") + ids = [case["id"] for case in suite["cases"]] + if len(set(ids)) != len(ids): + raise ValueError("duplicate case IDs") + metadata = json.loads(args.metadata.read_text()) if args.metadata else {} + arms = {"baseline": (args.baseline_url, api_key(args.baseline_auth_config))} + if args.candidate_url: + arms["candidate"] = (args.candidate_url, + api_key(args.candidate_auth_config or args.baseline_auth_config)) + rows = [] + for case in suite["cases"]: + payload = {"model": args.model, "messages": case["messages"], + "max_tokens": args.max_tokens, "temperature": 0, "seed": 42, + "reasoning_effort": "none", "stream": False} + for optional in ("tools", "tool_choice"): + if optional in case: + payload[optional] = case[optional] + for arm, (url, key) in arms.items(): + observation = request(url, key, payload, args.timeout_seconds) + rows.append({"arm": arm, "case_id": case["id"], "category": case["category"], + "warmup": True, "repeat": None, **observation, + "quality": judge(case, observation)}) + for repeat in range(args.repeats): + order = list(arms) if repeat % 2 == 0 else list(reversed(arms)) + for arm in order: + url, key = arms[arm] + observation = request(url, key, payload, args.timeout_seconds) + rows.append({"arm": arm, "case_id": case["id"], "category": case["category"], + "warmup": False, "repeat": repeat, **observation, + "quality": judge(case, observation)}) + report = {"schema": 1, "created_utc": dt.datetime.now(dt.timezone.utc).isoformat(), + "suite": suite["name"], "suite_sha256": hashlib.sha256(suite_bytes).hexdigest(), + "model": args.model, "configuration": {"repeats": args.repeats, + "max_tokens": args.max_tokens, "temperature": 0, "seed": 42, + "reasoning_effort": "none", "stream": False, "cache_state": + "one untimed warmup per case and arm, then sequential alternating arm order"}, + "metadata": metadata, "rows": rows, + "summary": summarize(rows, "candidate" in arms)} + output.parent.mkdir(parents=True, exist_ok=True) + old_mask = os.umask(0o077) + try: + with output.open("x", encoding="utf-8") as file: + json.dump(report, file, indent=2, ensure_ascii=False) + file.write("\n") + finally: + os.umask(old_mask) + print(json.dumps({"output": str(output), "summary": report["summary"]}, indent=2)) + + +if __name__ == "__main__": + try: + main() + except (OSError, ValueError, KeyError, urllib.error.URLError) as error: + print(f"benchmark failed: {type(error).__name__}", file=sys.stderr) + sys.exit(1)