File size: 4,229 Bytes
f10cac2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Keep only eval questions that BOTH king and challenger failed.

Reads scoring-results.jsonl. For each sample, a question is kept when every
parsed judge answered 0 for previous_king and 0 for challenger.

Usage:
  python filter_shared_fails.py evals/<eval_run_id>
  python filter_shared_fails.py evals/<eval_run_id>/scoring-results.jsonl
  python filter_shared_fails.py evals/<eval_run_id> --out shared-fails.jsonl
"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path


def load_records(path: Path) -> list[dict]:
    if path.is_dir():
        path = path / "scoring-results.jsonl"
    if not path.is_file():
        raise FileNotFoundError(f"no scoring-results.jsonl at {path}")
    return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]


def judge_by_side(record: dict) -> dict[str, dict]:
    out: dict[str, dict] = {}
    for result in record.get("judge_results") or []:
        if not result.get("parse_ok"):
            continue
        side = result.get("side")
        if side in ("previous_king", "challenger"):
            out[side] = result
    return out


def shared_fail_rows(record: dict) -> list[dict]:
    judges = judge_by_side(record)
    king = judges.get("previous_king")
    chal = judges.get("challenger")
    if not king or not chal:
        return []

    rows = []
    for question in record.get("questions") or []:
        qid = question.get("id")
        ka = (king.get("answers") or {}).get(qid)
        ca = (chal.get("answers") or {}).get(qid)
        if ka != "0" or ca != "0":
            continue
        rows.append(
            {
                "sample_id": record.get("sample_id"),
                "qid": qid,
                "tag": question.get("tag"),
                "weight": question.get("weight"),
                "requires": question.get("requires"),
                "step": question.get("step"),
                "text": question.get("text"),
                "example_bad": question.get("example_bad"),
                "evidence": question.get("evidence"),
                "king_answer": ka,
                "chal_answer": ca,
                "king_explanation": (king.get("explanations") or {}).get(qid),
                "chal_explanation": (chal.get("explanations") or {}).get(qid),
                "king_score": record.get("king_score"),
                "challenger_score": record.get("challenger_score"),
            }
        )
    return rows


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(
        description="Filter scoring-results.jsonl to questions both models answered 0."
    )
    parser.add_argument("path", type=Path, help="eval directory or scoring-results.jsonl")
    parser.add_argument(
        "--out",
        type=Path,
        help="output jsonl (default: <eval-dir>/shared-fails.jsonl)",
    )
    args = parser.parse_args(argv)

    source = args.path if args.path.is_file() else args.path / "scoring-results.jsonl"
    records = load_records(args.path)
    out_path = args.out or source.with_name("shared-fails.jsonl")

    kept = 0
    samples_with_fails = 0
    samples_scored = 0
    questions_total = 0
    out_path.parent.mkdir(parents=True, exist_ok=True)
    with out_path.open("w", encoding="utf-8") as handle:
        for record in records:
            questions_total += len(record.get("questions") or [])
            if record.get("scored"):
                samples_scored += 1
            rows = shared_fail_rows(record)
            if not rows:
                continue
            samples_with_fails += 1
            for row in rows:
                handle.write(json.dumps(row, ensure_ascii=False) + "\n")
                kept += 1

    print(f"scored samples     {samples_scored}/{len(records)}")
    print(f"questions          {questions_total}")
    print(f"shared fails       {kept}")
    print(f"samples with ≥1    {samples_with_fails}")
    print(f"wrote              {out_path}")
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except Exception as exc:  # noqa: BLE001
        print(f"error: {exc}", file=sys.stderr)
        raise SystemExit(1)