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
 
 
 
 
 
 
 
 
 
 
 
 
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
#!/usr/bin/env python3
"""Verifies the math answers in the dataset against the model outputs.
The dataset is a single row with the answer and predictions path is a jsonl file with single row of model output.

Example:

```
python notebooks/math_final_answer_verifier.py \
    --dataset-path.jsonl \
    --predictions-path model_output.json \
    --prediction-column model_output
```

Supported input formats: ``.jsonl``/``.ndjson``, ``.json``, ``.csv``,
``.tsv`` and ``.parquet`` (requires pandas).
"""

from __future__ import annotations

import argparse
import csv
import json
import math
import numbers
import re
import sys
import unicodedata
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable, Sequence


MODEL_OUTPUT_COL = "__model_output"
ROW_ID_COL = "__row_id"

# Regexes that help identify different final-answer formats.
BOXED_PATTERN = re.compile(r"\\boxed\s*\{([^}]*)\}")
HASH_PATTERN = re.compile(r"####\s*(.+)")
FINAL_ANSWER_PATTERNS = [
    re.compile(r"(?i)final answer(?: is)?\s*[:=\-]?\s*(.+)"),
    re.compile(r"(?i)final result(?: is)?\s*[:=\-]?\s*(.+)"),
    re.compile(r"(?i)the answer is\s*(.+)"),
    re.compile(r"(?i)answer(?: is)?\s*[:=\-]?\s*(.+)"),
    re.compile(r"(?i)ans(?: is)?\s*[:=\-]?\s*(.+)"),
    re.compile(r"(?i)result(?: is)?\s*[:=\-]?\s*(.+)"),
]


LATEX_TEXT_REPLACEMENTS = {
    "\\leq": "<=",
    "\\le": "<=",
    "\\geq": ">=",
    "\\ge": ">=",
    "\\neq": "!=",
    "\\times": "*",
    "\\cdot": "*",
    "\\div": "/",
    "\\pm": "+-",
    "\\pi": "pi",
    "\\Pi": "pi",
    "\\infty": "inf",
    "\\sqrt": "sqrt",
    "\\Gamma": "gamma",
    "\\Omega": "omega",
    "\\alpha": "alpha",
    "\\beta": "beta",
    "\\gamma": "gamma",
    "\\delta": "delta",
    "\\int": "integral",
    "\\log": "log",
    "\\ln": "ln",
}


SYMBOL_REPLACEMENTS = {
    "−": "-",
    "–": "-",
    "—": "-",
    "·": "*",
    "×": "*",
    "÷": "/",
    "π": "pi",
    "Π": "pi",
    "∞": "inf",
    "√": "sqrt",
    "≤": "<=",
    "≥": ">=",
    "≠": "!=",
    "∈": "in",
    "∉": "notin",
    "∪": "union",
    "∩": "intersect",
    "′": "'",
}


OUTPUT_KEYWORDS = {"final_answer", "answer", "prediction", "output", "result"}


@dataclass
class ComparisonResult:
    is_match: bool
    matched_candidate: str | None
    match_type: str | None
    normalized_gold: str | None
    normalized_candidate: str | None
    candidates: Sequence[str]


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Verify math final answers against model outputs")
    parser.add_argument("--dataset-path", required=True, help="Path to the JSONL/CSV/TSV/parquet dataset")
    parser.add_argument("--predictions-path", required=True, help="Path to the predictions file")
    parser.add_argument(
        "--final-answer-column",
        default="final_answer",
        help="Name of the column that holds the ground-truth final answer",
    )
    parser.add_argument(
        "--prediction-column",
        default="model_output",
        help="Name of the column that holds the model response",
    )
    parser.add_argument(
        "--id-column",
        default=None,
        help="Optional column used to align dataset rows with predictions (defaults to row order)",
    )
    parser.add_argument(
        "--dump-results",
        default=None,
        help="Optional path to write the per-row evaluation as JSONL",
    )
    parser.add_argument(
        "--dump-mismatches",
        default=None,
        help="Optional path to write only the mismatched rows as JSONL",
    )
    return parser.parse_args()


