Files
leleka/scripts/bench-chat-paired.py
T
Pavlo RatushnyiandClaude Sonnet 5.5 7f896a8bb8 import: Original-literal source-port snapshot (frozen 2026-10-12 06:36, uncompiled together, no GPU run)
Snapshot of target/stra169-direct-port-integration/source-port (without target/), now the tracked base for the full Strata Rust port.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 14:38:46 +02:00

298 lines
14 KiB
Python

#!/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("--single-arm-name", choices=("baseline", "candidate"),
default="baseline", help="label for an unpaired run")
parser.add_argument("--baseline-ready-url", help="optional baseline health/readiness URL")
parser.add_argument("--candidate-ready-url", help="optional candidate health/readiness 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("--ready-timeout-seconds", type=float, default=900.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 or args.ready_timeout_seconds <= 0):
parser.error("repeats must be 1..100, max-tokens positive and timeouts positive")
if args.candidate_auth_config and not args.candidate_url:
parser.error("candidate auth config requires candidate URL")
if args.candidate_ready_url and not args.candidate_url:
parser.error("candidate readiness URL requires candidate URL")
if args.candidate_url and args.single_arm_name != "baseline":
parser.error("single-arm-name applies only to an unpaired run")
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 materialize_messages(messages):
result = []
for message in messages:
content = message["content"]
if isinstance(content, dict):
parts = content.get("parts")
if not isinstance(parts, list) or not parts:
raise ValueError("message content parts must be a nonempty list")
expanded = []
for part in parts:
if not isinstance(part, dict):
raise ValueError("invalid deterministic content part")
if set(part) == {"text"} and isinstance(part["text"], str):
expanded.append(part["text"])
elif (set(part) == {"repeat", "count"} and
isinstance(part["repeat"], str) and
type(part["count"]) is int and 0 <= part["count"] <= 10000):
expanded.append(part["repeat"] * part["count"])
else:
raise ValueError("invalid deterministic content part")
content = "".join(expanded)
if len(content) > 1_000_000:
raise ValueError("materialized message is too large")
if not isinstance(content, str):
raise ValueError("message content must be text")
result.append({**message, "content": content})
return result
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 wait_ready(url, key, timeout):
if url is None:
return
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
headers = {"Authorization": "Bearer " + key} if key else {}
try:
with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=5) as response:
health = json.load(response)
if (response.status == 200 and isinstance(health, dict) and
health.get("ready") is not False and health.get("loaded") is not False and
health.get("max_context", 1) > 0):
return
except (OSError, ValueError, TypeError):
pass
time.sleep(min(2.0, max(0.0, deadline - time.monotonic())))
raise TimeoutError("endpoint did not become ready")
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 = {}
arm_names = ("baseline", "candidate") if paired else (rows[0]["arm"],)
for arm in arm_names:
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(
pair["baseline"]["http_status"] == pair["candidate"]["http_status"] == 200
and normalized_output(pair["baseline"]) is not None
and 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 = {args.single_arm_name: (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))
wait_ready(args.baseline_ready_url, arms[args.single_arm_name][1], args.ready_timeout_seconds)
if args.candidate_url:
wait_ready(args.candidate_ready_url, arms["candidate"][1], args.ready_timeout_seconds)
rows = []
for case in suite["cases"]:
payload = {"model": args.model, "messages": materialize_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"
if args.candidate_url else "one untimed warmup per case, then sequential repeats")},
"metadata": metadata, "rows": rows,
"summary": summarize(rows, bool(args.candidate_url))}
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)