File size: 6,897 Bytes
bdc469b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
"""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())