Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(reward-synth): read numeric golds with the shared answer parser and name rejected references (#1350) (#1533)

Momoyeyue104c9278370
diff --git a/changelog.d/0.75.1/1533.fixed.md b/changelog.d/0.75.1/1533.fixed.md
new file mode 100644
index 00000000..425e2d64
--- /dev/null
+++ b/changelog.d/0.75.1/1533.fixed.md
@@ -0,0 +1 @@
+- `soup reward synth`'s numeric verifier now reads both the gold and the completion with the shared answer parser the built-in `math` / `accuracy` rewards use, so `1,000`, `#### 1,000`, `\boxed {42}` and `#### −42` spellings score the same under the generated verifier as under the built-ins, and malformed comma groupings like `10,00` are no longer detected as numeric. Regeneration also stops paying some completions the old regex paid — `####` or `\boxed{}` answers carrying units, `%` or a non-dollar currency symbol or code (`#### 42 apples`, `\boxed{42\%}`, `#### €42`), hedged or justified answer phrases, and a wrong last box after a right first now score 0, matching the built-ins (bare `42%` and `The answer is 42%.` still pay). A `reward.py` synthesized before this version scored the newly-accepted spellings 0, so regenerate it before comparing runs; the emitted file now imports `soup_cli` rather than being fully self-contained. The calibration report and `--output-report` also name every reference the verifier rejects (`rejected_references`) instead of reporting only a refusal rate, and a refused run lists the first ten rejected references in the panel (#1350 by @Momoyeyu in #1533).
diff --git a/docs/training.md b/docs/training.md
index a40f877c..578ee6ea 100644
--- a/docs/training.md
+++ b/docs/training.md
@@ -1439,7 +1439,23 @@ References are a JSONL where each row's gold answer is in an `answer` field (ove
`--field`) or the last assistant turn of a `messages` list. `--min-discrimination` sets how
strongly the verifier must separate references from perturbed negatives before it's emitted.
v1 is deterministic families only — a `\boxed{}`/`####` marker helps the numeric verifier, and
-completions are prompted to mark their answer (standard RLVR practice).
+completions are prompted to mark their answer (standard RLVR practice). The numeric verifier
+reads both the gold and the completion with the parser the built-in `math` / `accuracy` rewards
+use (`soup_cli.utils.final_answer`), so `#### 1,000`, `\boxed {42}` and a `6*7=42\n#### 42` gold
+score the same under both; references written `1,000` count as numeric. The calibration report
+names every reference the emitted verifier rejects (`rejected_references` in `--output-report`).
+
+**Changed:** a `reward.py` synthesized before this version pulled the last number with a local
+regex; ones synthesized now read both sides with the shared answer parser, so `1,000`-style
+golds and `The answer is …` completions score where they scored 0 before — regenerate old
+verifiers before comparing runs. Regeneration also stops paying some completions the old regex
+paid: a `####` or `\boxed{}` answer carrying units, `%` or a non-dollar currency symbol or
+code (`#### 42 apples`, `\boxed{42\%}`, `#### €42`, `#### 42 USD`), a hedged or justified answer phrase (`The answer is either 41 or
+42`, `The answer is 42 because 6*7=42`), and a completion whose last `\boxed{}` is wrong after
+a right first one now score 0 — matching the built-ins. A bare `42%` or `The answer is 42%.`
+still pays, as under the built-ins; only marker-delimited answers refuse suffixes. The emitted
+file imports `soup_cli`, so it runs where Soup is installed rather than being fully
+self-contained.
### Stress-test a verifier for gameability (`soup reward stress`)
diff --git a/src/soup_cli/commands/reward.py b/src/soup_cli/commands/reward.py
index 4c5aaa55..0ba198ab 100644
--- a/src/soup_cli/commands/reward.py
+++ b/src/soup_cli/commands/reward.py
@@ -36,6 +36,7 @@ console = Console()
_MAX_INPUT_BYTES = 64 * 1024 * 1024
_MAX_ROWS = 1_000_000
+_MAX_LISTED_REJECTED = 10
_ALLOWED_KINDS = ("auto",) + rs.KINDS
_MAX_SENTINEL_LEN = 256
@@ -100,6 +101,8 @@ def _render_report_panel(report: rs.CalibrationReport, kind: str, out_path: str)
table.add_column()
table.add_row("verifier kind", escape(kind))
table.add_row("references (accepted)", f"{report.positives} ({report.pos_accept:.0%})")
+ for ref in report.rejected_references:
+ table.add_row("rejected reference", escape(repr(ref)))
table.add_row("negatives (accepted)", f"{report.negatives} ({report.neg_accept:.0%})")
table.add_row("discrimination", f"{report.discrimination:.2f}")
table.add_row("precision", f"{report.precision:.2f}")
@@ -233,8 +236,13 @@ def synth(
if report.refused:
_cleanup(candidate_path)
+ shown = report.rejected_references[:_MAX_LISTED_REJECTED]
+ rejected = "".join(f"\nrejected reference: {escape(repr(ref))}" for ref in shown)
+ remaining = len(report.rejected_references) - len(shown)
+ if remaining:
+ rejected += f"\n+{remaining} more (see --output-report)"
console.print(Panel(
- escape(report.reason),
+ escape(report.reason) + rejected,
title="[bold red]verifier refused (not emitted)[/]", border_style="red"))
raise typer.Exit(2)
diff --git a/src/soup_cli/utils/reward_synth.py b/src/soup_cli/utils/reward_synth.py
index 731f597f..7fcccc2e 100644
--- a/src/soup_cli/utils/reward_synth.py
+++ b/src/soup_cli/utils/reward_synth.py
@@ -39,7 +39,9 @@ _MIN_SELF_ACCEPT = 0.9
_MAX_ROWS = 1_000_000
_NUMBER_RE = re.compile(r"[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?")
-_WHOLE_NUMBER_RE = re.compile(r"^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$")
+_WHOLE_NUMBER_RE = re.compile(
+ r"^[+-]?(?:\d{1,3}(?:,\d{3})+(?:\.\d*)?|\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$"
+)
# ---------------------------------------------------------------------------
@@ -88,6 +90,8 @@ class CalibrationReport:
recall: float
refused: bool
reason: str
+ # References the verifier scored below 0.5 against themselves, in input order.
+ rejected_references: tuple[str, ...] = ()
SpecType = Union[NumericSpec, dict, ToolCallSpec, str]
@@ -340,7 +344,7 @@ def induce_regex(golds: Sequence[str]) -> Optional[str]:
_HEADER = '''"""Deterministic reward verifier — generated by `soup reward synth` (v0.71.40).
Kind: {kind}. Induced from {n_refs} reference output(s). EDIT FREELY — this is a
-self-contained, committable reward function. Wire it via:
+committable reward function (the numeric kind imports Soup's answer parser). Wire it via:
training:
reward_fn: {rel_hint}
@@ -358,48 +362,40 @@ def _last_content(completion):
'''
_NUMERIC_BODY = '''
-_NUMBER_RE = re.compile(r"[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][+-]?\\d+)?")
-_BOXED_RE = re.compile(r"\\\\boxed\\{([^}]*)\\}")
-
-
-def _extract_number(text):
- # Prefer an explicit answer marker (\\boxed{...} then ####) over "last number
- # in the whole string", so trailing chit-chat numbers do not hijack the score.
- boxed = _BOXED_RE.search(text)
- if boxed:
- nums = _NUMBER_RE.findall(boxed.group(1))
- if nums:
- return nums[-1]
- if "####" in text:
- nums = _NUMBER_RE.findall(text.split("####")[-1])
- if nums:
- return nums[-1]
- nums = _NUMBER_RE.findall(text)
- return nums[-1] if nums else None
+# Both sides are read by the parser Soup's built-in `math` / `accuracy` rewards use
+# (\\boxed{...}, "#### ...", "The answer is ...", "1,000", a Unicode minus), so this
+# verifier agrees with them on exact matches (near-misses inside the induced
+# tolerance are binary here, where the built-ins give partial credit). It is
+# loaded through `load_reward_fn`, where Soup is installed.
+from soup_cli.utils.final_answer import (
+ parse_completion,
+ parse_reference,
+ variables_conflict,
+)
def _numbers_match(pred, gold, tol):
- if pred is None:
- return False
- try:
- if tol == 0:
- # Exact: integer compare first so large ints dodge float rounding.
- try:
- return int(pred) == int(gold)
- except (ValueError, TypeError):
- pass
- return abs(float(pred) - float(gold)) <= tol
- except (ValueError, TypeError):
+ if pred is None or gold is None:
return False
+ if tol == 0:
+ return pred == gold # Decimal equality: large ints do not collide under float()
+ return abs(float(pred) - float(gold)) <= tol
def reward_fn(completions, **kwargs):
answers = kwargs.get("answer", [])
out = []
for completion, expected in zip(completions, answers):
- predicted = _extract_number(_last_content(completion))
- gold = str(expected).strip()
- out.append(1.0 if _numbers_match(predicted, gold, _TOLERANCE) else 0.0)
+ reference = parse_reference(str(expected))
+ predicted = parse_completion(_last_content(completion))
+ gold = reference.number if reference is not None else None
+ pred = predicted.number if predicted is not None else None
+ conflict = (
+ predicted is not None
+ and reference is not None
+ and variables_conflict(predicted, reference)
+ )
+ out.append(1.0 if not conflict and _numbers_match(pred, gold, _TOLERANCE) else 0.0)
return out
'''
@@ -516,7 +512,7 @@ def _safe_hint(value: object) -> str:
def render_verifier_py(kind: str, spec: Any, *, meta: Mapping[str, Any]) -> str:
- """Render a self-contained reward-verifier ``.py`` source string.
+ """Render a reward-verifier ``.py`` source string.
The induced spec is baked in as a top-level constant via ``repr`` (so the
code bodies stay literal — no ``str.format`` over code containing braces).
@@ -558,7 +554,7 @@ def perturb_negatives(golds: Sequence[str], kind: str) -> list[str]:
for gold in golds:
gold = gold.strip()
if kind == "numeric":
- num = _NUMBER_RE.findall(gold)
+ num = _NUMBER_RE.findall(gold.replace(",", ""))
if num:
try:
negatives.append(str(float(num[-1]) + 9999.0))
@@ -608,25 +604,26 @@ def calibrate(
all — a hard floor the user cannot disable via ``--min-discrimination 0``),
or (c) ``discrimination < min_discrimination``.
"""
- def _accept_rate(
- items: Sequence[str], answers: Sequence[str]
- ) -> tuple[float, int]:
+ def _accepted(items: Sequence[str], answers: Sequence[str]) -> list[bool]:
if not items:
- return 0.0, 0
+ return []
completions = [[{"role": "assistant", "content": s}] for s in items]
scores = reward_fn(completions, answer=list(answers))
- accepted = sum(1 for s in scores if float(s) >= 0.5)
- return accepted / len(items), accepted
+ return [float(s) >= 0.5 for s in scores]
# Positives are scored as content==gold. Negatives are corrupted completions
# but must be scored against the REAL gold (cycled), else a gold-comparison
# verifier would accept a corrupted answer matched against itself.
- pos_accept, tp = _accept_rate(positives, positives)
+ pos_hits = _accepted(positives, positives)
+ tp = sum(pos_hits)
+ pos_accept = tp / len(positives) if positives else 0.0
+ rejected = tuple(ref for ref, hit in zip(positives, pos_hits) if not hit)
if positives:
neg_answers = [positives[j % len(positives)] for j in range(len(negatives))]
else:
neg_answers = list(negatives)
- neg_accept, fp = _accept_rate(negatives, neg_answers)
+ fp = sum(_accepted(negatives, neg_answers))
+ neg_accept = fp / len(negatives) if negatives else 0.0
discrimination = pos_accept - neg_accept
precision = (tp / (tp + fp)) if (tp + fp) > 0 else 0.0
recall = pos_accept
@@ -665,6 +662,7 @@ def calibrate(
recall=recall,
refused=refused,
reason=reason,
+ rejected_references=rejected,
)
diff --git a/tests/test_issue1350_reward_synth_numeric_parser.py b/tests/test_issue1350_reward_synth_numeric_parser.py
new file mode 100644
index 00000000..506b2f3d
--- /dev/null
+++ b/tests/test_issue1350_reward_synth_numeric_parser.py
@@ -0,0 +1,209 @@
+"""#1350: the numeric verifier ``soup reward synth`` emits reads golds like the ``math`` reward.
+
+The emitted body parses both sides with ``soup_cli.utils.final_answer``, so ``#### 1,000``,
+``\\boxed {42}`` and a ``6*7=42\\n#### 42`` gold score the way ``math_verify_reward`` does. The
+calibration report names every reference the verifier rejects, and ``1,000`` is numeric.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+from pathlib import Path
+
+import pytest
+from typer.testing import CliRunner
+
+from soup_cli.trainer.rewards import math_verify_reward
+from soup_cli.utils import reward_synth as rs
+from tests.conftest import strip_ansi
+
+# (gold, correct completion) -- the table in #1350.
+_PAIRS = [
+ ("1000", "#### 1,000"),
+ ("42", r"\boxed {42}. The other option, 41, is wrong."),
+ ("42", r"First guess \boxed{41}; rechecking, 6*7 = \boxed{42}"),
+ ("42", "Six times seven.\n#### 42\nThat was step 3 of 5."),
+ ("-42", "#### \u221242"),
+ ("6*7=42\n#### 42", "#### 42"),
+ ("6*7=42\n#### 42", r"6*7 = \boxed{42}"),
+ ("1,000", "1000"),
+ ("1,000", "#### 1,000"),
+]
+_WRONG = [("42", "#### 420"), ("42", r"\boxed{41}")]
+_NINE = ["3", "8", "15", "16", "23", "42", "108", "7", "12"]
+
+
+def _msgs(*contents: str) -> list[list[dict]]:
+ return [[{"role": "assistant", "content": c}] for c in contents]
+
+
+def _write_jsonl(path: Path, golds: list[str]) -> None:
+ path.write_text(
+ "".join(json.dumps({"prompt": "q", "answer": g}) + "\n" for g in golds), encoding="utf-8"
+ )
+
+
+def verifier(tmp_path):
+ result = rs.synthesize([{"answer": g} for g in ["1000", "42", "-42", "1,000", "2,500"]])
+ path = tmp_path / "gen_reward.py"
+ path.write_text(result.source, encoding="utf-8")
+ spec = importlib.util.spec_from_file_location("gen_reward_1350", path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module.reward_fn
+
+
[email protected](("gold", "completion"), _PAIRS)
+def test_a_synthesized_verifier_pays_every_correct_completion(verifier, gold, completion):
+ assert verifier(_msgs(completion), answer=[gold]) == [1.0]
+ assert math_verify_reward(_msgs(completion), answer=[gold]) == [1.0]
+
+
[email protected](("gold", "completion"), _WRONG)
+def test_a_synthesized_verifier_still_refuses_a_wrong_answer(verifier, gold, completion):
+ assert verifier(_msgs(completion), answer=[gold]) == [0.0]
+
+
+def test_grouped_references_are_detected_as_numeric():
+ golds = _NINE[:8] + ["1,000", "2,500"]
+ assert rs.detect_kind(golds) == "numeric"
+ assert rs.induce_numeric(golds).is_float is False
+
+
+def _synth(tmp_path, monkeypatch, golds: list[str]):
+ from soup_cli.commands.reward import app
+
+ monkeypatch.chdir(tmp_path)
+ _write_jsonl(Path("refs.jsonl"), golds)
+ return CliRunner().invoke(
+ app, ["synth", "refs.jsonl", "-o", "reward.py", "--output-report", "report.json"]
+ )
+
+
+def test_the_issue_reference_set_is_accepted_whole(tmp_path, monkeypatch):
+ res = _synth(tmp_path, monkeypatch, _NINE + ["6*7=42\n#### 42"])
+ assert res.exit_code == 0, (res.output, repr(res.exception))
+ report = json.loads(Path("report.json").read_text(encoding="utf-8"))
+ assert report["pos_accept"] == 1.0
+ assert report["rejected_references"] == []
+
+
+def test_a_refusing_calibration_names_every_rejected_reference():
+ def digits_only(completions, answer):
+ return [1.0 if c[-1]["content"].isdigit() else 0.0 for c in completions]
+
+ refs = ["1", "2", "3", "forty-two", "a dozen"]
+ report = rs.calibrate(digits_only, refs, ["x", "y"], kind="numeric")
+ assert report.refused
+ assert report.rejected_references == ("forty-two", "a dozen")
+
+
+def test_the_report_names_a_rejected_reference(tmp_path, monkeypatch):
+ res = _synth(tmp_path, monkeypatch, _NINE + ["forty-two"])
+ assert res.exit_code == 0, (res.output, repr(res.exception))
+ assert "forty-two" in res.output
+ report = json.loads(Path("report.json").read_text(encoding="utf-8"))
+ assert report["rejected_references"] == ["forty-two"]
+
+
[email protected]("gold", ["10,00", "1,2", "12,34,567", "1,0000"])
+def test_malformed_comma_grouping_is_not_numeric(gold):
+ # comma groups must be exactly three digits: "10,00" is not a number
+ assert rs.detect_kind([gold]) != "numeric"
+
+
+def test_perturb_negatives_reads_the_grouped_value():
+ # the negative for "1,000" perturbs 1000, not the ",000" tail
+ assert "10999.0" in rs.perturb_negatives(["1,000"], "numeric")
+
+
+def test_a_synthesized_verifier_keeps_large_ints_exact(tmp_path):
+ # 2**53 and 2**53 + 1 are the same float; the emitted Decimal compare keeps them apart
+ gold = "9007199254740993"
+ result = rs.synthesize([{"answer": gold}, {"answer": "42"}, {"answer": "7"}])
+ path = tmp_path / "gen_reward_bigint.py"
+ path.write_text(result.source, encoding="utf-8")
+ spec = importlib.util.spec_from_file_location("gen_reward_1350_bigint", path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ assert module.reward_fn(_msgs("#### 9007199254740992"), answer=[gold]) == [0.0]
+ assert module.reward_fn(_msgs(f"#### {gold}"), answer=[gold]) == [1.0]
+
+
+def test_a_synthesized_float_verifier_refuses_an_unparseable_gold(tmp_path):
+ # float golds bake tol=1e-6, so a gold the parser cannot read must score 0,
+ # not reach float(None) mid-eval
+ result = rs.synthesize([{"answer": "0.5"}, {"answer": "1.5"}, {"answer": "2.5"}])
+ path = tmp_path / "gen_reward_float.py"
+ path.write_text(result.source, encoding="utf-8")
+ spec = importlib.util.spec_from_file_location("gen_reward_1350_float", path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ assert module.reward_fn(_msgs("#### 0.5"), answer=["forty-two"]) == [0.0]
+ assert module.reward_fn(_msgs("#### 0.5"), answer=["0.5"]) == [1.0]
+
+
+def test_a_multi_line_unmarked_gold_is_refused_like_the_builtin(verifier):
+ # parse_reference refuses a multi-line gold with no marker; reading it as a
+ # completion would take its last number (42) and score a bare "#### 42" 1.0
+ gold = "Step 1: 6\nStep 2: 42"
+ assert math_verify_reward(_msgs("#### 42"), answer=[gold]) == [0.0]
+ assert verifier(_msgs("#### 42"), answer=[gold]) == [0.0]
+
+
+def test_an_unmarked_multi_line_completion_reads_its_last_number(verifier):
+ completion = "Let me compute.\n6*7 = 42"
+ assert math_verify_reward(_msgs(completion), answer=["42"]) == [1.0]
+ assert verifier(_msgs(completion), answer=["42"]) == [1.0]
+
+
+def test_a_refused_synthesis_names_its_rejected_references(tmp_path, monkeypatch):
+ from soup_cli.commands.reward import app
+
+ monkeypatch.chdir(tmp_path)
+ golds = ['{"a": 1}'] * 7 + ["not json at all", "also bad", "nope"]
+ _write_jsonl(Path("refs.jsonl"), golds)
+ res = CliRunner().invoke(
+ app, ["synth", "refs.jsonl", "--kind", "json_schema", "-o", "reward.py"]
+ )
+ assert res.exit_code == 2, (res.output, repr(res.exception))
+ out = " ".join(strip_ansi(res.output).split())
+ assert "not json at all" in out and "also bad" in out and "nope" in out
+
+
+def test_a_synthesized_verifier_refuses_a_conflicting_variable(verifier):
+ # math_verify_reward refuses when both sides name different variables (#1346);
+ # the emitted verifier must too
+ assert math_verify_reward(_msgs(r"\boxed{y = 42}"), answer=["x = 42"]) == [0.0]
+ assert verifier(_msgs(r"\boxed{y = 42}"), answer=["x = 42"]) == [0.0]
+ assert verifier(_msgs(r"\boxed{x = 42}"), answer=["x = 42"]) == [1.0]
+
+
+def test_a_refused_synthesis_caps_the_rejected_listing(tmp_path, monkeypatch):
+ from soup_cli.commands.reward import app
+
+ monkeypatch.chdir(tmp_path)
+ bad = [f"bad-{i:02d}" for i in range(12)]
+ _write_jsonl(Path("refs.jsonl"), ['{"a": 1}'] * 7 + bad)
+ res = CliRunner().invoke(
+ app,
+ [
+ "synth",
+ "refs.jsonl",
+ "--kind",
+ "json_schema",
+ "-o",
+ "reward.py",
+ "--output-report",
+ "report.json",
+ ],
+ )
+ assert res.exit_code == 2, (res.output, repr(res.exception))
+ out = " ".join(strip_ansi(res.output).split())
+ assert "bad-00" in out and "bad-09" in out
+ assert "bad-10" not in out and "bad-11" not in out
+ assert "+2 more (see --output-report)" in out
+ report = json.loads(Path("report.json").read_text(encoding="utf-8"))
+ assert report["rejected_references"] == bad