From 7295e40c587339c0612e89e4b147823930f2befe Mon Sep 17 00:00:00 2001 From: eranario Date: Mon, 23 Nov 2026 13:02:46 -0800 Subject: [PATCH 1/2] AgriBench: kept in agml-full-v1, marked unavailable (removed from Hugging Face); pull, status, verify and eval show the notice Co-Authored-By: Claude Opus 5.5 --- src/agbench/bench.py | 20 +++++++++--- .../benchmarks/agml-full-v1/bundle.yaml | 4 +++ src/agbench/cli.py | 31 ++++++++++++++----- src/agbench/eval/cli.py | 11 +++++-- tests/test_bench.py | 11 +++++++ 5 files changed, 64 insertions(+), 13 deletions(-) diff --git a/src/agbench/bench.py b/src/agbench/bench.py index cfa0855..5197c10 100644 --- a/src/agbench/bench.py +++ b/src/agbench/bench.py @@ -65,6 +65,12 @@ def manifests(self) -> dict[str, dict]: def raw_items(self) -> list[dict]: return [json.loads(l) for l in self._text("items.jsonl.gz").splitlines()] + @property + def unavailable(self) -> dict[str, str]: + """Datasets whose source repo is gone, {dataset: notice}. They stay in the benchmark (a local copy is still + evaluated); without one their items are skipped.""" + return {u["dataset"]: f"{u['reason']} ({u['date']})" for u in self.spec.get("unavailable", [])} + @property def config_path(self) -> Path: return self.path / "config.yaml" @@ -116,7 +122,8 @@ def items(self, data_dir, tasks=None, formats=None, only: str | None = None, lim if not present[key]: if key not in seen: seen.add(key) - skipped.append({"dataset": r["dataset"], "task": r["task"], "reason": f"not downloaded (agbench data pull {self.name})"}) + why = self.unavailable.get(r["dataset"]) or f"not downloaded (agbench data pull {self.name})" + skipped.append({"dataset": r["dataset"], "task": r["task"], "reason": why}) continue keep.append(r) if limit_per_dataset: @@ -216,7 +223,8 @@ def freeze(name: str, items_path: Path, description: str, manifest_dir: Path | N # ---------------------------------------------------------------- local data def data_status(b: Bundle, data_dir, task=None, only=None) -> dict[str, str]: - """Per dataset: done | missing | stale (wrong revision or different samples) | failed.""" + """Per dataset: done | missing | stale (wrong revision or different samples) | failed | unavailable (source repo + gone, no local copy).""" from agbench.pipeline import base_dir, failure_path, TASK_DIRS out = {} @@ -228,6 +236,8 @@ def data_status(b: Bundle, data_dir, task=None, only=None) -> dict[str, str]: have = {json.loads(l)["sample_id"] for l in open(d / "samples.jsonl")} if (d / "samples.jsonl").exists() else set() same = meta.get("hf_sha") == m["hf_sha"] and have == {s["sample_id"] for s in m["samples"]} out[n] = "done" if same else "stale" + elif n in b.unavailable: + out[n] = "unavailable" else: out[n] = "failed" if failure_path(Path(data_dir), n).exists() else "missing" return out @@ -235,7 +245,8 @@ def data_status(b: Bundle, data_dir, task=None, only=None) -> dict[str, str]: def verify(b: Bundle, data_dir, task=None, only=None, decode: bool = True) -> dict[str, list[str]]: """Problems per dataset in a local copy: not downloaded, wrong revision, missing or extra samples, missing or - undecodable images. An empty dict means the local copy matches the bundle.""" + undecodable images. An empty dict means the local copy matches the bundle. Unavailable datasets (source repo + gone) without a local copy are not problems; with one, they are checked like the rest.""" from PIL import Image, ImageFile from agbench.pipeline import base_dir, TASK_DIRS @@ -249,7 +260,8 @@ def verify(b: Bundle, data_dir, task=None, only=None, decode: bool = True) -> di m, errs = b.manifests[n], [] d = base_dir(data_dir) / TASK_DIRS[m["task"]] / n if not (d / "meta.json").exists(): - problems[n] = ["not downloaded"] + if n not in b.unavailable: + problems[n] = ["not downloaded"] continue meta = json.loads((d / "meta.json").read_text()) if meta.get("hf_sha") != m["hf_sha"]: diff --git a/src/agbench/benchmarks/agml-full-v1/bundle.yaml b/src/agbench/benchmarks/agml-full-v1/bundle.yaml index 2f6617a..72bf525 100644 --- a/src/agbench/benchmarks/agml-full-v1/bundle.yaml +++ b/src/agbench/benchmarks/agml-full-v1/bundle.yaml @@ -59,3 +59,7 @@ repinned: date: '2026-11-23' reason: source repo re-uploaded; images matched by SHA-256, byte-identical; 0 of 250 rows have different conversation text (frozen items unaffected) +unavailable: +- dataset: AgriBench + date: '2026-11-23' + reason: removed from Hugging Face (Project-AgML/AgriBench no longer exists) diff --git a/src/agbench/cli.py b/src/agbench/cli.py index 4c14aa9..521e2bc 100644 --- a/src/agbench/cli.py +++ b/src/agbench/cli.py @@ -321,8 +321,11 @@ def data_pull( b = _bundle(name) cfg = load_config(b.config_path) status = bench.data_status(b, data_dir, task, only) - todo = [b.entry(n) for n, s in status.items() if refresh or s != "done"] - typer.echo(f"{name}: {len(status)} datasets selected, {len(status) - len(todo)} already present, {len(todo)} to download") + gone = [n for n, s in status.items() if s == "unavailable"] + todo = [b.entry(n) for n, s in status.items() if s not in ("unavailable", "done") or (refresh and n not in b.unavailable)] + typer.echo(f"{name}: {len(status)} datasets selected, {len(status) - len(todo) - len(gone)} already present, {len(todo)} to download" + + (f", {len(gone)} unavailable" if gone else "")) + _print_unavailable(b, gone) if not todo: return res = pipeline.run_many(cfg, str(b.config_path), todo, Path(data_dir).resolve(), @@ -336,6 +339,15 @@ def data_pull( raise typer.Exit(1) +def _print_unavailable(b, names: list[str]) -> None: + if not names: + return + n_items = Counter(r["dataset"] for r in b.raw_items) + typer.echo("Unavailable (kept in the benchmark; skipped without a local copy):") + for n in names: + typer.echo(f" {n} {b.unavailable[n]}; {n_items[n]} items") + + def _print_failures(data_dir: Path, names: list[str]) -> None: if not names: return @@ -353,14 +365,17 @@ def data_status(name: str = BenchArg, data_dir: Path = DataDirOpt, task: list[st """Which of a benchmark's datasets are present (done), missing, stale or failed in a data dir.""" from agbench import bench - st = bench.data_status(_bundle(name), data_dir, task, only) + b = _bundle(name) + st = bench.data_status(b, data_dir, task, only) typer.echo(" ".join(f"{k}={v}" for k, v in sorted(Counter(st.values()).items()))) for n, s in st.items(): - if s == "failed": + if s == "unavailable": + typer.echo(f"{s:<11} {n}: {b.unavailable[n]}") + elif s == "failed": reason = json.loads(pipeline.failure_path(Path(data_dir), n).read_text())["reason"] - typer.echo(f"{s:<8} {n}: {reason}") + typer.echo(f"{s:<11} {n}: {reason}") elif s != "done" or verbose: - typer.echo(f"{s:<8} {n}") + typer.echo(f"{s:<11} {n}") @data_app.command("verify") @@ -378,7 +393,9 @@ def data_verify(name: str = BenchArg, data_dir: Path = DataDirOpt, task: list[st n = len(b.datasets(task, only)) for ds, errs in bad.items(): typer.echo(f"{ds}: " + "; ".join(errs[:5]) + (f" (+{len(errs) - 5} more)" if len(errs) > 5 else "")) - typer.echo(f"{n - len(bad)} of {n} datasets match {name} (hash {b.hash})") + gone = [d for d, s in bench.data_status(b, data_dir, task, only).items() if s == "unavailable"] + typer.echo(f"{n - len(bad) - len(gone)} of {n} datasets match {name} (hash {b.hash})") + _print_unavailable(b, gone) if bad or problems: raise typer.Exit(1) diff --git a/src/agbench/eval/cli.py b/src/agbench/eval/cli.py index db628fb..14e3e85 100644 --- a/src/agbench/eval/cli.py +++ b/src/agbench/eval/cli.py @@ -95,7 +95,7 @@ def run( raise typer.BadParameter("--nota-position: end | random") bench = Benchmark(data_dir, task or None, fmt or None, only, limit_per_dataset, seed, mcqa=MCQAOptions(nota_rate, order_seed, nota_position, idk), bench=_bench(benchmark)) - typer.echo(f"{len(bench.items)} items; {len(bench.skipped)} datasets skipped") + _echo_items(bench) if method: m = _load_method(method, method_kwargs) rd = run_dir or _run_dir(out, m.name) @@ -122,6 +122,13 @@ def run( _print_summary(rd) +def _echo_items(bench) -> None: + typer.echo(f"{len(bench.items)} items; {len(bench.skipped)} datasets skipped") + for s in bench.skipped: + if s["reason"].startswith("removed from"): # source repo gone (bundle.yaml: unavailable) + typer.echo(f" note: {s['dataset']} skipped, {s['reason']}") + + @app.command() def baseline( data_dir: Path = DataDirOpt, @@ -141,7 +148,7 @@ def baseline( if kind not in KINDS: raise typer.BadParameter(f"--kind: {' | '.join(KINDS)}") bench = Benchmark(data_dir, task or None, fmt or None, only, None, seed, bench=_bench(benchmark)) - typer.echo(f"{len(bench.items)} items; {len(bench.skipped)} datasets skipped") + _echo_items(bench) m = NaiveBaseline(kind, priors(bench.items), gen_seed) rd = _run_dir(out, f"{m.name}_s{gen_seed}" if kind == "chance" else m.name) bench.run(m, rd, concurrency=64, resume=False) diff --git a/tests/test_bench.py b/tests/test_bench.py index 3f3f64c..8414687 100644 --- a/tests/test_bench.py +++ b/tests/test_bench.py @@ -80,3 +80,14 @@ def test_failure_reasons_are_actionable(): assert "pinned revision c421bed no longer exists" in explain(moved, repo, rev) assert "read-only" in explain(RuntimeError("403 Forbidden: You have read access"), repo, rev) assert explain(ValueError("boom"), repo, rev) == "ValueError: boom" + + +def test_unavailable_dataset_kept_with_notice(full, tmp_path): + assert "AgriBench" in full.manifests and "removed from Hugging Face" in full.unavailable["AgriBench"] + assert bench.data_status(full, tmp_path, only="^AgriBench$") == {"AgriBench": "unavailable"} + assert bench.verify(full, tmp_path, only="^AgriBench$", decode=False) == {} + _, skipped = full.items(tmp_path, only="^AgriBench$") + assert skipped[0]["reason"].startswith("removed from Hugging Face") + _fake_dataset(tmp_path, full, "AgriBench") # a local copy from before the removal is still used + assert bench.data_status(full, tmp_path, only="^AgriBench$") == {"AgriBench": "done"} + assert full.items(tmp_path, only="^AgriBench$")[0] From c631e5e976dfb2184ad986186ec16f565129b5a6 Mon Sep 17 00:00:00 2001 From: eranario Date: Mon, 23 Nov 2026 13:09:36 -0800 Subject: [PATCH 2/2] run_manifest.json, agbench eval check, hosted APIs (--api-key-env), pluggable judge with comparability - run_manifest.json on every finalize: version, benchmark name/hash/variant, method, seeds, judge, coverage, comparable + reasons - agbench eval check: files and prediction schema, items vs frozen benchmark, metrics vs predictions, coverage; runs after eval run (--strict) - Client: API key from an env var, hosted base URLs, max_completion_tokens / unsupported-parameter fallback, 401/403/404 stop the run, longer backoff on 429 - judge: any OpenAI-compatible judge (--judge-model/--judge-endpoint/--judge-api-key-env); records prompt sha; refuses to mix judges without --redo Co-Authored-By: Claude Opus 5.5 --- README.md | 15 +++ src/agbench/eval/check.py | 207 ++++++++++++++++++++++++++++++++++++ src/agbench/eval/cli.py | 72 +++++++++++-- src/agbench/eval/client.py | 103 +++++++++++++++--- src/agbench/eval/judge.py | 28 +++-- src/agbench/eval/methods.py | 10 +- src/agbench/eval/runner.py | 9 +- tests/test_check.py | 128 ++++++++++++++++++++++ 8 files changed, 536 insertions(+), 36 deletions(-) create mode 100644 src/agbench/eval/check.py create mode 100644 tests/test_check.py diff --git a/README.md b/README.md index 878368b..5ceef5a 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,15 @@ Already served (any OpenAI-compatible endpoint): uv run agbench eval run --model my-org/My-VLM --endpoint http://localhost:8000 --data-dir $DATA --judge ``` +Hosted API (OpenAI-compatible): + +```bash +export OPENAI_API_KEY=... +uv run agbench eval run --model gpt-5-mini --endpoint https://api.openai.com/v1 --api-key-env OPENAI_API_KEY --concurrency 8 --data-dir $DATA --judge +uv run agbench eval run --model gemini-2.5-flash --endpoint https://generativelanguage.googleapis.com/v1beta/openai --api-key-env GEMINI_API_KEY --data-dir $DATA --judge +uv run agbench eval run --model claude-sonnet-5-5 --endpoint https://api.anthropic.com/v1 --api-key-env ANTHROPIC_API_KEY --data-dir $DATA --judge +``` + Model settings: ```bash @@ -49,6 +58,7 @@ my-org/My-VLM: sampling: {temperature: 0.7, top_p: 0.95} thinking: {chat_template_kwargs: {enable_thinking: true}} no_thinking: {chat_template_kwargs: {enable_thinking: false}} + effort: {low: {reasoning_effort: low}, high: {reasoning_effort: high}} # request fields per --reasoning-effort box_order: xyxy # box_2d as [x_min, y_min, x_max, y_max]; default yxyx bbox_key_format: {bbox_2d: xyxy_px} # other box keys: xyxy_1000 | xyxy_px ``` @@ -84,18 +94,23 @@ res.metrics --gen-seed 1 # sampling seed (replicate runs) --run-dir runs/ # resume --benchmark agml-full-v1 # default; 'none' builds items from $DATA +--strict # exit non-zero if the run check fails or the run is not comparable ``` ## Results ```bash +uv run agbench eval check runs/ # files, schema, items vs benchmark, coverage, comparable uv run agbench eval judge --run runs/ +uv run agbench eval judge --run runs/ --judge-model gpt-5-mini --judge-endpoint https://api.openai.com/v1 --judge-api-key-env OPENAI_API_KEY # not comparable uv run agbench eval report --runs runs uv run agbench eval report --runs runs --csv reports/scores # scores.csv, ag_tasks.csv, datasets.csv uv run agbench eval stats --runs runs --out reports/stats uv run agbench eval view --runs runs # http://localhost:8502 ``` +`runs//run_manifest.json`: agbench version, benchmark name and hash, model and sampling, judge, coverage, `comparable`. + ## Benchmarks ```bash diff --git a/src/agbench/eval/check.py b/src/agbench/eval/check.py new file mode 100644 index 0000000..76e35ac --- /dev/null +++ b/src/agbench/eval/check.py @@ -0,0 +1,207 @@ +"""run_manifest.json (what a run was, and whether its scores compare with the reference results) and `agbench eval +check`: a run dir's files against the schema and its benchmark.""" + +import json +from collections import Counter +from datetime import datetime, timezone +from importlib.metadata import PackageNotFoundError, version +from pathlib import Path + +from agbench.eval import metrics as mx + +SCHEMA = 1 +REQUIRED = ("item_id", "dataset", "task", "format", "answer", "text", "correct", "parse_ok", "needs_judge", "judge_correct", + "finish_reason", "error") +BY_TASK = {"classification": ("gt_label",), "detection": ("tp", "fp", "fn", "mean_iou", "pred_boxes"), + "segmentation": ("tp", "fp", "fn", "mean_iou", "pred_boxes"), "image_text_to_text": ("qa_format",)} + + +def _version() -> str | None: + try: + return version("agbench") + except PackageNotFoundError: + return None + + +def _read_jsonl(p: Path) -> list[dict]: + return [json.loads(l) for l in open(p) if l.strip()] if p.exists() else [] + + +def _bundle(name: str | None): + from agbench import bench + + try: + return bench.load(name) if name else None + except KeyError: + return None + + +def comparability(run: dict, records: list[dict]) -> list[str]: + """Reasons a run's scores are not comparable with the benchmark's reference results (empty: comparable).""" + from agbench.bench import judge_prompt_sha + + bm = run.get("benchmark", {}).get("benchmark") + if not bm: + return ["no frozen benchmark (--benchmark none): items built from the local data"] + why = [] + b = _bundle(bm["name"]) + if b is None: + why.append(f"benchmark {bm['name']} is not installed") + elif b.hash != bm["hash"]: + why.append(f"benchmark hash {bm['hash']} differs from the installed {bm['name']} ({b.hash})") + if bm.get("variant"): + why.append(f"item {bm['variant']} (seed or multiple-choice options changed)") + if any(r.get("needs_judge") for r in records): + j = run.get("judge") or {} + ref = (b.spec["judge"] if b else {}) or {} + if any(r.get("needs_judge") and r.get("judge_correct") is None for r in records): + why.append("open-ended answers not judged yet (agbench eval judge)") + elif j: + if ref and j.get("model") != ref.get("model"): + why.append(f"judge {j.get('model')} is not the reference judge {ref.get('model')}") + if ref and j.get("prompt_sha", judge_prompt_sha()) != ref.get("prompt_sha"): + why.append("judge prompt differs from the reference judge prompt") + return why + + +def manifest(run_dir, records: list[dict] | None = None) -> dict | None: + """Summary of a run: agbench version, benchmark (name, hash, variant), method and sampling, item seed, judge, + coverage and comparability.""" + run_dir = Path(run_dir) + if not (run_dir / "run.json").exists(): + return None + run = json.loads((run_dir / "run.json").read_text()) + records = records if records is not None else _read_jsonl(run_dir / "predictions.jsonl") + args = run.get("benchmark", {}) + bm = args.get("benchmark") + b = _bundle(bm["name"]) if bm else None + skipped = json.loads((run_dir / "skipped.json").read_text()) if (run_dir / "skipped.json").exists() else [] + answered = {r["item_id"] for r in records if not r.get("error")} + cov = {"items": run.get("n_items"), "answered": len(answered), + "errors": sum(1 for r in records if r.get("error")), + "pending_judge": sum(1 for r in records if r.get("needs_judge") and r.get("judge_correct") is None), + "skipped_datasets": sorted({s["dataset"] for s in skipped if "dataset" in s})} + if b: + filters = {k: args.get(k) for k in ("tasks", "formats", "only", "limit_per_dataset") if args.get(k)} + cov |= {"benchmark_items": len(b.raw_items), "filters": filters, + "unavailable_datasets": sorted(set(b.unavailable) & set(cov["skipped_datasets"]))} + cov["complete"] = not filters and len(answered) == len(b.raw_items) - sum( + 1 for r in b.raw_items if r["dataset"] in cov["unavailable_datasets"]) + why = comparability(run, records) + return {"schema": SCHEMA, "written": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "agbench": {"version": _version(), "git": run.get("agbench_git")}, "benchmark": bm, + "method": run.get("method"), "item_seed": args.get("seed"), "mcqa": args.get("mcqa"), + "judge": run.get("judge"), "coverage": cov, "comparable": not why, "not_comparable": why} + + +def write_manifest(run_dir, records: list[dict] | None = None) -> dict | None: + m = manifest(run_dir, records) + if m: + (Path(run_dir) / "run_manifest.json").write_text(json.dumps(m, indent=2)) + return m + + +def _items_match_bundle(items: list[dict], b) -> list[str]: + """Run items that differ from the benchmark's frozen items (any field; images compared by relative path).""" + frozen = {r["item_id"]: r for r in b.raw_items} + bad = [] + for it in items: + f = frozen.get(it["item_id"]) + if f is None: + bad.append(f"{it['item_id']}: not in {b.name}") + continue + imgs_ok = len(it["images"]) == len(f["images"]) and all(a.endswith(p) for a, p in zip(it["images"], f["images"])) + diff = [k for k in f if k != "images" and it.get(k) != f[k]] + if diff or not imgs_ok: + bad.append(f"{it['item_id']}: {', '.join(diff + ([] if imgs_ok else ['images']))} differ from {b.name}") + return bad + + +def _same(a, b) -> bool: + if isinstance(a, float) and isinstance(b, float): + return a == b or (a != a and b != b) or abs(a - b) <= 1e-9 * max(abs(a), abs(b)) + if isinstance(a, dict) and isinstance(b, dict): + return a.keys() == b.keys() and all(_same(a[k], b[k]) for k in a) + if isinstance(a, list) and isinstance(b, list): + return len(a) == len(b) and all(_same(x, y) for x, y in zip(a, b)) + return a == b + + +def check_run(run_dir) -> dict: + """{'errors': [...], 'warnings': [...], 'stats': {...}}. Errors: the run's files are broken, inconsistent or do not + match its benchmark. Warnings: the run is valid but incomplete or not comparable with the reference results.""" + run_dir = Path(run_dir) + errors, warnings, stats = [], [], {} + for f in ("run.json", "items.jsonl", "predictions.jsonl"): + if not (run_dir / f).exists(): + errors.append(f"{f} missing") + if errors: + return {"errors": errors, "warnings": warnings, "stats": stats} + run = json.loads((run_dir / "run.json").read_text()) + items = _read_jsonl(run_dir / "items.jsonl") + recs = _read_jsonl(run_dir / "predictions.jsonl") + ids = {it["item_id"] for it in items} + + dup = [k for k, n in Counter(r.get("item_id") for r in recs).items() if n > 1] + if dup: + errors.append(f"{len(dup)} items with more than one prediction (e.g. {dup[0]})") + extra = [r["item_id"] for r in recs if r.get("item_id") not in ids] + if extra: + errors.append(f"{len(extra)} predictions for items not in items.jsonl (e.g. {extra[0]})") + bad_schema = Counter() + for r in recs: + for k in REQUIRED + BY_TASK.get(r.get("task"), ()): + if k not in r: + bad_schema[k] += 1 + if r.get("task") in mx.BOX_TASKS: + if not isinstance(r.get("correct"), (int, float)) or isinstance(r.get("correct"), bool): + bad_schema["correct (number for box tasks)"] += 1 + elif not isinstance(r.get("correct"), bool): + bad_schema["correct (bool)"] += 1 + for k, n in bad_schema.items(): + errors.append(f"{n} predictions missing or with a wrong type for '{k}'") + + bm = run.get("benchmark", {}).get("benchmark") + b = _bundle(bm["name"]) if bm else None + if bm and b and not bm.get("variant"): + diff = _items_match_bundle(items, b) + if diff: + errors.append(f"{len(diff)} items differ from the frozen benchmark (e.g. {diff[0]})") + + if (run_dir / "metrics.json").exists() and not bad_schema: + stored = json.loads((run_dir / "metrics.json").read_text()) + fresh = json.loads(json.dumps(mx.compute([r for r in recs if r.get("item_id") in ids]))) + # A dataset row's ag_task label (its most common bucket) broke ties by set order before agbench 0.1.0's fix; + # runs from then can carry either label for a tied dataset. Scores are compared; that label is not. + strip = lambda m: {**m, "datasets": [{k: v for k, v in r.items() if k != "ag_task"} for r in m.get("datasets", [])]} + if not _same(strip(fresh), strip(stored)): + errors.append("metrics.json does not match predictions.jsonl (rewrite it: agbench eval check --rescore)") + elif not (run_dir / "metrics.json").exists(): + warnings.append("metrics.json missing (run not finished)") + + have = {r["item_id"] for r in recs if not r.get("error")} + n_err = sum(1 for r in recs if r.get("error")) + n = len(recs) or 1 + stats = {"items": len(items), "predictions": len(recs), "answered": len(have), "errors": n_err, + "parse_fail_rate": round(sum(1 for r in recs if not r.get("parse_ok") and not r.get("error")) / n, 4), + "truncated_rate": round(sum(1 for r in recs if r.get("truncated")) / n, 4), + "idk_rate": round(sum(1 for r in recs if r.get("idk")) / n, 4), + "empty_answer_rate": round(sum(1 for r in recs if not (r.get("text") or "").strip() and not r.get("error")) / n, 4)} + if len(have) < len(items): + warnings.append(f"{len(items) - len(have)} of {len(items)} items without an answer ({n_err} request errors); " + "resume with --run-dir") + judges = Counter(r.get("judge_model") for r in recs if r.get("judge_correct") is not None) + if len(judges) > 1: + warnings.append(f"open-ended answers judged by more than one judge: {dict(judges)}") + m = manifest(run_dir, recs) + stats["comparable"] = m["comparable"] + stats["complete"] = m["coverage"].get("complete") + for w in m["not_comparable"]: + warnings.append(f"not comparable: {w}") + cov = m["coverage"] + if cov.get("complete") is False and len(have) == len(items): + warnings.append(f"covers {len(items)} of {cov['benchmark_items']} benchmark items" + + (f" ({', '.join(f'{k}={v}' for k, v in cov['filters'].items())})" if cov["filters"] else "")) + if m["coverage"].get("unavailable_datasets"): + warnings.append("skipped (source removed): " + ", ".join(m["coverage"]["unavailable_datasets"])) + return {"errors": errors, "warnings": warnings, "stats": stats} diff --git a/src/agbench/eval/cli.py b/src/agbench/eval/cli.py index 14e3e85..4be4483 100644 --- a/src/agbench/eval/cli.py +++ b/src/agbench/eval/cli.py @@ -18,6 +18,9 @@ TaskOpt = typer.Option(None, "--task", help="classification | detection | segmentation | image_text_to_text") FormatOpt = typer.Option(None, "--format", help="mcqa_within | mcqa_across | oeq | grounding | native | multiple_choice (ITT)") ModelsFileOpt = typer.Option(None, "--models-file", help="YAML of extra/overriding models (models.yaml layout).") +JudgeEndpointOpt = typer.Option(None, "--judge-endpoint", help="Running OpenAI-compatible server or hosted API for the judge (default: serve the judge model with vLLM).") +JudgeModelOpt = typer.Option(None, "--judge-model", help="Judge model (default: the reference judge; another judge makes scores not comparable).") +JudgeKeyOpt = typer.Option(None, "--judge-api-key-env", help="Environment variable holding the --judge-endpoint API key.") def _register(files: list[Path] | None): @@ -59,7 +62,8 @@ def run( model: str = typer.Option(None, "--model", help="Model id: registry entry, any HF repo or local path (served with vLLM)."), method: str = typer.Option(None, "--method", help="Custom method as module:Class."), method_kwargs: str = typer.Option(None, "--method-kwargs", help="JSON kwargs for --method."), - endpoint: str = typer.Option(None, "--endpoint", help="Use a running OpenAI-compatible server instead of launching one."), + endpoint: str = typer.Option(None, "--endpoint", help="Use a running OpenAI-compatible server or hosted API instead of launching one."), + api_key_env: str = typer.Option(None, "--api-key-env", help="Environment variable holding the --endpoint API key (e.g. OPENAI_API_KEY)."), task: list[str] = TaskOpt, fmt: list[str] = FormatOpt, only: str = typer.Option(None, "--only", help="Regex on dataset name."), @@ -78,7 +82,10 @@ def run( out: Path = typer.Option(Path("runs"), "--out"), run_dir: Path = typer.Option(None, "--run-dir", help="Resume into this run dir."), judge: bool = typer.Option(False, "--judge", help="Judge open-ended answers after the run."), - judge_endpoint: str = typer.Option(None, "--judge-endpoint"), + judge_endpoint: str = JudgeEndpointOpt, + judge_model: str = JudgeModelOpt, + judge_api_key_env: str = JudgeKeyOpt, + strict: bool = typer.Option(False, "--strict", help="Exit non-zero if the run check finds errors or the run is not comparable."), models_file: list[Path] = ModelsFileOpt, benchmark: str = BenchOpt, ): @@ -112,14 +119,17 @@ def run( ids = {it.item_id for it in bench.items} res = finalize(rd, [r for r in read_jsonl(rd / "predictions.jsonl") if r["item_id"] in ids]) elif endpoint: - res = bench.run(VLMMethod(endpoint, model, thinking, effort, max_tokens, gen_seed=gen_seed), rd, conc, key_formats=kf) + res = bench.run(VLMMethod(endpoint, model, thinking, effort, max_tokens, gen_seed=gen_seed, api_key_env=api_key_env), + rd, conc, key_formats=kf) else: with sampler() as gpu, _served(model, rd, "server.log", gpu, max_model_len=max_model_len) as srv: res = bench.run(VLMMethod(srv.endpoint, model, thinking, effort, max_tokens, gen_seed=gen_seed), rd, conc, key_formats=kf, gpu=gpu) if judge and res.metrics["pending_judge"]: - _judge([rd], judge_endpoint, None) + _judge([rd], judge_endpoint, judge_model, api_key_env=judge_api_key_env) _print_summary(rd) + if _print_check(rd) and strict: + raise typer.Exit(1) def _echo_items(bench) -> None: @@ -504,7 +514,7 @@ def _served(model_id: str, run_dir: Path, log_name: str, gpu, phase: str = "load yield srv -def _judge(run_dirs: list[Path], endpoint: str | None, judge_model: str | None, redo: bool = False): +def _judge(run_dirs: list[Path], endpoint: str | None, judge_model: str | None, redo: bool = False, api_key_env: str | None = None): from agbench.eval.gpu import sampler from agbench.eval.judge import judge_run from agbench.eval.resources import models @@ -512,7 +522,7 @@ def _judge(run_dirs: list[Path], endpoint: str | None, judge_model: str | None, jm = judge_model or models()["judge"] if endpoint: for d in run_dirs: - judge_run(d, endpoint, jm, redo=redo) + judge_run(d, endpoint, jm, redo=redo, api_key_env=api_key_env) return with sampler() as gpu, _served(jm, run_dirs[0], "judge_server.log", gpu, "judge_load") as srv: for d in run_dirs: @@ -522,14 +532,58 @@ def _judge(run_dirs: list[Path], endpoint: str | None, judge_model: str | None, @app.command("judge") def judge_cmd( run_dir: list[Path] = typer.Option(..., "--run", help="Run dir(s) to judge."), - judge_model: str = typer.Option(None, "--judge-model"), - endpoint: str = typer.Option(None, "--judge-endpoint"), + judge_model: str = JudgeModelOpt, + endpoint: str = JudgeEndpointOpt, + api_key_env: str = JudgeKeyOpt, redo: bool = typer.Option(False, "--redo", help="Re-judge answers that already have a verdict (e.g. after editing the judge prompts)."), models_file: list[Path] = ModelsFileOpt, ): """Judge open-ended answers with the judge model (default gemma-4-31B-it-FP8).""" _register(models_file) - _judge(run_dir, endpoint, judge_model, redo) + _judge(run_dir, endpoint, judge_model, redo, api_key_env) + for d in run_dir: + _print_check(d) + + +def _print_check(run_dir: Path, verbose: bool = False) -> bool: + """Print the run check; True if it found errors or the run is not comparable.""" + from agbench.eval.check import check_run + + c = check_run(run_dir) + st = c["stats"] + head = "ok" if not c["errors"] else f"{len(c['errors'])} errors" + comp = "comparable" if st.get("comparable") else "not comparable" + typer.echo(f"check {run_dir}: {head}; {comp}" + ("" if st.get("complete") in (None, True) else "; incomplete")) + for e in c["errors"]: + typer.echo(f" error: {e}") + for w in c["warnings"]: + typer.echo(f" {w}") + if verbose and st: + typer.echo(" " + " ".join(f"{k}={v}" for k, v in st.items())) + return bool(c["errors"]) or not st.get("comparable") + + +@app.command("check") +def check_cmd( + run_dir: list[Path] = typer.Argument(..., help="Run dir(s)."), + strict: bool = typer.Option(False, "--strict", help="Also fail on warnings: not comparable, incomplete."), + rescore: bool = typer.Option(False, "--rescore", help="Rewrite metrics.json and run_manifest.json from predictions.jsonl."), +): + """Check run dirs: files and prediction schema, items against the frozen benchmark, metrics against predictions, + coverage, comparability with the reference results.""" + from agbench.eval.check import check_run + from agbench.eval.runner import finalize, read_jsonl + + fail = False + for d in run_dir: + if rescore: + ids = {r["item_id"] for r in read_jsonl(d / "items.jsonl")} + finalize(d, [r for r in read_jsonl(d / "predictions.jsonl") if r["item_id"] in ids]) + c = check_run(d) + _print_check(d, verbose=True) + fail |= bool(c["errors"]) or (strict and bool(c["warnings"])) + if fail: + raise typer.Exit(1) def _print_summary(run_dir: Path): diff --git a/src/agbench/eval/client.py b/src/agbench/eval/client.py index 8b3fa33..ca93a89 100644 --- a/src/agbench/eval/client.py +++ b/src/agbench/eval/client.py @@ -1,8 +1,10 @@ -"""Async client for OpenAI-compatible VLM servers (vLLM, llama-server).""" +"""Async client for OpenAI-compatible endpoints: vLLM, llama-server, or a hosted API (OpenAI, Gemini, Claude, ...).""" import asyncio import base64 import io +import os +import re import time from dataclasses import asdict, dataclass @@ -46,20 +48,71 @@ def merge(a: dict, b: dict) -> dict: return out +class FatalAPIError(RuntimeError): + """The endpoint refuses every request (bad key, no access, unknown model): stop the run instead of recording an + error for each item.""" + + +def api_key_from_env(var: str | None) -> str: + """The API key held in environment variable `var` (the key itself is never passed on the command line or saved).""" + if not var: + return "EMPTY" + key = os.environ.get(var) + if not key: + raise FatalAPIError(f"environment variable {var} is not set (it should hold the API key)") + return key + + +def api_base(url: str) -> str: + """OpenAI-style base URL: a bare server address gets /v1; a URL that already has a version path is kept.""" + url = url.rstrip("/") + return url if re.search(r"/v\d+[a-z0-9]*(/|$)", url) else url + "/v1" + + class Client: def __init__(self, base_url: str, model: str | None = None, api_key: str = "EMPTY", timeout: float = 1800, - max_pixels: int = MAX_PIXELS, retries: int = 3): + max_pixels: int = MAX_PIXELS, retries: int = 3, prefer: str | None = None): + """`model`: the name to send. Unset: `prefer` if the endpoint lists it (or does not list models), else the + endpoint's only (or first) model.""" from openai import AsyncOpenAI - self.api = AsyncOpenAI(base_url=base_url.rstrip("/") + ("" if base_url.rstrip("/").endswith("/v1") else "/v1"), - api_key=api_key, timeout=timeout, max_retries=0) - self.model, self.max_pixels, self.retries = model, max_pixels, retries + self.api = AsyncOpenAI(base_url=api_base(base_url), api_key=api_key, timeout=timeout, max_retries=0) + self.model, self.prefer, self.max_pixels, self.retries = model, prefer, max_pixels, retries + self.token_param, self.dropped = "max_tokens", set() # adapted to what the endpoint accepts + self._lock = asyncio.Lock() async def resolve_model(self) -> str: - if not self.model: - self.model = (await self.api.models.list()).data[0].id + async with self._lock: + if not self.model: + try: + ids = [m.id for m in (await self.api.models.list()).data] + except Exception as e: + if _fatal(e) and not _status(e) == 404: + raise FatalAPIError(_describe(e)) from e + ids = [] + if self.prefer and (self.prefer in ids or not ids or len(ids) > 1): + self.model = self.prefer + elif ids: + self.model = ids[0] + else: + raise FatalAPIError("the endpoint lists no models; pass the model name") return self.model + def _adapt(self, e: Exception) -> bool: + """Switch to the parameter spelling a hosted API asks for (e.g. max_completion_tokens; no temperature).""" + msg = str(e).lower() + if _status(e) != 400: + return False + if "max_tokens" in msg and "max_completion_tokens" in msg and self.token_param == "max_tokens": + self.token_param = "max_completion_tokens" + return True + for k in ("temperature", "top_p", "top_k", "seed"): + if k in msg and ("unsupported" in msg or "not support" in msg or "unrecognized" in msg or "unknown" in msg) \ + and k not in self.dropped: + self.dropped.add(k) + return True + return False + async def chat(self, prompt: str, images: list[str], system: str | None = None, max_tokens: int = 16384, body: dict | None = None) -> Prediction: """One request. `body` holds sampling + chat_template_kwargs etc. (sent as extra_body).""" @@ -67,13 +120,13 @@ async def chat(self, prompt: str, images: list[str], system: str | None = None, encoded = [encode_image(p, self.max_pixels) for p in images] content = [{"type": "image_url", "image_url": {"url": u}} for u, _ in encoded] + [{"type": "text", "text": prompt}] messages = ([{"role": "system", "content": system}] if system else []) + [{"role": "user", "content": content}] - body = dict(body or {}) - temperature = body.pop("temperature", None) - t0, err = time.perf_counter(), None - for attempt in range(self.retries + 1): + t0, err, attempt = time.perf_counter(), None, 0 + while attempt <= self.retries: + b = {k: v for k, v in (body or {}).items() if k not in self.dropped} + kw = {k: b.pop(k) for k in ("temperature", "top_p", "seed") if k in b} + kw[self.token_param] = max_tokens try: - r = await self.api.chat.completions.create(model=model, messages=messages, max_tokens=max_tokens, - temperature=temperature, extra_body=body or None) + r = await self.api.chat.completions.create(model=model, messages=messages, extra_body=b or None, **kw) msg = r.choices[0].message reasoning = getattr(msg, "reasoning_content", None) or getattr(msg, "reasoning", None) or "" usage = r.usage @@ -81,9 +134,29 @@ async def chat(self, prompt: str, images: list[str], system: str | None = None, prompt_tokens=getattr(usage, "prompt_tokens", 0) or 0, completion_tokens=getattr(usage, "completion_tokens", 0) or 0, latency_s=time.perf_counter() - t0, sent_size=encoded[0][1] if encoded else None) - except Exception as e: # connection drops, 5xx, timeouts + except Exception as e: # connection drops, 5xx, timeouts, rate limits + if self._adapt(e): + continue + if _fatal(e): + raise FatalAPIError(_describe(e)) from e err = f"{type(e).__name__}: {e}" + if _status(e) == 400: # this request is refused as it is (e.g. image too large); retrying will not help + break if attempt < self.retries: - await asyncio.sleep(2 ** attempt * 5) + await asyncio.sleep(2 ** attempt * (20 if _status(e) == 429 else 5)) + attempt += 1 return Prediction(text="", finish_reason="error", latency_s=time.perf_counter() - t0, sent_size=encoded[0][1] if encoded else None, error=err) + + +def _status(e: Exception) -> int | None: + return getattr(e, "status_code", None) + + +def _fatal(e: Exception) -> bool: + return _status(e) in (401, 403, 404) + + +def _describe(e: Exception) -> str: + what = {401: "API key rejected (401)", 403: "no access to this model (403)", 404: "model or endpoint not found (404)"} + return f"{what.get(_status(e), type(e).__name__)}: {str(e)[:300]}" diff --git a/src/agbench/eval/judge.py b/src/agbench/eval/judge.py index 6dbe701..ab38f2f 100644 --- a/src/agbench/eval/judge.py +++ b/src/agbench/eval/judge.py @@ -6,7 +6,7 @@ import time from pathlib import Path -from agbench.eval.client import Client +from agbench.eval.client import Client, api_key_from_env from agbench.eval.methods import model_spec from agbench.eval.resources import models, prompts from agbench.eval.runner import finalize, log_compute, read_jsonl, write_jsonl @@ -32,10 +32,11 @@ def parse_verdict(text: str) -> bool | None: return m.group(1).lower() == "true" if m else None -async def judge_records(records: list[dict], endpoint: str, judge_model: str, concurrency: int = 32) -> int: +async def judge_records(records: list[dict], endpoint: str, judge_model: str, concurrency: int = 32, + api_key: str = "EMPTY") -> int: spec = model_spec(judge_model) body = {**(spec.get("no_thinking") or {}), "temperature": 0.0} - client = Client(endpoint) + client = Client(endpoint, api_key=api_key, prefer=judge_model) todo = [r for r in records if r.get("needs_judge") and r.get("judge_correct") is None] sem, prog = asyncio.Semaphore(concurrency), Progress("judge", len(todo), every=30) @@ -49,8 +50,15 @@ async def one(r): return len(todo) -def judge_run(run_dir, endpoint: str, judge_model: str | None = None, concurrency: int = 32, gpu=None, redo: bool = False) -> dict: - """Judge open-ended answers that have no verdict yet (`redo`: all of them, e.g. after changing the judge prompt).""" +def judge_run(run_dir, endpoint: str, judge_model: str | None = None, concurrency: int = 32, gpu=None, redo: bool = False, + api_key_env: str | None = None) -> dict: + """Judge open-ended answers that have no verdict yet (`redo`: all of them, e.g. after changing the judge prompt). + + Any judge model behind an OpenAI-compatible endpoint works (`api_key_env`: variable holding a hosted API's key). + Scores are comparable with the reference results only with the benchmark's reference judge and judge prompt + (run_manifest.json: comparable).""" + from agbench.bench import judge_prompt_sha + run_dir = Path(run_dir) judge_model = judge_model or models()["judge"] recs = read_jsonl(run_dir / "predictions.jsonl") @@ -59,14 +67,20 @@ def judge_run(run_dir, endpoint: str, judge_model: str | None = None, concurrenc if r.get("needs_judge"): r["judge_correct"] = r["judge_text"] = None t0 = time.time() - n = asyncio.run(judge_records(recs, endpoint, judge_model, concurrency)) + judged = {r.get("judge_model") for r in recs if r.get("judge_correct") is not None} + judged.discard(None) + if not redo and judged - {judge_model}: + raise ValueError(f"{run_dir} already has verdicts from {', '.join(map(str, judged - {judge_model}))}; " + f"use --redo to re-judge every answer with {judge_model}") + n = asyncio.run(judge_records(recs, endpoint, judge_model, concurrency, api_key_from_env(api_key_env))) t1 = time.time() if n: log_compute(run_dir, phase="judge", model=judge_model, items=n, concurrency=concurrency, wall_s=round(t1 - t0, 1), redo=redo, **(gpu.summary(t0, t1) if gpu else {})) write_jsonl(run_dir / "predictions.jsonl", recs) run = json.loads((run_dir / "run.json").read_text()) - run["judge"] = {"model": judge_model, "self_judged": run["method"].get("model_id") == judge_model} + run["judge"] = {"model": judge_model, "prompt_sha": judge_prompt_sha(), + "self_judged": run["method"].get("model_id") == judge_model} (run_dir / "run.json").write_text(json.dumps(run, indent=2)) log(f"judged {n} answers in {run_dir}") return finalize(run_dir, recs).metrics diff --git a/src/agbench/eval/methods.py b/src/agbench/eval/methods.py index 5acec9e..dac3f49 100644 --- a/src/agbench/eval/methods.py +++ b/src/agbench/eval/methods.py @@ -2,7 +2,7 @@ import hashlib -from agbench.eval.client import Client, Prediction, merge +from agbench.eval.client import Client, Prediction, api_key_from_env, merge from agbench.eval.items import EvalItem from agbench.eval.resources import models, prompts @@ -59,7 +59,8 @@ class VLMMethod(Method): def __init__(self, endpoint: str, model_id: str, thinking: bool = True, effort: str | None = "low", max_tokens: int | None = None, body: dict | None = None, served_name: str | None = None, - gen_seed: int | None = None): + gen_seed: int | None = None, api_key_env: str | None = None): + """`api_key_env`: name of the environment variable holding the endpoint's API key (hosted APIs).""" self.spec = model_spec(model_id) self.name, self.model_id, self.thinking, self.effort = model_id, model_id, thinking, effort self.max_tokens = max_tokens or self.spec["max_tokens"] @@ -67,7 +68,8 @@ def __init__(self, endpoint: str, model_id: str, thinking: bool = True, effort: self.system = prompts()["cot_system"] if (thinking and self.spec.get("cot")) else None self.box_order = self.spec.get("box_order", "yxyx") self.gen_seed = gen_seed # per-item sampling seed derived from it, so a run is reproducible - self.client = Client(endpoint, served_name) + self.api_key_env = api_key_env + self.client = Client(endpoint, served_name, api_key=api_key_from_env(api_key_env), prefer=model_id) def prompt(self, item: EvalItem) -> str: """The item prompt, with the grounding coordinate order switched to this model's `box_order`.""" @@ -83,4 +85,4 @@ async def predict(self, item: EvalItem) -> Prediction: def config(self) -> dict: return {"name": self.name, "model_id": self.model_id, "thinking": self.thinking, "effort": self.effort, "max_tokens": self.max_tokens, "body": self.body, "cot": bool(self.system), "box_order": self.box_order, - "gen_seed": self.gen_seed} + "gen_seed": self.gen_seed, **({"api_key_env": self.api_key_env} if self.api_key_env else {})} diff --git a/src/agbench/eval/runner.py b/src/agbench/eval/runner.py index 6087f9a..24f12b9 100644 --- a/src/agbench/eval/runner.py +++ b/src/agbench/eval/runner.py @@ -14,7 +14,7 @@ from agbench.bench import DEFAULT as DEFAULT_BENCH from agbench.eval import metrics as mx -from agbench.eval.client import Prediction +from agbench.eval.client import FatalAPIError, Prediction from agbench.eval.gpu import sampler from agbench.eval.grade import grade from agbench.eval.items import MCQAOptions, build_items @@ -153,6 +153,8 @@ async def one(it): async with sem: try: pred = await (asyncio.to_thread(method.predict, it) if sync else method.predict(it)) + except FatalAPIError: + raise except Exception as e: pred = Prediction(text="", finish_reason="error", error=f"{type(e).__name__}: {e}") try: @@ -183,6 +185,11 @@ async def one(it): def finalize(out: Path, records: list[dict]) -> Result: + """metrics.json and run_manifest.json from the records.""" + from agbench.eval.check import write_manifest + + out = Path(out) m = mx.compute(records) (out / "metrics.json").write_text(json.dumps(m, indent=2)) + write_manifest(out, records) return Result(out, m, records) diff --git a/tests/test_check.py b/tests/test_check.py new file mode 100644 index 0000000..4a2db40 --- /dev/null +++ b/tests/test_check.py @@ -0,0 +1,128 @@ +import asyncio +import json +import shutil + +import httpx +import pytest + +from agbench import bench +from agbench.eval.check import check_run +from agbench.eval.client import Client, FatalAPIError, api_base, api_key_from_env +from agbench.eval.methods import Method +from agbench.eval.runner import Benchmark + +from test_bench import _fake_dataset + + +def test_api_base(): + assert api_base("http://localhost:8000") == "http://localhost:8000/v1" + assert api_base("https://api.openai.com/v1") == "https://api.openai.com/v1" + assert api_base("https://generativelanguage.googleapis.com/v1beta/openai/") == "https://generativelanguage.googleapis.com/v1beta/openai" + + +def test_api_key_from_env(monkeypatch): + assert api_key_from_env(None) == "EMPTY" + monkeypatch.delenv("AGBENCH_TEST_KEY", raising=False) + with pytest.raises(FatalAPIError, match="AGBENCH_TEST_KEY is not set"): + api_key_from_env("AGBENCH_TEST_KEY") + monkeypatch.setenv("AGBENCH_TEST_KEY", "sk-test") + assert api_key_from_env("AGBENCH_TEST_KEY") == "sk-test" + + +def _client(handler, **kw) -> Client: + from openai import AsyncOpenAI + + c = Client("https://api.example.com/v1", "gpt-x", api_key="sk-test", retries=1, **kw) + c.api = AsyncOpenAI(base_url="https://api.example.com/v1", api_key="sk-test", max_retries=0, + http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler))) + return c + + +def _ok(text="A"): + return httpx.Response(200, json={"id": "x", "object": "chat.completion", "created": 0, "model": "gpt-x", + "choices": [{"index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": text}}], + "usage": {"prompt_tokens": 3, "completion_tokens": 1, "total_tokens": 4}}) + + +def test_client_adapts_to_hosted_api_parameters(): + seen = [] + + def handler(req): + body = json.loads(req.content) + seen.append(body) + if "max_tokens" in body: + return httpx.Response(400, json={"error": {"message": "Unsupported parameter: 'max_tokens' is not supported with this model. Use 'max_completion_tokens' instead."}}) + if "temperature" in body: + return httpx.Response(400, json={"error": {"message": "Unsupported value: 'temperature' does not support 0.0 with this model."}}) + return _ok("B") + + c = _client(handler) + p = asyncio.run(c.chat("q", [], max_tokens=64, body={"temperature": 0.0})) + assert p.text == "B" and p.error is None + assert seen[-1]["max_completion_tokens"] == 64 and "temperature" not in seen[-1] and len(seen) == 3 + + +def test_client_bad_key_stops_the_run(tmp_path): + c = _client(lambda req: httpx.Response(401, json={"error": {"message": "Incorrect API key provided"}})) + with pytest.raises(FatalAPIError, match="API key rejected"): + asyncio.run(c.chat("q", [])) + + class M(Method): + name = "m" + + async def predict(self, item): + return await c.chat(item.prompt, []) + + full = bench.load("agml-full-v1") + _fake_dataset(tmp_path, full, "bean_disease_uganda") + b = Benchmark(tmp_path, tasks=["classification"], formats=["mcqa_within"], limit_per_dataset=2) + with pytest.raises(FatalAPIError): + b.run(M(), tmp_path / "run") + + +class Letter(Method): + name = "letter-a" + + def predict(self, item): + return "A" + + +@pytest.fixture +def run_dir(tmp_path): + full = bench.load("agml-full-v1") + _fake_dataset(tmp_path, full, "bean_disease_uganda") + b = Benchmark(tmp_path, tasks=["classification"], formats=["mcqa_within", "mcqa_across"], limit_per_dataset=3) + b.run(Letter(), tmp_path / "run") + return tmp_path / "run" + + +def test_manifest_and_check(run_dir): + m = json.loads((run_dir / "run_manifest.json").read_text()) + assert m["benchmark"]["name"] == "agml-full-v1" and m["comparable"] and m["coverage"]["complete"] is False + c = check_run(run_dir) + assert c["errors"] == [] and c["stats"]["comparable"] and any("benchmark items" in w for w in c["warnings"]) + + +def test_check_catches_edits(run_dir, tmp_path): + bad = tmp_path / "edited" + shutil.copytree(run_dir, bad) + items = [json.loads(l) for l in open(bad / "items.jsonl")] + items[0]["answer"] = "something else" + (bad / "items.jsonl").write_text("".join(json.dumps(i) + "\n" for i in items)) + recs = [json.loads(l) for l in open(bad / "predictions.jsonl")] + recs[1]["correct"] = not recs[1]["correct"] + (bad / "predictions.jsonl").write_text("".join(json.dumps(r) + "\n" for r in recs + recs[:1])) + errs = " | ".join(check_run(bad)["errors"]) + assert "differ from the frozen benchmark" in errs and "more than one prediction" in errs and "metrics.json does not match" in errs + + +def test_other_judge_not_comparable(run_dir): + from agbench.eval.check import comparability + + run = json.loads((run_dir / "run.json").read_text()) + recs = [{"needs_judge": True, "judge_correct": True}] + assert comparability({**run, "judge": {"model": "gpt-x", "prompt_sha": bench.judge_prompt_sha()}}, recs) == \ + ["judge gpt-x is not the reference judge RedHatAI/gemma-4-31B-it-FP8-dynamic"] + ref = bench.load("agml-full-v1").spec["judge"] + assert comparability({**run, "judge": {"model": ref["model"], "prompt_sha": ref["prompt_sha"]}}, recs) == [] + assert "not judged yet" in comparability(run, [{"needs_judge": True, "judge_correct": None}])[0]