"""Evaluation phase: score a model on a benchmark with upstream's `evaluate.py` in the sandbox.""" import contextlib import json import os import shutil import subprocess import sys from pathlib import Path from . import config, sandbox # Upstream's retry protocol (`src/run_task.sh`): vLLM occasionally fails on long generations, # so after 4 failed attempts the generation budget is lowered, first to the left value # (3 attempts), then to the right one (2 attempts). Tasks not listed get 9 plain attempts. REDUCED_MAX_TOKENS = { "aime2025": ("--max-tokens", 12000, 8000), "arenahardwriting": ("--max-new-tokens", 12288, 8192), "bfcl": ("--max-tokens", 12000, 8000), "gpqamain": ("--max-tokens", 12000, 8000), "gsm8k": ("--max-tokens", 3000, 2000), "healthbench": ("--max-new-tokens", 12288, 8192), "humaneval": ("--max-tokens", 3000, 2000), } def attempts(task: str) -> list[list[str]]: """Extra `evaluate.py` arguments for each successive attempt.""" if task not in REDUCED_MAX_TOKENS: return [[]] * 9 flag, first, second = REDUCED_MAX_TOKENS[task] return [[]] * 4 + [[flag, str(first)]] * 3 + [[flag, str(second)]] * 2 @contextlib.contextmanager def judge_balancer(pool: list[str]): """Spread grading calls over every replica of the judge pool. Yields an OpenAI-style base URL for a loopback balancer, or "" when there is no pool. A healthbench cell is ~1900 grading calls and arenahardwriting ~500; sending them all to one replica would leave the rest of the pool's GPUs idle. """ if not pool: yield "" return process = subprocess.Popen( [sys.executable, str(config.REPO_ROOT / "scripts/ptb_uds_bridge.py"), "balance", "--targets", ",".join(pool)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) try: port = process.stdout.readline().strip() if not port.isdigit(): process.terminate() raise RuntimeError(f"Judge balancer did not start: {port!r}") print(f"Judge balancer on 127.0.0.1:{port} -> {', '.join(pool)}") yield f"http://127.0.0.1:{port}/v1" finally: process.terminate() process.wait(timeout=30) def evaluate(out_dir: Path, task: str, model: str, limit: int = -1) -> dict | None: """Evaluate `model` (a local directory or a HF model id); returns the metrics, or None on failure. Writes `metrics.json` and one `final_eval_.txt` log per attempt to `out_dir`. """ out_dir = out_dir.resolve() out_dir.mkdir(parents=True, exist_ok=True) metrics_file = out_dir / "metrics.json" task_src = config.UPSTREAM / "src/eval/tasks" / task binds = {config.UPSTREAM: f"{config.UPSTREAM}:ro", out_dir: str(out_dir)} if Path(model).is_dir(): model = str(Path(model).resolve()) binds[Path(model)] = f"{model}:ro" scratch = out_dir / "eval_sandbox" timeout_minutes = int(os.environ.get("PTB_EVAL_TIMEOUT_MINUTES", 8 * 60)) if timeout_minutes <= 0: raise ValueError("PTB_EVAL_TIMEOUT_MINUTES must be a positive integer") # arenahardwriting's evaluate.py opens its question set as the relative path # `evaluation_code/data/arena-hard-v2.0/question.jsonl`, and writes model answers and # judgments back under the same tree -- so it needs a writable copy next to the cwd we give # it, not the read-only upstream bind. Upstream gets this for free because run_task.sh copies # the task directory into the agent's workspace and runs there; our evaluation phase runs # from out_dir. The other benchmarks pull their data from the HF cache and do not care. if (evaluation_code := task_src / "evaluation_code").is_dir(): shutil.copytree(evaluation_code, out_dir / "evaluation_code", dirs_exist_ok=True) # OPENAI_BASE_URL points the LLM-graded benchmarks at the local vLLM judge pool # (scripts/ptb_judge_pool.sbatch) because api.openai.com is unreachable from the aws cluster. # Both graders build their client with no explicit base_url -- healthbench's # evaluation_code/grader.py `OpenAI(api_key=...)` and arenahardwriting's `openai.OpenAI()` -- # so the SDK picks the variable up and no upstream code has to change. This sandbox runs # without `--net`, so it shares the host's network namespace and can reach a loopback # balancer directly; the agent phase has to tunnel the same traffic over a unix socket. # The variable is dropped when empty: the SDK treats "" as a real base URL and every request # would fail, whereas an absent variable falls back to the public API. # arenahardwriting's evaluate.py calls tiktoken.encoding_for_model("gpt-4o") to count tokens, # which on a cache miss fetches o200k_base.tiktoken from openaipublic.blob.core.windows.net -- # unreachable from the aws login node (same Azure blob host as huggingface.co; SSL EOF, 9/9 attempts # failed). tiktoken keys its on-disk cache by sha1(blobpath), so dropping the file in under # that name short-circuits the fetch entirely; scripts/tiktoken_cache holds a copy recovered # from an earlier run's cache dir, content-hash-verified against the known-good file. tiktoken_cache = out_dir / "tiktoken_cache" shutil.copytree(config.REPO_ROOT / "scripts/tiktoken_cache", tiktoken_cache, dirs_exist_ok=True) with judge_balancer(config.judge_pool_targets()) as pool_url: base_url = os.environ.get("OPENAI_BASE_URL") or pool_url env = {"OPENAI_API_KEY": os.environ.get("OPENAI_API_KEY", "") or ("EMPTY" if base_url else ""), "OPENAI_BASE_URL": base_url, "HF_TOKEN": os.environ.get("HF_TOKEN", ""), "TIKTOKEN_CACHE_DIR": str(tiktoken_cache)} env = {k: v for k, v in env.items() if v or k == "OPENAI_API_KEY"} for n, extra_args in enumerate(attempts(task), start=1): print(f"Evaluation attempt {n} {' '.join(extra_args)}") sandbox.run( ["python", str(task_src / "evaluate.py"), "--model-path", model, "--limit", str(limit), "--templates-dir", str(config.UPSTREAM / "src/eval/templates"), "--json-output-file", str(metrics_file), *extra_args], scratch=scratch, hf_cache=config.HF_CACHE, binds=binds, workdir=str(out_dir), container=config.EVAL_CONTAINER, env=env, timeout_minutes=timeout_minutes, log=out_dir / f"final_eval_{n}.txt", ) if metrics_file.is_file(): break shutil.rmtree(scratch) return json.loads(metrics_file.read_text()) if metrics_file.is_file() else None