File size: 8,290 Bytes
f8fa087
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
"""Evaluate model predictions on VoxParadox.

Usage:
    python eval.py --predictions <preds.jsonl>
    python eval.py --predictions <preds.jsonl> --dataset voxparadox.json --report report.json

Predictions file format (JSONL, one JSON object per line):
    {"id": "age_prediction__0", "response": "Elderly adult"}

The `response` field is the raw model output string. The script parses it into
one of the four MCQ choices (A/B/C/D) using letter-extraction heuristics with a
choice-text fallback, then scores it against:

  * GT Accuracy -- match rate against `answer_gt`.
  * Adversarial-Label Agreement (ALA) -- match rate against any string in
    `adversarial_labels` (the transcript-implied labels).

Both metrics are reported per task and overall (macro = micro since each task
has exactly 200 examples).
"""

import argparse
import json
import os
import re
import unicodedata
from collections import defaultdict

# ---------- Response parsing ----------

MAX_TAIL_LINES = 2
MAX_TAIL_CHARS = 1000


def _nfkc(s):
    return unicodedata.normalize("NFKC", s or "")


def _norm(s):
    s = _nfkc(str(s)).casefold().replace("–", "-").replace("—", "-")
    return re.sub(r"\s+", " ", s).strip()


def _tail(text):
    text = _nfkc(text).replace("\r\n", "\n").replace("\r", "\n")
    lines = [ln.strip() for ln in text.split("\n") if ln.strip()]
    out = "\n".join(lines[-MAX_TAIL_LINES:]) if lines else text.strip()
    return out[-MAX_TAIL_CHARS:] if len(out) > MAX_TAIL_CHARS else out


def get_choices(item):
    return {L: str(item.get(f"choice_{L.lower()}", "")) for L in "ABCD"}


def _parse_choice_letter(response):
    """Extract an A/B/C/D letter from the response tail.

    First tries to match the entire last line as a single letter (possibly
    with brackets/punctuation), e.g. "A", "(B)", "C." -- this is the most
    confident signal. If that fails, scans the tail for any isolated A/B/C/D
    mention not embedded inside a longer word, and returns the LAST such
    occurrence (handles outputs like "I think the answer is B.").
    """
    if not response:
        return None
    tail = _tail(response)
    lines = [ln.strip() for ln in tail.split("\n") if ln.strip()]
    last = lines[-1] if lines else tail.strip()
    m = re.match(r"(?i)^[\(\[\{]?\s*([ABCD])\s*[\)\]\}]?\s*[,.;:!?\-–—]*\s*$", last)
    if m:
        return m.group(1).upper()
    rx = re.compile(r"(?i)(?<![A-Za-z0-9])[\(\[\{]?\s*([ABCD])\s*[\)\]\}]?\s*[,.;:!?\-–—]*\s*(?=$|\s)")
    ms = list(rx.finditer(tail))
    if ms:
        return ms[-1].group(1).upper()
    return None


def _parse_choice_by_content(response, choices):
    """Fallback parser: match by choice text appearing in the response tail.

    Picks the choice whose normalized text appears LATEST in the tail,
    ranked by `rfind` position. This mirrors the matching used to produce
    the paper's reported numbers, including the known caveat that overlapping
    choice text (e.g., "male" inside "female") is decided by position alone.
    """
    if not response:
        return None
    tail_n = _norm(_tail(response))
    tail_n_sp = tail_n.replace("-", " ")
    best_L, best_pos = None, -1
    for L, txt in choices.items():
        txt_n = _norm(txt)
        if not txt_n:
            continue
        txt_n_sp = txt_n.replace("-", " ")
        for t, hay in [(txt_n, tail_n), (txt_n_sp, tail_n_sp)]:
            pos = hay.rfind(t)
            if pos > best_pos:
                best_pos = pos
                best_L = L
    return best_L if best_pos >= 0 else None


def parse_response(response, item):
    """Map a model response to one of A/B/C/D.

    Letter-first: if the response contains an isolated A/B/C/D mention, use
    it. Otherwise fall back to matching the choice text in the response tail.
    This matches the parsing semantics used to produce the paper's reported
    numbers, so results from this script are directly comparable.
    """
    L = _parse_choice_letter(response)
    if L is not None:
        return L
    return _parse_choice_by_content(response, get_choices(item))


# ---------- Label resolution ----------

