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): end answer clause at justification connectives because and since (#1328) (#1501)
Nurkhan Esenbek6e44dadcdf28
diff --git a/changelog.d/0.75.1/1316.fixed.md b/changelog.d/0.75.1/1316.fixed.mdindex 3631dd0a..083fc23c 100644--- a/changelog.d/0.75.1/1316.fixed.md+++ b/changelog.d/0.75.1/1316.fixed.md@@ -1 +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).+- **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). Parenthetical justifications belong to the clause and hedge it (`The answer is 42 (6*7=42).`), while a connective ends the clause, so `The answer is 42 because 6*7=42.` and `The answer is 42, because 6*7=42.` both read 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/changelog.d/0.75.1/1501.fixed.md b/changelog.d/0.75.1/1501.fixed.mdnew file mode 100644index 00000000..1faabb5a--- /dev/null+++ b/changelog.d/0.75.1/1501.fixed.md@@ -0,0 +1 @@+- **GRPO's `accuracy` and verifiable `math` rewards now end the answer clause at justification connectives `because` and `since` (#1328).** Previously, an inline justification such as `The answer is 42 because 6*7=42.` stayed in the clause and counted all numbers, treating the answer as a hedge and scoring 0.0. The clause now ends at `because` or `since`, correctly reading 42 (#1328 by @kok-o in #1501).diff --git a/docs/training.md b/docs/training.mdindex 08f0f281..a6b74931 100644--- a/docs/training.md+++ b/docs/training.md@@ -1334,10 +1334,11 @@ answer is, in this order of precedence: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).`+ on the next line), up to the end of its clause: a `. `, `, ` or `; ` outside brackets, or at+ the connective `because` or `since` (case-insensitive, requiring whitespace on both sides; not `as`).+ 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@@ -1351,8 +1352,9 @@ An answer phrase's number is read from its own clause: `The answer is 41 apples,41, because the clause ends at the comma. A clause that names **more than one distinct value** isa 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.+gold written that way is refused. A `because` / `since` inline or after punctuation ends the clause+(`The answer is 42 because 6*7=42.` and `The answer is 42, because 6*7=42.` both read 42),+while parenthetical justifications belong to the clause and hedge it (`The answer is 42 (6*7=42).`).The same value twice is not a hedge (`42 (i.e. 42.0)`), and the digits of one bracketed or LaTeXanswer (`(3, 4)`, `\begin{pmatrix} 3 \\ 4 \end{pmatrix}`, `\frac{14}{3}`, `2^{10}`) or of a timeor a ratio (`3:45`, `1:1,000`) are not separate values; such an answer is compared as text.diff --git a/src/soup_cli/utils/final_answer.py b/src/soup_cli/utils/final_answer.pyindex b09c80f4..ad6b0874 100644--- a/src/soup_cli/utils/final_answer.py+++ b/src/soup_cli/utils/final_answer.py@@ -14,9 +14,10 @@ An answer is stated explicitly in one of three forms: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:+ of its clause. The clause ends at a line end, at ``". "``, ``", "`` or ``"; "`` outside+ brackets, or at the connective ``because`` or ``since`` (case-insensitive, requiring whitespace+ on both sides; not ``as``), 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@@ -33,11 +34,11 @@ from its clause: the stand-alone numbers outside brackets and LaTeX environments``2^{10}`` or ``2x``, and of a time or a ratio such as ``3:45`` or ``1:1,000``, belong to oneexpression, not to several values) and every stand-alone number in its aside. A clause withMORE 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.+answer, so a completion that hedges scores 0.0 and a gold that hedges is refused. A justification+inline or after punctuation ends the clause (``42 because 6*7=42`` and ``42, because 6*7=42`` both+answer 42), while parenthetical justifications belong to the clause and hedge it (``42 (6*7=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, whichmust fit on one line (a bare answer such as ``"42"`` or ``"Paris"``). A completion reads as its@@ -104,7 +105,7 @@ _PHRASE_RE = re.compile(_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"[()\[\]{}.,;]")+_CLAUSE_CHAR_RE = re.compile(r"[()\[\]{}.,;]|\b(?:because|since)\b", re.IGNORECASE)# A LaTeX line break '\\' is consumed whole, so its second backslash is never read as the# control space '\ ' ('\\ -14' must stay '\\ -14', not become '\-14')._LATEX_SPACING_RE = re.compile(r"\\\\|\\[,!;: ]")@@ -266,7 +267,9 @@ 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.+ or semicolon ("41, 42 or 43" is one clause), or at the connective "because" or "since"+ (case-insensitive, requiring whitespace on both sides; not "as").+ A " (" aside is in the clause, not the answer."""line = line.lstrip()depth = 0@@ -279,11 +282,18 @@ def _split_clause(line: str) -> tuple[str, str]:depth += 1elif 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+ elif depth == 0:+ if char in ".,;":+ if line[index + 1 : index + 2].isspace():+ if char in ",;" and _NUMBER_AHEAD_RE.match(line, index + 1):+ continue+ line = line[:index]+ break+ elif (index > 0 and line[index - 1].isspace()) and (+ index + len(char) == len(line) or line[index + len(char)].isspace()+ ):+ line = line[:index].rstrip()+ breakreturn (line, "") if aside is None else (line[:aside], line[aside:])diff --git a/tests/test_issue1226_clause_scanner_is_linear.py b/tests/test_issue1226_clause_scanner_is_linear.pyindex fe71c9d8..c335b889 100644--- a/tests/test_issue1226_clause_scanner_is_linear.py+++ b/tests/test_issue1226_clause_scanner_is_linear.py@@ -49,6 +49,12 @@ WHITESPACE_RUNS = {),"comma-dollar-spaces": lambda k: "The answer is 42, $" + " " * k + "x","comma-math-delimiter-spaces": lambda k: "The answer is 42, \\(" + " " * k + "x",+ "because-spaces": lambda k: "The answer is 42 because" + " " * k + "x",+ "since-spaces": lambda k: "The answer is 42 since" + " " * k + "x",+ "because-tokens": lambda k: "The answer is 42 " + "because " * k + "x",+ "since-tokens": lambda k: "The answer is 42 " + "since " * k + "x",+ "paren-because-tokens": lambda k: "The answer is 42 (" + "because " * k + "x",+ "glued-because": lambda k: "The answer is 42 " + "x-because " * k + "x",}_SCALE_N = 1_000@@ -107,6 +113,8 @@ ENDED_CLAUSES = ["The answer is 41, \\(x\\) is 42.","The answer is 41, -x is 42.","The answer is 41, . 42",+ "The answer is 41 because 6*7=42.",+ "The answer is 41 since 6*7=42.",]diff --git a/tests/test_issue1226_parser_edge_cases.py b/tests/test_issue1226_parser_edge_cases.pyindex ab5829ac..83c6df83 100644--- a/tests/test_issue1226_parser_edge_cases.py+++ b/tests/test_issue1226_parser_edge_cases.py@@ -3,9 +3,10 @@ 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 ananswer phrase that states one is compared as text instead of being read as a hedge betweenits 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.+2. **Parenthetical justifications hedge the answer clause, while connectives end it.** Parenthetical+ justifications belong to the clause and make it a hedge if numbers conflict. The justification+ connectives "because" or "since" (case-insensitive, requiring whitespace on both sides), or+ punctuation, end the clause before the justification.3. **A later answer phrase supersedes a "####" line**, chatter included ("I hope this answer ishelpful!"): 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@@ -116,37 +117,125 @@ class TestATimeOrARatioIsOneValue:# ===========================================================================-# 2. a justification inside the answer clause is a hedge (the ruling)+# 2. parenthetical justifications hedge, while connectives end the clause# ===========================================================================-# (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"]),+# (completion, every number in its clause). Parenthetical justifications belong to the clause+# and make it a hedge, scoring 0.0 against every one of them.+JUSTIFIED_IN_A_PARENTHESIS = [("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.+# A connective ("because", "since"), a comma, a period or a line end before the justification ends+# the clause, so the number before it is the answer.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",+ ("The answer is 42 because 6*7=42.", Decimal(42), "42"),+ ("The answer is 42 because 6 times 7 is 42.", Decimal(42), "42"),+ ("The answer is 42 since 6*7=42.", Decimal(42), "42"),+ ("So the answer is 18 dollars since 9 * 2 = 18.", Decimal(18), "18"),+ ("The answer is 42, because 6*7=42.", Decimal(42), "42"),+ ("The answer is 42. Because 6*7=42.", Decimal(42), "42"),+ ("The answer is 42\n6*7=42", Decimal(42), "42"),+]+# A hedge before the connective remains a hedge; a wrong answer before the connective is not paid.+HEDGED_OR_WRONG_WITH_A_CONNECTIVE = [+ ("The answer is 41 or 42 because I am not sure.", ["41", "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):+ @pytest.mark.parametrize(("completion", "numbers"), JUSTIFIED_IN_A_PARENTHESIS)+ def test_parenthetical_justification_is_a_hedge_and_pays_none_of_its_numbers(+ self, completion, numbers+ ):assert parse_completion(completion) is Noneassert parse_reference(completion) is None # as a gold, it is refusedfor 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):+ @pytest.mark.parametrize(("completion", "expected_number", "gold"), JUSTIFIED_AFTER_THE_CLAUSE)+ def test_after_the_clause_it_is_not_part_of_the_answer(self, completion, expected_number, gold):+ assert parse_completion(completion).number == expected_number+ ref = parse_reference(completion)+ assert ref is not None+ if ref.number is not None:+ assert ref.number == expected_number+ assert _scores(completion, gold) == (1.0, 1.0)++ @pytest.mark.parametrize(("completion", "numbers"), HEDGED_OR_WRONG_WITH_A_CONNECTIVE)+ def test_hedge_before_connective_remains_a_hedge(self, completion, numbers):+ assert parse_completion(completion) is None+ assert parse_reference(completion) is None+ for number in numbers:+ assert _scores(completion, number) == (0.0, 0.0), number++ def test_wrong_answer_before_connective_scores_zero(self):+ completion = "The answer is 41 because 6*7=42."+ assert parse_completion(completion).number == Decimal(41)+ assert _scores(completion, "42") == (0.0, 0.0)+++class TestTheConnectiveBoundaryItself:+ @pytest.mark.parametrize(+ "connective", ["because", "Because", "BECAUSE", "bEcAuSe", "since", "Since", "SINCE"]+ )+ def test_any_case_ends_the_clause(self, connective):+ completion = f"The answer is 42 {connective} 6*7=42."+ assert parse_completion(completion).number == Decimal(42)+ assert _scores(completion, "42") == (1.0, 1.0)++ @pytest.mark.parametrize("separator", ["\t", "\u00a0", " ", "\n"])+ def test_any_whitespace_on_both_sides(self, separator):+ completion = f"The answer is 42{separator}because{separator}6*7=42."+ assert parse_completion(completion).number == Decimal(42)+ assert _scores(completion, "42") == (1.0, 1.0)++ @pytest.mark.parametrize(+ "completion",+ [+ "The answer is 42 because-6*7=42.", # glued to what follows+ "The answer is 42 because6*7=42.",+ "The answer is 42-because 6*7=42.", # glued to what came before+ "The answer is 42 sincerely 6*7=42.", # a longer word+ "The answer is 42 (which is right since 6*7=42).", # inside a bracket: an aside+ ],+ )+ def test_only_a_stand_alone_connective_outside_brackets_ends_the_clause(self, completion):+ # Without a cut the clause keeps 6 and 7 next to 42: still a hedge, as before the rule.+ assert parse_completion(completion) is None+ assert _scores(completion, "42") == (0.0, 0.0)++ def test_the_connective_is_not_part_of_a_text_answer(self):+ completion = "The answer is Paris because it is the capital."+ assert parse_completion(completion).text == "Paris"+ assert _scores(completion, "Paris") == (1.0, 1.0)++ @pytest.mark.parametrize("word", ["as", "As", "AS"])+ def test_as_does_not_end_the_clause(self, word):+ # The ruling on #1328: not `as`, which appears inside answers. Without a cut the clause+ # keeps 6 and 7 next to 42: still a hedge.+ completion = f"The answer is 42 {word} 6*7=42."+ assert parse_completion(completion) is None+ assert _scores(completion, "42") == (0.0, 0.0)++ @pytest.mark.parametrize("connective", ["because", "Because", "since", "SINCE"])+ def test_a_connective_that_ends_the_text_ends_the_clause(self, connective):+ # A completion cut off at max_tokens right after the connective: no character follows it,+ # which must neither crash the reward nor stop it reading 42.+ completion = f"The answer is 42 {connective}"assert parse_completion(completion).number == Decimal(42)- assert parse_reference(completion).number == Decimal(42)assert _scores(completion, "42") == (1.0, 1.0)+ assert parse_completion(completion + "\n6*7=42").number == Decimal(42)+++class TestAnAnswerThatBeginsWithAConnective:+ """The connective ends a clause that has an answer in it; it never empties one."""++ @pytest.mark.parametrize(+ "gold", ["Answer: Because it rains.", "Answer: since 1990", "The answer is Since then."]+ )+ def test_a_text_gold_that_starts_with_one_is_still_a_gold(self, gold):+ assert parse_reference(gold) is not None# ===========================================================================@@ -155,8 +244,13 @@ class TestAJustificationInsideTheClause:class TestALaterAnswerPhraseAfterAMarker:- def test_a_justification_in_the_later_phrase_makes_it_a_hedge(self):+ def test_a_justification_with_connective_in_the_later_phrase_reads_the_answer(self):completion = "6*7=42\n#### 42\nThe answer is 42 because 6 x 7 = 42."+ assert parse_completion(completion).number == Decimal(42)+ assert _scores(completion, "42") == (1.0, 1.0)++ def test_a_hedge_in_the_later_phrase_makes_it_a_hedge(self):+ completion = "6*7=42\n#### 42\nThe answer is 41 or 42 because I am not sure."assert parse_completion(completion) is Noneassert _scores(completion, "42") == (0.0, 0.0)