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): read the gold answer with the completion's parser (#1226) (#1316)
Alpamys Makazhand506918e0dcb
diff --git a/changelog.d/0.75.1/1316.fixed.md b/changelog.d/0.75.1/1316.fixed.mdnew file mode 100644index 00000000..3631dd0a--- /dev/null+++ b/changelog.d/0.75.1/1316.fixed.md@@ -0,0 +1 @@+- **GRPO's `accuracy` and verifiable `math` rewards now read the gold answer the way they read the completion (#1226 in #1316).** An Alpaca `output` or a ShareGPT/ChatML reference turn such as `6*7=42\n#### 42` was compared raw, so every correct completion scored 0.0, every group had zero reward variance and GRPO got no signal, with no warning. Both sides now go through one parser: the text after the last `####`, the last `\boxed{}` (a space before the brace and nested braces allowed), or the text after `The answer is` / `Answer:` (also `**Answer**:`, and on the next line), whose number is read from its own clause, so `The answer is 41 apples, not 42.` is 41. An answer phrase that names more than one distinct value is a hedge and states no answer: `The answer is either 41 or 42.` scores 0.0 in both rewards whatever the gold, and a gold written that way is refused (the same value twice, as in `42 (i.e. 42.0)`, is not a hedge). Every number in the clause counts, so `The answer is 42 because 6*7=42.` is a hedge too, while `The answer is 42, because 6*7=42.` reads 42; a time or a ratio such as `3:45` or `1:1,000` is one answer, compared as text. `$`, `\(...\)`, trailing punctuation, thousands separators such as `1,000` and `1{,}000`, and the Unicode minus are normalised. A numeric gold is compared by value; any other gold, such as `\frac{14}{3}`, is compared as normalised text (case, whitespace, `\left` / `\right` and `\dfrac` ignored), now by `math` as well, so a dataset that mixes numeric and LaTeX golds, such as MATH-500, loads under `math`, and validation prints how many golds are compared as text. `accuracy` no longer pays 0.5 when the gold merely appears in the completion (that paid `#### 420` for a gold of 42) and scores only 0.0 or 1.0; a completion with no marked answer is scored by its last number, so `Six times seven is 42.`, and also `Not 42.`, now score 1.0 instead of 0.5. `math`'s 0.6 near-miss band is unchanged. A row whose gold states no single final answer, such as a multi-line reference with no marked answer, a hedge, or a `#### Solution` heading over a worked solution (a `####` line that is not a number and has more text after it), is refused before generation with its split, row and field and a count of the other such rows. PPO's `accuracy` and `math` rewards use the same scoring, but PPO's data is not validated this way (on the supported trl, PPO scores rollouts with its reward model).diff --git a/docs/training.md b/docs/training.mdindex 9a93ef70..aa74a23a 100644--- a/docs/training.md+++ b/docs/training.md@@ -1211,9 +1211,48 @@ soup train --config soup.yaml```**Built-in reward functions:**-- `accuracy` — checks if the final answer matches expected (supports `####` and `\boxed{}` formats)+- `accuracy` — 1.0 when the completion's final answer matches the gold's, else 0.0 (no partial credit)- `format` — checks for structured `<think>...</think>` reasoning blocks+`accuracy` and verifiable `math` read the completion and the gold with the same parser. The final+answer is, in this order of precedence:++1. the rest of the line after the last `####` (a `#### Final Answer` heading means the next line);+2. the content of the last `\boxed{}` (a space before the brace and nested braces such as+ `\boxed{\frac{1}{2}}` are fine);+3. what follows the last `The answer is` or `Answer:` (also `**Answer**:`, and the answer may be+ on the next line), up to the end of its clause: a `. `, `, ` or `; ` outside brackets. A comma+ or semicolon that a number follows continues a list instead (`41, 42 or 43`), and a+ parenthetical aside belongs to the clause. So `The answer is Washington, D.C.` reads+ `Washington`, `The answer is 42 (six times seven).` reads `42`, and `The answer is (3, 4).`+ reads `(3, 4)`.++A box outranks a phrase, and a `\boxed{}` or phrase that comes after a `####` line outranks it (the+line was a markdown heading, or an answer the text went on to correct). That includes chatter:+`#### Paris` followed by `I hope this answer is helpful!` reads `helpful`, so end a completion at+its `####` line. A completion with none of these is read by its last line and its last number, so+`Six times seven is 42.` and even `Not 42.` read as 42; only the final number counts, so listing+candidates earns nothing.++An answer phrase's number is read from its own clause: `The answer is 41 apples, not 42.` reads+41, because the clause ends at the comma. A clause that names **more than one distinct value** is+a hedge and states no answer: `The answer is either 41 or 42.`, `Answer: 41 or 42`,+`The answer is 42 (or 43).` and `the answer is 41, 42 or 43` score 0.0 against every gold, and a+gold written that way is refused. Every number in the clause counts, a justification's too:+`The answer is 42 because 6*7=42.` is a hedge, while `The answer is 42, because 6*7=42.` reads 42.+The same value twice is not a hedge (`42 (i.e. 42.0)`), and the digits of one bracketed or LaTeX+answer (`(3, 4)`, `\frac{14}{3}`, `2^{10}`) or of a time or a ratio (`3:45`, `1:1,000`) are not+separate values; such an answer is compared as text. `\boxed{}` and `####` answers are compared+whole, so a list there is one answer, and it can only match a gold that is the same list.++A numeric gold is compared by value, so `#### 1,000`, `\boxed{1000}` and `The answer is $1000.`+all match a gold of `1000`. Any other gold (`\frac{14}{3}`, `p - q`, `Paris`) is compared as text,+ignoring case and whitespace, `$`, `\(...\)` and `\[...\]`, `\left` / `\right`, and `\dfrac` /+`\tfrac` versus `\frac`; so `\boxed{\dfrac{14}{3}}` matches a gold of `\frac{14}{3}`. Both sides+also drop the trailing punctuation `. , ; : !`, LaTeX thousands separators such as `1{,}000`, and a+Unicode minus sign. Units, `^\circ`, `\text{}` and `x = ` prefixes are not stripped, 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 alsoexposed as `answer`; an explicit `answer` column takes precedence. Gold-dependent built-ins@@ -1221,10 +1260,21 @@ validate their inputs before generation:| Reward | Required source metadata ||---|---|-| `accuracy` or verifiable `math` | `answer`, or an assistant reference response |+| `accuracy` or verifiable `math` | `answer`, or an assistant reference response, that states a final answer || verifiable `code` | `expected` or `answer` || verifiable `json_schema` | `schema` |+A gold states its final answer with `####`, `\boxed{}`, `The answer is` or `Answer:`, or by being+the bare answer on one line (`42`, `Paris`, `\frac{14}{3}`). A row whose gold states none (for+example a multi-line reference solution with no marked answer, or one under a `#### Solution`+heading: a `####` line that is not a number and has more text after it may be a markdown heading,+so a gold cannot rely on it), or whose answer phrase hedges between values+(`The answer is either 41 or 42.`), is refused before generation, with its split,+row number and field and a count of the other rows with the same problem, because such a gold+would score every completion 0.0 and give GRPO no signal. A dataset that mixes numeric and+LaTeX golds, such as MATH-500, loads under `math` too; validation prints how many golds are+non-numeric and therefore compared as normalised text.+**Custom reward functions** — point to a Python file:```python# my_reward.py@@ -1327,7 +1377,7 @@ Three built-in domains:| Domain | What it checks ||---|---|-| `math` | Extracts the final numeric answer (supports `####`, `\boxed{}`) and compares via `float()` equality — no `eval()` on user output |+| `math` | Reads the final answer of the completion and of the gold with the shared parser described under "Built-in reward functions" (`####`, `\boxed{}`, `The answer is` / `Answer:`, else the completion's last number). A numeric gold scores 1.0 within 1e-4 and 0.6 within 1e-2 (compared as exact decimals); any other gold scores 1.0 on a normalised text match. Nothing is evaluated: no `eval()` on user output || `code` | Executes generated Python with a 5s timeout, 512 MB RLIMIT on POSIX, `python -I -S`, socket patch, ephemeral cwd. Output capped at 10KB. Warning panel on first use || `json_schema` | Validates output against a JSON Schema provided per-example in the dataset |diff --git a/src/soup_cli/envs/retrieval_qa.py b/src/soup_cli/envs/retrieval_qa.pyindex ce1f6840..74be674e 100644--- a/src/soup_cli/envs/retrieval_qa.py+++ b/src/soup_cli/envs/retrieval_qa.py@@ -2,7 +2,8 @@Generates deterministic short-document + question rows whose answer is a spanpresent in the document, as GRPO prompt+answer rows. Score with-``reward_fn='accuracy'`` (the answer span appears in the model's completion).+``reward_fn='accuracy'``: the completion's final answer must be the span, e.g. a+reply of just the value, as the prompt asks.Usage: ``training.rollout_backend='openenv'`` +``training.rollout_func='soup_cli.envs.retrieval_qa:rollout'``.diff --git a/src/soup_cli/trainer/grpo.py b/src/soup_cli/trainer/grpo.pyindex ac6940bf..ae806aaf 100644--- a/src/soup_cli/trainer/grpo.py+++ b/src/soup_cli/trainer/grpo.py@@ -13,6 +13,7 @@ from rich.console import Consolefrom soup_cli.config.schema import SoupConfig, TrainingConfigfrom soup_cli.data.chat_templates import apply_chat_template_overridefrom soup_cli.trainer.loss_summary import summarize_training_loss+from soup_cli.utils import final_answerfrom soup_cli.utils.gpu import (bf16_fp16_flags,estimate_batch_size,@@ -827,6 +828,11 @@ def _copy_grpo_metadata(row: dict, entry: dict) -> None:entry[key] = value+# Rewards that compare a completion's final answer with the gold's (#1226). A gold they cannot+# read would score every completion 0.0, so the group advantage would be zero with no warning.+_GOLD_PARSING_REWARDS = frozenset({"accuracy", "verifiable/math"})++def _validate_grpo_reward_metadata(data: list[dict],tcfg: TrainingConfig,@@ -862,6 +868,53 @@ def _validate_grpo_reward_metadata("'answer'.")+ gold_rewards = [name for name, _ in requirements if name in _GOLD_PARSING_REWARDS]+ # Seed rows that a rollout backend replaces are never scored (#565 still wants them+ # present); the rollout's own rows are validated as split "rollout".+ if gold_rewards and not (split == "train" and tcfg.rollout_backend is not None):+ _check_golds_are_readable(data, list(dict.fromkeys(gold_rewards)), split=split)+++def _check_golds_are_readable(data: list[dict], reward_names: list[str], *, split: str) -> None:+ """Refuse golds with no single extractable final answer (none, a "####" line that may be a+ markdown heading, or a hedge such as "The answer is either 41 or 42."); report the ones+ compared as text."""+ unreadable: list[int] = []+ text_golds = 0+ for row_index, row in enumerate(data):+ reference = final_answer.parse_reference(str(row["answer"]))+ if reference is None:+ unreadable.append(row_index)+ elif reference.number is None:+ text_golds += 1+ if unreadable:+ raise ValueError(_unreadable_gold_message(unreadable, len(data), reward_names, split))+ if text_golds:+ console.print(+ f"[dim]GRPO {split}: {text_golds} of {len(data)} golds are non-numeric and are "+ "compared as normalised text.[/]"+ )+++def _unreadable_gold_message(+ rows: list[int], total: int, reward_names: list[str], split: str+) -> str:+ names = " and ".join(repr(name) for name in reward_names)+ label = "reward" if len(reward_names) == 1 else "rewards"+ more = (+ f" {len(rows) - 1} more of the {total} rows have the same problem." if len(rows) > 1 else ""+ )+ return (+ f"GRPO {split} row {rows[0]} 'answer' states no single final answer that {label} "+ f"{names} can compare against: it states none (a '####' line that is not a number and "+ "has more text after it reads as a markdown heading), or its answer phrase names more "+ "than one number (a hedge such as 'The answer is either 41 or 42.'), so every "+ f"completion would score 0.0.{more} The field comes from an 'answer' column, an Alpaca "+ "'output' or the final assistant turn; rows count from 0 after the train/validation "+ "split. Put one answer after '####' on the last line, inside \\boxed{}, or after 'The "+ "answer is' or 'Answer:', make the field the bare answer on one line, or drop the row."+ )+def _has_grpo_reward_metadata(value: object) -> bool:"""Return whether a reward metadata value is usable as a gold target."""diff --git a/src/soup_cli/trainer/rewards.py b/src/soup_cli/trainer/rewards.pyindex 5f9d015e..ee2ce978 100644--- a/src/soup_cli/trainer/rewards.py+++ b/src/soup_cli/trainer/rewards.py@@ -31,6 +31,8 @@ from typing import Anyfrom rich.console import Consolefrom rich.panel import Panel+from soup_cli.utils import final_answer+console = Console()MAX_CODE_OUTPUT_BYTES = 10_000@@ -202,10 +204,15 @@ def _show_code_exec_warning_once() -> None:def accuracy_reward(completions: list[list[dict]], **kwargs) -> list[float]:- """Reward based on whether the final answer matches the expected answer.+ """Reward 1.0 when the completion's final answer matches the gold's, else 0.0.- Looks for the answer after the last '####' or in a \\boxed{} block.- Falls back to checking if the expected answer appears anywhere in the response.+ The completion and the gold are read by the same parser,+ :mod:`soup_cli.utils.final_answer`: the answer after the last '####', in the last+ \\boxed{}, or after 'answer is' / 'answer:'; an unmarked completion by its last line and+ its last number. A numeric gold is compared by value ('42' equals '#### 42.0'), any other+ gold as normalised text (case, whitespace and LaTeX wrappers ignored). There is no partial+ credit (#1226): the old 0.5 for "the gold appears somewhere in the completion" paid+ '#### 420' for a gold of 42.Args:completions: list of message lists, each containing a completion with 'content'.@@ -218,17 +225,12 @@ def accuracy_reward(completions: list[list[dict]], **kwargs) -> list[float]:rewards = []for completion, expected in zip(completions, answers):content = completion[-1]["content"] if completion else ""- expected_text = "" if expected is None else str(expected).strip()- if not expected_text:+ reference = None if expected is None else final_answer.parse_reference(str(expected))+ if reference is None:rewards.append(0.0)continue- predicted = _extract_answer(content)- if predicted is not None and predicted.strip() == expected_text:- rewards.append(1.0)- elif expected_text.lower() in content.lower():- rewards.append(0.5)- else:- rewards.append(0.0)+ predicted = final_answer.parse_completion(content)+ rewards.append(1.0 if final_answer.answers_match(predicted, reference) else 0.0)return rewards@@ -262,75 +264,54 @@ def format_reward(completions: list[list[dict]], **kwargs) -> list[float]:def _extract_answer(text: str) -> str | None:- """Extract the final answer from model output.+ """Return the final answer ``text`` states explicitly ('####', \\boxed{}, 'answer is').- Supports:- - #### <answer> format (GSM8K style)- - \\boxed{<answer>} format (math style)+ Kept as a thin alias: the parser lives in :mod:`soup_cli.utils.final_answer` (#1226)."""- # Try #### format- parts = text.split("####")- if len(parts) > 1:- return parts[-1].strip()- # Try \\boxed{} format- match = re.search(r"\\boxed\{([^}]+)\}", text)- if match:- return match.group(1).strip()- return None+ return final_answer.extract_final_answer(text)# --- RLVR: verifiable rewards (Part C of v0.25.0) ----_MATH_NUM_RE = re.compile(r"-?\d+(?:\.\d+)?")---def _extract_numeric_answer(text: str) -> "float | None":- """Extract a numeric answer using safe regex (never calls eval())."""- answer_str = _extract_answer(text)- if answer_str is None:- # Fallback: find the last number in text- nums = _MATH_NUM_RE.findall(text)- if not nums:- return None- answer_str = nums[-1]-- # Accept only simple numeric literals — reject anything else- match = _MATH_NUM_RE.fullmatch(answer_str.strip())- if match is None:- return None- try:- return float(match.group(0))- except (ValueError, TypeError):- return None-def math_verify_reward(completions: list[list[dict]],tolerance: float = 1e-4,**kwargs,) -> list[float]:- """RLVR math reward: compare extracted numeric answer to expected.+ """RLVR math reward: compare the completion's final answer with the gold's.- Security: never uses ``eval()``. Only numeric literals that match a strict- regex are accepted. Non-numeric answers score 0.0.+ Both sides are read by :mod:`soup_cli.utils.final_answer`, so a GSM8K-shaped gold such as+ '6*7=42\\n#### 42' is the number 42 (#1226). A numeric gold scores 1.0 within ``tolerance``+ and 0.6 within max(100 x ``tolerance``, 1e-2). A gold that is not a number, such as+ '\\frac{14}{3}' or 'p - q', is compared as normalised text: 1.0 on an exact match, else+ 0.0. Security: never uses ``eval()``; nothing is evaluated."""answers = kwargs.get("answer", [])rewards: list[float] = []for completion, expected in zip(completions, answers):content = completion[-1]["content"] if completion else ""- predicted = _extract_numeric_answer(content)+ reference = None if expected is None else final_answer.parse_reference(str(expected))+ parsed = final_answer.parse_completion(content)+ if reference is None or parsed is None:+ rewards.append(0.0)+ continue+ if reference.number is None:+ matched = final_answer.answers_match(parsed, reference)+ rewards.append(1.0 if matched else 0.0)+ continue+ if parsed.number is None:+ rewards.append(0.0)+ continuetry:- expected_num = float(str(expected).strip())- except (ValueError, TypeError):- expected_num = None-- if predicted is None or expected_num is None:+ error = float(abs(parsed.number - reference.number))+ except ArithmeticError: # an exponent beyond Decimal's range cannot be comparedrewards.append(0.0)continue- if abs(predicted - expected_num) <= tolerance:+ if error <= tolerance:rewards.append(1.0)- elif abs(predicted - expected_num) <= max(tolerance * 100, 1e-2):+ elif error <= max(tolerance * 100, 1e-2):rewards.append(0.6)else:rewards.append(0.0)diff --git a/src/soup_cli/utils/final_answer.py b/src/soup_cli/utils/final_answer.pynew file mode 100644index 00000000..1773094a--- /dev/null+++ b/src/soup_cli/utils/final_answer.py@@ -0,0 +1,390 @@+"""One parser for the final answer a text states (#1226).++GRPO's ``accuracy`` and ``verifiable/math`` rewards compare the final answer of a completion with+the final answer of a gold reference. Both sides are read here, so a spelling understood on one+side is understood on the other. Before #1226 only the completion was parsed: an Alpaca or+ShareGPT reference such as ``"6*7=42\\n#### 42"`` was compared raw, and every correct completion+scored 0.0.++An answer is stated explicitly in one of three forms:++1. ``####`` (GSM8K): the rest of the line after the last marker. A ``####`` line that only says+ ``Final Answer`` is a markdown heading, and its answer is the next non-empty line;+2. ``\\boxed{...}``: the last box that closes; whitespace is allowed before the brace and nested+ braces are balanced, so ``\\boxed {\\frac{1}{2}}`` reads ``\\frac{1}{2}``;+3. ``answer is`` / ``answer:`` in any case, with markdown emphasis allowed around the word+ (``**Answer**:``) and the answer allowed on the next line: the last such phrase, up to the end+ of its clause. The clause ends at a line end, or at ``". "``, ``", "`` or ``"; "`` outside+ brackets, except that a comma or semicolon followed by a number continues a list+ (``41, 42 or 43``). A ``" ("`` aside belongs to the clause but not to the answer:+ ``42 (i.e. 42.0)`` answers ``42``.++A box outranks a phrase. A ``####`` line outranks both, unless one of them comes after it: then+the ``####`` line was a markdown heading, or an answer the text went on to correct. Any later+phrase counts, chatter such as ``I hope this answer is helpful!`` included, because it cannot+be told apart from an answer under a heading. A reference is held to more: a ``####`` line that+is not a number and has more text after it may be a heading over an unmarked body, so such a+reference states no answer.++The two delimited forms are authoritative: what they enclose IS the answer, number or not, so a+list or a tuple there is one answer. A phrase has no closing delimiter, so its values are read+from its clause: the stand-alone numbers outside brackets (the digits of ``(3, 4)``,+``\\frac{14}{3}``, ``2^{10}`` or ``2x``, and of a time or a ratio such as ``3:45`` or+``1:1,000``, belong to one expression, not to several values) and every stand-alone number in+its aside. A clause with MORE THAN ONE distinct value is a hedge+(``The answer is either 41 or 42.``): it states no answer, so a completion that hedges scores+0.0 and a gold that hedges is refused. Every number in the clause counts, a justification's+too (``42 because 6*7=42`` is a hedge), and a comma or a period before a justification ends the+clause (``42, because 6*7=42`` is 42). One value, even repeated (``42 or 42.0``), is the+clause's number; a clause with no digits at all falls back to a completion's last number.++A text that states no explicit answer is free text. A reference is then its whole value, which+must fit on one line (a bare answer such as ``"42"`` or ``"Paris"``). A completion reads as its+last non-empty line, and its number is the last number anywhere in it, which is how+``math_verify`` has always read an unmarked completion.++Both sides are normalised the same way: surrounding whitespace; every ``$``, ``\\$``, ``\\(``,+``\\)``, ``\\[`` and ``\\]``; ``\\left`` / ``\\right``; ``\\dfrac`` / ``\\tfrac`` read as+``\\frac``; LaTeX spacing (``\\,``, ``\\!``, ``\\;``, ``\\:``, ``\\ ``) 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.++Every scan is linear in its input, because a completion is untrusted model output.+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from decimal import Decimal, InvalidOperation+from typing import NamedTuple++__all__ = [+ "FinalAnswer",+ "answers_match",+ "extract_final_answer",+ "normalize_answer",+ "parse_completion",+ "parse_number",+ "parse_reference",+]++_MARKER = "####"+# LaTeX allows whitespace between a command and its argument: ``\boxed {42}``.+_BOXED_OPEN_RE = re.compile(r"\\boxed\s*\{")+_BRACE_RE = re.compile(r"[{}]")+# "answer is", "answer:", "**Answer**:", "Answer:\n42". Look-arounds rather than \b, so that+# "__Answer__:" matches while "answers:" and "the answer isn't" do not.+_PHRASE_RE = re.compile(+ r"(?<![A-Za-z0-9])answer(?![A-Za-z0-9])[*_\s]*(?:is\b(?:[*_\s]*:)?|:)[*_\s]*",+ re.IGNORECASE,+)+# The rest of a '####' line that is only an answer label ("#### Final Answer"): a heading.+_ANSWER_LABEL_RE = re.compile(r"[*_\s]*(?:final\s+)?answer[*_\s]*(?::[*_\s]*)?", re.IGNORECASE)+_NON_SPACE_RE = re.compile(r"\S")+# The characters that can end a phrase's clause, or open or close a bracket inside it.+_CLAUSE_CHAR_RE = re.compile(r"[()\[\]{}.,;]")+_LATEX_SPACING_RE = re.compile(r"\\[,!;: ]")+_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])")+_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)+# Not glued to a word ("2x", "3rd") or to a LaTeX expression ("\frac{14}{3}", "2^{10}", "4/5").+_STANDS_ALONE = r"(?<![\w\\{}^/.])"+# A bracket, which lets a scan track depth; a time or a ratio ("3:45", "1:1,000"), which is ONE+# answer and is matched whole so that none of its numbers reads as a value; or, as group 1, a+# number that stands alone.+_VALUE_TOKEN_RE = re.compile(+ r"[()\[\]{}]"+ + "|" + _STANDS_ALONE + "[-+]?" + _UNSIGNED_PATTERN + "(?::" + _UNSIGNED_PATTERN + ")+"+ + "|" + _STANDS_ALONE + r"(?<!\d:)(" + _NUMBER_PATTERN + r")(?![\w{}^/]|:\d)"+)+# After ", " or "; " inside a clause: a number next means a list that goes on ("41, 42 or 43",+# "41, $42$"). Only one ``\s*`` can match a given whitespace run, because the second one follows+# a mandatory "$", "\(" or "\[", so a run that no number follows costs linear time. With+# ``\s*(?:...)?\s*`` every split of the run was retried: one completion ending in a comma and+# 40,000 spaces took over 90 s to score.+_NUMBER_AHEAD_RE = re.compile(r"\s*(?:(?:\$|\\[(\[])\s*)?[-+\u2212]?\.?\d")+_DIGIT_RE = re.compile(r"\d")++_EDGE_CHARS = " \t\r\n*"+_TRAILING_CHARS = _EDGE_CHARS + ".,;:!"+_OPENERS = "([{"+_CLOSERS = ")]}"+++@dataclass(frozen=True)+class FinalAnswer:+ """A final answer: its normalised ``text`` and, when it has one, its ``number``."""++ text: str+ number: Decimal | None = None+++def _canonical_symbols(text: str) -> str:+ """Rewrite spellings that change no value: the Unicode minus, LaTeX thousands separators."""+ text = text.replace("\u2212", "-").replace("{,}", ",")+ return _LATEX_SPACING_RE.sub("", text)+++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 = text.lstrip(_EDGE_CHARS).rstrip(_TRAILING_CHARS)+ return " ".join(text.split())+++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()+++def _to_decimal(literal: str) -> Decimal | None:+ try:+ return Decimal(literal.replace(",", ""))+ except InvalidOperation: # pragma: no cover - _NUMBER_RE admits only valid literals+ return None+++def parse_number(text: str) -> Decimal | None:+ """Return the value of ``text`` when, normalised, it is exactly one number; else ``None``."""+ candidate = normalize_answer(text)+ if _NUMBER_RE.fullmatch(candidate) is None:+ return None+ return _to_decimal(candidate)+++def _line_end(text: str, start: int) -> int:+ end = text.find("\n", start)+ return len(text) if end < 0 else end+++def _split_clause(line: str) -> tuple[str, str]:+ """Split the text after an answer phrase into its clause's ``(answer, aside)``.++ The clause ends at ". ", ", " or "; " outside brackets, unless a number follows the comma+ or semicolon ("41, 42 or 43" is one clause). A " (" aside is in the clause, not the answer.+ """+ line = line.lstrip()+ depth = 0+ aside = None+ for match in _CLAUSE_CHAR_RE.finditer(line):+ char, index = match.group(), match.start()+ if char in _OPENERS:+ if char == "(" and depth == 0 and aside is None and index and line[index - 1].isspace():+ aside = index+ depth += 1+ elif char in _CLOSERS:+ depth = max(0, depth - 1)+ elif depth == 0 and line[index + 1 : index + 2].isspace():+ if char in ",;" and _NUMBER_AHEAD_RE.match(line, index + 1):+ continue+ line = line[:index]+ break+ return (line, "") if aside is None else (line[:aside], line[aside:])+++def _clause_values(answer: str, aside: str) -> frozenset[Decimal]:+ """The distinct values a clause names: the answer's stand-alone numbers outside brackets,+ and every stand-alone number in its aside. Both texts are normalised."""+ values: set[Decimal | None] = set()+ depth = 0+ for match in _VALUE_TOKEN_RE.finditer(answer):+ token = match.group()+ if match.group(1) is not None:+ if depth == 0:+ values.add(_to_decimal(match.group(1)))+ elif token in _OPENERS:+ depth += 1+ elif token in _CLOSERS:+ depth = max(0, depth - 1)+ # Any other token is a time or a ratio: one answer, not a value.+ values.update(_to_decimal(m.group(1)) for m in _VALUE_TOKEN_RE.finditer(aside) if m.group(1))+ values.discard(None)+ return frozenset(values)+++def _clause_reading(text: str, start: int) -> tuple[str, frozenset[Decimal]]:+ """Return ``(answer, values)`` for the clause that starts at ``start``."""+ answer, aside = _split_clause(text[start : _line_end(text, start)])+ answer = normalize_answer(answer)+ return answer, _clause_values(answer, normalize_answer(aside))+++class _Explicit(NamedTuple):+ """An answer a text states explicitly."""++ answer: str+ delimited: bool # after '####' or inside \boxed{}+ values: frozenset[Decimal] # a phrase clause's distinct values; empty when delimited+ text_follows: bool = False # a '####' answer with more text after its line+++def _marker_answer(text: str) -> tuple[int, _Explicit] | None:+ """Return ``(position, explicit answer)`` for the last ``####`` line, if it has one."""+ index = text.rfind(_MARKER)+ if index < 0:+ return None+ start = index + len(_MARKER)+ end = _line_end(text, start)+ if _ANSWER_LABEL_RE.fullmatch(text, start, end):+ # "#### Final Answer" is a markdown heading; the answer is the next non-empty line,+ # read like an answer phrase's clause.+ found = _NON_SPACE_RE.search(text, end)+ if found is None:+ return None+ answer, values = _clause_reading(text, found.start())+ return (found.start(), _Explicit(answer, False, values)) if answer else None+ answer = normalize_answer(text[start:end])+ if not answer:+ return None+ text_follows = _NON_SPACE_RE.search(text, end) is not None+ return start, _Explicit(answer, True, frozenset(), text_follows)+++def _closing_brace(text: str, start: int, limit: int) -> int | None:+ depth = 1+ for match in _BRACE_RE.finditer(text, start, limit):+ depth += 1 if match.group() == "{" else -1+ if depth == 0:+ return match.start()+ return None+++def _boxed_answer(text: str) -> tuple[int, str] | None:+ """Return ``(position, answer)`` for the last ``\\boxed{...}`` that closes, if any."""+ # Walk the boxes from the last one back. When a box never closes, an earlier box can only+ # close BEFORE that box's brace (it would have to close the later box first), so each scan+ # stops at the next box's brace and the whole walk is linear.+ matches = list(_BOXED_OPEN_RE.finditer(text))+ limit = len(text)+ for match in reversed(matches):+ close = _closing_brace(text, match.end(), limit)+ if close is not None:+ answer = normalize_answer(text[match.end() : close])+ return (match.start(), answer) if answer else None+ limit = match.end() - 1+ return None+++def _phrase_answer(text: str) -> tuple[int, _Explicit] | None:+ """Return ``(position, explicit answer)`` for the last answer phrase, if its clause is not+ empty."""+ last = None+ for last in _PHRASE_RE.finditer(text):+ pass+ if last is None:+ return None+ answer, values = _clause_reading(text, last.end())+ return (last.end(), _Explicit(answer, False, values)) if answer else None+++def _explicit_answer(text: str) -> _Explicit | None:+ """Return ``(answer, delimited, values)`` for the answer ``text`` states explicitly."""+ marker = _marker_answer(text)+ boxed = _boxed_answer(text)+ phrase = _phrase_answer(text)+ if marker is not None:+ position, explicit = marker+ # A box or a phrase that comes after the '####' line supersedes it.+ boxed = boxed if boxed is not None and boxed[0] >= position else None+ phrase = phrase if phrase is not None and phrase[0] >= position else None+ if boxed is None and phrase is None:+ return explicit+ if boxed is not None:+ return _Explicit(boxed[1], True, frozenset())+ if phrase is not None:+ return phrase[1]+ return None+++def _is_hedge(explicit: _Explicit) -> bool:+ """An answer clause that names more than one distinct value ("either 41 or 42")."""+ return not explicit.delimited and len(explicit.values) > 1+++def _names_an_answer_form(text: str) -> bool:+ return (+ _MARKER in text+ or _BOXED_OPEN_RE.search(text) is not None+ or _PHRASE_RE.search(text) is not None+ )+++def _last_number(text: str) -> Decimal | None:+ last = None+ for last in _NUMBER_RE.finditer(_canonical_symbols(text)):+ pass+ return None if last is None else _to_decimal(last.group())+++def extract_final_answer(text: str) -> str | None:+ """Return the normalised answer ``text`` states explicitly, or ``None`` when it states none+ (a hedge such as "The answer is either 41 or 42." states none)."""+ found = _explicit_answer(text)+ return None if found is None or _is_hedge(found) else found.answer+++def parse_reference(text: str) -> FinalAnswer | None:+ """Read a gold reference; ``None`` when it states no answer a reward could compare against.++ A reference is never read as free text: without an explicit answer it must be a bare,+ one-line answer. A reference that names an answer form but leaves it empty+ (``"...\\n####"``, ``"\\boxed{}"``), or whose answer phrase hedges between several values,+ is ``None`` too. So is one whose ``####`` line is not a number and has more text after it+ (``"#### Solution\\nSix times seven is 42."``): that line may be a markdown heading over an+ unmarked body, and a reference must not be ambiguous. A completion's ``####`` line is its+ answer either way (``"#### Paris\\nHope this helps!"``).+ """+ 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):+ return None+ return FinalAnswer(found.answer, number)+ 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+++def parse_completion(text: str) -> FinalAnswer | None:+ """Read a model completion; ``None`` when it is empty or its answer phrase hedges."""+ found = _explicit_answer(text)+ 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)+ 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:+ number = _last_number(text)+ return FinalAnswer(found.answer, number)+ stripped = text.rstrip()+ if not stripped:+ return None+ last_line = stripped[stripped.rfind("\n") + 1 :]+ return FinalAnswer(normalize_answer(last_line), _last_number(text))+++def answers_match(completion: FinalAnswer | None, reference: FinalAnswer) -> bool:+ """Exact match: by value when the reference is a number, else as normalised text."""+ if completion is None:+ return False+ if reference.number is not None:+ return completion.number is not None and completion.number == reference.number+ key = _text_key(reference.text)+ return bool(key) and _text_key(completion.text) == keydiff --git a/tests/test_grpo.py b/tests/test_grpo.pyindex 8f7c131a..7910b9b2 100644--- a/tests/test_grpo.py+++ b/tests/test_grpo.py@@ -140,12 +140,15 @@ class TestAccuracyReward:rewards = accuracy_reward(completions, answer=["42"])assert rewards == [1.0]- def test_partial_match(self):+ def test_answer_phrase_followed_by_a_unit_scores_full_credit(self):+ # #1226: there is no 0.5 substring credit any more. After an answer phrase, "42 degrees"+ # is not a bare number, so its number is read from that clause: 42. (After '####' or+ # inside \boxed{} the answer must BE the number: '#### 42 apples' scores 0.0.)from soup_cli.trainer.rewards import accuracy_rewardcompletions = [[{"role": "assistant", "content": "The answer is 42 degrees"}]]rewards = accuracy_reward(completions, answer=["42"])- assert rewards == [0.5]+ assert rewards == [1.0]def test_no_match(self):from soup_cli.trainer.rewards import accuracy_reward@@ -163,7 +166,8 @@ class TestAccuracyReward:[{"role": "assistant", "content": "The answer is 42"}],]rewards = accuracy_reward(completions, answer=["42", "42", "42"])- assert rewards == [1.0, 0.0, 0.5]+ # #1226: "The answer is 42" is an explicit answer now, not a 0.5 substring hit.+ assert rewards == [1.0, 0.0, 1.0]def test_empty_completion(self):from soup_cli.trainer.rewards import accuracy_rewarddiff --git a/tests/test_issue1226_clause_scanner_is_linear.py b/tests/test_issue1226_clause_scanner_is_linear.pynew file mode 100644index 00000000..fe71c9d8--- /dev/null+++ b/tests/test_issue1226_clause_scanner_is_linear.py@@ -0,0 +1,124 @@+r"""The #1226 answer-clause scanner is linear in a whitespace run (found reviewing the fix).++An answer clause ends at ", " or "; " unless a number follows ("41, 42 or 43"). The look-ahead+for that number had two ``\s*`` around an optional ``$`` / ``\(`` / ``\[``, so a whitespace run+that no number follows was re-split between them at every length: "The answer is 42," plus+40,000 spaces took over 90 s across the two rewards, and that text is a GRPO policy's own+completion.++The test compares the time at N with the time at 8N instead of checking an absolute time, so it+holds on any machine and fails fast: a linear scan grows about 8x, the quadratic one grew+61-66x, and at N = 1,000 the quadratic scan failed each case in 10-13 s. The absolute 2 s+bound on 20,000 spaces is in ``TestAdversarialInputsStayLinear`` of+``test_issue1226_reward_gold_parsing.py``.++The second class pins what the look-ahead matches, so a faster rewrite cannot change which+clauses continue a list.+"""++from __future__ import annotations++import time+from decimal import Decimal++import pytest++from soup_cli.trainer.rewards import accuracy_reward, math_verify_reward+from soup_cli.utils.final_answer import parse_completion+++def _msg(text: str) -> list[list[dict]]:+ return [[{"role": "assistant", "content": text}]]+++def _scores(completion: str, gold: str) -> tuple[float, float]:+ return (+ accuracy_reward(_msg(completion), answer=[gold])[0],+ math_verify_reward(_msg(completion), answer=[gold])[0],+ )+++# A whitespace run after ", " or "; " in an answer clause, with no number after it. The first+# three were quadratic. The last two put the run after "$" or "\(", where the look-ahead's+# second whitespace match sits, so a rewrite cannot move the problem there unnoticed.+WHITESPACE_RUNS = {+ "comma-spaces": lambda k: "The answer is 42," + " " * k + "x",+ "semicolon-tabs": lambda k: "Answer: 42;" + "\t" * k + "x",+ "comma-unicode-whitespace": lambda k: (+ "The answer is 42," + " \t\N{NO-BREAK SPACE}\N{IDEOGRAPHIC SPACE}" * (k // 4) + "x"+ ),+ "comma-dollar-spaces": lambda k: "The answer is 42, $" + " " * k + "x",+ "comma-math-delimiter-spaces": lambda k: "The answer is 42, \\(" + " " * k + "x",+}++_SCALE_N = 1_000+# A linear scan takes about 8x as long on 8x the input: 6.5-7.4x measured, the fixed cost of a+# call pulling it below 8. The quadratic scan took 61-66x. The limit leaves 3x of slack over+# linear, and every time is a best of several runs, so a stall on a busy runner would have to+# hit every run of the larger input to fail the test.+_SCALE_LIMIT = 24.0+++def _best_time(text: str, repeats: int) -> float:+ best = float("inf")+ for _ in range(repeats):+ start = time.perf_counter()+ parse_completion(text)+ best = min(best, time.perf_counter() - start)+ return best+++class TestTheClauseScannerIsLinear:+ @pytest.mark.parametrize("build", list(WHITESPACE_RUNS.values()), ids=list(WHITESPACE_RUNS))+ def test_time_grows_linearly_with_a_whitespace_run(self, build):+ small, large = build(_SCALE_N), build(8 * _SCALE_N)+ # The clause ends at the comma or semicolon, so the answer is 42 at every size.+ assert parse_completion(large).number == Decimal(42)+ 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 <= _SCALE_LIMIT * t_small:+ break+ assert t_large <= _SCALE_LIMIT * t_small, (+ f"8x the whitespace took {t_large / t_small:.0f}x as long "+ f"({t_small * 1e3:.2f} ms -> {t_large * 1e3:.2f} ms)"+ )+++# After ", " or "; " a number continues the list in every spelling the look-ahead accepts: a+# sign, a leading ".", a "$", "\(" or "\[" before it, and whitespace in between.+CONTINUED_LISTS = [+ ("The answer is 41, 42 or 43.", ["41", "42", "43"]),+ ("The answer is 41,\t42.", ["41", "42"]),+ ("The answer is 41, $42$.", ["41", "42"]),+ ("The answer is 41, $ 42$.", ["41", "42"]),+ ("The answer is 41, \\(42\\).", ["41", "42"]),+ ("The answer is 41, \\[ 42 \\].", ["41", "42"]),+ ("The answer is 41, -42.", ["41", "-42"]),+ ("The answer is 41, +42.", ["41", "42"]),+ ("The answer is 41; \N{MINUS SIGN}42.", ["41", "-42"]),+ ("The answer is 41, .5.", ["41", "0.5"]),+]+# ...and anything else after the comma ends the clause, whose one value is the answer.+ENDED_CLAUSES = [+ "The answer is 41, not 42.",+ "The answer is 41, $x$ is 42.",+ "The answer is 41, \\(x\\) is 42.",+ "The answer is 41, -x is 42.",+ "The answer is 41, . 42",+]+++class TestWhatContinuesAList:+ @pytest.mark.parametrize(("completion", "values"), CONTINUED_LISTS)+ def test_a_number_after_the_comma_continues_the_list(self, completion, values):+ assert parse_completion(completion) is None # the list is a hedge+ for value in values:+ assert _scores(completion, value) == (0.0, 0.0), value++ @pytest.mark.parametrize("completion", ENDED_CLAUSES)+ def test_anything_else_after_the_comma_ends_the_clause(self, completion):+ assert parse_completion(completion).number == Decimal(41)+ assert _scores(completion, "41") == (1.0, 1.0)+ assert _scores(completion, "42") == (0.0, 0.0)diff --git a/tests/test_issue1226_grpo_gold_validation.py b/tests/test_issue1226_grpo_gold_validation.pynew file mode 100644index 00000000..36261718--- /dev/null+++ b/tests/test_issue1226_grpo_gold_validation.py@@ -0,0 +1,417 @@+"""GRPO data-side regression tests for #1226: loader -> validation -> reward.++``_validate_grpo_reward_metadata`` reads every gold with the same parser the rewards use+(``soup_cli.utils.final_answer``). It refuses a gold only when no final answer can be extracted+from it at all, and it reports how many golds are non-numeric (compared as normalised text) so a+dataset that silently scores 0.0 is visible. The parsing matrix itself is in+``test_issue1226_reward_gold_parsing.py``.+"""++from __future__ import annotations++import importlib+import json+import re+from decimal import Decimal+from pathlib import Path++import pytest++from soup_cli.config.loader import load_config_from_string+from soup_cli.config.schema import DataConfig, TrainingConfig+from soup_cli.data.loader import load_dataset+from soup_cli.trainer.grpo import _prepare_grpo_dataset, _validate_grpo_reward_metadata+from soup_cli.trainer.rewards import (+ load_reward_fn,+ load_reward_fns,+ math_verify_reward,+ validate_reward_funcs,+)++_REPO = Path(__file__).resolve().parents[1]+_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")+_SUMMARY = "golds are non-numeric and are compared as normalised text"+++def _plain(text: str) -> str:+ """ANSI-stripped, whitespace-collapsed console output, safe to substring-match."""+ return " ".join(_ANSI_RE.sub("", text).split())+++def _msg(text: str) -> list[list[dict]]:+ return [[{"role": "assistant", "content": text}]]+++def _write_jsonl(path: Path, rows: list[dict]) -> Path:+ path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8")+ return path+++def _load_prepared(tmp_path: Path, rows: list[dict], fmt: str) -> list[dict]:+ path = _write_jsonl(tmp_path / "train.jsonl", rows)+ loaded = load_dataset(+ DataConfig(train=str(path), format=fmt, val_split=0), preserve_source_columns=True+ )+ return _prepare_grpo_dataset(loaded["train"])+++# ===========================================================================+# the real data path: loader -> _prepare_grpo_dataset -> validation -> reward+# ===========================================================================++_GROUP = [+ "Six times seven is 42.\n#### 42",+ r"6*7 = \boxed{42}",+ "The product is 42.\n#### 42",+ "I think it is 41.\n#### 41",+]+++def _alpaca_rows() -> list[dict]:+ return [+ {"instruction": f"What is 6*7? (v{i})", "input": "", "output": "6*7=42\n#### 42"}+ for i in range(4)+ ]+++def _sharegpt_rows() -> list[dict]:+ return [+ {+ "conversations": [+ {"from": "human", "value": f"What is 6*7? (v{i})"},+ {"from": "gpt", "value": r"6 times 7 is \boxed{42}"},+ ]+ }+ for i in range(4)+ ]+++def _chatml_rows() -> list[dict]:+ return [+ {+ "messages": [+ {"role": "user", "content": f"What is 6*7? (v{i})"},+ {"role": "assistant", "content": "The answer is 42."},+ ]+ }+ for i in range(4)+ ]+++class TestGrpoDataPath:+ @pytest.mark.parametrize(+ ("fmt", "make_rows"),+ [("alpaca", _alpaca_rows), ("sharegpt", _sharegpt_rows), ("chatml", _chatml_rows)],+ )+ @pytest.mark.parametrize(("reward_fn", "domain"), [("accuracy", None), ("verifiable", "math")])+ def test_three_correct_one_wrong_group_has_reward_variance(+ self, tmp_path, fmt, make_rows, reward_fn, domain+ ):+ prepared = _load_prepared(tmp_path, make_rows(), fmt)+ tcfg = TrainingConfig(reward_fn=reward_fn, verifiable_domain=domain)+ _validate_grpo_reward_metadata(prepared, tcfg, split="train")++ reward = validate_reward_funcs(+ load_reward_fns(tcfg.reward_fn, verifiable_domain=tcfg.verifiable_domain)+ )[0]+ gold = prepared[0]["answer"]+ rewards = reward(+ completions=[_msg(text)[0] for text in _GROUP], answer=[gold] * len(_GROUP)+ )+ assert rewards == [1.0, 1.0, 1.0, 0.0]+ assert len(set(rewards)) > 1 # non-zero group variance: GRPO gets an advantage signal+++# ===========================================================================+# a MATH-500-like dataset mixing numeric and LaTeX golds (maintainer ruling)+# ===========================================================================++# (problem, gold, a correct completion, a wrong completion)+MIXED_MATH = [+ ("What is 6*7?", "42", r"\boxed{42}", r"\boxed{41}"),+ (+ "Simplify 28/6.",+ r"\frac{14}{3}",+ r"So it is \boxed{\dfrac{14}{3}}.",+ r"\boxed{\frac{3}{14}}",+ ),+ (+ "Convert (0,3) to polar coordinates.",+ r"\left( 3, \frac{\pi}{2} \right)",+ r"The answer is \left(3,\frac{\pi}{2}\right).",+ r"\boxed{(3, \pi)}",+ ),+ ("Simplify -(q - p).", "p - q", r"\boxed{p-q}", r"\boxed{q - p}"),+ ("How many clips?", "Natalia sold 72 clips.\n#### 72", "#### 72", "#### 27"),+ ("The angle?", r"90^\circ", r"\boxed{90^\circ}", r"\boxed{45^\circ}"),+ ("Half of one?", r"\dfrac{1}{2}", r"\boxed{\tfrac{1}{2}}", r"\boxed{\frac{1}{3}}"),+ ("How many?", "10", "There are 10 of them.", "There are 11 of them."),+]+++def _mixed_rows() -> list[dict]:+ return [+ {"instruction": problem, "input": "", "output": "A worked solution.", "answer": gold}+ for problem, gold, _right, _wrong in MIXED_MATH+ ]+++class TestMixedMathDataset:+ @pytest.mark.parametrize(("reward_fn", "domain"), [("verifiable", "math"), ("accuracy", None)])+ def test_a_mixed_dataset_loads_and_reports_its_text_golds(+ self, tmp_path, capsys, reward_fn, domain+ ):+ 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)++ def test_every_row_pays_its_right_answer_and_not_its_wrong_one(self, tmp_path):+ prepared = _load_prepared(tmp_path, _mixed_rows(), "alpaca")+ golds = [row["answer"] for row in prepared]+ right = [_msg(right)[0] for _p, _g, right, _w in MIXED_MATH]+ wrong = [_msg(wrong)[0] for _p, _g, _r, wrong in MIXED_MATH]+ assert math_verify_reward(right, answer=golds) == [1.0] * len(golds)+ assert math_verify_reward(wrong, answer=golds) == [0.0] * len(golds)++ def test_no_summary_when_every_gold_is_a_number(self, tmp_path, capsys):+ prepared = _load_prepared(tmp_path, _alpaca_rows(), "alpaca")+ tcfg = TrainingConfig(reward_fn="verifiable", verifiable_domain="math")+ _validate_grpo_reward_metadata(prepared, tcfg, split="train")+ assert _SUMMARY not in _plain(capsys.readouterr().out)+++# ===========================================================================+# a gold with no extractable final answer is refused before generation+# ===========================================================================+++class TestUnparseableGoldRefused:+ @pytest.mark.parametrize(+ ("reward_fn", "domain", "reward_name", "gold"),+ [+ ("verifiable", "math", "verifiable/math", "6*7 is\nforty-two"),+ ("verifiable", "math", "verifiable/math", "6*7=42\n####"),+ ("verifiable", "math", "verifiable/math", r"\boxed{}"),+ ("accuracy", None, "accuracy", "Step 1: multiply six by seven.\nStep 2: report it."),+ ("accuracy", None, "accuracy", "6*7=42\n####"),+ ("accuracy", None, "accuracy", r"\boxed{}"),+ ("accuracy", None, "accuracy", "Answer:"),+ ("accuracy,format", None, "accuracy", "Line one\nLine two"),+ ],+ )+ def test_refusal_names_the_row_the_field_and_the_remedy(+ self, reward_fn, domain, reward_name, gold+ ):+ tcfg = TrainingConfig(reward_fn=reward_fn, verifiable_domain=domain)+ rows = [+ {"prompt": "q0", "answer": "#### 42"},+ {"prompt": "q1", "answer": r"\frac{14}{3}"},+ {"prompt": "q2", "answer": gold},+ ]+ with pytest.raises(ValueError) as excinfo:+ _validate_grpo_reward_metadata(rows, tcfg, split="train")+ message = str(excinfo.value)+ assert "GRPO train row 2 'answer'" in message+ assert f"reward {reward_name!r}" in message+ assert "Alpaca 'output'" in message # where the field comes from+ assert "####" in message and r"\boxed{}" in message and "drop the row" in message+ assert "more of the" not in message # only one row is unreadable++ def test_refusal_counts_every_unreadable_row(self):+ tcfg = TrainingConfig(reward_fn="verifiable", verifiable_domain="math")+ rows = [+ {"prompt": "q0", "answer": "42"},+ {"prompt": "q1", "answer": "Step 1.\nStep 2."},+ {"prompt": "q2", "answer": r"\frac{1}{2}"},+ {"prompt": "q3", "answer": r"\boxed{}"},+ {"prompt": "q4", "answer": "Line one\nLine two"},+ ]+ with pytest.raises(ValueError) as excinfo:+ _validate_grpo_reward_metadata(rows, tcfg, split="train")+ message = str(excinfo.value)+ assert "GRPO train row 1 'answer'" in message+ assert "2 more of the 5 rows have the same problem" in message++ def test_a_hedged_gold_is_refused_and_counted_like_an_unreadable_one(self):+ tcfg = TrainingConfig(reward_fn="verifiable", verifiable_domain="math")+ rows = [+ {"prompt": "q0", "answer": "42"},+ {"prompt": "q1", "answer": "The answer is either 41 or 42."},+ {"prompt": "q2", "answer": r"\frac{1}{2}"},+ {"prompt": "q3", "answer": "Line one\nLine two"},+ ]+ with pytest.raises(ValueError) as excinfo:+ _validate_grpo_reward_metadata(rows, tcfg, split="train")+ message = str(excinfo.value)+ assert "GRPO train row 1 'answer'" in message+ assert "1 more of the 4 rows have the same problem" in message+ assert "more than one number" in message++ @pytest.mark.parametrize(+ "gold",+ [+ "The answer is 42 (i.e. 42.0).", # one value, said twice+ "The answer is 41 apples, not 42.", # the clause ends at the comma+ "#### 41 or 42", # inside a delimiter the answer is compared whole, as text+ "(3, 4)", # a tuple is one answer+ "-2, 1", # a bare list gold (MATH-500 has them) is not a phrase+ ],+ )+ @pytest.mark.parametrize(("reward_fn", "domain"), [("accuracy", None), ("verifiable", "math")])+ def test_single_value_phrases_and_delimited_or_bare_lists_pass(self, gold, reward_fn, domain):+ _validate_grpo_reward_metadata(+ [{"prompt": "q", "answer": gold}],+ TrainingConfig(reward_fn=reward_fn, verifiable_domain=domain),+ split="train",+ )++ def test_refusal_names_the_split(self):+ with pytest.raises(ValueError, match=r"GRPO validation row 0 'answer'"):+ _validate_grpo_reward_metadata(+ [{"prompt": "q", "answer": "Line one\nLine two"}],+ TrainingConfig(reward_fn="verifiable", verifiable_domain="math"),+ split="validation",+ )++ @pytest.mark.parametrize(+ ("reward_fn", "domain", "gold"),+ [+ (reward_fn, domain, gold)+ for reward_fn, domain in (("accuracy", None), ("verifiable", "math"))+ for gold in (+ "42", 42, 3.5, "1,000", "#### 42", "6*7=42\n#### 42", r"\boxed{42}",+ "The answer is 42.", "**Answer**: 42", r"\(42\)", "Answer:\n42",+ "#### Final Answer\n42", "Paris", "The answer is forty-two.", r"\frac{1}{2}",+ r"\left( 3, \frac{\pi}{2} \right)", "p - q", r"90^\circ",+ )+ ]+ + [("verifiable", "code", "multi\nline stdout")],+ )+ def test_extractable_golds_pass_for_both_rewards(self, reward_fn, domain, gold):+ _validate_grpo_reward_metadata(+ [{"prompt": "q", "answer": gold}],+ TrainingConfig(reward_fn=reward_fn, verifiable_domain=domain),+ split="train",+ )+++# ===========================================================================+# seed rows that a rollout backend replaces are never scored, so they are not parsed+# ===========================================================================+++class TestSeedRowsBeforeARollout:+ def _tcfg(self, rollout: bool) -> TrainingConfig:+ extra = (+ {"rollout_backend": "openenv", "rollout_func": "soup_cli.envs.calculator:rollout"}+ if rollout+ else {}+ )+ return TrainingConfig(reward_fn="verifiable", verifiable_domain="math", **extra)++ def test_seed_rows_keep_the_presence_check_but_are_not_parsed(self):+ unreadable = [{"prompt": "q", "answer": "Step 1.\nStep 2."}]+ _validate_grpo_reward_metadata(unreadable, self._tcfg(rollout=True), split="train")+ with pytest.raises(ValueError, match="missing or empty 'answer'"):+ _validate_grpo_reward_metadata(+ [{"prompt": "q"}], self._tcfg(rollout=True), split="train"+ )++ def test_the_rows_that_are_scored_are_still_parsed(self):+ unreadable = [{"prompt": "q", "answer": "Step 1.\nStep 2."}]+ for split, rollout in (("rollout", True), ("validation", True), ("train", False)):+ with pytest.raises(ValueError, match=f"GRPO {split} row 0 'answer'"):+ _validate_grpo_reward_metadata(unreadable, self._tcfg(rollout), split=split)+++# ===========================================================================+# the repo's own GRPO data still validates, and now gets a signal+# ===========================================================================+++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+ ):+ from soup_cli.utils.final_answer import parse_reference++ example = _REPO / "examples" / "configs" / "grpo_reasoning.yaml"+ cfg = load_config_from_string(example.read_text(encoding="utf-8"))+ assert cfg.training.reward_fn == "accuracy"+ data = DataConfig(+ train=str(_REPO / "examples" / "data" / "reasoning_math.jsonl"),+ format="alpaca",+ val_split=0,+ )+ 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)++ 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)]++ @pytest.mark.parametrize(+ ("module", "reward_fn", "domain"),+ [+ ("calculator", "verifiable", "math"),+ ("guess_number", "verifiable", "math"),+ ("retrieval_qa", "accuracy", None),+ ],+ )+ def test_bundled_rollout_envs_validate_and_pay_a_just_the_value_reply(+ self, module, reward_fn, domain+ ):+ rows = importlib.import_module(f"soup_cli.envs.{module}").rollout([])+ prepared = _prepare_grpo_dataset([dict(row) for row in rows])+ tcfg = TrainingConfig(reward_fn=reward_fn, verifiable_domain=domain)+ _validate_grpo_reward_metadata(prepared, tcfg, split="rollout")++ # Every env prompt says "Reply with just the value/number".+ reward = load_reward_fns(reward_fn, verifiable_domain=domain)[0]+ golds = [row["answer"] for row in prepared]+ assert reward([_msg(gold)[0] for gold in golds], answer=golds) == [1.0] * len(golds)+++# ===========================================================================+# the reward-hacking surface: answer spray no longer pays+# ===========================================================================+++class TestAnswerSprayNoLongerPays:+ def test_builtin_accuracy_rejects_every_answer_spray_variant(self):+ import soup_cli.utils.reward_stress as rst++ report = rst.run_stress(load_reward_fn("accuracy"), ["42", "17", "1000", "-3"])+ per_attack = {attack.kind: attack for attack in report.attacks}+ assert per_attack["answer_spray"].accepted == 0+ assert report.gameable is False+ assert report.reference_accept == 1.0++ def test_reward_stress_cli_reports_builtin_accuracy_robust(self, tmp_path, monkeypatch):+ from typer.testing import CliRunner++ from soup_cli.cli import app as soup_app++ monkeypatch.chdir(tmp_path)+ refs = _write_jsonl(tmp_path / "refs.jsonl", [{"answer": "42"}, {"answer": "17"}])+ report_path = tmp_path / "report.json"+ result = CliRunner().invoke(+ soup_app,+ [+ "reward", "stress", "accuracy",+ "--references", str(refs),+ "--output-report", str(report_path),+ ],+ )+ assert result.exit_code == 0, (result.output, repr(result.exception))+ assert "robust (not gameable)" in _plain(result.output).lower()+ report = json.loads(report_path.read_text(encoding="utf-8"))+ per_attack = {attack["kind"]: attack for attack in report["attacks"]}+ assert per_attack["answer_spray"]["accepted"] == 0diff --git a/tests/test_issue1226_parser_edge_cases.py b/tests/test_issue1226_parser_edge_cases.pynew file mode 100644index 00000000..b9ea06a5--- /dev/null+++ b/tests/test_issue1226_parser_edge_cases.py@@ -0,0 +1,221 @@+r"""Edge cases of the #1226 final-answer parser, found while reviewing the fix.++1. **A time or a ratio is one value.** "3:45" and "1:1,000" are one answer, like "4/5", so an+ answer phrase that states one is compared as text instead of being read as a hedge between+ its numbers (or, for "3:45pm", as the value 3).+2. **A justification inside the answer clause is a hedge.** This pins the ruling in+ ``test_issue1226_reward_gold_parsing.py``: every stand-alone number in the clause counts. A+ comma or a period before the justification ends the clause.+3. **A later answer phrase supersedes a "####" line**, chatter included ("I hope this answer is+ helpful!"): it cannot be told apart from a heading followed by its answer.+4. **A "####" heading is not a gold.** A reference whose "####" line is not a number and has more+ text after it ("#### Solution") may be a markdown heading over an unmarked body. It is+ refused before generation instead of becoming the text gold "Solution", which every+ completion would miss. A completion's "####" line stays its answer.++The linear-time check of the clause scanner is in ``test_issue1226_clause_scanner_is_linear.py``.+"""++from __future__ import annotations++from decimal import Decimal++import pytest++from soup_cli.config.schema import TrainingConfig+from soup_cli.trainer.grpo import _validate_grpo_reward_metadata+from soup_cli.trainer.rewards import accuracy_reward, math_verify_reward+from soup_cli.utils.final_answer import FinalAnswer, parse_completion, parse_reference++_REWARDS = [("accuracy", None), ("verifiable", "math")]+++def _msg(text: str) -> list[list[dict]]:+ return [[{"role": "assistant", "content": text}]]+++def _scores(completion: str, gold: str) -> tuple[float, float]:+ return (+ accuracy_reward(_msg(completion), answer=[gold])[0],+ math_verify_reward(_msg(completion), answer=[gold])[0],+ )+++def _validate(golds: list[str], reward_fn: str, domain: str | None) -> None:+ _validate_grpo_reward_metadata(+ [{"prompt": f"q{index}", "answer": gold} for index, gold in enumerate(golds)],+ TrainingConfig(reward_fn=reward_fn, verifiable_domain=domain),+ split="train",+ )+++# ===========================================================================+# 1. a time or a ratio is one value+# ===========================================================================++# (completion, the gold it states). Each is ONE answer, like "4/5", compared as text.+TIMES_AND_RATIOS = [+ ("The answer is 3:45.", "3:45"),+ ("The answer is 3:45 PM.", "3:45 PM"),+ ("The answer is 3:45pm.", "3:45pm"),+ ("Answer: 12:30", "12:30"),+ ("The answer is 12:30:15.", "12:30:15"),+ ("The answer is 3:4.", "3:4"),+ ("The final answer is 1:1,000.", "1:1,000"),+]+# (completion, numbers it contains): none of them is paid as the answer.+TIME_DIGITS = [+ ("The answer is 3:45.", ["3", "45"]),+ ("The answer is 3:45pm.", ["3", "45"]),+ ("The answer is 12:30:15.", ["12", "30", "15"]),+ ("The final answer is 1:10,500.", ["1", "10", "500", "10500"]),+]+++class TestATimeOrARatioIsOneValue:+ @pytest.mark.parametrize(("completion", "gold"), TIMES_AND_RATIOS)+ def test_it_is_read_whole_and_compared_as_text(self, completion, gold):+ assert parse_completion(completion) == FinalAnswer(gold, None)+ assert _scores(completion, gold) == (1.0, 1.0)++ @pytest.mark.parametrize(("completion", "numbers"), TIME_DIGITS)+ def test_none_of_its_numbers_is_paid_as_the_answer(self, completion, numbers):+ for number in numbers:+ assert _scores(completion, number) == (0.0, 0.0), number++ @pytest.mark.parametrize(("reward_fn", "domain"), _REWARDS)+ def test_a_gold_that_states_one_is_read_not_refused(self, reward_fn, domain):+ assert parse_reference("The answer is 3:45.") == FinalAnswer("3:45", None)+ _validate(+ ["The answer is 3:45.", "Answer: 12:30 PM", "The answer is 1:1,000."],+ reward_fn,+ domain,+ )++ def test_a_spaced_colon_is_two_values_as_a_spaced_slash_is(self):+ # Only a colon between two digits joins them, as only "4/5" (not "4 / 5") is a fraction.+ for completion in ("The answer is 3 : 4.", "The answer is 4 / 5."):+ assert parse_completion(completion) is None, completion++ def test_a_clause_naming_two_times_pays_neither(self):+ completion = "The answer is 3:45 or 4:15."+ assert _scores(completion, "3:45") == (0.0, 0.0)+ assert _scores(completion, "4:15") == (0.0, 0.0)+++# ===========================================================================+# 2. a justification inside the answer clause is a hedge (the ruling)+# ===========================================================================++# (completion, every number in its clause). Each scores 0.0 against every one of them.+JUSTIFIED_IN_THE_CLAUSE = [+ ("The answer is 42 because 6*7=42.", ["42", "6", "7"]),+ ("The answer is 42 because 6 times 7 is 42.", ["42", "6", "7"]),+ ("The answer is 42 (6*7=42).", ["42", "6", "7"]),+ ("The answer is 42 (option 3).", ["42", "3"]),+]+# A comma, a period or a line end before the justification ends the clause.+JUSTIFIED_AFTER_THE_CLAUSE = [+ "The answer is 42, because 6*7=42.",+ "The answer is 42. Because 6*7=42.",+ "The answer is 42\n6*7=42",+]+++class TestAJustificationInsideTheClause:+ @pytest.mark.parametrize(("completion", "numbers"), JUSTIFIED_IN_THE_CLAUSE)+ def test_is_a_hedge_and_pays_none_of_its_numbers(self, completion, numbers):+ assert parse_completion(completion) is None+ assert parse_reference(completion) is None # as a gold, it is refused+ for number in numbers:+ assert _scores(completion, number) == (0.0, 0.0), number++ @pytest.mark.parametrize("completion", JUSTIFIED_AFTER_THE_CLAUSE)+ def test_after_the_clause_it_is_not_part_of_the_answer(self, completion):+ assert parse_completion(completion).number == Decimal(42)+ assert parse_reference(completion).number == Decimal(42)+ assert _scores(completion, "42") == (1.0, 1.0)+++# ===========================================================================+# 3. a later answer phrase supersedes a '####' line, chatter included+# ===========================================================================+++class TestALaterAnswerPhraseAfterAMarker:+ def test_a_justification_in_the_later_phrase_makes_it_a_hedge(self):+ completion = "6*7=42\n#### 42\nThe answer is 42 because 6 x 7 = 42."+ assert parse_completion(completion) is None+ assert _scores(completion, "42") == (0.0, 0.0)++ def test_a_later_phrase_with_no_digits_leaves_the_number_to_the_last_number(self):+ completion = "#### 42\nI hope this answer is helpful!"+ assert parse_completion(completion) == FinalAnswer("helpful", Decimal(42))+ assert _scores(completion, "42") == (1.0, 1.0)++ def test_chatter_after_a_text_marker_supersedes_it_as_an_answer_under_a_heading_does(self):+ # Both texts are "#### <text>" followed by a later answer phrase; the parser cannot tell+ # the heading from the answer, so the later phrase wins in both.+ assert _scores("#### Solution\nThe answer is Paris.", "Paris") == (1.0, 1.0)+ assert _scores("#### Paris\nI hope this answer is helpful!", "Paris") == (0.0, 0.0)+ # With no answer phrase after it, the '####' line stays the answer.+ assert _scores("#### Paris\nHope this helps!", "Paris") == (1.0, 1.0)+++# ===========================================================================+# 4. a '####' heading is not a gold+# ===========================================================================++# A '####' line that is not a number and has more text after it may be a markdown heading over+# an unmarked body, so a gold cannot rely on it.+HEADING_GOLDS = [+ "#### Solution\nSix times seven is 42.",+ "#### Step 1\n6*7 = 42",+ "#### 1. Multiply\n6*7 = 42",+ "#### Worked solution\n\nMultiply six by seven to get 42.",+ "#### Paris\n(the capital of France)", # an answer and a note, or a heading: refused+]+# (gold, what it reads as): a '####' line that is a number (never a heading), the last line,+# or superseded by a later box or answer phrase is still read.+MARKER_GOLDS = [+ ("#### 42\nFrom GSM8K.", FinalAnswer("42", Decimal(42))),+ ("#### 1,000\nThat is the total.", FinalAnswer("1,000", Decimal(1000))),+ ("6*7=42\n#### 42\n\n", FinalAnswer("42", Decimal(42))),+ ("#### Paris", FinalAnswer("Paris", None)),+ ("#### Solution\nThe answer is 42.", FinalAnswer("42", Decimal(42))),+ ("#### Solution\n\\boxed{42}", FinalAnswer("42", Decimal(42))),+ ("#### Final Answer\n42", FinalAnswer("42", Decimal(42))),+]+++class TestAMarkerHeadingIsNotAGold:+ @pytest.mark.parametrize("gold", HEADING_GOLDS)+ @pytest.mark.parametrize(("reward_fn", "domain"), _REWARDS)+ def test_a_heading_gold_states_no_answer_and_is_refused(self, gold, reward_fn, domain):+ assert parse_reference(gold) is None+ with pytest.raises(ValueError) as excinfo:+ _validate([gold], reward_fn, domain)+ message = str(excinfo.value)+ assert "GRPO train row 0 'answer' states no single final answer" in message+ assert "markdown heading" in message++ def test_every_heading_row_is_counted(self):+ golds = ["42", HEADING_GOLDS[0], "Paris", HEADING_GOLDS[1], HEADING_GOLDS[2]]+ with pytest.raises(ValueError) as excinfo:+ _validate(golds, "verifiable", "math")+ message = str(excinfo.value)+ assert "GRPO train row 1 'answer'" in message+ assert "2 more of the 5 rows have the same problem" in message++ @pytest.mark.parametrize(("gold", "reading"), MARKER_GOLDS)+ @pytest.mark.parametrize(("reward_fn", "domain"), _REWARDS)+ def test_a_marker_that_is_an_answer_is_still_read(self, gold, reading, reward_fn, domain):+ assert parse_reference(gold) == reading+ _validate([gold], reward_fn, domain)++ def test_a_completion_keeps_its_marker_line_as_its_answer(self):+ # A completion is scored, never refused: its '####' line is its answer.+ assert parse_completion("#### Paris\nHope this helps!") == FinalAnswer("Paris", None)+ assert _scores("#### Paris\nHope this helps!", "Paris") == (1.0, 1.0)+ assert _scores("#### 42\nHope this helps!", "42") == (1.0, 1.0)+ assert _scores("#### Solution\nSix times seven is 42.", "42") == (0.0, 0.0)diff --git a/tests/test_issue1226_reward_gold_parsing.py b/tests/test_issue1226_reward_gold_parsing.pynew file mode 100644index 00000000..ab938f29--- /dev/null+++ b/tests/test_issue1226_reward_gold_parsing.py@@ -0,0 +1,793 @@+"""Regression tests for #1226: GRPO rewards parse the gold answer the way they parse completions.++``accuracy`` and ``verifiable/math`` extracted the final answer from the completion but compared+it with the RAW gold. With an Alpaca ``output`` or a ShareGPT reference turn such as+``6*7=42\\n#### 42`` exposed as ``answer``, every correct completion scored 0.0 and GRPO got no+signal; meanwhile the 0.5 substring credit paid wrong answers such as ``#### 420``. Both sides+now go through the one parser in ``soup_cli.utils.final_answer``.++The variant list below was written BEFORE the implementation, and the tests iterate all of it.+The boxed-answer fix for #357 matched the ticket's exact string and missed ``\\boxed {C}``, one+space to the left (#396), so no spelling here is checked in isolation.++The GRPO data side (loader -> validation -> reward, refusals, the validation summary, shipped+data, answer spray) is in ``test_issue1226_grpo_gold_validation.py``.+"""++from __future__ import annotations++import time+from collections import Counter+from decimal import Decimal++import pytest++from soup_cli.config.schema import TrainingConfig+from soup_cli.trainer.grpo import _validate_grpo_reward_metadata+from soup_cli.trainer.rewards import _extract_answer, accuracy_reward, math_verify_reward++MINUS = "\N{MINUS SIGN}" # U+2212, which models emit for a negative sign++# ===========================================================================+# THE VARIANT LIST - enumerated before any code was written. G/C/W 1-17 came first; the entries+# marked "review" were added before the second round of code (the review of this fix).+# ===========================================================================++# Gold spellings whose final answer is 42. G1-G9 are the table in #1226; G10+ are neighbours.+GOLDS_42 = {+ "G1 bare": "42",+ "G2 bare + newline": "42\n",+ "G3 decimal": "42.0",+ "G4 marker": "#### 42",+ "G5 marker without space": "####42",+ "G6 gsm8k reference": "6*7=42\n#### 42",+ "G7 boxed": r"\boxed{42}",+ "G8 boxed reference": r"6*7 = \boxed{42}",+ "G9 prose reference": "The answer is 42.",+ "G10 answer colon": "Answer: 42",+ "G11 boxed, space before brace": r"\boxed {42}",+ "G12 leading dollar": "$42",+ "G13 inline math": "The final answer is $42$.",+ "G14 multi-line reference ending in Answer:": "Step 1: 6*7 = 42\n\nAnswer: 42",+ "G15 surrounding whitespace": " 42 ",+ "G16 marker + period": "6*7=42\n#### 42.",+ "G17 explicit plus sign": "+42",+ "G18 markdown bold": "**Answer:** 42",+ # review: siblings of G13 / G18, the newline form, and a markdown heading before the answer+ "G19 bold label, colon outside": "**Answer**: 42",+ "G20 bold final label": "**Final Answer**: 42",+ "G21 inline math \\(...\\)": r"\(42\)",+ "G22 display math \\[...\\]": r"\[42\]",+ "G23 phrase + inline math": r"The answer is \(42\).",+ "G24 answer on the next line": "Answer:\n42",+ "G25 bold label, answer below": "**Answer:**\n\n42",+ "G26 heading before a box": "#### Final Answer\n" + r"\boxed{42}",+ "G27 heading before a phrase": "#### Step 1: multiply\n6*7 = 42\nThe answer is 42.",+ "G28 answer-label heading, answer below": "#### Final Answer\n42",+ "G29 heading with an inline label": "#### Answer: 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$",+}++# Completions that state the correct answer (42). C1-C10 are the table in #1226.+CORRECT_42 = {+ "C1 marker": "Six times seven is 42.\n#### 42",+ "C2 marker without space": "Six times seven is 42.\n####42",+ "C3 boxed": r"Six times seven is \boxed{42}.",+ "C4 boxed, space before brace": r"Six times seven is \boxed {42}.",+ "C5 boxed, inner spaces": r"Six times seven is \boxed{ 42 }.",+ "C6 prose only": "Six times seven is 42.",+ "C7 marker + trailing line": "#### 42\nHope this helps!",+ "C8 marker + period": "Six times seven.\n#### 42.",+ "C9 marker + dollar": "It costs\n#### $42",+ "C10 decimal": "#### 42.0",+ "C11 answer is": "Six times seven, so the answer is 42.",+ "C12 answer colon": "6 * 7\nAnswer: 42",+ "C13 minerva style": "Final Answer: The final answer is $42$. I hope it is correct.",+ "C14 markdown bold": "**Answer:** 42",+ "C15 boxed inside inline math": r"So $\boxed{42}$",+ "C16 boxed escaped dollar": r"\boxed{\$42}",+ "C17 marker + trailing spaces": "#### 42 ",+ "C18 lowercase answer": "answer: 42",+ "C19 answer, then a clause": "The answer is 42, which is 6 times 7.",+ "C20 five hashes": "##### 42",+ "C21 marker + exclamation": "#### 42!",+ "C22 the last box is the final answer": r"First guess \boxed{41}; corrected: \boxed{42}",+ "C23 answer phrase + unit": "The answer is 42 apples.",+ # review+ "C24 bold label, colon outside": "6 * 7\n**Answer**: 42",+ "C25 bold final label": "**Final Answer**: 42",+ "C26 marker + inline math": r"#### \(42\)",+ "C27 phrase + display math": r"The answer is \[42\]",+ "C28 answer on the next line": "6 * 7\nAnswer:\n42",+ "C29 bold label, answer below": "**Answer:**\n\n42",+ "C30 heading before a box": "#### Step 1\n6 * 7 = 42\n" + r"\boxed{42}",+ "C31 heading before a phrase": "#### Step 1: multiply\n6*7 = 42\nThe answer is 42.",+ "C32 answer-label heading, answer below": "#### Final Answer\n42",+ "C33 heading with an inline label": "#### Answer: 42",+ "C34 marker, then a box": r"#### \boxed{42}",+ "C35 phrase, answer on the next line": "The answer is\n42",+ "C36 the clause names the right answer first": "The answer is 42 apples, not 41.",+ "C37 worded clause, digits in an aside": "The answer is: forty-two (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}",+}++# Completions that state a WRONG answer (gold 42). W1-W2 are from #1226. None may score above 0.+WRONG_42 = {+ "W1 mentions the gold, boxes 41": r"It is not 42, so the answer is \boxed{41}.",+ "W2 420": "#### 420",+ "W3 gold in the reasoning, marker 41": "Is it 42?\n#### 41",+ "W4 boxed 420": r"\boxed{420}",+ "W5 answer is 41": "42 is tempting, but the answer is 41.",+ "W6 answer colon 41": "Answer: 41",+ "W7 self-correction": "The answer is 41, not 42.",+ "W8 near decimal": "#### 42.5",+ "W9 sign flipped": "#### -42",+ "W10 scaled": r"\boxed{4.2}",+ "W11 thousands": "#### 4,200",+ "W12 answer spray": "The candidate options considered were 42, 52, 62, and 44.",+ "W13 hedge inside the marker": "#### 42 or 43",+ "W14 the last box is wrong": r"\boxed{42} at first, then \boxed{41}",+ "W15 attached variable": r"\boxed{42x}",+ "W16 power": r"\boxed{42^2}",+ "W17 empty": "",+ # review: the answer clause is read first, so a gold named AFTER it is not the answer+ "W18 clause names the gold after the answer": "The answer is 41 apples, not 42.",+ "W19 colon form of W18": "Answer: 41 apples, not 42",+ "W20 gold in a parenthetical aside": "The answer is 41 apples (not 42).",+ "W21 gold in the next sentence": "The answer is 41 apples. 42 was my first guess.",+ "W22 gold after a semicolon": "The final answer is 41 apples; 42 is wrong.",+ "W23 a later box supersedes a right marker": "#### 42\n" + r"\boxed{41}",+ "W24 self-correction after a marker": "#### 42\nWait, the answer is 41.",+ "W25 bold label, wrong": "**Answer**: 41",+ "W26 answer-label heading, wrong answer below": "#### Final Answer\n41",+}++# Other values: thousands separators, negatives, decimals. (gold spellings, correct, wrong)+NUMERIC_GROUPS = {+ "1000": (+ ["1000", "1,000", "#### 1,000", r"\boxed{1{,}000}", "The answer is 1,000."],+ [+ "#### 1,000",+ r"\boxed{1,000}",+ "#### 1000",+ "The answer is 1,000.",+ r"\boxed{1{,}000}",+ r"\boxed{1,\!000}",+ r"\boxed{1\;000}",+ "#### $1,000",+ "The total is 1,000.",+ ],+ ["#### 1,001", "#### 100", "#### 10,000", r"\boxed{1,00}"],+ ),+ "1000000": (+ ["1000000", "1,000,000"],+ ["#### 1,000,000", r"\boxed{1,000,000}", "#### 1000000"],+ ["#### 1,000,001", "#### 100,000"],+ ),+ "-42": (+ ["-42", "#### -42", r"\boxed{-42}", "The answer is -42.", MINUS + "42", r"\(-42\)"],+ [+ "#### -42",+ r"\boxed{-42}",+ "The answer is -42.",+ "#### " + MINUS + "42",+ "It drops to -42.",+ r"\boxed{ -42 }",+ "#### -$42",+ ],+ ["#### 42", "#### -41", r"\boxed{-4.2}"],+ ),+ "0.5": (+ ["0.5", ".5", "#### 0.5", r"\boxed{0.50}"],+ ["#### 0.5", "#### .5", r"\boxed{0.50}", "The answer is 0.5.", "It is 0.5."],+ ["#### 5", "#### 0.05", "#### 50"],+ ),+ "-3.25": (+ ["-3.25", "#### -3.25"],+ ["#### -3.25", r"\boxed{-3.25}", "Answer: -3.25", r"\[-3.25\]"],+ ["#### 3.25", "#### -3.2"],+ ),+}++# Non-numeric golds: (gold, completion, expected). Both rewards compare them as normalised text.+STRING_GOLD_CASES = [+ ("Paris", "#### Paris", 1.0),+ ("Paris", r"\boxed{Paris}", 1.0),+ ("Paris", "The answer is Paris.", 1.0),+ ("Paris", "Paris", 1.0),+ ("Paris", "paris", 1.0),+ ("Paris", "Answer: PARIS", 1.0),+ ("Paris", "Let me think.\nParis", 1.0),+ ("Paris", "**Answer**: Paris", 1.0),+ ("Paris", "#### London", 0.0),+ ("Paris", "The answer is London, not Paris.", 0.0),+ ("Paris", "Not Paris.", 0.0),+ ("Paris", "Paris or London", 0.0),+ ("76 years", "76 years", 1.0),+ ("76 years", "The answer is 76 years.", 1.0),+ ("76 years", "#### 76 years", 1.0),+ ("76 years", "80 years", 0.0),+ ("76 years", "It is not 76 years.", 0.0),+ (r"\frac{1}{2}", r"\boxed{\frac{1}{2}}", 1.0),+ (r"\boxed{\frac{1}{2}}", r"so x = \boxed{\frac{1}{2}}", 1.0),+ (r"\frac{1}{2}", r"$\frac{1}{2}$", 1.0),+ (r"\frac{1}{2}", r"\boxed{\frac{1}{3}}", 0.0),+ # review (maintainer ruling): LaTeX golds, as in MATH-500+ (r"\frac{14}{3}", r"\boxed{\frac{14}{3}}", 1.0),+ (r"\frac{14}{3}", r"\boxed{\dfrac{14}{3}}", 1.0),+ (r"\dfrac{14}{3}", r"\boxed{\tfrac{14}{3}}", 1.0),+ (r"\frac{14}{3}", r"\boxed{\frac {14} {3}}", 1.0),+ (r"\frac{14}{3}", r"The answer is $\frac{14}{3}$.", 1.0),+ (r"\frac{14}{3}", r"The answer is \(\frac{14}{3}\).", 1.0),+ (r"\frac{14}{3}", r"\boxed{\frac{3}{14}}", 0.0),+ (r"\left( 3, \frac{\pi}{2} \right)", r"\boxed{(3,\frac{\pi}{2})}", 1.0),+ (r"\left( 3, \frac{\pi}{2} \right)", r"The answer is \left(3, \frac{\pi}{2}\right).", 1.0),+ (r"\left( 3, \frac{\pi}{2} \right)", r"\boxed{(3,\frac{\pi}{4})}", 0.0),+ ("p - q", r"\boxed{p-q}", 1.0),+ (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"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),+]++# Hedges (ruling): an answer clause that names more than one DISTINCT value states no answer.+# (completion, every value it hedges between). None of them may be paid for any of its values.+HEDGES = [+ ("The answer is either 41 or 42.", ["41", "42"]),+ ("Answer: 41 or 42", ["41", "42"]),+ ("the answer is 41, 42 or 43", ["41", "42", "43"]),+ ("The answer is 42 or 43.", ["42", "43"]),+ ("The answer is 42 (or 43).", ["42", "43"]), # an aside is part of the clause+ ("**Answer**: 41 or 42", ["41", "42"]),+ ("Answer:\n41 or 42", ["41", "42"]),+ ("#### Final Answer\n41 or 42", ["41", "42"]),+ ("#### 42\nThe answer is 41 or 42.", ["41", "42"]), # a later phrase supersedes the marker+ ("The final answer is 42; 43 is also possible.", ["42", "43"]), # "; " + a number goes on+ ("The answer is 41 apples (not 42).", ["41", "42"]),+ ("The answer is 41 apples or 42.", ["41", "42"]),+ ("The answer is 1,000 or 2,000.", ["1000", "2000"]),+ ("The answer is -3 or 3.", ["-3", "3"]),+ ("The answer is $41$ or $42$.", ["41", "42"]),+ ("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+]++# Not hedges: ONE value, maybe repeated or respelled; a tuple or an expression is one answer.+# (completion, gold, expected score in both rewards)+SINGLE_VALUE_CLAUSES = [+ ("The answer is 42 (i.e. 42.0).", "42", 1.0),+ ("The answer is 42 or 42.0.", "42", 1.0),+ ("The answer is 42, i.e. 42.0.", "42", 1.0),+ ("The answer is -42 (that is, " + MINUS + "42).", "-42", 1.0),+ ("The answer is 1,000 (one thousand).", "1000", 1.0),+ ("The answer is 41 apples, not 42.", "41", 1.0), # the comma ends the clause: only 41+ ("The answer is 41 apples, not 42.", "42", 0.0),+ ("The answer is 42 apples, not 41.", "42", 1.0),+ ("The answer is 42. 41 was my first guess.", "42", 1.0), # ". " ends the clause+ ("The answer is (3, 4).", "(3, 4)", 1.0), # a tuple is one answer+ (r"The answer is \left(3, \frac{\pi}{2}\right).", r"\left( 3, \frac{\pi}{2} \right)", 1.0),+ (r"The answer is \frac{14}{3}.", r"\frac{14}{3}", 1.0), # so is an expression...+ (r"The answer is \frac{14}{3}.", "3", 0.0), # ...and its digits are not its value+ (r"The answer is 2^{10}.", "10", 0.0),+ ("The answer is 2x.", "2", 0.0),+ ("41 or 42", "42", 1.0), # no answer phrase: an unmarked completion reads its last number+ (r"\boxed{42}. The answer is 41 or 42.", "42", 1.0), # a box outranks the phrase+ ("#### 41 or 42", "42", 0.0), # a delimited answer is compared whole: never a number+]++# Hedged golds are a data problem: refused, never compared.+HEDGED_GOLDS = [+ "The answer is either 41 or 42.",+ "Answer: 41 or 42",+ "the answer is 41, 42 or 43",+ "The answer is 42 (or 43).",+ "6*7 is 42.\nThe answer is 42 or 43.",+ "#### Final Answer\n41 or 42",+]++# The partial-credit policy, pinned: (completion, gold, accuracy before #1226, accuracy now).+# The 0.5 substring credit is REMOVED. It paid a wrong answer that mentions the gold exactly as+# much as a right answer in a spelling the parser missed, which is a reward-hacking surface.+POLICY_CHANGES = [+ ("The answer is 42 degrees", "42", 0.5, 1.0),+ ("Six times seven is 42.", "42", 0.5, 1.0),+ ("Not 42.", "42", 0.5, 1.0), # ruling: an unmarked completion is read by its last number+ (r"Not 42, so \boxed{41}", "42", 0.5, 0.0),+ ("#### 420", "42", 0.5, 0.0),+ ("The answer is 41 apples, not 42.", "42", 0.5, 0.0),+ ("The capital of France is Paris.", "Paris", 0.5, 0.0),+ # A '####' or \boxed{} answer must BE the number: a unit after it is not stripped.+ ("#### 42 apples", "42", 0.5, 0.0),+]++# Control: plain numeric golds that already worked. Identical on origin/main and after the fix.+# (completion, gold, accuracy, math_verify)+CONTROL_BOTH = [+ ("The answer is #### 42", "42", 1.0, 1.0),+ (r"So \boxed{42} is the result", "42", 1.0, 1.0),+ (r"\boxed{3.14}", "3.14", 1.0, 1.0),+ ("#### 3.14159", "3.14160", 0.0, 1.0),+ ("#### 3.141", "3.142", 0.0, 0.6),+ ("#### 3.0", "3.14159", 0.0, 0.0),+ ("#### 100", "42", 0.0, 0.0),+ ("no answer here", "42", 0.0, 0.0),+ ("I don't know", "42", 0.0, 0.0),+ ("#### __import__('os').system('rm')", "42", 0.0, 0.0),+ ("#### -17", "-17", 1.0, 1.0),+ ("#### 42.0", "42.0", 1.0, 1.0),+ ("Wrong answer", "42", 0.0, 0.0),+ ("", "42", 0.0, 0.0),+]+# math_verify only (accuracy's value for these moved to numeric equality by design).+CONTROL_MATH = [+ ("#### 100000", "1e5", 1.0),+ ("#### 42", "042", 1.0),+ ("Six times seven is 42.", "42", 1.0),+ ("The answer is 42", "42", 1.0),+ ("The answer is 42 apples.", "42", 1.0),+ ("#### 5", "+5", 1.0),+ ("The product is 1000", "1000", 1.0),+ ("#### 3.14", " 3.14 \n", 1.0),+]++# ===========================================================================+# helpers+# ===========================================================================+++def _msg(text: str) -> list[list[dict]]:+ return [[{"role": "assistant", "content": text}]]+++def _scores(completion: str, gold: str) -> tuple[float, float]:+ return (+ accuracy_reward(_msg(completion), answer=[gold])[0],+ math_verify_reward(_msg(completion), answer=[gold])[0],+ )+++def _short(name: str) -> str:+ return name.split(" ", 1)[0]+++def _pairs(completions: dict[str, str], golds: dict[str, str]) -> list:+ return [+ pytest.param(c_text, g_text, id=f"{_short(c_name)}-{_short(g_name)}")+ for c_name, c_text in completions.items()+ for g_name, g_text in golds.items()+ ]+++def _group_params(kind: str) -> list:+ params = []+ for value, (golds, correct, wrong) in NUMERIC_GROUPS.items():+ completions = correct if kind == "correct" else wrong+ for gi, gold in enumerate(golds):+ for ci, completion in enumerate(completions):+ params.append(pytest.param(completion, gold, id=f"{value}-g{gi}-c{ci}"))+ return params+++# ===========================================================================+# the issue's own reproduction+# ===========================================================================+++class TestIssueRepro:+ def test_gsm8k_reference_gold_pays_correct_completions(self):+ gold = "6*7=42\n#### 42"+ for text in ("Six times seven is 42.\n#### 42", r"6*7 = \boxed{42}"):+ assert accuracy_reward(_msg(text), answer=[gold]) == [1.0], text+ assert math_verify_reward(_msg(text), answer=[gold]) == [1.0], text++ def test_bare_gold_boxed_spellings_and_wrong_answers(self):+ assert accuracy_reward(_msg(r"6*7 = \boxed{42}"), answer=["42"]) == [1.0]+ assert accuracy_reward(_msg(r"6*7 = \boxed {42}"), answer=["42"]) == [1.0]+ assert accuracy_reward(_msg(r"Not 42, so \boxed{41}"), answer=["42"]) == [0.0]+ assert accuracy_reward(_msg("#### 420"), answer=["42"]) == [0.0]++ def test_nested_braces_extract_the_whole_fraction(self):+ text = r"so x = \boxed{\frac{1}{2}}"+ assert _extract_answer(text) == r"\frac{1}{2}"+ assert accuracy_reward(_msg(text), answer=[r"\frac{1}{2}"]) == [1.0]+++# ===========================================================================+# the spelling matrix: every gold x every completion, both rewards+# ===========================================================================+++class TestSpellingMatrix:+ @pytest.mark.parametrize(("completion", "gold"), _pairs(CORRECT_42, GOLDS_42))+ def test_every_correct_completion_scores_one_against_every_gold(self, completion, gold):+ assert _scores(completion, gold) == (1.0, 1.0)++ @pytest.mark.parametrize(("completion", "gold"), _pairs(WRONG_42, GOLDS_42))+ def test_every_wrong_completion_scores_zero_against_every_gold(self, completion, gold):+ assert _scores(completion, gold) == (0.0, 0.0)++ @pytest.mark.parametrize(("completion", "gold"), _group_params("correct"))+ def test_thousands_negative_and_decimal_spellings_match(self, completion, gold):+ assert _scores(completion, gold) == (1.0, 1.0)++ @pytest.mark.parametrize(("completion", "gold"), _group_params("wrong"))+ def test_thousands_negative_and_decimal_wrong_answers_score_zero(self, completion, gold):+ assert _scores(completion, gold) == (0.0, 0.0)++ @pytest.mark.parametrize(("gold", "completion", "expected"), STRING_GOLD_CASES)+ def test_non_numeric_golds_compare_as_normalised_text_in_both_rewards(+ self, gold, completion, expected+ ):+ assert _scores(completion, gold) == (expected, expected)+++# ===========================================================================+# hedges: an answer clause naming more than one distinct value (ruling)+# ===========================================================================+++class TestHedges:+ @pytest.mark.parametrize(("completion", "values"), HEDGES)+ def test_a_hedged_answer_extracts_nothing_and_is_paid_for_none_of_its_values(+ self, completion, values+ ):+ from soup_cli.utils.final_answer import extract_final_answer, parse_completion++ assert extract_final_answer(completion) is None+ assert parse_completion(completion) is None+ for value in values:+ assert _scores(completion, value) == (0.0, 0.0), value++ @pytest.mark.parametrize(("completion", "gold", "expected"), SINGLE_VALUE_CLAUSES)+ def test_one_value_repeated_or_respelled_is_not_a_hedge(self, completion, gold, expected):+ assert _scores(completion, gold) == (expected, expected)++ @pytest.mark.parametrize("gold", HEDGED_GOLDS)+ def test_a_hedged_gold_is_not_a_reference(self, gold):+ from soup_cli.utils.final_answer import parse_reference++ assert parse_reference(gold) is None+ for completion in ("#### 41", "#### 42", "#### 43", "41 or 42"):+ assert _scores(completion, gold) == (0.0, 0.0), completion++ def test_the_clause_rule_decides_what_the_hedge_rule_sees(self):+ from soup_cli.utils.final_answer import parse_completion, parse_reference++ # The comma ends the clause, so only 41 is in it: one value, read as 41 (not a hedge).+ assert parse_completion("The answer is 41 apples, not 42.").number == Decimal(41)+ assert parse_reference("The answer is 41 apples, not 42.") is not None+ # The same two numbers inside ONE clause are a hedge.+ assert parse_completion("The answer is 41 apples or 42.") is None+ assert parse_completion("The answer is 41 apples (not 42).") is None+ # A comma that a number follows continues a list rather than ending the clause.+ assert parse_completion("The answer is 41, 42 or 43.") is None+ assert parse_completion("The answer is 41, then 42.").number == Decimal(41)+++# ===========================================================================+# the partial-credit policy+# ===========================================================================+++class TestPartialCreditPolicy:+ @pytest.mark.parametrize(("completion", "gold", "before", "now"), POLICY_CHANGES)+ def test_policy_is_pinned(self, completion, gold, before, now):+ assert before != now # every row documents a real change of policy+ assert accuracy_reward(_msg(completion), answer=[gold]) == [now]++ def test_accuracy_pays_only_zero_or_one_across_the_whole_variant_list(self):+ golds = list(GOLDS_42.values()) + ["Paris", "76 years", r"\frac{1}{2}"]+ completions = (+ list(CORRECT_42.values())+ + list(WRONG_42.values())+ + [case[1] for case in STRING_GOLD_CASES]+ + [case[0] for case in POLICY_CHANGES]+ )+ seen = {+ accuracy_reward(_msg(completion), answer=[gold])[0]+ for gold in golds+ for completion in completions+ }+ assert seen == {0.0, 1.0}+++# ===========================================================================+# one parser: the gold and the completion go through the same function+# ===========================================================================++REFLEXIVE_SPELLINGS = list(GOLDS_42.values()) + [+ "#### 1,000",+ r"\boxed{1{,}000}",+ "The answer is -3.25.",+ r"\boxed{\frac{1}{2}}",+ r"\boxed{\left( 3, \frac{\pi}{2} \right)}",+ "Answer: Paris",+ "#### 76 years",+ MINUS + "42",+]+++class TestOneParser:+ @pytest.mark.parametrize("spelling", REFLEXIVE_SPELLINGS)+ def test_a_spelling_used_as_both_gold_and_completion_matches_itself(self, spelling):+ from soup_cli.utils import final_answer++ reference = final_answer.parse_reference(spelling)+ completion = final_answer.parse_completion(spelling)+ assert reference is not None and completion is not None+ assert completion.text.casefold() == reference.text.casefold()+ assert accuracy_reward(_msg(spelling), answer=[spelling]) == [1.0]+ assert math_verify_reward(_msg(spelling), answer=[spelling]) == [1.0]+ if reference.number is not None:+ assert completion.number == reference.number++ def test_rewards_and_validation_parse_through_the_shared_helper(self, monkeypatch):+ from soup_cli.utils import final_answer++ calls: Counter = Counter()+ real_reference = final_answer.parse_reference+ real_completion = final_answer.parse_completion++ def spy_reference(text):+ calls["reference", text] += 1+ return real_reference(text)++ def spy_completion(text):+ calls["completion", text] += 1+ return real_completion(text)++ monkeypatch.setattr(final_answer, "parse_reference", spy_reference)+ monkeypatch.setattr(final_answer, "parse_completion", spy_completion)++ gold = "6*7=42\n#### 42"+ assert accuracy_reward(_msg("#### 42"), answer=[gold]) == [1.0]+ assert math_verify_reward(_msg("#### 42"), answer=[gold]) == [1.0]+ _validate_grpo_reward_metadata(+ [{"prompt": "q", "answer": gold}], TrainingConfig(reward_fn="accuracy"), split="train"+ )+ assert calls == Counter({("reference", gold): 3, ("completion", "#### 42"): 2})+++# ===========================================================================+# the shared helper, directly+# ===========================================================================++EXPLICIT_ANSWERS = [+ ("Some work\n#### 42", "42"),+ ("####42", "42"),+ ("#### 42\nHope this helps!", "42"),+ ("#### 42.", "42"),+ ("#### $42", "42"),+ ("#### 42 ", "42"),+ ("##### 42", "42"),+ ("#### step\n#### 42", "42"),+ ("#### 42 #### 43", "43"),+ ("#### 1,000", "1,000"),+ (r"\boxed{42}", "42"),+ (r"\boxed {42}", "42"),+ (r"\boxed{ 42 }", "42"),+ (r"so x = \boxed{\frac{1}{2}}", r"\frac{1}{2}"),+ (r"\boxed{\sqrt{\frac{1}{2}}}", r"\sqrt{\frac{1}{2}}"),+ (r"\boxed{41} then \boxed{42}", "42"),+ (r"$\boxed{42}$", "42"),+ (r"\boxed{\$42}", "42"),+ (r"\boxed{1{,}000}", "1,000"),+ (r"\boxed{1,\!000}", "1,000"),+ ("#### 41\n" + r"\boxed{42}", "42"), # a box AFTER a marker supersedes it+ (r"\boxed{41}" + "\n#### 42", "42"), # a marker after a box still wins+ ("The answer is 42.", "42"),+ ("Answer: 42", "42"),+ ("answer: 42", "42"),+ ("ANSWER IS 42", "42"),+ ("Final Answer: The final answer is $42$. I hope it is correct.", "42"),+ ("**Answer:** 42", "42"),+ ("The answer is 41, not 42.", "41"),+ ("The answer is 42 (six times seven).", "42"),+ ("The answer is -42.", "-42"),+ ("The answer is " + MINUS + "42.", "-42"),+ ("The answer is Paris.", "Paris"),+ ("The answer is New York.", "New York"),+ # review+ ("**Answer**: 42", "42"),+ ("**Final Answer**: 42", "42"),+ ("*Answer*: 42", "42"),+ ("__Answer__: 42", "42"),+ (r"#### \(42\)", "42"),+ (r"The answer is \[42\].", "42"),+ ("Answer:\n42", "42"),+ ("**Answer:**\n\n42", "42"),+ ("The answer is\n42", "42"),+ ("#### Final Answer\n" + r"\boxed{42}", "42"),+ ("#### Step 1: multiply\n6*7 = 42\nThe answer is 42.", "42"),+ ("#### Final Answer\n42", "42"),+ ("#### Final Answer:\n\n42", "42"),+ ("#### Answer: 42", "42"),+ (r"#### \boxed{42}", "42"),+ ("#### 42\nWait, the answer is 41.", "41"),+ ("The answer is 41 apples, not 42.", "41 apples"),+ (r"The answer is \left( 3, \frac{\pi}{2} \right).", r"( 3, \frac{\pi}{2} )"),+ ("The answer is (3, 4).", "(3, 4)"),+ (r"\boxed{\dfrac{14}{3}}", r"\frac{14}{3}"),+ (r"\boxed{\tfrac{1}{2}}", r"\frac{1}{2}"),+ (r"The answer is x \leftarrow y.", r"x \leftarrow y"),+]++NO_EXPLICIT_ANSWER = [+ "Just plain text", "Six times seven is 42.", "", "#### ", r"\boxed{}",+ r"\boxed{\frac{1}{2}", "the answer isn't 41; it's 42", "What is the answer?",+ "The answers: 41 and 42",+]++NUMBERS = [+ ("42", "42"), ("42.0", "42"), ("-42", "-42"), ("+42", "42"), (MINUS + "42", "-42"),+ ("1,000", "1000"), ("1,000,000", "1000000"), ("1,000.5", "1000.5"), (".5", "0.5"),+ ("-.5", "-0.5"), ("1e5", "100000"), ("1E-3", "0.001"), ("042", "42"), ("42.", "42"),+ ("$42", "42"), (r"\$42", "42"), (" 42 ", "42"), ("1{,}000", "1000"),+ (r"1\;000", "1000"), (r"\(42\)", "42"), (r"\[-3.5\]", "-3.5"),+]++NOT_NUMBERS = [+ "1,00", "12,34", "42 apples", "4 2", "42x", "x", "", "1/2", r"\frac{1}{2}", "nan",+ "inf", "1_000", "--42", "4.2.1", "0x1A", "42 or 43",+]+++class TestSharedHelper:+ @pytest.mark.parametrize(("text", "expected"), EXPLICIT_ANSWERS)+ def test_extract_final_answer(self, text, expected):+ from soup_cli.utils.final_answer import extract_final_answer++ assert extract_final_answer(text) == expected+ # The reward module's private name stays a thin alias of the shared helper.+ assert _extract_answer(text) == expected++ @pytest.mark.parametrize("text", NO_EXPLICIT_ANSWER)+ def test_text_without_an_explicit_answer(self, text):+ from soup_cli.utils.final_answer import extract_final_answer++ assert extract_final_answer(text) is None++ @pytest.mark.parametrize(("text", "expected"), NUMBERS)+ def test_parse_number(self, text, expected):+ from soup_cli.utils.final_answer import parse_number++ assert parse_number(text) == Decimal(expected)++ @pytest.mark.parametrize("text", NOT_NUMBERS)+ def test_parse_number_refuses_anything_that_is_not_exactly_one_number(self, text):+ from soup_cli.utils.final_answer import parse_number++ assert parse_number(text) is None++ def test_reference_readings(self):+ from soup_cli.utils.final_answer import parse_reference++ gsm8k = parse_reference("6*7=42\n#### 42")+ assert (gsm8k.text, gsm8k.number) == ("42", Decimal(42))+ paris = parse_reference("Paris")+ assert (paris.text, paris.number) == ("Paris", None)+ worded = parse_reference("The answer is forty-two.")+ assert (worded.text, worded.number) == ("forty-two", None)+ # A reference is never read as free text: its answer must be stated.+ unit = parse_reference("The answer is 42 apples.")+ 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)++ @pytest.mark.parametrize(+ "text",+ ["", " ", "Step 1: multiply.\nStep 2: report.", "6*7=42\n####", r"\boxed{}", "Answer:"],+ )+ def test_a_reference_with_no_statable_answer_is_none(self, text):+ from soup_cli.utils.final_answer import parse_reference++ assert parse_reference(text) is None++ def test_completion_readings(self):+ from soup_cli.utils.final_answer import parse_completion++ prose = parse_completion("Six times seven is 42.")+ assert (prose.text, prose.number) == ("Six times seven is 42", Decimal(42))+ unit = parse_completion("The answer is 42 apples.")+ assert (unit.text, unit.number) == ("42 apples", Decimal(42))+ # The answer clause is read first: a number AFTER the clause is not the answer.+ after = parse_completion("The answer is 41 apples, not 42.")+ assert (after.text, after.number) == ("41 apples", Decimal(41))+ # With no digits in the clause, the completion's last number is read instead.+ worded = parse_completion("The answer is: forty-two (42).")+ assert (worded.text, worded.number) == ("forty-two", Decimal(42))+ # A delimited answer is authoritative: no fallback to other numbers in the text.+ marker = parse_completion("6*7 = 42\n#### 42 apples")+ assert (marker.text, marker.number) == ("42 apples", None)+ last_line = parse_completion("Let me think.\nParis")+ assert (last_line.text, last_line.number) == ("Paris", None)+ assert parse_completion("") is None+ assert parse_completion(" \n ") is None++ @pytest.mark.parametrize(+ ("left", "right"),+ [+ (r"\frac{14}{3}", r"\frac {14} {3}"),+ (r"\dfrac{14}{3}", r"\tfrac{14}{3}"),+ (r"\left( 3, \frac{\pi}{2} \right)", r"(3,\frac{\pi}{2})"),+ (r"\(p - q\)", "p-q"),+ ("New York", "new york"),+ ],+ )+ def test_text_answers_compare_ignoring_whitespace_case_and_latex_wrappers(self, left, right):+ from soup_cli.utils.final_answer import answers_match, parse_reference++ assert answers_match(parse_reference(right), parse_reference(left))+ assert answers_match(parse_reference(left), parse_reference(right))+++# ===========================================================================+# exact numbers: Decimal, not float+# ===========================================================================+++class TestExactNumbers:+ def test_integers_beyond_two_to_the_53_do_not_collide(self):+ big, neighbour = "12345678901234567890", "12345678901234567891"+ assert float(big) == float(neighbour) # what a float comparison would have seen+ assert _scores(r"\boxed{" + big + "}", neighbour) == (0.0, 0.0)+ assert _scores(r"\boxed{" + big + "}", big) == (1.0, 1.0)++ def test_an_exponent_beyond_decimal_range_scores_zero_instead_of_raising(self):+ assert math_verify_reward(_msg("#### 1e999999999"), answer=["1"]) == [0.0]+ assert math_verify_reward(_msg("#### 1e999999999"), answer=["1e999999999"]) == [1.0]+++# ===========================================================================+# control: data that already worked does not change+# ===========================================================================+++class TestControlUnchanged:+ @pytest.mark.parametrize(("completion", "gold", "accuracy", "math"), CONTROL_BOTH)+ def test_plain_numeric_gold_scores_are_unchanged(self, completion, gold, accuracy, math):+ assert _scores(completion, gold) == (accuracy, math)++ @pytest.mark.parametrize(("completion", "gold", "math"), CONTROL_MATH)+ def test_plain_numeric_gold_math_verify_is_unchanged(self, completion, gold, math):+ assert math_verify_reward(_msg(completion), answer=[gold]) == [math]+++# ===========================================================================+# untrusted model output cannot make the parser quadratic+# ===========================================================================+++class TestAdversarialInputsStayLinear:+ @pytest.mark.parametrize(+ "text",+ [+ "\\boxed{" * 20_000,+ "\\boxed{" * 10_000 + "}" + "\\boxed{" * 10_000,+ "the answer is " * 20_000,+ "#### " * 20_000,+ "1," * 50_000,+ " " * 100_000 + "x",+ "{" * 100_000,+ "answer" + " " * 200_000 + "x",+ "**answer" * 50_000,+ "The answer is " + "(" * 200_000,+ "#### Final Answer\n" * 20_000,+ "The answer is 42," + " " * 20_000 + "x", # see test_issue1226_clause_scanner_*+ ],+ ids=["open-boxes", "open-boxes-around-a-close", "phrases", "markers", "commas",+ "whitespace", "braces", "phrase-whitespace", "bold-labels", "open-parens",+ "answer-headings", "clause-whitespace"],+ )+ def test_parsing_is_fast_on_adversarial_output(self, text):+ start = time.perf_counter()+ accuracy_reward(_msg(text), answer=["42"])+ math_verify_reward(_msg(text), answer=["42"])+ assert time.perf_counter() - start < 2.0diff --git a/tests/test_issue814_reward_stress.py b/tests/test_issue814_reward_stress.pyindex 6849b558..8f5629eb 100644--- a/tests/test_issue814_reward_stress.py+++ b/tests/test_issue814_reward_stress.py@@ -2,7 +2,9 @@Verifies:1. `soup reward stress format` reports gameable and exits 2.-2. `soup reward stress accuracy --references g.jsonl` flags answer_spray at default threshold.+2. `soup reward stress <verifier.py> --references g.jsonl` flags answer_spray at default threshold+ for a verifier that pays partial credit when the gold appears anywhere (the built-in+ `accuracy` paid that credit until #1226 removed it).3. `soup reward stress verifiable --verifiable-domain math --references g.jsonl`reports robust (exit 0).4. Each attack family contributes more than one distinct string and n reflects distinct attempts.@@ -34,6 +36,17 @@ def _plain(text: str) -> str:return " ".join(_ANSI_RE.sub("", text).split())+_SUBSTRING_CREDIT_VERIFIER = '''+def reward_fn(completions, **kwargs):+ answers = kwargs.get("answer") or []+ out = []+ for completion, gold in zip(completions, answers):+ text = completion[-1]["content"] if completion else ""+ out.append(0.5 if str(gold).strip().lower() in text.lower() else 0.0)+ return out+'''++def _write_jsonl(path: Path, filename: str, rows: list[dict]) -> Path:target = path / filenamewith target.open("w", encoding="utf-8") as f:@@ -107,14 +120,21 @@ class TestIssue814ScoringAndCli:for a in data["attacks"]:assert a["n"] > 1- def test_accuracy_reward_flags_answer_spray_exit_2(self, tmp_path, monkeypatch):+ def test_substring_crediting_verifier_flags_answer_spray_exit_2(+ self, tmp_path, monkeypatch+ ):+ # The built-in `accuracy` reward paid this 0.5 substring credit until #1226 removed it;+ # the verifier below reproduces it so the stress CLI's answer_spray detection stays+ # pinned. (`accuracy` itself is now robust: tests/test_issue1226_reward_gold_parsing.py.)monkeypatch.chdir(tmp_path)refs = _write_jsonl(tmp_path, "refs.jsonl", [{"answer": "42"}, {"answer": "17"}])+ verifier = tmp_path / "substring_reward.py"+ verifier.write_text(_SUBSTRING_CREDIT_VERIFIER, encoding="utf-8")rep_file = tmp_path / "rep.json"r = runner.invoke(soup_app,[- "reward", "stress", "accuracy",+ "reward", "stress", str(verifier),"--references", str(refs),"--output-report", str(rep_file),],@@ -127,7 +147,7 @@ class TestIssue814ScoringAndCli:data = json.loads(rep_file.read_text(encoding="utf-8"))assert data["gameable"] is Trueper_attack = {a["kind"]: a for a in data["attacks"]}- # answer_spray achieves 100% acceptance on accuracy (0.5 score >= 0.5 threshold)+ # answer_spray achieves 100% acceptance (0.5 score >= 0.5 threshold)assert per_attack["answer_spray"]["accept_rate"] == 1.0assert per_attack["answer_spray"]["accepted"] == per_attack["answer_spray"]["n"]