"""Conservative final-answer extraction and scoring for the MATH-500 pilot. Scoring is deliberately three-way at its core: a confidently parsed answer can be marked correct or incorrect; answers that cannot be interpreted reliably remain unparsed. Completion extraction can additionally abstain when the output contains a malformed or explicitly ambiguous final answer. ``math_verify`` is used when installed, but runs in a child process so a hard wall-clock limit applies even on platforms where its own signal-based timeout is unavailable. Without it, the fallback only compares identical normalized answers or exact numeric scalars/fractions. """ from __future__ import annotations import importlib.util import json import re import subprocess import sys from dataclasses import dataclass from decimal import Decimal, InvalidOperation from fractions import Fraction from typing import Literal ExtractionStatus = Literal["parsed", "abstained", "unparsed"] ScoreStatus = Literal["correct", "incorrect", "abstained", "unparsed"] @dataclass(frozen=True) class ExtractionResult: status: ExtractionStatus answer: str | None = None reason: str = "" @dataclass(frozen=True) class ScoreResult: status: ScoreStatus predicted_answer: str | None expected_answer: str method: str reason: str = "" _BOX_OPEN = re.compile(r"\\(?:boxed|fbox)\s*\{") _FINAL_MARKER = re.compile( r"(?:\bfinal\s+answer\b|\banswer\b)\s*(?:is\s*)?(?:[:=]\s*)?", re.IGNORECASE, ) _REASONING_AFTER_ANSWER = re.compile( r"\b(?:because|since|therefore|thus|so|which\s+means|this\s+gives)\b", re.IGNORECASE, ) _MATH_VERIFY_WORKER = r''' import json, sys predicted, expected = json.load(sys.stdin) try: from math_verify import ExprExtractionConfig, LatexExtractionConfig, parse, verify except ImportError: print(json.dumps({"kind": "unavailable"})) raise SystemExit(0) try: extraction = [LatexExtractionConfig(), ExprExtractionConfig()] parse_options = { "extraction_config": extraction, "fallback_mode": "no_fallback", "extraction_mode": "first_match", "parsing_timeout": 0, "raise_on_error": True, } parsed_expected = parse(expected, **parse_options) parsed_predicted = parse(predicted, **parse_options) if not parsed_expected or not parsed_predicted: print(json.dumps({"kind": "unparsed"})) else: matches = verify( parsed_expected, parsed_predicted, timeout_seconds=0, raise_on_error=True, ) print(json.dumps({"kind": "verified", "matches": bool(matches)})) except BaseException as exc: print(json.dumps({"kind": "error", "error": type(exc).__name__})) ''' def _read_braced(text: str, open_brace: int) -> tuple[str | None, int]: """Read a balanced brace expression; return its contents and end offset.""" depth = 0 escaped = False for position in range(open_brace, len(text)): char = text[position] if escaped: escaped = False continue if char == "\\": escaped = True continue if char == "{": depth += 1 elif char == "}": depth -= 1 if depth == 0: return text[open_brace + 1 : position], position + 1 return None, len(text) def _boxed_answers(text: str) -> tuple[list[tuple[str, int, int]], bool]: found: list[tuple[str, int, int]] = [] malformed = False for match in _BOX_OPEN.finditer(text): open_brace = match.end() - 1 answer, end = _read_braced(text, open_brace) if answer is None: malformed = True continue found.append((answer.strip(), match.start(), end)) return found, malformed def _clean_final_candidate(candidate: str) -> str: candidate = candidate.strip() candidate = re.sub(r"^\*{1,2}|\*{1,2}$", "", candidate).strip() # A single terminal sentence mark is prose punctuation, not part of a value. candidate = re.sub(r"[.!?]+\s*$", "", candidate).strip() return candidate def _answer_from_marker(text: str) -> tuple[str | None, int | None, bool]: """Get the tail after the last explicit answer label, if it is self-contained.""" matches = list(_FINAL_MARKER.finditer(text)) if not matches: return None, None, False marker = matches[-1] candidate = _clean_final_candidate(text[marker.end() :]) if not candidate: return None, marker.start(), True if "\n" in candidate or _REASONING_AFTER_ANSWER.search(candidate): return None, marker.start(), True # Avoid treating a sentence that continues after the answer as a clean value. if len(candidate.split()) > 12: return None, marker.start(), True return candidate, marker.start(), False def extract_final_answer(completion: str) -> ExtractionResult: """Extract an explicitly marked final answer without guessing from reasoning. Accepted forms are a final ``\\boxed{...}``/``\\fbox{...}``, a terminal ``answer: ...`` or ``final answer is ...`` label, or a terminal ``#### ...`` line. A bare number or expression without one of these markers is unparsed. """ if not isinstance(completion, str) or not completion.strip(): return ExtractionResult("unparsed", reason="empty or non-text completion") boxes, malformed_box = _boxed_answers(completion) boxed: tuple[str, int, int] | None = boxes[-1] if boxes else None marker_answer, marker_position, malformed_marker = _answer_from_marker(completion) if malformed_box and (boxed is None or completion.rfind(r"\boxed") > boxed[1]): return ExtractionResult("abstained", reason="final boxed answer is incomplete") if malformed_marker and (marker_position is not None) and ( boxed is None or marker_position >= boxed[1] ): return ExtractionResult("abstained", reason="answer label is ambiguous or followed by explanation") # A later explicit answer label takes precedence over an earlier boxed value. if marker_answer is not None and (boxed is None or marker_position >= boxed[1]): if re.search(r"\b(?:or|either)\b", marker_answer, re.IGNORECASE): return ExtractionResult("abstained", reason="final answer presents alternatives") return ExtractionResult("parsed", marker_answer, "terminal answer label") if boxed is not None: answer, _, end = boxed if not answer: return ExtractionResult("abstained", reason="final boxed answer is empty") # In a construction such as ``\\boxed{1} or \\boxed{2}``, selecting one # answer would be arbitrary. Earlier boxed work by itself is not ambiguous. if len(boxes) > 1 and re.search( r"\b(?:or|either)\b", completion[boxes[-2][2] : boxes[-1][1]], re.IGNORECASE ): return ExtractionResult("abstained", reason="final answer presents alternatives") if re.search(r"\b(?:or|either)\b", completion[end : end + 80], re.IGNORECASE): return ExtractionResult("abstained", reason="boxed answer is followed by an alternative") return ExtractionResult("parsed", answer, "last complete boxed answer") # Support the common GSM-style final answer marker for generated pilot text. final_lines = re.findall(r"(?m)^\s*####\s*(.*?)\s*$", completion) if final_lines: answer = _clean_final_candidate(final_lines[-1]) if answer and not re.search(r"\b(?:or|either)\b", answer, re.IGNORECASE): return ExtractionResult("parsed", answer, "terminal #### answer line") return ExtractionResult("abstained", reason="final answer line is empty or ambiguous") return ExtractionResult("unparsed", reason="no explicit final-answer marker found") def _unwrap_math_delimiters(value: str) -> str: value = value.strip().replace("−", "-").replace("+", "+").replace("×", "*").replace("÷", "/") value = value.replace(r"\left", "").replace(r"\right", "") pairs = (("$", "$"), (r"\(", r"\)"), (r"\[", r"\]")) changed = True while changed: changed = False for left, right in pairs: if value.startswith(left) and value.endswith(right) and len(value) >= len(left) + len(right): value = value[len(left) : len(value) - len(right)].strip() changed = True return value _NUMBER = r"[+-]?(?:\d+(?:\.\d*)?|\.\d+)" _PLAIN_FRACTION = re.compile(rf"^\s*({_NUMBER})\s*/\s*({_NUMBER})\s*$") _LATEX_FRACTION = re.compile(rf"^\\(?:dfrac|tfrac|frac)\s*\{{\s*({_NUMBER})\s*\}}\s*\{{\s*({_NUMBER})\s*\}}$") _SIMPLE_NUMBER = re.compile(rf"^\s*({_NUMBER})\s*$") def _fraction_from_decimal(text: str) -> Fraction: if len(text) > 256: raise ValueError("numeric answer is too long") return Fraction(Decimal(text)) def _numeric_value(value: str) -> Fraction | None: value = _unwrap_math_delimiters(value) if len(value) > 512: return None match = _LATEX_FRACTION.fullmatch(value) if match: try: return _fraction_from_decimal(match.group(1)) / _fraction_from_decimal(match.group(2)) except (InvalidOperation, ValueError, ZeroDivisionError): return None match = _PLAIN_FRACTION.fullmatch(value) if match: try: return _fraction_from_decimal(match.group(1)) / _fraction_from_decimal(match.group(2)) except (InvalidOperation, ValueError, ZeroDivisionError): return None match = _SIMPLE_NUMBER.fullmatch(value) if match: try: return _fraction_from_decimal(match.group(1)) except (InvalidOperation, ValueError, ZeroDivisionError): return None return None def _canonical_literal(value: str) -> str: value = _unwrap_math_delimiters(value) value = re.sub(r"\s+", "", value) return value def _fallback_score(predicted: str, expected: str) -> tuple[ScoreStatus, str, str]: predicted_number = _numeric_value(predicted) expected_number = _numeric_value(expected) if predicted_number is not None and expected_number is not None: if predicted_number == expected_number: return "correct", "exact_numeric", "exact numeric values match" return "incorrect", "exact_numeric", "exact numeric values differ" if _canonical_literal(predicted) and _canonical_literal(predicted) == _canonical_literal(expected): return "correct", "exact_literal", "normalized answer text matches exactly" return "unparsed", "none", "unsupported answer form without math_verify" def _math_verify_available() -> bool: try: return importlib.util.find_spec("math_verify") is not None except (ImportError, ValueError): return False def _run_math_verify(predicted: str, expected: str, timeout_seconds: float) -> tuple[str, str] | None: if not _math_verify_available(): return None try: process = subprocess.Popen( [sys.executable, "-c", _MATH_VERIFY_WORKER], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, ) try: stdout, _ = process.communicate( input=json.dumps([predicted, expected]), timeout=timeout_seconds ) except subprocess.TimeoutExpired: process.kill() process.communicate() return "timeout", "math_verify exceeded the scoring timeout" if process.returncode != 0 or not stdout.strip(): return "error", "math_verify subprocess failed" payload = json.loads(stdout.strip().splitlines()[-1]) except (OSError, ValueError, json.JSONDecodeError): return "error", "math_verify subprocess could not be read" kind = payload.get("kind") if kind == "unavailable": return None if kind == "verified": return ("correct" if payload.get("matches") else "incorrect"), "math_verify equivalence check" if kind == "unparsed": return "unparsed", "math_verify could not parse one or both answers" if kind == "error": return "error", f"math_verify raised {payload.get('error', 'an error')}" return "error", "math_verify returned an unexpected result" def score_extracted_answer( predicted_answer: str, expected_answer: str, *, timeout_seconds: float = 3.0, ) -> ScoreResult: """Score two answer strings, abstaining whenever the comparison is unclear.""" if not isinstance(predicted_answer, str) or not predicted_answer.strip(): return ScoreResult("unparsed", None, str(expected_answer), "none", "prediction is empty or non-text") if not isinstance(expected_answer, str) or not expected_answer.strip(): return ScoreResult("unparsed", predicted_answer, str(expected_answer), "none", "reference answer is empty or non-text") if timeout_seconds <= 0: raise ValueError("timeout_seconds must be positive") verified = _run_math_verify(predicted_answer, expected_answer, timeout_seconds) if verified is not None: status, reason = verified if status == "correct": return ScoreResult("correct", predicted_answer, expected_answer, "math_verify", reason) if status == "incorrect": return ScoreResult("incorrect", predicted_answer, expected_answer, "math_verify", reason) if status == "timeout": return ScoreResult("unparsed", predicted_answer, expected_answer, "math_verify", reason) status, method, reason = _fallback_score(predicted_answer, expected_answer) if verified is not None and reason == "unsupported answer form without math_verify": reason = f"{verified[1]}; {reason}" return ScoreResult(status, predicted_answer, expected_answer, method, reason) def score_completion( completion: str, expected_answer: str, *, timeout_seconds: float = 3.0, ) -> ScoreResult: """Extract and score a generated completion against its reference answer.""" extracted = extract_final_answer(completion) if extracted.status == "unparsed": return ScoreResult("unparsed", None, str(expected_answer), "none", extracted.reason) if extracted.status == "abstained": return ScoreResult("abstained", None, str(expected_answer), "none", extracted.reason) result = score_extracted_answer( extracted.answer or "", expected_answer, timeout_seconds=timeout_seconds ) return ScoreResult( result.status, result.predicted_answer, result.expected_answer, result.method, result.reason, ) def score_answer( text: str, reference: str, *, timeout_seconds: float = 3.0, ) -> dict[str, object]: """Return a JSON-serializable scoring record for a generated completion. ``correct`` is ``True`` for a verified match, ``False`` for a confidently verified mismatch, and ``None`` when extraction or comparison is uncertain. """ result = score_completion(text, reference, timeout_seconds=timeout_seconds) correct: bool | None if result.status == "correct": correct = True elif result.status == "incorrect": correct = False else: correct = None return { "correct": correct, "status": result.status, "answer": result.predicted_answer, "reference": result.expected_answer, "method": result.method, "reason": result.reason, } __all__ = [ "ExtractionResult", "ScoreResult", "extract_final_answer", "score_answer", "score_completion", "score_extracted_answer", ]