Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(rewards): normalize \text{}, ^\circ, compact \frac and a variable prefix (#1346) (#1371)
Amir Fathi94d6fea6bb76
diff --git a/changelog.d/0.75.1/1371.fixed.md b/changelog.d/0.75.1/1371.fixed.mdnew file mode 100644index 00000000..80b7878a--- /dev/null+++ b/changelog.d/0.75.1/1371.fixed.md@@ -0,0 +1 @@+- **`accuracy` and `verifiable/math` scored 0.0 on common MATH answer spellings (#1346 by @AmirF194 in #1371).** `normalize_answer` had no rule for `\text{}` / `\textbf{}` / `\mathrm{}` / `\mbox{}` wrappers, degree marks, or the compact `\frac12` / `\frac1{2}` / `\frac{1}2` spellings, and a phrase answer's one-letter variable prefix (`x = 7`) was read on the completion side but not the reference side. A correct completion in any of those spellings scored 0.0 against a gold in the other. All four are now handled the same way on both sides, though the variable split runs in the two parsers rather than inside the shared normaliser. A variable name is kept rather than discarded: when both sides name one and the names differ (`x = 3` against `y = 3`), the pair still scores 0.0, since a directrix or an asymptote's variable is part of its answer, and its case is part of its name (`x = 5` does not match `\boxed{X = 5}`). A gold with a variable prefix and nothing after it (`\boxed{x =}`, `x =`) states no answer and is now refused before generation (it was compared as the text `x =`). A side effect of running the degree and `\text{}` rewrites before the hedge scan: a clause such as `30^\circ, 60^\circ` now reads as two distinct values and hedges, where it previously read as one: a gold such as `The answer is 30^\circ, 60^\circ.` is now refused before generation, as `The answer is 30, 60.` already is. Units are still not stripped and nothing is evaluated (`\frac{1}{2}` does not equal `0.5`); see `docs/training.md`.diff --git a/docs/training.md b/docs/training.mdindex 5ffd15eb..6156e040 100644--- a/docs/training.md+++ b/docs/training.md@@ -1321,8 +1321,15 @@ ignoring case and whitespace, `$`, `\(...\)` and `\[...\]`, `\left` / `\right`,`\tfrac` versus `\frac`; so `\boxed{\dfrac{14}{3}}` matches a gold of `\frac{14}{3}`. Both sidesalso drop the trailing punctuation `. , ; : !`, LaTeX thousands separators such as `1{,}000`, theLaTeX spacing commands `\,` `\!` `\;` `\:` and `\ `, and a Unicode minus sign. A `\\` row break is-kept whole, so a matrix matches however its rows are spaced. Units, `^\circ`, `\text{}` and-`x = ` prefixes are not stripped, and nothing is evaluated (`\frac{1}{2}` does not equal `0.5`).+kept whole, so a matrix matches however its rows are spaced. One `\text{}` / `\textbf{}` /+`\mathrm{}` / `\mbox{}` wrapper is unwrapped to its contents, `^\circ` / `^{\circ}` / `°` are+dropped, a compact `\frac` argument is braced to match whether it is a single bare character or+an already-braced group, with or without a space before it (`\frac12`, `\frac1{2}`, `\frac{1}2`,+`\frac 34` and `\frac9{19}` all read `\frac{N}{D}`), and a one-letter variable prefix reads its+right-hand side (`x = 7` reads `7`, on either side), though when both sides name a variable and+the names differ (`x = 3` against `y = 3`), the pair scores 0.0, since a directrix or an+asymptote's variable is part of its answer. Units are still not stripped (`42 apples` against+`42`), and nothing is evaluated (`\frac{1}{2}` does not equal `0.5`).For GRPO, Soup preserves source dataset columns and TRL passes them to reward functions askeyword arguments. An Alpaca `output` or the final assistant turn in ShareGPT/ChatML is alsodiff --git a/src/soup_cli/trainer/rewards.py b/src/soup_cli/trainer/rewards.pyindex ee2ce978..5a07ae65 100644--- a/src/soup_cli/trainer/rewards.py+++ b/src/soup_cli/trainer/rewards.py@@ -300,7 +300,7 @@ def math_verify_reward(matched = final_answer.answers_match(parsed, reference)rewards.append(1.0 if matched else 0.0)continue- if parsed.number is None:+ if parsed.number is None or final_answer.variables_conflict(parsed, reference):rewards.append(0.0)continuetry:diff --git a/src/soup_cli/utils/final_answer.py b/src/soup_cli/utils/final_answer.pyindex 623cd7a5..b09c80f4 100644--- a/src/soup_cli/utils/final_answer.py+++ b/src/soup_cli/utils/final_answer.py@@ -46,12 +46,25 @@ last non-empty line, and its number is the last number anywhere in it, which isBoth sides are normalised the same way: surrounding whitespace; every ``$``, ``\\$``, ``\\(``,``\\)``, ``\\[`` and ``\\]``; ``\\left`` / ``\\right``; ``\\dfrac`` / ``\\tfrac`` read as-``\\frac``; LaTeX spacing (``\\,``, ``\\!``, ``\\;``, ``\\:``, ``\\ ``, but never the second-backslash of a ``\\\\`` line break) and ``{,}`` thousands separators; markdown ``*`` at either-end; trailing ``. , ; : !``; and the Unicode minus sign. A number is then exactly one literal: an-optional sign, digits with optional ``,`` groups of three, an optional fraction and an optional-exponent (``-1,000.5``, ``.5``, ``1e5``). Anything else, such as ``42 apples``,-``\\frac{14}{3}`` or ``p - q``, is compared as text, ignoring case and whitespace.+``\\frac``; one ``\\text{}`` / ``\\textbf{}`` / ``\\mathrm{}`` / ``\\mbox{}`` wrapper, unwrapped to+its contents; ``^\\circ``, ``^{\\circ}`` and ``\N{DEGREE SIGN}``, dropped; a compact ``\\frac``+argument, braced to match, whether it is a single bare character or an already-braced group+without nested braces, and whether or not a space separates it from ``\\frac`` (``\\frac12``,+``\\frac1{2}``, ``\\frac{1}2``, ``\\frac 34`` and ``\\frac9{19}`` all read ``\\frac{N}{D}``);+LaTeX spacing (``\\,``, ``\\!``, ``\\;``, ``\\:``, ``\\ ``, but never the second backslash of a+``\\\\`` line break) and ``{,}`` thousands separators; markdown ``*`` at either end; trailing+``. , ; : !``; and the Unicode minus sign. A number is then exactly one literal: an optional+sign, digits with optional ``,`` groups of three, an optional fraction and an optional exponent+(``-1,000.5``, ``.5``, ``1e5``). Anything else, such as ``42 apples``, ``\\frac{14}{3}`` or+``p - q``, is compared as text, ignoring case and whitespace. Units are not stripped+(``42 apples`` against ``42``), and nothing is evaluated (``\\frac{1}{2}`` against ``0.5``).++A single-letter variable prefix (``x = 7``) reads its right-hand side as the answer, on either+side, but the letter itself is kept: when BOTH sides name one and the names differ (``x = 3``+against ``y = 3``), the two answers conflict and the pair scores 0.0 even though their+right-hand sides are equal, because in an asymptote, directrix or axis problem the variable is+part of the answer. A side that names no variable never conflicts, so ``7`` still accepts+``\\boxed{x = 7}`` and ``x = 7`` still accepts ``\\boxed{7}``.Every scan is linear in its input, because a completion is untrusted model output."""@@ -74,6 +87,7 @@ __all__ = ["parse_completion","parse_number","parse_reference",+ "variables_conflict",]_MARKER = "####"@@ -98,6 +112,20 @@ _MATH_DELIMITER_RE = re.compile(r"\\[()\[\]]")# Not followed by a letter, so ``\leftarrow`` and ``\rightarrow`` stay whole._SIZING_RE = re.compile(r"\\(?:left|right)(?![A-Za-z])")_FRAC_VARIANT_RE = re.compile(r"\\[dt]frac(?![A-Za-z])")+# One \text{}/\textbf{}/\mathrm{}/\mbox{} wrapper: what it encloses IS the answer (#1346).+_TEXT_WRAP_OPEN_RE = re.compile(r"\\(?:text|textbf|mathrm|mbox)\s*\{")+# "^\circ", "^{\circ}" or the degree sign; no unit beyond that is stripped (#1346). The two+# braces are matched as one alternative each, never independently optional, so this cannot+# eat the closing brace of an enclosing group (`\frac{180^\circ}{3}`'s outer `}`).+_DEGREE_RE = re.compile(r"\^(?:\{\\circ\}|\\circ)|\N{DEGREE SIGN}")+# A \frac argument: a braced group without nested braces, or a single bare character (TeX skips+# whitespace before an undelimited macro argument, so a space before it is allowed too).+# \frac12, \frac1{2}, \frac{1}2, \frac 34 and \frac9{19} all read \frac{N}{D} (#1346).+_FRAC_COMPACT_RE = re.compile(r"\\frac\s*(\{[^{}]*\}|[^\s{}\\])\s*(\{[^{}]*\}|[^\s{}\\])")+# A single-letter variable prefix at the start of an answer: "x = 7" splits into ("x", "7")+# (#1346). The name is kept on ``FinalAnswer.variable`` rather than discarded here, so a+# reference and a completion that name DIFFERENT variables can still be told apart.+_VAR_PREFIX_RE = re.compile(r"^([A-Za-z])\s*=\s*")_UNSIGNED_PATTERN = r"(?:(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?|\.\d+)"_NUMBER_PATTERN = r"[-+]?" + _UNSIGNED_PATTERN + r"(?:[eE][-+]?\d+)?"_NUMBER_RE = re.compile(_NUMBER_PATTERN)@@ -128,10 +156,12 @@ _CLOSERS = ")]}"@dataclass(frozen=True)class FinalAnswer:- """A final answer: its normalised ``text`` and, when it has one, its ``number``."""+ """A final answer: its normalised ``text``, its ``number`` when it has one, and the+ single-letter ``variable`` a prefix such as ``x = 7`` named, when it named one."""text: strnumber: Decimal | None = None+ variable: str | None = None@dataclass(frozen=True)@@ -153,15 +183,60 @@ def _canonical_symbols(text: str) -> str:return _LATEX_SPACING_RE.sub(lambda match: "\\\\" if match.group() == "\\\\" else "", text)+def _unwrap_text_command(text: str) -> str:+ """Unwrap one ``\\text{}``/``\\textbf{}``/``\\mathrm{}``/``\\mbox{}``: what it encloses IS+ the answer, so ``\\text{Paris}`` reads ``Paris``."""+ match = _TEXT_WRAP_OPEN_RE.search(text)+ if match is None:+ return text+ depth = 1+ for brace in _BRACE_RE.finditer(text, match.end()):+ depth += 1 if brace.group() == "{" else -1+ if depth == 0:+ close = brace.start()+ return text[: match.start()] + text[match.end() : close] + text[close + 1 :]+ return text+++def _frac_compact_repl(match: re.Match[str]) -> str:+ numerator, denominator = match.group(1), match.group(2)+ numerator = numerator[1:-1] if numerator.startswith("{") else numerator+ denominator = denominator[1:-1] if denominator.startswith("{") else denominator+ return f"\\frac{{{numerator}}}{{{denominator}}}"++def normalize_answer(text: str) -> str:"""Normalise an answer for comparison; see the module docstring for the rules."""text = _MATH_DELIMITER_RE.sub("", _canonical_symbols(text))text = text.replace("\\$", "").replace("$", "")text = _FRAC_VARIANT_RE.sub(r"\\frac", _SIZING_RE.sub("", text))+ text = _unwrap_text_command(text)+ text = _DEGREE_RE.sub("", text)+ text = _FRAC_COMPACT_RE.sub(_frac_compact_repl, text)text = text.lstrip(_EDGE_CHARS).rstrip(_TRAILING_CHARS)return " ".join(text.split())+def _split_variable(answer: str) -> tuple[str | None, str]:+ """Split a one-letter variable prefix off a normalised answer: ``x = 7`` -> ``("x", "7")``.++ The split happens after normalisation rather than inside it, so a name is available to+ :func:`variables_conflict` instead of being discarded (#1346)."""+ match = _VAR_PREFIX_RE.match(answer)+ return (None, answer) if match is None else (match.group(1), answer[match.end() :])+++def variables_conflict(completion: FinalAnswer, reference: FinalAnswer) -> bool:+ """Both sides name a variable (``x = 3`` against ``y = 3``) and they are not the same one.++ A side that names no variable never conflicts, so a gold of ``7`` still accepts+ ``\\boxed{x = 7}`` and a gold of ``x = 7`` still accepts ``\\boxed{7}`` (#1346). The+ comparison is case-sensitive: a variable's case is part of its name, so ``x = 5``+ conflicts with ``\\boxed{X = 5}``."""+ named = reference.variable is not None and completion.variable is not None+ return named and completion.variable != reference.variable++def _text_key(text: str) -> str:"""The form in which two non-numeric answers are compared: no whitespace, any case."""return "".join(text.split()).casefold()@@ -380,15 +455,16 @@ def parse_reference(text: str) -> FinalAnswer | None:"""found = _explicit_answer(text)if found is not None:- number = parse_number(found.answer)- if _is_hedge(found) or (found.text_follows and number is None):+ variable, answer = _split_variable(found.answer)+ number = parse_number(answer)+ if not answer or _is_hedge(found) or (found.text_follows and number is None):return None- return FinalAnswer(found.answer, number)+ return FinalAnswer(answer, number, variable)bare = text.strip()if not bare or "\n" in bare or _names_an_answer_form(bare):return None- answer = normalize_answer(bare)- return FinalAnswer(answer, parse_number(answer)) if answer else None+ variable, answer = _split_variable(normalize_answer(bare))+ return FinalAnswer(answer, parse_number(answer), variable) if answer else Nonedef parse_completion(text: str) -> FinalAnswer | None:@@ -397,27 +473,32 @@ def parse_completion(text: str) -> FinalAnswer | None:if found is not None:if _is_hedge(found):return None # "The answer is either 41 or 42." states no answer- number = parse_number(found.answer)+ variable, answer = _split_variable(found.answer)+ number = parse_number(answer)if number is None and not found.delimited:# A phrase's clause names at most one value here: "The answer is 41 apples, not# 42." is 41, as the clause ends at the comma. An expression ("\frac{14}{3}") has# no value of its own; a clause with no digits at all reads the text's last number.if found.values:(number,) = found.values- elif _DIGIT_RE.search(found.answer) is None:+ elif _DIGIT_RE.search(answer) is None:number = _last_number(text)- return FinalAnswer(found.answer, number)+ return FinalAnswer(answer, number, variable)stripped = text.rstrip()if not stripped:return Nonelast_line = stripped[stripped.rfind("\n") + 1 :]- return FinalAnswer(normalize_answer(last_line), _last_number(text))+ variable, answer = _split_variable(normalize_answer(last_line))+ return FinalAnswer(answer, _last_number(text), variable)def answers_match(completion: FinalAnswer | None, reference: FinalAnswer) -> bool:- """Exact match: by value when the reference is a number, else as normalised text."""+ """Exact match: by value when the reference is a number, else as normalised text; ``False``+ when the two sides name different variables (#1346)."""if completion is None:return False+ if variables_conflict(completion, reference):+ return Falseif reference.number is not None:return completion.number is not None and completion.number == reference.numberkey = _text_key(reference.text)diff --git a/tests/test_issue1226_grpo_gold_validation.py b/tests/test_issue1226_grpo_gold_validation.pyindex 36261718..5fe2ff38 100644--- a/tests/test_issue1226_grpo_gold_validation.py+++ b/tests/test_issue1226_grpo_gold_validation.py@@ -164,7 +164,9 @@ class TestMixedMathDataset:prepared = _load_prepared(tmp_path, _mixed_rows(), "alpaca")tcfg = TrainingConfig(reward_fn=reward_fn, verifiable_domain=domain)_validate_grpo_reward_metadata(prepared, tcfg, split="train") # no refusal- assert f"GRPO train: 5 of 8 {_SUMMARY}" in _plain(capsys.readouterr().out)+ # #1346: normalize_answer now drops ^\circ, so the "The angle?" row's gold (90^\circ)+ # reads as the number 90 and is no longer one of the non-numeric golds.+ assert f"GRPO train: 4 of 8 {_SUMMARY}" in _plain(capsys.readouterr().out)def test_every_row_pays_its_right_answer_and_not_its_wrong_one(self, tmp_path):prepared = _load_prepared(tmp_path, _mixed_rows(), "alpaca")@@ -331,13 +333,8 @@ class TestSeedRowsBeforeARollout:class TestShippedDataStillValidates:- @pytest.mark.parametrize(- ("reward_fn", "domain", "summary"),- [("accuracy", None, "2 of 5"), ("verifiable", "math", "2 of 5")],- )- def test_the_grpo_reasoning_example_data_validates(- self, capsys, reward_fn, domain, summary- ):+ @pytest.mark.parametrize(("reward_fn", "domain"), [("accuracy", None), ("verifiable", "math")])+ def test_the_grpo_reasoning_example_data_validates(self, capsys, reward_fn, domain):from soup_cli.utils.final_answer import parse_referenceexample = _REPO / "examples" / "configs" / "grpo_reasoning.yaml"@@ -351,11 +348,19 @@ class TestShippedDataStillValidates:prepared = _prepare_grpo_dataset(load_dataset(data, preserve_source_columns=True)["train"])tcfg = TrainingConfig(reward_fn=reward_fn, verifiable_domain=domain)_validate_grpo_reward_metadata(prepared, tcfg, split="train")- assert f"GRPO train: {summary} {_SUMMARY}" in _plain(capsys.readouterr().out)+ # #1346: normalize_answer now reads a one-letter variable prefix, so "c = 5" and+ # "x = 7" (rows 1 and 3) read as numbers too and no row is left non-numeric.+ assert _SUMMARY not in _plain(capsys.readouterr().out)parsed = [parse_reference(row["answer"]) for row in prepared]- assert [p.text for p in parsed] == ["17", "c = 5", "6", "x = 7", "30"]- assert [p.number for p in parsed] == [Decimal(17), None, Decimal(6), None, Decimal(30)]+ assert [p.text for p in parsed] == ["17", "5", "6", "7", "30"]+ assert [p.number for p in parsed] == [+ Decimal(17),+ Decimal(5),+ Decimal(6),+ Decimal(7),+ Decimal(30),+ ]@pytest.mark.parametrize(("module", "reward_fn", "domain"),diff --git a/tests/test_issue1226_reward_gold_parsing.py b/tests/test_issue1226_reward_gold_parsing.pyindex ab938f29..354e068a 100644--- a/tests/test_issue1226_reward_gold_parsing.py+++ b/tests/test_issue1226_reward_gold_parsing.py@@ -68,6 +68,11 @@ GOLDS_42 = {"G30 marker, then a box": r"#### \boxed{42}","G31 phrase, answer on the next line": "The answer is\n42","G32 dollars around the bare answer": "$42$",+ # #1346: spelling-matrix coverage for the new rewrites, each tested against every completion+ # below.+ "G33 text-wrapped": r"\text{42}",+ "G34 degree": r"42^\circ",+ "G35 variable prefix": "x = 42",}# Completions that state the correct answer (42). C1-C10 are the table in #1226.@@ -113,6 +118,10 @@ CORRECT_42 = {"C38 dollars around the bare answer": "$42$","C39 italic label": "*Answer*: 42","C40 a later box supersedes a marker": "#### 41\n" + r"\boxed{42}",+ # #1346: spelling-matrix coverage for the new rewrites, each tested against every gold above.+ "C41 text-wrapped box": r"\boxed{\text{42}}",+ "C42 degree box": r"\boxed{42^\circ}",+ "C43 variable prefix box": r"\boxed{x = 42}",}# Completions that state a WRONG answer (gold 42). W1-W2 are from #1226. None may score above 0.@@ -231,9 +240,47 @@ STRING_GOLD_CASES = [(r"\(p - q\)", r"\boxed{p - q}", 1.0),("p - q", r"\boxed{q-p}", 0.0),(r"90^\circ", r"\boxed{90^\circ}", 1.0),- (r"90^\circ", r"\boxed{90}", 0.0), # no unit or degree stripping+ (r"90^\circ", r"\boxed{90}", 1.0), # #1346: ^\circ is dropped, so both read 90+ (r"90^\circ", r"\boxed{45}", 0.0),+ (r"90", r"\boxed{90^\circ}", 1.0), # #1346: degree stripping is symmetric+ (r"90^{\circ}", r"\boxed{90}", 1.0), # #1346: the braced spelling too+ ("90\N{DEGREE SIGN}", r"\boxed{90}", 1.0), # #1346: and the bare degree sign(r"x \leftarrow y", r"\boxed{x \leftarrow y}", 1.0), # \left is not stripped from \leftarrow(r"x \leftarrow y", r"\boxed{x arrow y}", 0.0),+ # #1346: \text{}/\textbf{}/\mathrm{}/\mbox{} wrap what IS the answer.+ ("Paris", r"\boxed{\text{Paris}}", 1.0),+ ("Paris", r"\boxed{\text{Lyon}}", 0.0),+ ("Paris", r"\boxed{\textbf{Paris}}", 1.0),+ ("Paris", r"\boxed{\mathrm{Paris}}", 1.0),+ ("Paris", r"\boxed{\mbox{Paris}}", 1.0),+ ("42", r"\boxed{42 \text{ apples}}", 0.0), # a unit inside \text{} is still a unit+ # #1346: a compact \frac argument (a single bare or braced character) reads \frac{N}{D}.+ (r"\frac{1}{2}", r"\boxed{\frac12}", 1.0),+ (r"\frac{1}{2}", r"\boxed{\frac1{2}}", 1.0),+ (r"\frac{1}{2}", r"\boxed{\frac{1}2}", 1.0),+ (r"\frac{1}{2}", r"\boxed{\frac13}", 0.0),+ (r"\frac{14}{3}", r"\boxed{\frac{14}{3}}", 1.0), # multi-digit args are untouched+ # #1346: a one-letter variable prefix reads its right-hand side, on either side.+ ("7", r"\boxed{x = 7}", 1.0),+ ("x = 7", r"\boxed{7}", 1.0),+ ("x = 7", r"\boxed{8}", 0.0),+ ("x = 7", "Answer: x = 7", 1.0),+ # review: both sides name a variable, and the names differ, so the pair conflicts even+ # though the right-hand sides are equal (a vertical line is not a horizontal one).+ ("x = 3", r"\boxed{y = 3}", 0.0), # a vertical line is not a horizontal one+ ("y = 7", r"\boxed{x = 7}", 0.0),+ (r"y = -\frac{47}{8}", r"\boxed{x = -\frac{47}{8}}", 0.0), # a directrix names its axis+ ("7", r"\boxed{2x + 1 = 7}", 0.0), # an equation is not its solution+ ("7", r"\boxed{ab = 7}", 0.0), # only a one-letter left-hand side is a prefix+ ("x = 5", r"\boxed{X = 5}", 0.0), # a variable's case is part of its name+ # review: a compact \frac argument may be preceded by a space, or already be a braced+ # group longer than one character; both spellings still read \frac{N}{D}.+ (r"\frac 34", r"\boxed{\frac34}", 1.0), # MATH-500; 1.0 on main, 0.0 before this fix+ (r"\frac 59", r"\boxed{\frac{5}{9}}", 1.0), # MATH-500+ (r"\frac9{19}", r"\boxed{\frac{9}{19}}", 1.0), # MATH-500+ (r"\frac{270}7\text{ degrees}", r"\boxed{\frac{270}{7}\text{ degrees}}", 1.0), # MATH-500+ (r"\frac{1}{10}", r"\boxed{\frac1{10}}", 1.0),+ (r"\frac{180^\circ}{3}", r"\boxed{\frac{180}{3}}", 1.0), # needs the _DEGREE_RE brace fix]# Hedges (ruling): an answer clause that names more than one DISTINCT value states no answer.@@ -257,6 +304,10 @@ HEDGES = [("The answer is 6 times 7 which is 42.", ["6", "7", "42"]), # boundary: every number counts("The answer is 42 (6 times 7).", ["42", "6", "7"]), # boundary: so does an aside's("The answer is 3, 4.", ["3", "4"]), # boundary: a bare list in a phrase is a hedge+ # #1346 (accepted, undocumented before this row): dropping ^\circ and unwrapping \text{}+ # runs before the hedge scan, so digits that used to be glued to a unit now stand alone.+ ("The answer is 30^\\circ, 60^\\circ.", ["30", "60"]),+ (r"The answer is \text{2 and 3}.", ["2", "3"]),]# Not hedges: ONE value, maybe repeated or respelled; a tuple or an expression is one answer.@@ -290,6 +341,9 @@ HEDGED_GOLDS = ["The answer is 42 (or 43).","6*7 is 42.\nThe answer is 42 or 43.","#### Final Answer\n41 or 42",+ # #1346 (accepted): a degree-marked pair now hedges as a gold too, since the ^\circ is+ # dropped before the clause's values are scanned.+ "The answer is 30^\\circ, 60^\\circ.",]# The partial-credit policy, pinned: (completion, gold, accuracy before #1226, accuracy now).@@ -399,6 +453,73 @@ class TestIssueRepro:assert accuracy_reward(_msg(text), answer=[r"\frac{1}{2}"]) == [1.0]+class TestIssue1346:+ """#1346: a spelling normalised on one side must be normalised the same way on the other."""++ @pytest.mark.parametrize(+ ("gold", "completion"),+ [+ (r"90^\circ", r"\boxed{90}"),+ ("90", r"\boxed{90^\circ}"),+ ("Paris", r"\boxed{\text{Paris}}"),+ ("7", r"\boxed{x = 7}"),+ ("x = 7", r"\boxed{7}"),+ (r"\frac{1}{2}", r"\boxed{\frac12}"),+ ],+ )+ def test_each_pair_from_the_issue_scores_one(self, gold, completion):+ assert accuracy_reward(_msg(completion), answer=[gold]) == [1.0]+ assert math_verify_reward(_msg(completion), answer=[gold]) == [1.0]++ @pytest.mark.parametrize(+ ("gold", "completion"),+ [+ (r"90^\circ", r"\boxed{45}"),+ ("Paris", r"\boxed{\text{Lyon}}"),+ ("x = 7", r"\boxed{8}"),+ ],+ )+ def test_a_wrong_neighbour_still_scores_zero(self, gold, completion):+ assert accuracy_reward(_msg(completion), answer=[gold]) == [0.0]+ assert math_verify_reward(_msg(completion), answer=[gold]) == [0.0]++ def test_the_same_phrase_reads_the_same_number_on_both_sides(self):+ from soup_cli.utils.final_answer import parse_completion, parse_reference++ text = "Answer: x = 7"+ assert parse_completion(text) == parse_reference(text)+ assert parse_reference(text).number == Decimal(7)++ def test_a_unit_is_still_not_stripped(self):+ # Units stay unstripped; the ruling is recorded on #1346.+ assert accuracy_reward(_msg("#### 42 apples"), answer=["42"]) == [0.0]+ assert accuracy_reward(_msg(r"\boxed{42 \text{ apples}}"), answer=["42"]) == [0.0]+ assert math_verify_reward(_msg("#### 42 apples"), answer=["42"]) == [0.0]+ assert math_verify_reward(_msg(r"\boxed{42 \text{ apples}}"), answer=["42"]) == [0.0]++ def test_the_answer_is_42_apples_as_a_gold_reads_42_as_a_completion(self):+ from soup_cli.utils.final_answer import parse_completion, parse_reference++ gold = parse_reference("The answer is 42 apples.")+ assert (gold.text, gold.number) == ("42 apples", None)+ completion = parse_completion("The answer is 42 apples.")+ assert (completion.text, completion.number) == ("42 apples", Decimal(42))++ @pytest.mark.parametrize("gold", [r"\boxed{x =}", "Answer: x =", "#### x =", "x ="])+ def test_a_variable_with_nothing_after_it_is_not_a_reference(self, gold):+ from soup_cli.utils.final_answer import parse_reference++ assert parse_reference(gold) is None+ tcfg = TrainingConfig(reward_fn="accuracy")+ with pytest.raises(ValueError, match="states no single final answer"):+ _validate_grpo_reward_metadata([{"prompt": "p", "answer": gold}], tcfg, split="train")++ def test_a_control_sequence_is_not_split_as_a_frac_argument(self):+ from soup_cli.utils.final_answer import normalize_answer++ assert normalize_answer(r"\frac\pi2") == r"\frac\pi2"++# ===========================================================================# the spelling matrix: every gold x every completion, both rewards# ===========================================================================@@ -680,6 +801,13 @@ class TestSharedHelper:assert (unit.text, unit.number) == ("42 apples", None)latex = parse_reference(r"\left( 3, \dfrac{\pi}{2} \right)")assert (latex.text, latex.number) == (r"( 3, \frac{\pi}{2} )", None)+ # #1346: a text-wrapper, a degree mark and a variable prefix are read on the bare path.+ wrapped = parse_reference(r"\text{Paris}")+ assert (wrapped.text, wrapped.number) == ("Paris", None)+ degree = parse_reference(r"90^\circ")+ assert (degree.text, degree.number) == ("90", Decimal(90))+ prefixed = parse_reference("x = 7")+ assert (prefixed.text, prefixed.number) == ("7", Decimal(7))@pytest.mark.parametrize("text",@@ -719,6 +847,8 @@ class TestSharedHelper:(r"\left( 3, \frac{\pi}{2} \right)", r"(3,\frac{\pi}{2})"),(r"\(p - q\)", "p-q"),("New York", "new york"),+ (r"\text{Paris}", "Paris"), # #1346+ (r"\frac12", r"\frac{1}{2}"), # #1346],)def test_text_answers_compare_ignoring_whitespace_case_and_latex_wrappers(self, left, right):diff --git a/tests/test_issue1346_rewrites_are_linear.py b/tests/test_issue1346_rewrites_are_linear.pynew file mode 100644index 00000000..32b50817--- /dev/null+++ b/tests/test_issue1346_rewrites_are_linear.py@@ -0,0 +1,59 @@+r"""#1346: the four normalisation rewrites stay linear in a completion's length.++A completion is untrusted model output, so each rewrite gets an input aimed at it, and the time+at 8N is compared with the time at N, as in ``test_issue1226_clause_scanner_is_linear.py``: a+linear scan grows about 8x, a quadratic one about 64x.+"""++from __future__ import annotations++import time++import pytest++from soup_cli.trainer.rewards import accuracy_reward, math_verify_reward++_SCALE_N = 1_000+_SCALE_LIMIT = 24.0 # the same 3x slack over linear as the #1226 growth test++REWRITE_INPUTS = {+ "text-wrapper-never-closes": lambda k: "\\text{" * k,+ "text-wrapper-deep-braces": lambda k: "The answer is \\text{" + "{" * k,+ "text-command-then-spaces": lambda k: "The answer is \\text" + " " * k + "x",+ "many-closed-text-wrappers": lambda k: "\\boxed{" + "\\text{a}" * k + "}",+ "degree-carets": lambda k: "#### " + "^\\circ" * k,+ "degree-open-braces": lambda k: "#### " + "^{\\circ" * k,+ "degree-signs": lambda k: "#### " + "\N{DEGREE SIGN}" * k,+ "compact-fracs": lambda k: "#### " + "\\frac12" * k,+ "bare-fracs": lambda k: "#### " + "\\frac" * k,+ "spaced-fracs": lambda k: "#### \\frac" + " " * k + "1",+ "open-frac-group": lambda k: "#### \\frac{" + "a" * k,+ "variable-then-spaces": lambda k: "#### x" + " " * k,+ "variable-spaces-equals-spaces": lambda k: "#### x" + " " * k + "=" + " " * k,+}+++def _msg(text: str) -> list[list[dict]]:+ return [[{"role": "assistant", "content": text}]]+++def _best_time(text: str, repeats: int) -> float:+ best = float("inf")+ for _ in range(repeats):+ start = time.perf_counter()+ accuracy_reward(_msg(text), answer=["42"])+ math_verify_reward(_msg(text), answer=["42"])+ best = min(best, time.perf_counter() - start)+ return best++[email protected]("build", list(REWRITE_INPUTS.values()), ids=list(REWRITE_INPUTS))+def test_each_rewrite_grows_linearly(build):+ small, large = build(_SCALE_N), build(8 * _SCALE_N)+ t_small = max(_best_time(small, repeats=5), 1e-7)+ t_large = float("inf")+ for _ in range(5): # stop as soon as the larger input is shown to be fast enough+ t_large = min(t_large, _best_time(large, repeats=1))+ if t_large / t_small < _SCALE_LIMIT:+ break+ assert t_large / t_small < _SCALE_LIMIT, (t_small, t_large)