def load_records(path: Path) -> list[dict[str, Any]]:
    if not path.exists():
        raise FileNotFoundError(f"Missing file: {path}")
    ext = path.suffix.lower()
    if ext in {".jsonl", ".ndjson"}:
        rows: list[dict[str, Any]] = []
        with path.open(encoding="utf-8") as handle:
            for line in handle:
                line = line.strip()
                if not line:
                    continue
                obj = json.loads(line)
                if isinstance(obj, dict):
                    rows.append(obj)
                else:
                    rows.append({"value": obj})
        return rows
    if ext == ".json":
        content = json.loads(path.read_text(encoding="utf-8"))
        if isinstance(content, list):
            return [dict(row) if isinstance(row, dict) else {"value": row} for row in content]
        if isinstance(content, dict):
            return [content]
        raise ValueError(f"Unsupported JSON structure in {path}")
    if ext in {".csv", ".tsv"}:
        delimiter = "\t" if ext == ".tsv" else ","
        with path.open(encoding="utf-8", newline="") as handle:
            reader = csv.DictReader(handle, delimiter=delimiter)
            return [dict(row) for row in reader]
    if ext == ".parquet":
        try:
            import pandas as pd  # type: ignore
        except ImportError as exc:  # pragma: no cover - optional dependency
            raise ImportError("Reading parquet files requires pandas and pyarrow.") from exc
        return pd.read_parquet(path).to_dict(orient="records")
    raise ValueError(f"Unsupported file format: {path}")


def align_tables(
    dataset_rows: Sequence[dict[str, Any]],
    prediction_rows: Sequence[dict[str, Any]],
    *,
    id_column: str | None,
    prediction_column: str,
) -> tuple[list[dict[str, Any]], str]:
    if not prediction_rows:
        raise ValueError("Predictions file has no rows")

    if not any(prediction_column in row for row in prediction_rows):
        raise KeyError(f"Prediction column '{prediction_column}' not found in predictions")

    key_column = ROW_ID_COL

    if id_column:
        missing_ids = [idx for idx, row in enumerate(dataset_rows) if row.get(id_column) is None]
        if missing_ids:
            raise KeyError(
                f"Dataset rows missing '{id_column}' (first few indices: {missing_ids[:5]})"
            )
        prediction_index: dict[Any, dict[str, Any]] = {}
        for pred in prediction_rows:
            key = pred.get(id_column)
            if key is None:
                continue
            prediction_index[key] = pred

        aligned: list[dict[str, Any]] = []
        missing = 0
        for idx, row in enumerate(dataset_rows):
            merged = dict(row)
            merged[ROW_ID_COL] = idx
            pred_row = prediction_index.get(row[id_column])
            if pred_row is not None and prediction_column in pred_row:
                merged[MODEL_OUTPUT_COL] = pred_row.get(prediction_column)
            else:
                merged[MODEL_OUTPUT_COL] = None
                missing += 1
            aligned.append(merged)

        if missing:
            print(
                f"[warn] {missing} dataset rows did not have matching predictions by '{id_column}'",
                file=sys.stderr,
            )
        return aligned, id_column

    # Fall back to row order when an ID column is not provided.
    align_len = min(len(dataset_rows), len(prediction_rows))
    if align_len == 0:
        raise ValueError("No overlapping rows between dataset and predictions")
    if len(dataset_rows) != len(prediction_rows):
        shorter = "predictions" if len(prediction_rows) < len(dataset_rows) else "dataset"
        print(
            f"[warn] {shorter} has fewer rows (evaluating on {align_len} aligned samples)",
            file=sys.stderr,
        )
    trimmed: list[dict[str, Any]] = []
    for idx in range(align_len):
        merged = dict(dataset_rows[idx])
        merged[ROW_ID_COL] = idx
        merged[MODEL_OUTPUT_COL] = prediction_rows[idx].get(prediction_column)
        trimmed.append(merged)
    return trimmed, ROW_ID_COL


def normalize_answer_text(value: Any) -> str | None:
    if value is None:
        return None
    if isinstance(value, float) and math.isnan(value):
        return None
    text = str(value).strip()
    if not text:
        return None

    text = unicodedata.normalize("NFKC", text)
    text = strip_leading_label(text)
    for src, dst in SYMBOL_REPLACEMENTS.items():
        text = text.replace(src, dst)
    for src, dst in LATEX_TEXT_REPLACEMENTS.items():
        text = text.replace(src, dst)

    text = re.sub(r"\\text\s*\{([^}]*)\}", r"\1", text)
    text = re.sub(r"\\boxed\s*\{([^}]*)\}", r"\1", text)
    text = text.replace("\\", "")
    text = text.replace("{", "").replace("}", "")
    text = text.replace("\r", "\n")
    text = text.replace("\t", " ")
    text = re.sub(r"\s+", " ", text).strip()
    if not text:
        return None
    text = text.lower()
    text = text.replace(" ", "")
    return text


