Download tools/eval_openai_endpoint.py from Shangy/DR-256-backup: direct link, hf CLI and curl.
- Browser
- Download file 9.36 kB
-
https://huggingface.co/datasets/Shangy/DR-256-backup/resolve/main/tools/eval_openai_endpoint.py
- Command line
-
hf download hf://datasets/Shangy/DR-256-backup/tools/eval_openai_endpoint.py
-
curl -L -o eval_openai_endpoint.py https://huggingface.co/datasets/Shangy/DR-256-backup/resolve/main/tools/eval_openai_endpoint.py
9.36 kB
| #!/usr/bin/env python3 | |
| """Run DeepResearch-9K agentic evaluation against an OpenAI endpoint. | |
| The search/open/finish loop is the same one used by BrowseComp training, but | |
| the default scorer is entirely local. ``--remote-judge`` is opt-in so a local | |
| search smoke never silently incurs grader API traffic. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import asyncio | |
| import json | |
| import statistics | |
| import sys | |
| import time | |
| from pathlib import Path | |
| from typing import Any | |
| REPO_ROOT = Path(__file__).resolve().parents[2] | |
| BROWSECOMP_DIR = REPO_ROOT / "examples" / "browsecomp" | |
| sys.path.insert(0, str(BROWSECOMP_DIR)) | |
| import browsecomp_agent # noqa: E402 | |
| from browsecomp_env import em_score # noqa: E402 | |
| async def evaluate_one( | |
| semaphore: asyncio.Semaphore, | |
| *, | |
| index: int, | |
| record: dict[str, Any], | |
| base_url: str, | |
| request_kwargs: dict[str, Any], | |
| seed_base: int | None, | |
| max_seq_len: int, | |
| remote_judge: bool, | |
| ) -> dict[str, Any]: | |
| metadata = dict(record.get("metadata") or {}) | |
| metadata["max_seq_len"] = max_seq_len | |
| label = metadata.get("answer") or record.get("label") or "" | |
| queued_at = time.perf_counter() | |
| row: dict[str, Any] = { | |
| "index": index, | |
| "qid": metadata.get("qid"), | |
| "manifest_qid": metadata.get("manifest_qid"), | |
| "difficulty": metadata.get("difficulty"), | |
| "teacher_correct": metadata.get("teacher_correct"), | |
| "benchmark": metadata.get("benchmark") or {}, | |
| "question": metadata.get("question", ""), | |
| "label": label, | |
| } | |
| episode_request_kwargs = dict(request_kwargs) | |
| if seed_base is not None: | |
| episode_seed = seed_base + index | |
| episode_request_kwargs["seed"] = episode_seed | |
| row["sampling_seed"] = episode_seed | |
| async with semaphore: | |
| started_at = time.perf_counter() | |
| row["queue_seconds"] = started_at - queued_at | |
| try: | |
| output = await browsecomp_agent.run( | |
| base_url, | |
| record["prompt"], | |
| request_kwargs=episode_request_kwargs, | |
| metadata=metadata, | |
| ) | |
| predicted = output.get("predicted_answer") | |
| row.update( | |
| predicted=predicted, | |
| explanation=output.get("explanation"), | |
| confidence=output.get("confidence"), | |
| num_turns=output.get("num_turns"), | |
| stop_reason=output.get("stop_reason"), | |
| tool_stats=output.get("tool_stats") or {}, | |
| usage=output.get("usage") or {}, | |
| visited_pages=output.get("visited_pages"), | |
| local_em=int(bool(predicted) and em_score(label, predicted)), | |
| ) | |
| except Exception as exc: # keep the remaining smoke rows running | |
| row.update( | |
| predicted=None, | |
| local_em=0, | |
| stop_reason="agent_error", | |
| error=f"{type(exc).__name__}: {exc}"[:1000], | |
| ) | |
| if remote_judge and row.get("predicted"): | |
| try: | |
| import browsecomp_rm | |
| row["judge_score"] = await browsecomp_rm.judge( | |
| row["question"], label, row["predicted"] | |
| ) | |
| except Exception as exc: | |
| row["judge_error"] = f"{type(exc).__name__}: {exc}"[:1000] | |
| row["active_seconds"] = time.perf_counter() - started_at | |
| row["wall_seconds"] = time.perf_counter() - queued_at | |
| return row | |
| def summarize(rows: list[dict[str, Any]], *, remote_judge: bool) -> dict[str, Any]: | |
| finished = [row for row in rows if row.get("stop_reason") == "finish"] | |
| turns = [int(row["num_turns"]) for row in rows if row.get("num_turns") is not None] | |
| wall = [float(row["wall_seconds"]) for row in rows] | |
| active = [float(row["active_seconds"]) for row in rows] | |
| queued = [float(row["queue_seconds"]) for row in rows] | |
| summary: dict[str, Any] = { | |
| "questions": len(rows), | |
| "agent_errors": sum(bool(row.get("error")) for row in rows), | |
| "finished": len(finished), | |
| "finish_rate": len(finished) / len(rows) if rows else None, | |
| "local_em_correct": sum(int(row.get("local_em", 0)) for row in rows), | |
| "local_em_accuracy": ( | |
| sum(int(row.get("local_em", 0)) for row in rows) / len(rows) if rows else None | |
| ), | |
| "mean_turns": statistics.fmean(turns) if turns else None, | |
| "mean_active_seconds": statistics.fmean(active) if active else None, | |
| "mean_queue_seconds": statistics.fmean(queued) if queued else None, | |
| "mean_wall_seconds": statistics.fmean(wall) if wall else None, | |
| "search_calls": sum(int((row.get("tool_stats") or {}).get("search", 0)) for row in rows), | |
| "open_page_calls": sum( | |
| int((row.get("tool_stats") or {}).get("open_page", 0)) for row in rows | |
| ), | |
| "stop_reasons": {}, | |
| "scoring_note": ( | |
| "local_em is the repository's lenient normalized exact match. It is conservative " | |
| "for aliases, paraphrases, lists, and explanatory answers." | |
| ), | |
| } | |
| for row in rows: | |
| reason = row.get("stop_reason") or "missing" | |
| summary["stop_reasons"][reason] = summary["stop_reasons"].get(reason, 0) + 1 | |
| if remote_judge: | |
| judged = [row for row in rows if row.get("judge_score") is not None] | |
| summary.update( | |
| judge_questions=len(judged), | |
| judge_errors=sum(bool(row.get("judge_error")) for row in rows), | |
| judge_accuracy=( | |
| sum(float(row["judge_score"]) for row in judged) / len(judged) if judged else None | |
| ), | |
| ) | |
| return summary | |
| async def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--base-url", required=True) | |
| parser.add_argument("--data", type=Path, required=True) | |
| parser.add_argument("--out", type=Path, required=True) | |
| parser.add_argument("--offset", type=int, default=0) | |
| parser.add_argument("--limit", type=int, default=0) | |
| parser.add_argument("--max-seq-len", type=int, default=36_864) | |
| parser.add_argument("--concurrency", type=int, default=2) | |
| parser.add_argument("--temperature", type=float, default=0.6) | |
| parser.add_argument("--top-p", type=float, default=0.95) | |
| parser.add_argument("--top-k", type=int, default=20) | |
| parser.add_argument( | |
| "--seed-base", | |
| type=int, | |
| help=( | |
| "Optional deterministic sampling seed. Episode index i uses seed-base+i; " | |
| "reuse the same value for paired checkpoint evaluations." | |
| ), | |
| ) | |
| parser.add_argument( | |
| "--model-label", | |
| default="", | |
| help="Checkpoint/model identifier recorded in the summary (not sent to the endpoint).", | |
| ) | |
| parser.add_argument("--remote-judge", action="store_true") | |
| args = parser.parse_args() | |
| if args.offset < 0 or args.limit < 0 or args.concurrency < 1: | |
| parser.error("offset/limit must be non-negative and concurrency must be positive") | |
| records = [json.loads(line) for line in args.data.open() if line.strip()] | |
| records = records[args.offset : args.offset + args.limit if args.limit else None] | |
| request_kwargs = { | |
| "temperature": args.temperature, | |
| "top_p": args.top_p, | |
| "top_k": args.top_k, | |
| } | |
| semaphore = asyncio.Semaphore(args.concurrency) | |
| tasks = [ | |
| asyncio.create_task( | |
| evaluate_one( | |
| semaphore, | |
| index=args.offset + index, | |
| record=record, | |
| base_url=args.base_url.rstrip("/"), | |
| request_kwargs=request_kwargs, | |
| seed_base=args.seed_base, | |
| max_seq_len=args.max_seq_len, | |
| remote_judge=args.remote_judge, | |
| ) | |
| ) | |
| for index, record in enumerate(records) | |
| ] | |
| args.out.parent.mkdir(parents=True, exist_ok=True) | |
| rows: list[dict[str, Any]] = [] | |
| with args.out.open("w") as output_file: | |
| for task in asyncio.as_completed(tasks): | |
| row = await task | |
| rows.append(row) | |
| output_file.write(json.dumps(row, ensure_ascii=False) + "\n") | |
| output_file.flush() | |
| print( | |
| f"completed={len(rows)}/{len(tasks)} qid={row.get('qid')} " | |
| f"finish={row.get('stop_reason') == 'finish'} em={row.get('local_em')} " | |
| f"turns={row.get('num_turns')} wall={row['wall_seconds']:.1f}s", | |
| flush=True, | |
| ) | |
| rows.sort(key=lambda row: row["index"]) | |
| summary = summarize(rows, remote_judge=args.remote_judge) | |
| summary.update( | |
| data=str(args.data), | |
| output=str(args.out), | |
| offset=args.offset, | |
| limit=len(records), | |
| concurrency=args.concurrency, | |
| temperature=args.temperature, | |
| top_p=args.top_p, | |
| top_k=args.top_k, | |
| seed_base=args.seed_base, | |
| max_seq_len=args.max_seq_len, | |
| model_label=args.model_label or None, | |
| remote_judge=args.remote_judge, | |
| ) | |
| summary_path = args.out.with_name(f"{args.out.stem}.summary.json") | |
| summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True) + "\n") | |
| print("FINAL_LOCAL_EVAL " + json.dumps(summary, sort_keys=True), flush=True) | |
| if __name__ == "__main__": | |
| asyncio.run(main()) | |