def text_to_letter(text, choices):
    if not text:
        return None
    if text.upper() in {"A", "B", "C", "D"}:
        return text.upper()
    n = _norm(text)
    for L, t in choices.items():
        if _norm(t) == n:
            return L
    return None


def gt_letter(item):
    return text_to_letter(item.get("answer_gt", ""), get_choices(item))


def adv_letters(item):
    choices = get_choices(item)
    out = set()
    for s in item.get("adversarial_labels", []) or []:
        L = text_to_letter(s, choices)
        if L:
            out.add(L)
    return out


# ---------- Evaluation ----------

def evaluate(dataset, predictions):
    pred_map = {p["id"]: p.get("response", "") for p in predictions}
    gt_correct = defaultdict(int)
    adv_correct = defaultdict(int)
    total = defaultdict(int)
    missing = 0
    parse_fail = 0
    for item in dataset:
        task = item["task_name"]
        total[task] += 1
        resp = pred_map.get(item["id"])
        if resp is None:
            missing += 1
            continue
        pred = parse_response(resp, item)
        if pred is None:
            parse_fail += 1
            continue
        gt = gt_letter(item)
        adv = adv_letters(item)
        if gt and pred == gt:
            gt_correct[task] += 1
        if pred in adv:
            adv_correct[task] += 1
    return dict(gt_correct), dict(adv_correct), dict(total), missing, parse_fail


def main():
    ap = argparse.ArgumentParser(description="Evaluate model predictions on VoxParadox.")
    ap.add_argument("--predictions", required=True, help="Path to predictions JSONL file.")
    ap.add_argument("--dataset", default=os.path.join(os.path.dirname(__file__), "voxparadox.json"),
                    help="Path to voxparadox.json (default: alongside this script).")
    ap.add_argument("--report", default=None, help="Optional path to write a JSON report.")
    args = ap.parse_args()

    with open(args.dataset) as f:
        dataset = json.load(f)
    predictions = []
    with open(args.predictions) as f:
        for ln in f:
            ln = ln.strip()
            if not ln:
                continue
            predictions.append(json.loads(ln))

    gt_c, adv_c, total, missing, parse_fail = evaluate(dataset, predictions)

    tasks = sorted(total.keys())
    n_total = sum(total.values())
    sum_gt = sum(gt_c.get(t, 0) for t in tasks)
    sum_adv = sum(adv_c.get(t, 0) for t in tasks)

    print(f"VoxParadox Evaluation")
    print(f"  Dataset:     {n_total} examples across {len(tasks)} tasks")
    print(f"  Predictions: {len(predictions)} loaded "
          f"(missing: {missing}, parse-failed: {parse_fail})")
    print()
    print(f"{'Task':<32} {'N':>5} {'GT Acc':>9} {'ALA':>9}")
    print("-" * 58)
    for t in tasks:
        n = total[t]
        gt = 100.0 * gt_c.get(t, 0) / n if n else 0
        ala = 100.0 * adv_c.get(t, 0) / n if n else 0
        print(f"{t:<32} {n:>5} {gt:>8.2f}% {ala:>8.2f}%")
    print("-" * 58)
    overall_gt = 100.0 * sum_gt / n_total if n_total else 0
    overall_ala = 100.0 * sum_adv / n_total if n_total else 0
    print(f"{'Overall':<32} {n_total:>5} {overall_gt:>8.2f}% {overall_ala:>8.2f}%")

    if args.report:
        report = {
            "dataset": os.path.abspath(args.dataset),
            "predictions": os.path.abspath(args.predictions),
            "n_examples": n_total,
            "n_predictions": len(predictions),
            "n_missing": missing,
            "n_parse_failed": parse_fail,
            "overall": {"gt_acc": overall_gt, "ala": overall_ala},
            "per_task": {
                t: {
                    "n": total[t],
                    "gt_correct": gt_c.get(t, 0),
                    "adv_correct": adv_c.get(t, 0),
                    "gt_acc": 100.0 * gt_c.get(t, 0) / total[t] if total[t] else 0,
                    "ala": 100.0 * adv_c.get(t, 0) / total[t] if total[t] else 0,
                }
                for t in tasks
            },
        }
        with open(args.report, "w") as f:
            json.dump(report, f, indent=2)
        print(f"\n[report] {args.report}")


if __name__ == "__main__":
    main()