def strip_leading_label(text: str) -> str:
    candidate = text
    patterns = [
        re.compile(r"(?i)^\s*(?:the\s+)?final\s+answer\s*(?:is)?\s*[:=\-]?\s*"),
        re.compile(r"(?i)^\s*(?:the\s+)?answer\s*(?:is)?\s*[:=\-]?\s*"),
        re.compile(r"(?i)^\s*ans\s*(?:is)?\s*[:=\-]?\s*"),
        re.compile(r"(?i)^\s*(?:final\s+result|result)\s*(?:is)?\s*[:=\-]?\s*"),
    ]
    for pattern in patterns:
        stripped = pattern.sub("", candidate, count=1)
        if stripped != candidate:
            return stripped.strip()
    return candidate


def extract_candidate_answers(value: Any) -> list[str]:
    if value is None:
        return []
    if isinstance(value, (dict, list)):
        text = json.dumps(value, ensure_ascii=False)
    else:
        text = str(value)
    text = text.strip()
    if not text:
        return []

    candidates: list[str] = []

    candidates.extend(_maybe_extract_from_json(text))

    boxed_matches = BOXED_PATTERN.findall(text)
    for match in reversed(boxed_matches):
        stripped = match.strip()
        if stripped:
            candidates.append(stripped)

    hash_matches = HASH_PATTERN.findall(text)
    if hash_matches:
        candidates.append(hash_matches[-1].strip())

    for pattern in FINAL_ANSWER_PATTERNS:
        for match in pattern.finditer(text):
            snippet = match.group(1).strip()
            if snippet:
                candidates.append(snippet)

    equals_match = re.search(r"=\s*([^=\n]+)$", text)
    if equals_match:
        candidates.append(equals_match.group(1).strip())

    lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
    if lines:
        candidates.append(lines[-1])

    candidates.append(text)

    return _dedupe_preserving_order(candidates)


def _maybe_extract_from_json(text: str) -> list[str]:
    stripped = text.strip()
    if not stripped or stripped[0] not in "[{":
        return []
    try:
        payload = json.loads(stripped)
    except json.JSONDecodeError:
        return []

    values: list[str] = []

    def _collect(obj: Any) -> None:
        if isinstance(obj, dict):
            for key, val in obj.items():
                if isinstance(val, (str, int, float)) and key.lower() in OUTPUT_KEYWORDS:
                    values.append(str(val))
                elif isinstance(val, (dict, list)):
                    _collect(val)
        elif isinstance(obj, list):
            for item in obj:
                _collect(item)

    _collect(payload)
    return values


def _dedupe_preserving_order(items: Iterable[str]) -> list[str]:
    seen: set[str] = set()
    deduped: list[str] = []
    for item in items:
        if not item:
            continue
        if item in seen:
            continue
        seen.add(item)
        deduped.append(item)
    return deduped


def compare_answers(gold: str, prediction: str) -> ComparisonResult:
    normalized_gold = normalize_answer_text(gold)
    candidates = extract_candidate_answers(prediction)
    if not normalized_gold:
        return ComparisonResult(False, None, None, normalized_gold, None, candidates)

    for candidate in candidates:
        normalized_candidate = normalize_answer_text(candidate)
        if not normalized_candidate:
            continue
        if normalized_candidate == normalized_gold:
            return ComparisonResult(True, candidate.strip(), "exact", normalized_gold, normalized_candidate, candidates)
        if normalized_gold in normalized_candidate:
            return ComparisonResult(True, candidate.strip(), "substring_match", normalized_gold, normalized_candidate, candidates)

    return ComparisonResult(False, None, None, normalized_gold, None, candidates)


