splatbench / scripts /run_eval.py
spratyey's picture
Add files using upload-large-folder tool
bdc469b verified
Raw History Blame Contribute Delete
6.9 kB
"""Evaluate a model on SplatBench through any OpenAI-compatible endpoint. Resumable: finished episodes are skipped.
# OpenAI
OPENAI_API_KEY=... uv run python scripts/run_eval.py --models gpt-6.1-sol --effort medium
# OpenRouter (cost per response is read from the endpoint); label=endpoint_id keeps the leaderboard name
OPENROUTER_API_KEY=... uv run python scripts/run_eval.py --base-url https://openrouter.ai/api/v1 \
--api-key-env OPENROUTER_API_KEY --models claude-opus-5.5=anthropic/claude-opus-5.5 \
--extra-body '{"reasoning": {"effort": "medium"}}'
# an open model on a local vLLM or SGLang server
uv run python scripts/run_eval.py --base-url http://localhost:8000/v1 --api-key-env NONE --models your-model
The leaderboard protocol is every task twice (`--runs 2`). Episodes go to <out>/<model>/run<k>/<task_id>/; an episode
that failed for infrastructure reasons (timeout, endpoint error) is moved aside and retried on the next invocation.
At the end the script prints each model's SplatScore (mean over tasks of the mean over runs, with a 95% bootstrap
interval over tasks), cost and time per episode, comparable with the leaderboard.
"""
import argparse
import asyncio
import glob
import json
import os
import statistics as st
import time
from collections import defaultdict
from pathlib import Path
import numpy as np
from splatbench.agent import Pricing, run_episode
from splatbench.env import PROTOCOLS, load_task, task_variant
ap = argparse.ArgumentParser()
ap.add_argument("--models", nargs="+", required=True, help="endpoint model ids, or label=endpoint_model_id")
ap.add_argument("--tasks", nargs="+", default=sorted(glob.glob("data/bench/tasks/*.json")))
ap.add_argument("--runs", type=int, default=2, help="runs per task (the leaderboard uses 2)")
ap.add_argument("--out", default="runs")
ap.add_argument("--base-url", default=None, help="OpenAI-compatible base URL (default: OpenAI)")
ap.add_argument("--api-key-env", default="OPENAI_API_KEY", help="environment variable with the API key; NONE for none")
ap.add_argument("--concurrency", type=int, default=3)
ap.add_argument("--effort", default=None, help="reasoning_effort to send, e.g. medium (omitted if not given)")
ap.add_argument("--extra-body", default=None, help='JSON merged into each request, e.g. \'{"reasoning": {"effort": "high"}}\'')
ap.add_argument("--protocol", default="standard", choices=PROTOCOLS,
help="standard | early_submit_refused (the first submit before call 20 is refused once) | "
"one_shot (build tasks only: one call, no renders)")
ap.add_argument("--timeout", type=float, default=2400, help="seconds per episode")
ap.add_argument("--max-tokens", type=int, default=None)
ap.add_argument("--price-in", type=float, default=None, help="USD per 1M input tokens")
ap.add_argument("--price-out", type=float, default=None, help="USD per 1M output tokens")
ap.add_argument("--price-cached", type=float, default=None, help="USD per 1M cached input tokens")
ap.add_argument("--budget-usd", type=float, default=None, help="start no new episode beyond this total cost")
ap.add_argument("--device", default=None, help="cuda or cpu (default: cuda if available)")
a = ap.parse_args()
def summarize(out_root: Path, labels: list[str]):
print("\nmodel episodes SplatScore [95% CI] USD/episode min/episode")
for label in labels:
res = [json.loads(p.read_text()) for p in sorted((out_root / label).glob("run*/*/result.json"))]
if not res:
continue
by_task = defaultdict(list)
for r in res:
by_task[r["task_id"]].append(r["final"]["score"])
tm = np.array([st.mean(v) for _, v in sorted(by_task.items())])
rng = np.random.default_rng(0)
b = tm[rng.integers(0, len(tm), (10000, len(tm)))].mean(1) if len(tm) > 1 else tm
costs = [r["usage"]["cost_usd"] for r in res if r["usage"]["cost_usd"] is not None]
print(f"{label:24s}{len(res):8d} {tm.mean():6.1f} [{np.percentile(b, 2.5):6.1f}, {np.percentile(b, 97.5):6.1f}]"
f" {('$%.3f' % st.mean(costs)) if costs else 'n/a':>10s} {st.mean(r['wall_s'] for r in res) / 60:10.1f}")
async def main():
from openai import AsyncOpenAI
key = "none" if a.api_key_env == "NONE" else os.environ[a.api_key_env]
client = AsyncOpenAI(base_url=a.base_url, api_key=key, timeout=a.timeout, max_retries=4)
pricing = Pricing(a.price_in, a.price_out, a.price_cached)
extra = json.loads(a.extra_body) if a.extra_body else None
sem = asyncio.Semaphore(a.concurrency)
models = [tuple(m.split("=", 1)) if "=" in m else (m, m) for m in a.models]
jobs = []
for run in range(1, a.runs + 1):
for tp in a.tasks: # interleave models so that every model progresses at the same rate
for label, mid in models:
task = load_task(tp)
if a.protocol == "one_shot" and task.kind != "sculpt":
continue
task = task_variant(task, a.protocol)
od = Path(a.out) / label / f"run{run}" / task.task_id
if (od / "result.json").exists():
continue
jobs.append((label, mid, task, od))
spent = {"usd": 0.0}
async def one(label, mid, task, od):
async with sem:
if a.budget_usd is not None and spent["usd"] > a.budget_usd:
print(f"budget reached, skipping {label} {task.task_id}", flush=True)
return
t0 = time.time()
try:
r = await run_episode(client, mid, task, od, label=label, reasoning_effort=a.effort, extra_body=extra,
pricing=pricing, timeout_s=a.timeout, max_tokens=a.max_tokens, device=a.device)
except Exception as e:
print(f"FAIL {label} {od.parent.name}/{task.task_id}: {type(e).__name__}: {e}", flush=True)
return
spent["usd"] += r["usage"]["cost_usd"] or 0.0
cost = r["usage"]["cost_usd"]
print(f"done {label} {od.parent.name}/{task.task_id} score={r['final']['score']:.1f} calls={r['n_tool_calls']} "
f"gaussians={r['final']['n_gaussians']} cost={'n/a' if cost is None else f'${cost:.3f}'} "
f"t={time.time() - t0:.0f}s", flush=True)
if r["failed"]:
dst = od.parent / ".failed" / f"{task.task_id}_{int(time.time())}"
dst.parent.mkdir(parents=True, exist_ok=True)
od.rename(dst)
print(f" {label} {task.task_id} failed ({r['status']}); moved to {dst}, will be retried", flush=True)
print(f"{len(jobs)} episodes to run", flush=True)
await asyncio.gather(*(one(*j) for j in jobs))
summarize(Path(a.out), [label for label, _ in models])
asyncio.run(main())