File size: 8,178 Bytes
57c7939
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
207
208
209
210
211
212
213
214
215
216
#!/usr/bin/env python3
"""Score model outputs on the AudioSpan release.

Two modes (both stdlib-only, no external dependencies):
  accuracy — multiple choice on native audio, per-layer breakdown.
  chain    — first-error truncation over P->U->R chains on anchor audio.

For rubric scoring (which requires a judge model), use score_rubric.py.

The answer file carries only what the model produced, one record per
question: {"qa_id": ..., "answer": "..."}. For multiple choice the scorer
extracts the option letter from the answer text. Correct answers and
question profiles are joined in from metadata/<mode>/{S,M,L}.jsonl;
questions with no answer count as wrong.

Usage:
    python score.py --mode accuracy --input results/<model>/accuracy.jsonl
    python score.py --mode chain    --input results/<model>/chain.jsonl
"""

import argparse
import json
import logging
import re
import sys
from collections import defaultdict
from pathlib import Path

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)

RELEASE_ROOT = Path(__file__).resolve().parent.parent
TIERS = ("S", "M", "L")
LAYER_ORDER = ["perception", "understanding", "reasoning"]
LAYER_BY_CODE = {"P": "perception", "U": "understanding", "R": "reasoning"}


def load_questions(mode: str, data_root: Path) -> list[dict]:
    questions = []
    for tier in TIERS:
        path = data_root / "metadata" / mode / f"{tier}.jsonl"
        if not path.is_file():
            sys.exit(f"ERROR: metadata not found: {path}")
        with open(path, encoding="utf-8") as fh:
            questions.extend(json.loads(line) for line in fh if line.strip())
    return questions


def extract_option(answer) -> str | None:
    """Normalize a model answer to an option letter (A-D), or None."""
    if answer is None:
        return None
    if not isinstance(answer, str):
        answer = str(answer)
    text = answer.strip()
    if re.fullmatch(r"[A-Da-d]", text):
        return text.upper()
    m = re.search(r"\b(?:answer|option|choice)\s*(?:is|:)?\s*[\((]?([A-Da-d])[\))]?\b",
                  text, re.IGNORECASE)
    if m:
        return m.group(1).upper()
    m = re.search(r"[\((]([A-Da-d])[\))]", text)
    if m:
        return m.group(1).upper()
    m = re.fullmatch(r"([A-Da-d])[\.\)、::].*", text, re.DOTALL)
    if m:
        return m.group(1).upper()
    return None


def load_answers(path: str) -> dict[str, str]:
    """Map qa_id -> raw answer; later duplicates win."""
    preds: dict[str, str] = {}
    with open(path, encoding="utf-8", errors="replace") as fh:
        for lineno, line in enumerate(fh, 1):
            line = line.strip()
            if not line:
                continue
            try:
                rec = json.loads(line)
            except json.JSONDecodeError as e:
                logger.warning("Skipping bad line %d: %s", lineno, e)
                continue
            qa_id = rec.get("qa_id")
            if not qa_id:
                logger.warning("Skipping line %d: missing qa_id", lineno)
                continue
            preds[qa_id] = rec.get("answer")
    return preds


def score_accuracy(questions: list[dict], preds: dict[str, str]) -> dict:
    scored = []
    layer_stats: dict[str, dict[str, int]] = defaultdict(lambda: {"correct": 0, "total": 0})

    for q in questions:
        predicted = extract_option(preds.get(q["qa_id"]))
        is_correct = predicted is not None and predicted == q["correct_option"]
        layer = (q.get("question_profile") or {}).get("level", "unknown")
        layer_stats[layer]["total"] += 1
        if is_correct:
            layer_stats[layer]["correct"] += 1
        scored.append({"qa_id": q["qa_id"], "predicted": predicted, "correct": is_correct})

    total = len(scored)
    correct = sum(1 for s in scored if s["correct"])
    per_layer = {
        layer: {
            "accuracy": round(s["correct"] / s["total"] * 100, 2) if s["total"] else 0,
            "correct": s["correct"], "total": s["total"],
        }
        for layer, s in sorted(layer_stats.items())
    }
    return {
        "mode": "accuracy", "total": total, "correct": correct,
        "accuracy": round(correct / total * 100, 2) if total else 0,
        "per_layer": per_layer, "scored_records": scored,
    }


