File size: 8,175 Bytes
a06d854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#!/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()