Download code/pocket_math/grading.py from Palaestra/pocket-math-ops: direct link, hf CLI and curl.
- Browser
- Download file 9.59 kB
-
https://huggingface.co/datasets/Palaestra/pocket-math-ops/resolve/main/code/pocket_math/grading.py
- Command line
-
hf download hf://datasets/Palaestra/pocket-math-ops/code/pocket_math/grading.py
-
curl -L -o grading.py https://huggingface.co/datasets/Palaestra/pocket-math-ops/resolve/main/code/pocket_math/grading.py
9.59 kB
| """Final-answer checking: the last \\boxed{} of a response against a gold answer. | |
| Cheap string and number rules decide most pairs in the calling process. The rest go to | |
| Math-Verify in worker processes that are killed when they overrun, so a slow sympy case | |
| returns False instead of hanging, on Windows and Linux alike. | |
| """ | |
| from __future__ import annotations | |
| import logging | |
| import multiprocessing as mp | |
| import re | |
| import threading | |
| import time | |
| from fractions import Fraction | |
| from multiprocessing.connection import wait | |
| _BOX = re.compile(r"\\(?:boxed|fbox)") | |
| _BOX_PREFIX = re.compile(r"\\(?:boxed|fbox)\s*") | |
| _SPACING = re.compile(r"\\left(?![A-Za-z])|\\right(?![A-Za-z])|\\displaystyle|(?<!\\)\\[,;: ]") | |
| _NEGATIVE_SPACE = re.compile(r"(?<!\\)\\!") | |
| _DEGREES = re.compile(r"\^\s*\{\s*\\circ\s*\}|\^\s*\\circ|°") | |
| _FACTORIAL_POWER = re.compile(r"(\d+)!\s*\^") | |
| _TEXT = re.compile(r"\\(?:text|textbf|textrm|mathrm|mbox)\s*\{([^{}]*)\}") | |
| _DECIMAL = re.compile(r"[+-]?\d+(?:\.\d+)?") | |
| _WORDS = re.compile(r"[A-Za-z]+(?: [A-Za-z]+)*") | |
| _STARTUP_SECONDS = 180.0 | |
| def extract_boxed(text: str) -> str | None: | |
| """Content of the last well-formed \\boxed{...} or \\fbox{...} (nested braces allowed), or of | |
| a trailing "\\boxed 5". None if there is none.""" | |
| for m in reversed(list(_BOX.finditer(text))): | |
| content = _box_content(text, m.end()) | |
| if content is not None: | |
| return content.strip() | |
| return None | |
| def _box_content(text: str, i: int) -> str | None: | |
| j = i | |
| while j < len(text) and text[j].isspace(): | |
| j += 1 | |
| if j < len(text) and text[j] == "{": | |
| end = _closing_brace(text, j) | |
| return None if end is None else text[j + 1 : end] | |
| if j > i: | |
| m = re.match(r"[^\s$]+", text[j:]) | |
| return m.group(0) if m else None | |
| return None | |
| def _closing_brace(text: str, start: int) -> int | None: | |
| depth = 0 | |
| k = start | |
| while k < len(text): | |
| c = text[k] | |
| if c == "\\": | |
| k += 2 | |
| continue | |
| if c == "{": | |
| depth += 1 | |
| elif c == "}": | |
| depth -= 1 | |
| if depth == 0: | |
| return k | |
| k += 1 | |
| return None | |
| def _unbox(s: str) -> str: | |
| while (m := _BOX_PREFIX.match(s)) and s[m.end() : m.end() + 1] == "{": | |
| end = _closing_brace(s, m.end()) | |
| if end != len(s) - 1: | |
| break | |
| s = s[m.end() + 1 : end].strip() | |
| return s | |
| def _clean(s: str) -> str: | |
| s = _unbox(s.strip()).strip("$ ").rstrip(".").strip() | |
| s = s.replace("\\dfrac", "\\frac").replace("\\tfrac", "\\frac") | |
| # Deleted, not spaced: "10,\!000" must stay one number, not become the list "10, 000". | |
| s = _NEGATIVE_SPACE.sub("", s) | |
| s = _SPACING.sub(" ", s) | |
| s = _DEGREES.sub("", s) | |
| # latex2sympy cannot parse "100!^{2}"; it needs "(100!)^{2}". | |
| s = _FACTORIAL_POWER.sub(r"(\1!)^", s) | |
| return s.strip() | |
| def _key(s: str) -> str: | |
| return re.sub(r"\s+", "", s) | |
| def _number(s: str) -> Fraction | None: | |
| if len(s) <= 1000 and _DECIMAL.fullmatch(s): | |
| return Fraction(s) | |
| return None | |
| def _words(s: str) -> str | None: | |
| s = " ".join(_TEXT.sub(r"\1", s).split()) | |
| return s.casefold() if len(s) >= 2 and _WORDS.fullmatch(s) else None | |
| def _fast(gold: str, pred: str | None) -> bool | None: | |
| """True/False when cheap rules settle the pair, None when Math-Verify must decide.""" | |
| if not gold or not pred: | |
| return False | |
| if _key(gold) == _key(pred): | |
| return True | |
| a, b = _number(gold), _number(pred) | |
| if a is not None and b is not None: | |
| return a == b | |
| # Math-Verify reads a bare word as a product of one-letter symbols, so "Alice" would equal "Alcie". | |
| a, b = _words(gold), _words(pred) | |
| if a is not None and b is not None: | |
| return a == b | |
| return None | |
| def _serve(conn) -> None: | |
| # Math-Verify and sympy are imported only here, keeping them out of the caller's process. | |
| from math_verify import LatexExtractionConfig, parse, verify | |
| from sympy import Basic, MatrixBase | |
| logging.getLogger("math_verify").setLevel(logging.CRITICAL) | |
| config = (LatexExtractionConfig(boxed_match_priority=0),) | |
| def parsed(s: str) -> list: | |
| return parse("\\boxed{" + s + "}", extraction_config=config, parsing_timeout=None) | |
| def equal(gold: str, pred: str, symmetric: bool) -> bool: | |
| g, p = parsed(gold), parsed(pred) | |
| if not g or not p: | |
| return False | |
| return verify(g, p, timeout_seconds=None) or (symmetric and verify(p, g, timeout_seconds=None)) | |
| def parses(s: str) -> bool: | |
| return any(isinstance(x, (Basic, MatrixBase)) for x in parsed(s)) | |
| ops = {"equal": equal, "parses": parses} | |
| conn.send("ready") | |
| while True: | |
| try: | |
| op, args = conn.recv() | |
| except (EOFError, OSError): | |
| return | |
| try: | |
| result = bool(ops[op](*args)) | |
| except Exception: | |
| result = False | |
| conn.send(result) | |
| class _Worker: | |
| def __init__(self) -> None: | |
| ctx = mp.get_context("spawn") | |
| self.conn, child = ctx.Pipe() | |
| self.proc = ctx.Process(target=_serve, args=(child,), daemon=True) | |
| self.proc.start() | |
| child.close() | |
| self.born = time.monotonic() | |
| self.ready = False | |
| def stop(self) -> None: | |
| self.proc.kill() | |
| self.proc.join() | |
| self.conn.close() | |
| _WORKERS: list[_Worker] = [] | |
| _LOCK = threading.Lock() | |
| def _replace(k: int) -> None: | |
| _WORKERS[k].stop() | |
| _WORKERS[k] = _Worker() | |
| def _run(jobs: list[tuple[str, tuple]], workers: int, timeout: float) -> list[bool]: | |
| """Run worker ops in order; a job that overruns `timeout` seconds is killed and counts False.""" | |
| results = [False] * len(jobs) | |
| if not jobs: | |
| return results | |
| n = max(1, min(workers, len(jobs))) | |
| with _LOCK: | |
| while len(_WORKERS) < n: | |
| _WORKERS.append(_Worker()) | |
| queue = list(reversed(range(len(jobs)))) | |
| busy: dict[int, tuple[int, float]] = {} | |
| try: | |
| while queue or busy: | |
| _step(jobs, results, queue, busy, n, timeout) | |
| finally: | |
| # A worker left mid-job would hand its stale answer to the next caller. | |
| for k in busy: | |
| _replace(k) | |
| return results | |
| def _step(jobs: list, results: list[bool], queue: list[int], busy: dict[int, tuple[int, float]], n: int, | |
| timeout: float) -> None: | |
| for k in range(n): | |
| if _WORKERS[k].ready and k not in busy and queue: | |
| i = queue.pop() | |
| _WORKERS[k].conn.send(jobs[i]) | |
| busy[k] = (i, time.monotonic() + timeout) | |
| watched = [k for k in range(n) if k in busy or not _WORKERS[k].ready] | |
| deadline = min([d for _, d in busy.values()] | |
| + [_WORKERS[k].born + _STARTUP_SECONDS for k in watched if not _WORKERS[k].ready]) | |
| ready = wait([_WORKERS[k].conn for k in watched], max(0.0, deadline - time.monotonic())) | |
| for k in watched: | |
| w = _WORKERS[k] | |
| if w.conn not in ready: | |
| continue | |
| try: | |
| msg = w.conn.recv() | |
| except (EOFError, OSError): | |
| if not w.ready: | |
| raise RuntimeError("grading worker died on startup; is math-verify installed?") from None | |
| del busy[k] | |
| _replace(k) | |
| continue | |
| if w.ready: | |
| i, _ = busy.pop(k) | |
| results[i] = msg | |
| else: | |
| w.ready = True | |
| now = time.monotonic() | |
| for k, (_, d) in list(busy.items()): | |
| if now >= d: | |
| del busy[k] | |
| _replace(k) | |
| if any(not _WORKERS[k].ready and now >= _WORKERS[k].born + _STARTUP_SECONDS for k in range(n)): | |
| raise RuntimeError("grading worker did not start in time") | |
| def _equal_many(pairs: list[tuple[str, str | None]], symmetric: bool, workers: int, timeout: float) -> list[bool]: | |
| cleaned = [(_clean(a), None if b is None else _clean(b)) for a, b in pairs] | |
| results = [_fast(a, b) for a, b in cleaned] | |
| slow = [i for i, r in enumerate(results) if r is None] | |
| verdicts = _run([("equal", (*cleaned[i], symmetric)) for i in slow], workers, timeout) | |
| for i, v in zip(slow, verdicts, strict=True): | |
| results[i] = v | |
| return [bool(r) for r in results] | |
| def grade_many(pairs: list[tuple[str, str]], workers: int = 4, timeout: float = 5.0) -> list[bool]: | |
| """grade() over (response, gold) pairs, in order. `timeout` applies to each pair.""" | |
| return _equal_many([(gold, extract_boxed(response)) for response, gold in pairs], False, workers, timeout) | |
| def grade(response: str, gold: str, timeout: float = 5.0) -> bool: | |
| """True iff the last boxed answer in `response` equals `gold` mathematically.""" | |
| return grade_many([(response, gold)], workers=1, timeout=timeout)[0] | |
| def same_answer(a: str, b: str, timeout: float = 5.0) -> bool: | |
| """Whether two extracted answers are equivalent, checked in both directions (for vote clustering).""" | |
| return _equal_many([(a, b)], True, workers=1, timeout=timeout)[0] | |
| def parseable(answers: list[str], workers: int = 4, timeout: float = 5.0) -> list[bool]: | |
| """Whether Math-Verify turns each answer into a sympy object, so equivalent forms can match it.""" | |
| return _run([("parses", (_clean(a),)) for a in answers], workers, timeout) | |