#!/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()