Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,9 @@ uv run agbench eval judge --run runs/<run_dir>
uv run agbench eval judge --run runs/<run_dir> --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 report --runs runs --html reports/report.html # charts, tables, runs; one offline file
uv sync --extra viz && uv run agbench eval report --runs runs --figures reports/figures # paper figures (PNG)
uv run agbench eval report --runs runs --html reports/report.html --label "my-org/My-VLM=My VLM" --label "baseline/chance=Chance"
uv run agbench eval stats --runs runs --out reports/stats
uv run agbench eval view --runs runs # http://localhost:8502
```
Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ dependencies = [
[project.optional-dependencies]
# Few-shot YOLO11 baselines (agbench eval yolo)
yolo = ["ultralytics>=8.3.0"]
# PNG figures (agbench eval report --figures)
viz = ["matplotlib>=3.11"]

[project.scripts]
agbench = "agbench.cli:app"
Expand Down
20 changes: 19 additions & 1 deletion src/agbench/eval/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -599,8 +599,13 @@ def report(
average: str = typer.Option("macro", "--average", help="macro | micro"),
out: Path = typer.Option(None, "--out", help="Write the leaderboard markdown here."),
csv: Path = typer.Option(None, "--csv", help="Write scores.csv (per task), ag_tasks.csv and datasets.csv to this dir."),
html: Path = typer.Option(None, "--html", help="Write a self-contained HTML report (charts, tables, runs)."),
figures: Path = typer.Option(None, "--figures", help="Write the paper's figures as PNG to this dir (uv sync --extra viz)."),
label: list[str] = typer.Option(None, "--label", help="Display name: METHOD_NAME=LABEL (repeatable)."),
title: str = typer.Option("AgML benchmark results", "--title", help="HTML report title."),
):
"""Leaderboard across runs."""
"""Leaderboard across runs. --html and --figures group repeated runs of a setting (sampling seeds) and aggregate
them as in the paper: per-dataset mean, macro over datasets, 95% bootstrap CI."""
from agbench.eval.report import leaderboard_md, load_runs, write_csv

rs = load_runs(runs)
Expand All @@ -610,6 +615,19 @@ def report(
out.write_text(md)
if csv:
typer.echo(f"csv: {write_csv(rs, csv)}")
if html or figures:
from agbench.viz.aggregate import entries

labels = dict(x.split("=", 1) for x in label or [])
es = entries(runs, labels)
if html:
from agbench.viz.html import write

typer.echo(f"html: {write(es, html, title)}")
if figures:
from agbench.viz.figures import agtask, main_results

typer.echo(f"figures: {main_results(es, figures / 'fig_main_results.png')}, {agtask(es, figures / 'fig_agtask.png')}")


@app.command()
Expand Down
Empty file added src/agbench/viz/__init__.py
Empty file.
170 changes: 170 additions & 0 deletions src/agbench/viz/aggregate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
"""Scores for charts and reports, aggregated as in the paper.

Per run, an item's score is the judge verdict for an open-ended answer and its graded score otherwise (accuracy for
boxes). Scores are averaged per dataset; repeated runs of one entry (sampling seeds, YOLO training subsets, chance
seeds) are averaged per dataset; the entry's score is the macro mean over datasets, with a 95% bootstrap CI over
datasets.

An entry is one method with one setting: runs that differ only in their sampling seed are its replicates. Chance
baselines (baseline/chance) become reference lines; YOLO runs (method name yolo*) score classification by top-1
accuracy, the same value in every classification format.
"""

import json
import random
from collections import defaultdict
from dataclasses import dataclass, field
from pathlib import Path

import numpy as np

COLS = [("mcqa_across", "MCQA across"), ("mcqa_within", "MCQA within"), ("oeq", "OEQ"), ("itt", "VQA"),
("detection", "Detection"), ("segmentation", "Segmentation")]
AG = [("disease", "Disease"), ("pest_damage", "Pest/Damage"), ("species_id", "Species"), ("quality_maturity", "Quality")]
CLS_FORMATS = [("mcqa_across", "MCQA across"), ("mcqa_within", "MCQA within"), ("oeq", "OEQ (judged)")]


def column(p: dict) -> str:
if p["task"] == "classification":
return p["format"]
return "itt" if p["task"] == "image_text_to_text" else p["task"]


def item_score(p: dict) -> float:
if p.get("needs_judge"):
return 1.0 if p.get("judge_correct") else 0.0
c = p.get("correct")
if isinstance(c, bool):
return 1.0 if c else 0.0
return float(p.get("acc", c) or 0.0)


def _mean(v):
return sum(v) / len(v) if len(v) else float("nan")


def boot_ci(vals, B: int = 10000, seed: int = 0, exact: bool = False) -> tuple[float, float]:
"""95% bootstrap CI of the mean. `exact`: the paper's pure-Python resampling (same numbers, slower)."""
if not len(vals):
return float("nan"), float("nan")
if exact:
rnd, n = random.Random(seed), len(vals)
ms = sorted(sum(rnd.choice(vals) for _ in range(n)) / n for _ in range(B))
return ms[int(0.025 * B)], ms[int(0.975 * B) - 1]
v = np.asarray(vals, float)
ms = np.sort(v[np.random.default_rng(seed).integers(0, len(v), (B, len(v)))].mean(1))
return float(ms[int(0.025 * B)]), float(ms[int(0.975 * B) - 1])


@dataclass
class RunScores:
"""Per-dataset mean scores of one run."""
dir: str
per: dict = field(default_factory=dict) # (col, dataset) -> mean score
ag: dict = field(default_factory=dict) # (format, ag_task, dataset) -> mean score (classification)
fuzzy: dict = field(default_factory=dict) # (ag_task, dataset) -> mean fuzzy-match score (OEQ)
itt_fmt: dict = field(default_factory=dict) # qa_format -> pooled mean over questions
pending_judge: int = 0

@classmethod
def load(cls, run_dir) -> "RunScores":
per, ag, fz, itt = (defaultdict(list) for _ in range(4))
pending = 0
with open(Path(run_dir) / "predictions.jsonl") as f:
for line in f:
p = json.loads(line)
s, k = item_score(p), column(p)
pending += bool(p.get("needs_judge") and p.get("judge_correct") is None)
per[(k, p["dataset"])].append(s)
if p["task"] == "classification":
ag[(k, p.get("ag_task"), p["dataset"])].append(s)
if k == "oeq":
fz[(p.get("ag_task"), p["dataset"])].append(1.0 if p.get("correct") else 0.0)
elif p["task"] == "image_text_to_text":
itt[p.get("qa_format")].append(s)
m = lambda d: {k: _mean(v) for k, v in d.items()} # noqa: E731
return cls(str(run_dir), m(per), m(ag), m(fz), m(itt), pending)


@dataclass
class Entry:
label: str
kind: str # model | yolo | chance
runs: list[RunScores]
meta: list[dict] # run_manifest.json (or run.json) of each run
cells: dict = field(default_factory=dict) # col -> (mean, lo, hi, n datasets), percent
ag: dict = field(default_factory=dict) # (format, ag_task) -> (mean, lo, hi, n)
fuzzy: dict = field(default_factory=dict) # ag_task -> mean, percent
itt_fmt: dict = field(default_factory=dict) # qa_format -> mean, percent
datasets: dict = field(default_factory=dict) # (col, dataset) -> mean over replicates, percent

@property
def replicates(self) -> int:
return len(self.runs)


def _cell(runs: list[RunScores], key_of, exact: bool) -> tuple:
keys = sorted({k for r in runs for k in key_of(r)})
vals = [100 * _mean([key_of(r)[k] for r in runs if k in key_of(r)]) for k in keys]
return (_mean(vals), *boot_ci(vals, exact=exact), len(vals)) if vals else (float("nan"),) * 3 + (0,)


def _meta(d: Path) -> dict:
for f in ("run_manifest.json", "run.json"):
if (d / f).exists():
return json.loads((d / f).read_text())
return {}


def _setting(meta: dict) -> tuple:
"""What makes runs one entry: the method and its settings, minus the sampling seed."""
m = dict(meta.get("method") or {})
m.pop("gen_seed", None)
m["body"] = {k: v for k, v in (m.get("body") or {}).items() if k != "seed"}
args = meta.get("benchmark") if "item_seed" not in meta else {"seed": meta.get("item_seed"), "mcqa": meta.get("mcqa")}
args = args or {}
return json.dumps(m, sort_keys=True, default=str), json.dumps({"seed": args.get("seed"), "mcqa": args.get("mcqa")}, sort_keys=True)


def run_dirs(paths) -> list[Path]:
out = []
for p in map(Path, paths):
dirs = [p] if (p / "predictions.jsonl").exists() else sorted(d.parent for d in p.glob("**/predictions.jsonl"))
out += [d for d in dirs if (d / "run.json").exists()]
return out


def entries(paths, labels: dict | None = None, exact: bool = False) -> list[Entry]:
"""Group the runs under `paths` into entries and aggregate them. `labels`: {method name: display label}."""
groups: dict[tuple, list[Path]] = defaultdict(list)
for d in run_dirs(paths):
meta = _meta(d)
groups[(str((meta.get("method") or {}).get("name", d.name)), *_setting(meta))].append(d)
names = defaultdict(list)
for key in groups:
names[key[0]].append(key)
out = []
for key, dirs in groups.items():
name = key[0]
kind = "chance" if name == "baseline/chance" else "yolo" if name.lower().startswith("yolo") else "model"
label = (labels or {}).get(name, name.split("/")[-1] if kind == "model" else name)
if len(names[name]) > 1: # one method in several settings
label += f" [{names[name].index(key) + 1}]"
runs = [RunScores.load(d) for d in dirs]
e = Entry(label, kind, runs, [_meta(d) for d in dirs])
for col, _ in COLS:
src = "oeq" if kind == "yolo" and col in ("mcqa_across", "mcqa_within") else col
e.cells[col] = _cell(runs, lambda r, s=src: {d: v for (c, d), v in r.per.items() if c == s}, exact)
for f, _ in CLS_FORMATS:
for a, _ in AG:
src = "oeq" if kind == "yolo" else f
e.ag[(f, a)] = _cell(runs, lambda r, s=src, a=a: {d: v for (c, g, d), v in r.ag.items() if c == s and g == a}, exact)
for a, _ in AG:
e.fuzzy[a] = _cell(runs, lambda r, a=a: {d: v for (g, d), v in r.fuzzy.items() if g == a}, exact)[0]
for q in sorted({q for r in runs for q in r.itt_fmt}):
e.itt_fmt[q] = 100 * _mean([r.itt_fmt[q] for r in runs if q in r.itt_fmt])
for k in sorted({k for r in runs for k in r.per}):
e.datasets[k] = 100 * _mean([r.per[k] for r in runs if k in r.per])
out.append(e)
order = {"model": 0, "yolo": 1, "chance": 2}
return sorted(out, key=lambda e: (order[e.kind], e.label.lower()))
132 changes: 132 additions & 0 deletions src/agbench/viz/figures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
"""The paper's result figures for any set of runs (matplotlib; uv sync --extra viz).

main_results(entries, "fig_main_results.png") accuracy per task, 95% CI over datasets; YOLO hatched; chance lines
agtask(entries, "fig_agtask.png") classification by agricultural task, per question format
"""

from pathlib import Path

from agbench.viz.aggregate import AG, CLS_FORMATS, COLS, Entry

# Categorical slots in fixed order (validated for colour-vision deficiency; contrast relief: legend + tables)
PALETTE = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300", "#6250d6", "#e34948"]
INK, MUTED, GRID = "#0b0b0b", "#52514e", "#e1e0d9"
YOLO_STYLE = {"facecolor": "#d9d9d9", "edgecolor": "#555555", "hatch": "////", "lw": 0.6}
MAX_MODELS = len(PALETTE)


def _plt():
try:
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
except ImportError as e:
raise SystemExit("figures need matplotlib: uv sync --extra viz") from e
plt.rcParams.update({"font.size": 9, "font.family": "sans-serif", "axes.edgecolor": MUTED, "axes.labelcolor": INK,
"xtick.color": MUTED, "ytick.color": MUTED, "text.color": INK})
return plt


def _split(entries: list[Entry]):
models = [e for e in entries if e.kind == "model"]
if len(models) > MAX_MODELS:
raise ValueError(f"{len(models)} models: a figure shows at most {MAX_MODELS} (pass fewer runs)")
return models, [e for e in entries if e.kind == "yolo"][:1], [e for e in entries if e.kind == "chance"][:1]


def _style(ax):
ax.yaxis.grid(True, color=GRID, lw=0.6)
ax.set_axisbelow(True)
for s in ("top", "right"):
ax.spines[s].set_visible(False)


def _err(cells):
return [[c[0] / 100 - c[1] / 100 for c in cells], [c[2] / 100 - c[0] / 100 for c in cells]]


ERR = {"elinewidth": 0.6, "capsize": 1.2, "ecolor": "#444444"}


def main_results(entries: list[Entry], path, cols=None) -> Path:
"""Accuracy per CV task (macro over datasets, 95% bootstrap CI): one bar per model, YOLO hatched (top-1 accuracy
in the classification columns), chance as a dashed line over each group."""
plt = _plt()
models, yolo, chance = _split(entries)
cols = [c for c in (cols or COLS) if any(e.cells[c[0]][3] for e in models + yolo)]
nb = len(models) + len(yolo)
w = 0.8 / max(nb, 1)
fig, ax = plt.subplots(figsize=(10, 4.6))
for i, e in enumerate(models + yolo):
js = [j for j, (k, _) in enumerate(cols) if e.cells[k][3]]
xs = [j + (i - nb / 2 + 0.5) * w for j in js]
cells = [e.cells[cols[j][0]] for j in js]
style = YOLO_STYLE if e.kind == "yolo" else {"color": PALETTE[i]}
label = e.label + (" (top-1 for classification)" if e.kind == "yolo" else "")
ax.bar(xs, [c[0] / 100 for c in cells], w * 0.92, label=label, yerr=_err(cells), error_kw=ERR, **style)
for e in chance:
for j, (k, _) in enumerate(cols):
if e.cells[k][3]:
ax.hlines(e.cells[k][0] / 100, j - 0.43, j + 0.43, colors="#222222", linestyles=[(0, (3, 2))], lw=1.1, zorder=5,
label="Chance (random answer)" if j == 0 else None)
n = {k: max((e.cells[k][3] for e in models + yolo), default=0) for k, _ in cols}
ax.set_xticks(range(len(cols)))
ax.set_xticklabels([f"{h}\n(n={n[k]})" for k, h in cols])
ax.set_ylabel("Accuracy (avg. across datasets)")
ax.set_xlabel("Task (n = number of datasets)")
ax.set_ylim(0, 1)
_style(ax)
h, lab = ax.get_legend_handles_labels()
k = [i for i, x in enumerate(lab) if x.startswith("Chance")] # chance last
h, lab = [h[i] for i in range(len(h)) if i not in k] + [h[i] for i in k], [lab[i] for i in range(len(lab)) if i not in k] + [lab[i] for i in k]
ncol = 3 if max(map(len, lab), default=0) > 30 else 4
fig.legend(h, lab, loc="lower center", ncol=ncol, frameon=False, fontsize=8)
fig.tight_layout(rect=(0, 0.06 + 0.045 * -(-len(lab) // ncol), 1, 1))
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
fig.savefig(path, dpi=200)
plt.close(fig)
return path


def agtask(entries: list[Entry], path) -> Path:
"""Classification accuracy by agricultural task, one panel per question format; OEQ panel also shows the
fuzzy-match score (hatched ghost bar, dark tick)."""
plt = _plt()
from matplotlib.lines import Line2D
from matplotlib.patches import Patch

models, yolo, _ = _split(entries)
ags = [(a, h) for a, h in AG if any(e.ag[(f, a)][3] for e in models + yolo for f, _ in CLS_FORMATS)]
nb = len(models) + len(yolo)
w = 0.8 / max(nb, 1)
fig, axes = plt.subplots(1, len(CLS_FORMATS), figsize=(10, 4.4), sharey=True)
for ax, (f, title) in zip(axes, CLS_FORMATS):
for i, e in enumerate(models + yolo):
xs = [j + (i - nb / 2 + 0.5) * w for j in range(len(ags))]
cells = [e.ag[(f, a)] for a, _ in ags]
style = YOLO_STYLE if e.kind == "yolo" else {"color": PALETTE[i]}
ax.bar(xs, [c[0] / 100 for c in cells], w * 0.92, zorder=2, label=e.label + (", top-1 (same in every panel)" if e.kind == "yolo" else ""), **style)
ax.errorbar(xs, [c[0] / 100 for c in cells], yerr=_err(cells), fmt="none", zorder=4, **{**ERR, "capsize": 1.0})
if f == "oeq" and e.kind == "model":
ys = [e.fuzzy[a] / 100 for a, _ in ags]
ax.bar(xs, ys, w * 0.92, facecolor="none", edgecolor=PALETTE[i], hatch="//////", lw=0, zorder=1)
ax.hlines(ys, [x - w / 2 for x in xs], [x + w / 2 for x in xs], color="#222222", lw=0.9, zorder=3)
ax.set_xticks(range(len(ags)))
ax.set_xticklabels([h.replace("/", "/\n") for _, h in ags])
ax.set_title(title if f != "oeq" else "OEQ (judged vs. fuzzy match)")
_style(ax)
axes[0].set_ylabel("Accuracy (avg. across datasets)")
axes[0].set_ylim(0, 1)
h, lab = axes[0].get_legend_handles_labels()
h += [Patch(facecolor="#888888"), (Patch(facecolor="none", edgecolor="#888888", hatch="//////", lw=0), Line2D([], [], color="#222222", lw=0.9))]
lab += ["OEQ: LLM judge", "OEQ: fuzzy match"]
ncol = 3 if max(map(len, lab), default=0) > 30 else 4
fig.legend(h, lab, loc="lower center", ncol=ncol, frameon=False, fontsize=7.5)
fig.tight_layout(rect=(0, 0.06 + 0.045 * -(-len(lab) // ncol), 1, 1))
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
fig.savefig(path, dpi=200)
plt.close(fig)
return path
Loading
Loading