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(eval): read the MCQ boxed letter through the shared answer scan (#1347) (#1365)

dymux0d13d5a386c4
diff --git a/changelog.d/0.75.1/1365.fixed.md b/changelog.d/0.75.1/1365.fixed.md
new file mode 100644
index 00000000..30408a9a
--- /dev/null
+++ b/changelog.d/0.75.1/1365.fixed.md
@@ -0,0 +1 @@
+- **The eval gate's MCQ scorer read `\boxed{B.}` and `\boxed{**B**}` as C on a completion that echoes the option list, while the reward parser read B (#1347 by @putramkti in #1365).** The letter tier kept its own boxed regex after #1316 replaced the parser's with a normalising, brace-balancing read, so the two readers disagreed on the same box: the right answer scored wrong and the echoed option scored right. Both now read the boxes through one shared scan in `utils/final_answer.py`, and a test pins the tier to it so they cannot drift apart again.
diff --git a/src/soup_cli/eval/forgetting.py b/src/soup_cli/eval/forgetting.py
index 2bdd0738..2ca4daef 100644
--- a/src/soup_cli/eval/forgetting.py
+++ b/src/soup_cli/eval/forgetting.py
@@ -10,6 +10,8 @@ import re
from dataclasses import dataclass
from typing import Callable, Literal, Optional, Tuple
+from soup_cli.utils.final_answer import iter_boxed_answers
+
MiniBenchmark = list[dict[str, str]]
@@ -42,15 +44,15 @@ _CUE_RE = re.compile(
# Parenthesised choice marker: "(B)" or "B)".
_PAREN_RE = re.compile(r"(?<![A-Za-z0-9])\(?([A-Ja-j])\)(?![A-Za-z0-9])")
# LaTeX ``\boxed{C}`` — how a reasoning-tuned model states its final answer.
-# Mirrors ``trainer/rewards._extract_answer``'s boxed regex, but this is an
-# OPTION-LETTER tier and deliberately narrower: it fires only when the box holds
-# a single A–J letter. ``\boxed{4}`` is the model answering with a VALUE, and
+# Read through ``utils.final_answer``'s shared scan instead of a local regex: the
+# box counts as an OPTION LETTER when the scan's normalised content is a single
+# A–J letter, which keeps this tier and the reward parser on one reading of the
+# same box (they diverged once: ``\boxed{B.}`` and ``\boxed{**B**}`` read C here
+# and B there, #1347). The scan also allows whitespace between the command and
+# its brace, so the spaced spelling ``\boxed {A}`` scores — the same #357 defect,
+# one space to the left. ``\boxed{4}`` is the model answering with a VALUE, and
# reading that as "option 4" would be a wrong credit rather than a repair — the
# prompt is what has to change there (see ``_MCQ_ANSWER_CUE``). #357.
-# The ``\s*`` after ``\boxed`` matters: LaTeX permits whitespace between the
-# command and its brace and models emit it (``\boxed {A}``), so without it the
-# spaced spelling scores zero — the same #357 defect, one space to the left.
-_BOXED_LETTER_RE = re.compile(r"\\boxed\s*\{\s*([A-Ja-j])\s*\}")
# Bare standalone UPPERCASE letter that TERMINATES a clause — i.e. followed by
# end-of-string or sentence punctuation, not by more words. Requiring upper-case
# skips the lower-case article "a"/"an", and the terminating look-ahead skips a
@@ -121,7 +123,11 @@ def extract_mcq_letter(output: str) -> Optional[str]:
return None
output = output[:_MAX_SCORE_OUTPUT]
latest: Optional[Tuple[int, str]] = None
- for regex in (_BOXED_LETTER_RE, _CUE_RE, _PAREN_RE):
+ for box in iter_boxed_answers(output):
+ letter = box.answer.upper()
+ if len(letter) == 1 and letter in _MCQ_OPTIONS and (latest is None or box.end > latest[0]):
+ latest = (box.end, letter)
+ for regex in (_CUE_RE, _PAREN_RE):
for match in regex.finditer(output):
if latest is None or match.end() > latest[0]:
latest = (match.end(), match.group(1))
diff --git a/src/soup_cli/utils/final_answer.py b/src/soup_cli/utils/final_answer.py
index 628eb61c..623cd7a5 100644
--- a/src/soup_cli/utils/final_answer.py
+++ b/src/soup_cli/utils/final_answer.py
@@ -59,14 +59,17 @@ Every scan is linear in its input, because a completion is untrusted model outpu
from __future__ import annotations
import re
+from collections.abc import Iterator
from dataclasses import dataclass
from decimal import Decimal, InvalidOperation
from typing import NamedTuple
__all__ = [
+ "BoxedAnswer",
"FinalAnswer",
"answers_match",
"extract_final_answer",
+ "iter_boxed_answers",
"normalize_answer",
"parse_completion",
"parse_number",
@@ -131,6 +134,19 @@ class FinalAnswer:
number: Decimal | None = None
+@dataclass(frozen=True)
+class BoxedAnswer:
+ """One closed ``\\boxed{...}``: the braces' positions and the normalised content.
+
+ ``end`` is the index just past the closing brace, so a caller can rank a box against other
+ matches by position and read the last committed one.
+ """
+
+ start: int
+ end: int
+ answer: str
+
+
def _canonical_symbols(text: str) -> str:
"""Rewrite spellings that change no value: the Unicode minus, LaTeX thousands separators."""
text = text.replace("\u2212", "-").replace("{,}", ",")
@@ -254,29 +270,43 @@ def _marker_answer(text: str) -> tuple[int, _Explicit] | 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 iter_boxed_answers(text: str) -> Iterator[BoxedAnswer]:
+ """Yield the innermost ``\\boxed{...}`` answers in ``text``, in the order they close.
+
+ One pass over the braces. A box that holds another box is skipped: its content is the inner
+ box, so it is never itself an answer, and skipping it stops the normalised contents from
+ overlapping, which is what keeps the pass linear. A box that never closes is skipped too,
+ instead of swallowing the rest of the text.
+ """
+ opens = {match.end() - 1: match.start() for match in _BOXED_OPEN_RE.finditer(text)}
+ open_braces: list[int] = []
+ open_boxes: list[int] = [] # the braces of the boxes still open, innermost last
+ holds_a_box: set[int] = set()
+ for match in _BRACE_RE.finditer(text):
+ brace_at = match.start()
+ if match.group() == "{":
+ open_braces.append(brace_at)
+ if brace_at in opens:
+ if open_boxes:
+ holds_a_box.add(open_boxes[-1])
+ open_boxes.append(brace_at)
+ elif open_braces:
+ brace = open_braces.pop()
+ if brace in opens:
+ open_boxes.pop()
+ if brace not in holds_a_box:
+ answer = normalize_answer(text[brace + 1 : brace_at])
+ yield BoxedAnswer(opens[brace], match.end(), answer)
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
+ last = None
+ for last in iter_boxed_answers(text):
+ pass
+ if last is None or not last.answer:
+ return None
+ return last.start, last.answer
def _phrase_answer(text: str) -> tuple[int, _Explicit] | None:
diff --git a/tests/test_issue1347_boxed_scan.py b/tests/test_issue1347_boxed_scan.py
new file mode 100644
index 00000000..b4b345ef
--- /dev/null
+++ b/tests/test_issue1347_boxed_scan.py
@@ -0,0 +1,109 @@
+"""#1347: the shared ``\\boxed{...}`` scan behind both answer readers.
+
+`extract_mcq_letter` (`eval/forgetting.py`) and the reward parser
+(`utils/final_answer.py`) each read the same boxed answer. #1316 replaced the
+parser's boxed regex with a normalising, brace-balancing read, but the letter
+tier kept the old regex whose comment still claimed the two mirrored each other.
+They diverged on ``\\boxed{B.}`` and ``\\boxed{**B**}`` (B there, C here).
+
+`iter_boxed_answers` is that read, exposed: one pass over the braces, yielding
+every box that closes with its position and normalised content. The parser takes
+the last box, and the letter tier takes the last box whose content is one A–J
+letter. Neither owns a regex any more.
+"""
+
+from __future__ import annotations
+
+import time
+
+from soup_cli.utils.final_answer import BoxedAnswer, iter_boxed_answers, parse_completion
+
+# Long enough that the scan's own cost dominates the interpreter's.
+_GROWTH_INPUT = 20_000
+
+
+def _best_seconds(text: str, repeats: int = 3) -> float:
+ """The fastest of ``repeats`` full scans, to keep a loaded runner out of the way."""
+ best = float("inf")
+ for _ in range(repeats):
+ started = time.perf_counter()
+ sum(1 for _ in iter_boxed_answers(text))
+ best = min(best, time.perf_counter() - started)
+ return best
+
+
+class TestIssue1347TheScanReadsEveryClosedBox:
+ def test_innermost_boxes_are_yielded_once(self):
+ text = r"a \boxed{1} b \boxed{\frac{2}{3}} c \boxed{} d \boxed{4"
+ assert [(box.start, box.answer) for box in iter_boxed_answers(text)] == [
+ (2, "1"),
+ (14, r"\frac{2}{3}"),
+ (36, ""),
+ ]
+
+ def test_the_positions_bracket_the_box(self):
+ text = r"so \boxed{ 42 }."
+ (box,) = iter_boxed_answers(text)
+ assert isinstance(box, BoxedAnswer)
+ assert (box.start, box.end) == (3, len(text) - 1)
+ assert (box.answer, text[box.start : box.end]) == ("42", r"\boxed{ 42 }")
+
+ def test_the_last_box_that_closes_is_the_answer(self):
+ """Two boxes in one completion: the LAST one is the commitment, as on main."""
+ parsed = parse_completion(r"first \boxed{1}, so \boxed{42}")
+ assert parsed is not None and parsed.text == "42"
+
+ def test_a_box_that_never_closes_is_skipped(self):
+ assert list(iter_boxed_answers(r"\boxed{B")) == []
+ assert list(iter_boxed_answers(r"\boxed{B \boxed{C}"))[0].answer == "C"
+
+ def test_the_box_scan_and_the_reward_parser_read_the_same_content(self):
+ """The parser takes the scan's last box, so the two agree by construction."""
+ for completion in (r"\boxed{B.}", r"\boxed{**B**}", r"\boxed{42}", r"\boxed{ 42 }"):
+ (box,) = iter_boxed_answers(completion)
+ parsed = parse_completion(completion)
+ assert parsed is not None and parsed.text == box.answer
+
+
+class TestIssue1347TheScanGrowsLinearly:
+ def test_unclosed_boxes_cost_linear_time(self):
+ """A run of ``\boxed{`` that never closes is the scan's worst case: every brace is
+ walked and nothing is yielded. Quadratic growth would be ~64x for 8x the input, so
+ the bound sits far above the ~8x a linear scan measures."""
+ small = r"\boxed{" * _GROWTH_INPUT
+ large = r"\boxed{" * (_GROWTH_INPUT * 8)
+
+ assert sum(1 for _ in iter_boxed_answers(small)) == 0
+
+ small_seconds = _best_seconds(small)
+ large_seconds = _best_seconds(large)
+ assert large_seconds < small_seconds * 20, (small_seconds, large_seconds)
+ assert large_seconds < 3.0, large_seconds
+
+ def test_closed_boxes_cost_linear_time_too(self):
+ small = r"\boxed{B} " * _GROWTH_INPUT
+ large = r"\boxed{B} " * (_GROWTH_INPUT * 8)
+
+ assert sum(1 for _ in iter_boxed_answers(large)) == _GROWTH_INPUT * 8
+
+ small_seconds = _best_seconds(small)
+ large_seconds = _best_seconds(large)
+ assert large_seconds < small_seconds * 20, (small_seconds, large_seconds)
+ assert large_seconds < 3.0, large_seconds
+
+
+class TestIssue1347NestedBoxes:
+ def test_nested_closed_boxes_cost_linear_time(self):
+ """Every box closes and holds the next, so the boxes' contents overlap. Skipping the
+ boxes that hold a box is what keeps this linear: normalising them all would be quadratic
+ in the nesting depth."""
+ small = r"\boxed{" * 1_000 + "B" + "}" * 1_000
+ large = r"\boxed{" * 8_000 + "B" + "}" * 8_000
+
+ small_seconds = _best_seconds(small)
+ large_seconds = _best_seconds(large)
+ assert large_seconds < small_seconds * 20, (small_seconds, large_seconds)
+
+ def test_a_box_inside_a_box_reads_the_inner_answer(self):
+ parsed = parse_completion(r"\boxed{\boxed{42}}")
+ assert parsed is not None and parsed.text == "42"
diff --git a/tests/test_issue1347_mcq_boxed_letter.py b/tests/test_issue1347_mcq_boxed_letter.py
new file mode 100644
index 00000000..24806f4e
--- /dev/null
+++ b/tests/test_issue1347_mcq_boxed_letter.py
@@ -0,0 +1,79 @@
+"""#1347: `extract_mcq_letter` read `\\boxed{B.}` and `\\boxed{**B**}` as C.
+
+The letter tier kept its own boxed regex, `\\boxed\\s*\\{\\s*([A-Ja-j])\\s*\\}`, whose
+comment claimed it mirrored the reward parser. It did not. The reward parser
+normalises the box content, so a trailing `.` or markdown `*` is dropped and the
+braces are balanced, and `utils/final_answer` replaced that regex in #1316.
+
+The two readers disagreed on a completion that echoes the option list. When the
+box tier found no letter, the parenthesised tier took the last option of the
+echo, so `\\boxed{B.}` after `(A) 3 (B) 4 (C) 5` read C: the right answer scored
+wrong and the wrong option scored right.
+
+The tier now reads the boxes through the shared scan in `utils.final_answer` (see
+`test_issue1347_boxed_scan.py`), so the two readers cannot diverge again.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from soup_cli.eval import forgetting
+from soup_cli.eval.forgetting import extract_mcq_letter, score_answer
+from soup_cli.utils.final_answer import parse_completion
+
+# The echo is what made the defect visible: without it, the parenthesised tier
+# has nothing to fall back to and the box tier's miss looked like "no answer".
+_ECHOED_OPTIONS = "What is 2 + 2? (A) 3 (B) 4 (C) 5\n"
+
+
+class TestIssue1347ABoxedLetterIsReadAfterAnEchoedOptionList:
+ @pytest.mark.parametrize(
+ "completion",
+ [
+ r"\boxed{B}",
+ r"\boxed {B}", # whitespace between the command and its brace
+ r"\boxed{ B }", # whitespace inside the box
+ r"\boxed{B.}", # trailing full stop
+ r"\boxed{**B**}", # markdown emphasis
+ r"$\boxed{B}$", # math delimiters around the box
+ ],
+ )
+ def test_both_readers_read_the_boxed_letter(self, completion):
+ output = _ECHOED_OPTIONS + completion
+ assert extract_mcq_letter(output) == "B"
+ assert parse_completion(output).text == "B"
+
+ def test_the_right_answer_scores_and_the_echoed_option_does_not(self):
+ output = _ECHOED_OPTIONS + r"\boxed{B.}"
+ assert score_answer(output, "B") is True
+ assert score_answer(output, "C") is False
+
+
+class TestIssue1347TheTierReadsBoxesThroughTheSharedScan:
+ def test_the_tier_scans_the_boxes_with_the_shared_scan(self, monkeypatch):
+ """A local regex is what let the two readers drift apart: this pins the call."""
+ seen: list[str] = []
+ output = r"(C) x \boxed{A}"
+
+ def fake_scan(text: str):
+ seen.append(text)
+ return iter([SimpleNamespace(answer="B", end=len(text))])
+
+ monkeypatch.setattr(forgetting, "iter_boxed_answers", fake_scan)
+ assert forgetting.extract_mcq_letter(output) == "B"
+ assert seen == [output]
+
+ def test_a_box_that_never_closes_does_not_hide_the_one_before_it(self):
+ """The last CLOSED box is the commitment, so a half-written box is not read."""
+ assert extract_mcq_letter(r"first \boxed{A}, then \boxed{B") == "A"
+
+ def test_a_stray_closing_brace_before_a_box_is_ignored(self):
+ assert extract_mcq_letter(_ECHOED_OPTIONS + r"x} so \boxed{B}") == "B"
+
+ def test_a_boxed_value_is_still_not_an_option_letter(self):
+ """``\\boxed{4}`` answers with a value; only A–J in a box is a choice."""
+ assert extract_mcq_letter(r"\boxed{4}") is None
+ assert extract_mcq_letter(r"\boxed{4}") != "D"