def score_chain(questions: list[dict], preds: dict[str, str]) -> dict:
    layer_correct: dict[str, int] = defaultdict(int)
    layer_total: dict[str, int] = defaultdict(int)
    chains: dict[str, dict[str, bool | None]] = defaultdict(lambda: {l: None for l in LAYER_ORDER})

    for q in questions:
        chain_key, layer_code = q["qa_id"].rsplit("_", 1)
        layer = LAYER_BY_CODE.get(layer_code)
        if layer not in LAYER_ORDER:
            continue
        predicted = extract_option(preds.get(q["qa_id"]))
        is_correct = predicted is not None and predicted == q["correct_option"]
        chains[chain_key][layer] = is_correct
        layer_total[layer] += 1
        if is_correct:
            layer_correct[layer] += 1

    complete = {cid: layers for cid, layers in chains.items()
                if all(v is not None for v in layers.values())}
    k = len(LAYER_ORDER)

    n_dist = defaultdict(int)
    scored = []
    group_scores = []
    for cid, layers in complete.items():
        n = 0
        for layer in LAYER_ORDER:
            if layers[layer]:
                n += 1
            else:
                break
        n_dist[n] += 1
        group_scores.append(n / k)
        scored.append({
            "chain_id": cid,
            "per_layer": {l: bool(layers[l]) for l in LAYER_ORDER},
            "n_correct": n,
            "correct": n == k,
            "chain_score": round(n / k * 100, 2),
        })

    chain_score = sum(group_scores) / len(group_scores) * 100 if group_scores else 0
    per_layer = {
        layer: {
            "accuracy": round(layer_correct[layer] / layer_total[layer] * 100, 2) if layer_total[layer] else 0,
            "correct": layer_correct[layer], "total": layer_total[layer],
        }
        for layer in LAYER_ORDER
    }
    return {
        "mode": "chain", "total_chains": len(complete),
        "chain_score": round(chain_score, 2),
        "per_layer": per_layer,
        "n_distribution": {str(n): cnt for n, cnt in sorted(n_dist.items())},
        "scored_records": scored,
    }


def main():
    parser = argparse.ArgumentParser(description="Score AudioSpan model outputs (accuracy/chain)")
    parser.add_argument("--input", required=True,
                        help="Prediction JSONL: {\"qa_id\": ..., \"answer\": \"...\"} per line")
    parser.add_argument("--mode", required=True, choices=["accuracy", "chain"])
    parser.add_argument("--data-root", type=Path, default=RELEASE_ROOT,
                        help="release root holding metadata/ (default: parent of evaluate/)")
    parser.add_argument("--output", help="Scored output path (default: <input>_scored.jsonl)")
    args = parser.parse_args()

    preds = load_answers(args.input)
    if not preds:
        print(f"ERROR: no valid answers in {args.input}", file=sys.stderr)
        sys.exit(1)

    questions = load_questions(args.mode, args.data_root.resolve())
    known = {q["qa_id"] for q in questions}
    unknown = sorted(set(preds) - known)
    if unknown:
        logger.warning("Ignoring %d unknown qa_id(s), e.g. %s", len(unknown), unknown[0])
    covered = sum(1 for q in questions if q["qa_id"] in preds)
    logger.info("Answers cover %d/%d questions (missing count as wrong)", covered, len(questions))

    summary = score_accuracy(questions, preds) if args.mode == "accuracy" else score_chain(questions, preds)

    out_path = args.output or args.input.replace(".jsonl", "_scored.jsonl")
    with open(out_path, "w", encoding="utf-8") as fh:
        for s in summary.get("scored_records", []):
            fh.write(json.dumps(s, ensure_ascii=False) + "\n")
    logger.info("Scored records: %s", out_path)

    print(json.dumps({k: v for k, v in summary.items() if k != "scored_records"},
                     indent=2, ensure_ascii=False))


if __name__ == "__main__":
    main()