def evaluate_rows(
    records: Sequence[dict[str, Any]], *, final_answer_column: str, key_column: str
) -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    for idx, row in enumerate(records):
        gold = row.get(final_answer_column)
        prediction = row.get(MODEL_OUTPUT_COL)
        key = row.get(key_column, row.get(ROW_ID_COL, idx))

        gold_text = str(gold)
        has_prediction = not _is_missing(prediction)

        if has_prediction:
            comp = compare_answers(gold_text, str(prediction))
        else:
            comp = ComparisonResult(False, None, None, normalize_answer_text(gold_text), None, [])

        key_value: Any = key
        if isinstance(key_value, numbers.Integral):
            key_value = int(key_value)
        elif isinstance(key_value, numbers.Real) and float(key_value).is_integer():
            key_value = int(key_value)

        record = {
            "row_key_column": key_column,
            "row_key": key_value,
            "final_answer": gold_text,
            "model_output": str(prediction) if has_prediction else None,
            "has_prediction": has_prediction,
            "is_correct": has_prediction and comp.is_match,
            "match_type": comp.match_type if has_prediction else None,
            "matched_candidate": comp.matched_candidate,
            "first_candidate": comp.candidates[0] if comp.candidates else None,
            "candidate_count": len(comp.candidates),
            "normalized_final_answer": comp.normalized_gold,
            "normalized_candidate": comp.normalized_candidate,
        }

        if not has_prediction:
            record["failure_reason"] = "no_prediction"
        elif not comp.candidates:
            record["failure_reason"] = "no_candidate"
        elif not comp.is_match:
            record["failure_reason"] = "mismatch"
        else:
            record["failure_reason"] = None

        rows.append(record)
    return rows


def _is_missing(value: Any) -> bool:
    if value is None:
        return True
    if isinstance(value, float) and math.isnan(value):
        return True
    if isinstance(value, str) and not value.strip():
        return True
    return False


def write_jsonl(path: Path, rows: Sequence[dict[str, Any]]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8") as handle:
        for row in rows:
            handle.write(json.dumps(row, ensure_ascii=False) + "\n")


def main() -> None:
    args = parse_args()
    dataset_rows = load_records(Path(args.dataset_path))
    if not dataset_rows:
        raise ValueError("Dataset file is empty")
    if not any(args.final_answer_column in row for row in dataset_rows):
        raise KeyError(
            f"'{args.final_answer_column}' not found in dataset columns"
        )
    filtered_dataset = [
        row for row in dataset_rows if not _is_missing(row.get(args.final_answer_column))
    ]
    if not filtered_dataset:
        raise ValueError("Dataset does not contain rows with non-empty final answers")

    prediction_rows = load_records(Path(args.predictions_path))
    aligned_rows, key_column = align_tables(
        filtered_dataset,
        prediction_rows,
        id_column=args.id_column,
        prediction_column=args.prediction_column,
    )

    evaluation_rows = evaluate_rows(aligned_rows, final_answer_column=args.final_answer_column, key_column=key_column)

    total_rows = len(evaluation_rows)
    with_prediction = sum(1 for row in evaluation_rows if row["has_prediction"])
    matches = sum(1 for row in evaluation_rows if row["is_correct"])
    no_candidate = sum(1 for row in evaluation_rows if row["failure_reason"] == "no_candidate")
    no_prediction = sum(1 for row in evaluation_rows if row["failure_reason"] == "no_prediction")

    accuracy = matches / with_prediction if with_prediction else 0.0

    print(f"Evaluated rows: {total_rows}")
    print(f"Rows with predictions: {with_prediction}")
    print(f"Matches: {matches}")
    print(f"Accuracy: {accuracy:.2%}")
    if no_prediction:
        print(f"Rows without predictions: {no_prediction}")
    if no_candidate:
        print(f"Rows where no final answer was extractable: {no_candidate}")

    mismatches = [row for row in evaluation_rows if not row["is_correct"]]

    if args.dump_results:
        write_jsonl(Path(args.dump_results), evaluation_rows)
        print(f"Wrote detailed results to {args.dump_results}")
    if args.dump_mismatches:
        write_jsonl(Path(args.dump_mismatches), mismatches)
        print(f"Wrote mismatches to {args.dump_mismatches}")

    reward = "pass" if total_rows and matches == total_rows else "fail"
    print(f"Reward: {reward}")


if __name__ == "__main__":
    main()