File size: 6,590 Bytes
3c29d68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Evaluate a model on ShadowBench 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 one episode on each of the 20 certified plates per model and reasoning effort.
Episodes go to <out>/<label>@<effort>/<task_id>/ (the layout of the published episodes); 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 mean score with a 95% bootstrap interval over plates, cost and time per episode,
comparable with the leaderboard.
"""
import os

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")  # collision checks run in threads; one BLAS thread each

import argparse
import asyncio
import json
import statistics as st
import time
from pathlib import Path

import numpy as np

from shadowbench import tasks
from shadowbench.agent import Pricing, run_episode

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=None, help="plates (default: all 20 certified plates)")
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("--timeout", type=float, default=3600, 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")
a = ap.parse_args()
setting = a.effort or "default"


def summarize(out_root: Path, labels: list[str]):
    print("\nmodel                       episodes  score [95% CI]          USD/episode  min/episode")
    for label in labels:
        res = [json.loads(p.read_text()) for p in sorted((out_root / f"{label}@{setting}").glob("*/result.json"))]
        res = [x for x in res if not x["failed"]]
        if not res:
            continue
        # scores as the report rounds them, plates in a fixed order
        s = np.array([round(x["final"]["score"], 2) for x in sorted(res, key=lambda x: x["task_id"])])
        rng = np.random.default_rng(20261105)
        b = s[rng.integers(0, len(s), (10000, len(s)))].mean(1) if len(s) > 1 else s
        costs = [x["usage"]["cost_usd"] for x in res if x["usage"]["cost_usd"] is not None]
        print(f"{label + '@' + setting:28s}{len(res):8d}  {s.mean():6.2f} [{np.percentile(b, 2.5):6.2f}, {np.percentile(b, 97.5):6.2f}]"
              f"   {('$%.3f' % st.mean(costs)) if costs else 'n/a':>10s}  {st.mean(x['seconds'] for x 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=600, 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 task_id in a.tasks or tasks():  # interleave models so that every model progresses at the same rate
        for label, mid in models:
            od = Path(a.out) / f"{label}@{setting}" / task_id
            if (od / "result.json").exists():
                continue
            jobs.append((label, mid, task_id, od))
    spent = {"usd": 0.0}

    async def one(label, mid, task_id, od):
        async with sem:
            if a.budget_usd is not None and spent["usd"] > a.budget_usd:
                print(f"budget reached, skipping {label} {task_id}", flush=True)
                return
            if od.exists():  # a partial episode from an interrupted run
                dst = od.parent / ".failed" / f"{task_id}_{int(time.time())}"
                dst.parent.mkdir(parents=True, exist_ok=True)
                od.rename(dst)
            t0 = time.time()
            try:
                r = await run_episode(client, mid, task_id, od, label=label, reasoning_effort=a.effort, extra_body=extra,
                                      pricing=pricing, timeout_s=a.timeout, max_tokens=a.max_tokens)
            except Exception as e:
                print(f"FAIL  {label} {task_id}: {type(e).__name__}: {e}", flush=True)
                return
            spent["usd"] += r["usage"]["cost_usd"] or 0.0
            cost = r["usage"]["cost_usd"]
            score = r["final"]["score"] if r["final"] else float("nan")
            print(f"done  {label} {task_id} score={score:.1f} calls={r['calls']} refused={r['refusals']} "
                  f"cost={'n/a' if cost is None else f'${cost:.3f}'} t={time.time() - t0:.0f}s", flush=True)
            if r["failed"]:
                dst = od.parent / ".failed" / f"{task_id}_{int(time.time())}"
                dst.parent.mkdir(parents=True, exist_ok=True)
                od.rename(dst)
                print(f"      {label} {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())