Datasets:
File size: 9,595 Bytes
e1ced61 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | """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
|