"""MathVision (MATH-V) prompt and answer scoring for the seed-variance study. The system prompt is the one shipped with the pinned dataset revision (`eval.yaml`, inspect-ai task `mathvision`): reason step by step, then end with `ANSWER: `; the scorer matches the answer at the end. """ from __future__ import annotations import re from fractions import Fraction HF_DATASET = "MathLLMs/MathVision" HF_REVISION = "2837ddb3f13abaf6b3997c12d80753e5470bd46a" TEST_PARQUET = "data/test-00000-of-00001-3532b8d3f1b4047a.parquet" SYSTEM_PROMPT = ( "Solve the following mathematics problem, analyzing the accompanying\n" "image. If answer options are provided, choose the single best one.\n" "Reason step by step, then on the final line output ONLY your answer\n" "in the form:\n" "ANSWER: \n" ) _IMAGE_TAG = re.compile(r"\s*\s*") _ANSWER = re.compile(r"ANSWER\s*:\s*(.+)", re.IGNORECASE) _BOXED = re.compile(r"\\boxed\{((?:[^{}]|\{[^{}]*\})*)\}") def user_text(item: dict, lettered: bool = True) -> str: """Question without tags (the single image is sent first), plus the choices. lettered=True (v2): choices whose text is not already the letter are shown as "(A) text", so the model can answer with the letter the gold uses. lettered=False (v1, runs/main): "Choices: text1, text2, ..." without letters. """ text = _IMAGE_TAG.sub("\n", item["question"]).strip() options = item["options"] if options and lettered and options != list(LETTERS[: len(options)]): text += "\n\nChoices:\n" + "\n".join(f"({LETTERS[i]}) {o}" for i, o in enumerate(options)) elif options: text += "\n\nChoices: " + ", ".join(options) return text def extract_answer(text: str | None) -> str | None: """Last `ANSWER:` line; fallback: last \\boxed{...}.""" if not text: return None matches = _ANSWER.findall(text) if matches: return matches[-1].strip() boxed = _BOXED.findall(text) return boxed[-1].strip() if boxed else None def _clean(value: str) -> str: value = value.strip().rstrip(".").strip().strip("$").strip() value = re.sub(r"^\\\(|\\\)$", "", value).strip() value = re.sub(r"\\text\{([^}]*)\}", r"\1", value) boxed = _BOXED.findall(value) if boxed: value = boxed[-1] return value.rstrip(".").strip() def _number(value: str): v = value.replace(",", "").replace(" ", "") v = re.sub(r"\\[dt]?frac\{([^{}]+)\}\{([^{}]+)\}", r"(\1)/(\2)", v) v = v.replace("^\\circ", "").replace("°", "").replace("\\%", "").replace("%", "") if re.fullmatch(r"\(?-?\d+(\.\d+)?\)?(/\(?-?\d+(\.\d+)?\)?)?", v): try: return float(Fraction(v.replace("(", "").replace(")", ""))) except (ValueError, ZeroDivisionError): return None return None LETTERS = "ABCDEFGH" def _canon(value: str) -> str: """Option/answer text without LaTeX styling, units spacing, or degree marks.""" v = _clean(value).replace("$", "") v = re.sub(r"\\(?:mathrm|text|mathbf|operatorname)\{([^}]*)\}", r"\1", v) v = v.replace("\\times", "x").replace("×", "x").replace("\\quad", "").replace("\\pi", "pi") v = v.replace("^{2}", "^2").replace("²", "^2").replace("^{3}", "^3").replace("³", "^3") v = v.replace("~", "").replace("^{\\circ}", "").replace("^\\circ", "").replace("°", "") v = v.replace("\\,", "").replace("\\!", "").replace("\\ ", "") return re.sub(r"\s+", "", v).lower() def option_letter(prediction: str | None, options: list[str]) -> str | None: """Map a multiple-choice reply to an option letter: a bare letter, or text/number equal to exactly one option's content (when options are shown without letters).""" if prediction is None: return None pred = _clean(prediction) match = re.match(r"\(?\s*([A-H])\s*\)?(?![A-Za-z])", pred) if match and match.group(1) in LETTERS[: len(options)]: return match.group(1) hits = [] for index, option in enumerate(options): a, b = _number(_canon(pred)), _number(_canon(option)) if (a is not None and b is not None and abs(a - b) <= 1e-6 * max(1.0, abs(b))) or _canon(pred) == _canon(option): hits.append(LETTERS[index]) return hits[0] if len(hits) == 1 else None def is_correct(prediction: str | None, gold: str, options: list[str]) -> bool: if prediction is None: return False pred = _clean(prediction) if options: # multiple choice: gold is a letter return option_letter(prediction, options) == gold.strip() a, b = _number(pred), _number(gold) if a is None and b is not None: # "140 g", "140 grams", "x = 140": take the number unit = re.fullmatch(r"(?:[A-Za-z]\s*=\s*)?(-?[\d.,/]+)\s*(?:\\text\{[^}]*\}|\\?[A-Za-z]+\.?|cm\^?2)?", pred) a = _number(unit.group(1)) if unit else None if a is not None and b is not None: return abs(a - b) <= 1e-6 * max(1.0, abs(b)) norm = lambda s: re.sub(r"\s+", "", s).lower() # noqa: E731 return norm(pred) == norm(_clean(gold))