DR-256 / tools /aggregate_eval.py
Shangy's picture
Publish DeepResearch-9K local-search frontier v1
a06d854 verified
Raw History Blame Contribute Delete
8.18 kB
#!/usr/bin/env python3
"""Merge DeepResearch evaluation shards and emit validated stratified metrics."""
from __future__ import annotations
import argparse
import hashlib
import json
import statistics
from collections import Counter
from pathlib import Path
from typing import Any, Callable
def read_jsonl(path: Path) -> list[dict[str, Any]]:
with path.open(encoding="utf-8") as handle:
return [json.loads(line) for line in handle if line.strip()]
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for block in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def score_metrics(rows: list[dict[str, Any]], key: str) -> dict[str, Any]:
scores = [float(row[key]) for row in rows if row.get(key) is not None]
return {
"questions": len(rows),
"scored": len(scores),
"correct": sum(scores),
"accuracy": statistics.fmean(scores) if scores else None,
}
def grouped_metrics(
rows: list[dict[str, Any]],
key: str,
group: Callable[[dict[str, Any]], Any],
) -> dict[str, Any]:
names = sorted({str(group(row)) for row in rows})
return {
name: score_metrics([row for row in rows if str(group(row)) == name], key)
for name in names
}
def difficulty_teacher(row: dict[str, Any]) -> str:
return f"D{row.get('difficulty')}/teacher_{str(row.get('teacher_correct')).lower()}"
def benchmark_cell(row: dict[str, Any]) -> str:
bucket = (row.get("benchmark") or {}).get("selection_bucket")
return f"{difficulty_teacher(row)}/{bucket}"
def calibration_tier(row: dict[str, Any]) -> str:
return str((row.get("benchmark") or {}).get("calibration_tier") or "unspecified")
def tier_bucket(row: dict[str, Any]) -> str:
benchmark = row.get("benchmark") or {}
return f"{calibration_tier(row)}/{benchmark.get('selection_bucket')}"
def build_summary(
rows: list[dict[str, Any]],
*,
input_files: list[Path],
expected_data: Path | None,
model_label: str,
) -> dict[str, Any]:
turns = [int(row["num_turns"]) for row in rows if row.get("num_turns") is not None]
active = [float(row["active_seconds"]) for row in rows if row.get("active_seconds") is not None]
result: dict[str, Any] = {
"questions": len(rows),
"model_label": model_label or None,
"input_files": [str(path) for path in input_files],
"expected_data": str(expected_data) if expected_data else None,
"expected_data_sha256": sha256(expected_data) if expected_data else None,
"agent_errors": sum(bool(row.get("error")) for row in rows),
"finish_rate": (
sum(row.get("stop_reason") == "finish" 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,
"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": dict(sorted(Counter(row.get("stop_reason") or "missing" for row in rows).items())),
"local_em": score_metrics(rows, "local_em"),
}
for score_key in ("judge_score",):
if any(row.get(score_key) is not None for row in rows):
result[score_key] = score_metrics(rows, score_key)
result[f"{score_key}_by_difficulty"] = grouped_metrics(
rows, score_key, lambda row: row.get("difficulty")
)
result[f"{score_key}_by_teacher_correct"] = grouped_metrics(
rows, score_key, lambda row: row.get("teacher_correct")
)
result[f"{score_key}_by_difficulty_teacher"] = grouped_metrics(
rows, score_key, difficulty_teacher
)
result[f"{score_key}_by_selection_bucket"] = grouped_metrics(
rows,
score_key,
lambda row: (row.get("benchmark") or {}).get("selection_bucket"),
)
result[f"{score_key}_by_calibration_tier"] = grouped_metrics(
rows, score_key, calibration_tier
)
result[f"{score_key}_by_calibration_tier_selection_bucket"] = grouped_metrics(
rows, score_key, tier_bucket
)
result[f"{score_key}_by_cell"] = grouped_metrics(
rows, score_key, benchmark_cell
)
result["local_em_by_difficulty"] = grouped_metrics(
rows, "local_em", lambda row: row.get("difficulty")
)
result["local_em_by_teacher_correct"] = grouped_metrics(
rows, "local_em", lambda row: row.get("teacher_correct")
)
result["local_em_by_difficulty_teacher"] = grouped_metrics(
rows, "local_em", difficulty_teacher
)
result["local_em_by_selection_bucket"] = grouped_metrics(
rows,
"local_em",
lambda row: (row.get("benchmark") or {}).get("selection_bucket"),
)
result["local_em_by_calibration_tier"] = grouped_metrics(
rows, "local_em", calibration_tier
)
result["local_em_by_calibration_tier_selection_bucket"] = grouped_metrics(
rows, "local_em", tier_bucket
)
result["local_em_by_cell"] = grouped_metrics(rows, "local_em", benchmark_cell)
result["judge_errors"] = sum(bool(row.get("judge_error")) for row in rows)
result["judge_remote_calls"] = sum(bool(row.get("judge_remote_called")) for row in rows)
return result
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--inputs", nargs="+", type=Path, required=True)
parser.add_argument("--out", type=Path, required=True)
parser.add_argument("--expected-data", type=Path)
parser.add_argument("--model-label", default="")
args = parser.parse_args()
rows = [row for path in args.inputs for row in read_jsonl(path)]
if not rows:
raise ValueError("no evaluation rows found")
indexes = [int(row["index"]) for row in rows]
duplicate_indexes = [index for index, count in Counter(indexes).items() if count > 1]
if duplicate_indexes:
raise ValueError(f"duplicate result indexes: {sorted(duplicate_indexes)}")
rows.sort(key=lambda row: int(row["index"]))
if args.expected_data:
expected = read_jsonl(args.expected_data)
expected_indexes = list(range(len(expected)))
if indexes := sorted(indexes):
if indexes != expected_indexes:
missing = sorted(set(expected_indexes) - set(indexes))
extra = sorted(set(indexes) - set(expected_indexes))
raise ValueError(f"result coverage mismatch: missing={missing} extra={extra}")
for index, (row, record) in enumerate(zip(rows, expected, strict=True)):
metadata = record.get("metadata") or {}
expected_qid = metadata.get("qid") or metadata.get("manifest_qid")
actual_qid = row.get("qid") or row.get("manifest_qid")
if actual_qid != expected_qid:
raise ValueError(
f"qid mismatch at index={index}: actual={actual_qid!r} expected={expected_qid!r}"
)
args.out.parent.mkdir(parents=True, exist_ok=True)
with args.out.open("w", encoding="utf-8") as handle:
for row in rows:
handle.write(json.dumps(row, ensure_ascii=False) + "\n")
summary = build_summary(
rows,
input_files=args.inputs,
expected_data=args.expected_data,
model_label=args.model_label,
)
summary["output"] = str(args.out)
summary["output_sha256"] = sha256(args.out)
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",
encoding="utf-8",
)
print("FINAL_AGGREGATE " + json.dumps(summary, sort_keys=True))
if __name__ == "__main__":
main()