sungguk's picture
Release visual answerability benchmark v1.0.0
e1ced61 verified
Raw History Blame Contribute Delete
9.6 kB
"""Strict final-answer parsing and deterministic answer normalisation."""
from __future__ import annotations
import re
import unicodedata
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from fractions import Fraction
from typing import Any
ANSWER_OPEN = "<answer>"
ANSWER_CLOSE = "</answer>"
UNANSWERABLE_TOKEN = "<UNANSWERABLE>"
# Anything that looks like an answer tag but is not one of the two exact tags
# is malformed. This rejects case variants, attributes, and partially relaxed
# XML rather than silently changing the public output contract.
_ANSWER_LIKE = re.compile(r"<\s*/?\s*answer\b[^>]*>", flags=re.IGNORECASE)
_SHORT_TEXT_PUNCT = re.compile(r"[^\w\s]", flags=re.UNICODE)
_SHORT_TEXT_SPACE = re.compile(r"\s+")
_ARTICLES = frozenset({"a", "an", "the"})
@dataclass(frozen=True)
class AnswerParse:
"""Result of checking the exact ``<answer>...</answer>`` contract."""
valid: bool
content: str | None
error: str | None
reasoning_prefix: str = ""
def require_content(self) -> str:
if not self.valid or self.content is None:
raise ValueError(self.error or "invalid answer")
return self.content
class NormalizationError(ValueError):
"""Raised when an answer cannot be normalized for its declared type."""
def parse_answer(response: str) -> AnswerParse:
"""Parse exactly one non-empty final answer tag at response end.
Trailing whitespace is permitted. Multiple, nested, case-variant,
attributed, unmatched, or trailing-text tags are rejected. The function
returns a structured failure instead of raising so reward code can trace the
precise parser branch.
"""
if not isinstance(response, str):
return AnswerParse(False, None, "response_not_string")
if "\x00" in response:
return AnswerParse(False, None, "nul_byte")
answer_like = list(_ANSWER_LIKE.finditer(response))
if any(match.group(0) not in {ANSWER_OPEN, ANSWER_CLOSE} for match in answer_like):
return AnswerParse(False, None, "malformed_answer_tag")
if response.count(ANSWER_OPEN) != 1 or response.count(ANSWER_CLOSE) != 1:
if response.count(ANSWER_OPEN) + response.count(ANSWER_CLOSE) == 0:
return AnswerParse(False, None, "missing_answer_tag")
return AnswerParse(False, None, "multiple_or_unmatched_answer_tags")
start = response.find(ANSWER_OPEN)
close = response.find(ANSWER_CLOSE)
if close < start:
return AnswerParse(False, None, "closing_tag_before_opening_tag")
content_start = start + len(ANSWER_OPEN)
content = response[content_start:close]
if ANSWER_OPEN in content or ANSWER_CLOSE in content:
return AnswerParse(False, None, "nested_answer_tag")
if not content.strip():
return AnswerParse(False, None, "empty_answer")
end = close + len(ANSWER_CLOSE)
if response[end:].strip():
return AnswerParse(False, None, "trailing_text")
return AnswerParse(True, content.strip(), None, response[:start])
def _choice_records(choices: Sequence[Mapping[str, Any]] | None) -> list[tuple[str, str]]:
records: list[tuple[str, str]] = []
for choice in choices or ():
if "key" not in choice or "text" not in choice:
raise NormalizationError("choice requires key and text")
records.append((str(choice["key"]).strip(), str(choice["text"]).strip()))
return records
def normalize_short_text(value: Any) -> str:
"""Normalizer-v1 short-text branch: case, punctuation, articles, whitespace."""
text = unicodedata.normalize("NFKC", str(value)).casefold()
text = _SHORT_TEXT_PUNCT.sub(" ", text)
tokens = [token for token in _SHORT_TEXT_SPACE.split(text.strip()) if token]
return " ".join(token for token in tokens if token not in _ARTICLES)
# Largest decimal-exponent magnitude we will let ``Fraction`` materialize.
# A model prediction such as ``1e100000000`` would otherwise make the
# ``Fraction`` constructor build a 100-million-digit integer -- CPU-bound
# big-int arithmetic that wedges the reward path for minutes (looks like a
# stall with one GPU idle, but is live compute, not a deadlock). Values up to
# ~1e10000 construct in milliseconds and are still rejected downstream by
# ``_format_rational`` (Python 3.12's 4300-digit int->str cap, CVE-2020-10735),
# so this guard only intercepts the truly degenerate exponents that would hang
# construction itself; such predictions are scored as invalid (zero-reward).
_MAX_RATIONAL_EXPONENT = 10000
_RATIONAL_EXPONENT = re.compile(r"[eE]([-+]?\d+)")
def _fraction(value: Any) -> Fraction:
if isinstance(value, bool):
raise NormalizationError("boolean is not numeric")
if isinstance(value, Fraction):
return value
if isinstance(value, int):
return Fraction(value)
if isinstance(value, float):
# Decimal text avoids the implementation-specific binary expansion.
return Fraction(str(value))
text = unicodedata.normalize("NFKC", str(value)).strip().replace(",", "")
# Bound degenerate huge-magnitude text BEFORE constructing the Fraction,
# so a prediction like ``1e100000000`` raises instead of wedging on the
# giant-integer allocation. Both reward paths catch NormalizationError and
# score the completion as an incorrect (zero-reward) answer.
exp_match = _RATIONAL_EXPONENT.search(text)
if exp_match is not None and abs(int(exp_match.group(1))) > _MAX_RATIONAL_EXPONENT:
raise NormalizationError(f"numeric answer exponent too large: {value!r}")
try:
return Fraction(text)
except (ValueError, ZeroDivisionError) as exc:
raise NormalizationError(f"not an exact rational: {value!r}") from exc
def _format_rational(number: Fraction) -> str:
"""Stringify a ``Fraction``, rejecting integers too large to convert.
Python 3.12 caps int->str conversion at 4300 digits (CVE-2020-10735). A
model prediction such as ``1e5000`` parses (via :func:`_fraction`) into a
>4300-digit numerator; ``str(number.numerator)`` then raises ``ValueError``.
Treat such degenerate values as un-normalizable so the reward path scores
them as an invalid/incorrect answer instead of crashing the whole run.
"""
try:
if number.denominator == 1:
return str(number.numerator)
return f"{number.numerator}/{number.denominator}"
except ValueError as exc:
raise NormalizationError("numeric answer has too many digits to represent") from exc
def normalize_answer(
value: Any,
answer_type: str,
*,
choices: Sequence[Mapping[str, Any]] | None = None,
) -> str:
"""Normalize one prediction or gold value using deterministic v1 branches."""
text = str(value).strip()
if text == UNANSWERABLE_TOKEN:
return UNANSWERABLE_TOKEN
if answer_type == "multiple_choice":
records = _choice_records(choices)
key_matches = [key for key, _ in records if text == key]
if len(key_matches) == 1:
return key_matches[0]
if len(key_matches) > 1:
raise NormalizationError("duplicate matching choice key")
normalized_text = normalize_short_text(text)
text_matches = [
key
for key, choice_text in records
if normalize_short_text(choice_text) == normalized_text
]
if len(text_matches) == 1:
return text_matches[0]
if not text_matches:
raise NormalizationError("answer does not map to a choice")
raise NormalizationError("choice text mapping is ambiguous")
if answer_type == "integer":
number = _fraction(value)
if number.denominator != 1:
raise NormalizationError("integer answer has a fractional value")
return _format_rational(number)
if answer_type == "number":
number = _fraction(value)
return _format_rational(number)
if answer_type == "expression":
try:
number = _fraction(value)
except NormalizationError:
expression = "".join(unicodedata.normalize("NFKC", text).split())
if not expression:
raise NormalizationError("empty expression") from None
return expression
return _format_rational(number)
if answer_type == "boolean":
if isinstance(value, bool):
return "true" if value else "false"
lowered = unicodedata.normalize("NFKC", text).casefold()
mapping = {
"true": "true",
"yes": "true",
"false": "false",
"no": "false",
}
try:
return mapping[lowered]
except KeyError:
raise NormalizationError("boolean answer must be true/false or yes/no") from None
if answer_type == "short_text":
normalized = normalize_short_text(value)
if not normalized:
raise NormalizationError("empty normalized short-text answer")
return normalized
raise NormalizationError(f"unsupported answer_type: {answer_type!r}")
def answers_equal(
prediction: Any,
gold: Any,
answer_type: str,
*,
choices: Sequence[Mapping[str, Any]] | None = None,
) -> bool:
"""Return normalized equality; invalid predictions are simply incorrect."""
try:
predicted = normalize_answer(prediction, answer_type, choices=choices)
expected = normalize_answer(gold, answer_type, choices=choices)
except NormalizationError:
return False
return predicted == expected