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(eval): score wrapped and leading MCQ letters (#1924)
苏俊杰daa5e7b06e4c
diff --git a/changelog.d/0.76.0/1924.fixed.md b/changelog.d/0.76.0/1924.fixed.mdnew file mode 100644index 00000000..9b6f75ac--- /dev/null+++ b/changelog.d/0.76.0/1924.fixed.md@@ -0,0 +1 @@+- **Fixed MCQ forgetting scoring for unboxed letter spellings (#1442 by @Momoyeyu in #1924).** `extract_mcq_letter` now accepts a lone option letter wrapped in markdown emphasis, quotes, backticks or square brackets, and a standalone uppercase letter that leads the output before an explanation; boxed values and prose openers such as `A cat ...` still earn no credit.diff --git a/src/soup_cli/eval/forgetting.py b/src/soup_cli/eval/forgetting.pyindex 715f7b11..edbb3fc3 100644--- a/src/soup_cli/eval/forgetting.py+++ b/src/soup_cli/eval/forgetting.py@@ -44,6 +44,22 @@ _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])")+# A lone uppercase letter wrapped in markdown emphasis, quotes or square+# brackets: "**B**", "__B__", "*B*", "_B_", "`B`", "\"B\"", "'B'", "[B]".+# Deliberate markup of a single letter is an explicit commitment like "(B)",+# so it joins the last-wins tier — position decides against boxed/cue matches+# the same way. Keeping the letter uppercase leaves prose such as "the word+# 'a' is an article" untouched. (#1442)+_WRAPPED_RE = re.compile(+ r"(?<![A-Za-z0-9])(?:\*{1,2}|_{1,2}|[`\"'\[])\s*([A-J])\s*"+ r"(?:\*{1,2}|_{1,2}|[`\"'\]])(?![A-Za-z0-9])"+)+# Standalone uppercase letter LEADING the output, followed by a line break+# or " is" / " -" — the model led with its answer then explained itself+# ("B is the correct answer.", "B\n\nBecause ..."). Restricted to the start+# so a stray "B is" mid-prose cannot claim the slot, and kept uppercase so+# the article "a" still cannot. (#1442)+_LEADING_RE = re.compile(r"^([A-J])(?=\r?\n| is\b| -)")# LaTeX ``\boxed{C}`` — how a reasoning-tuned model states its final answer.# 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@@ -102,20 +118,25 @@ def build_mcq_prompt(question: str, answer: str) -> str:def extract_mcq_letter(output: str) -> Optional[str]:"""Pull the model's chosen MCQ option letter (A–J) from ``output``.- Three "explicit commitment" forms are considered together — a LaTeX- ``\\boxed{C}``, an ``answer/option/...`` cue, and a parenthesised- ``(B)``/``B)`` marker — and the LAST one to appear anywhere in the output+ Four "explicit commitment" forms are considered together — a LaTeX+ ``\\boxed{C}``, an ``answer/option/...`` cue, a parenthesised+ ``(B)``/``B)`` marker, and a markdown/quote/bracket-wrapped lone letter+ (``**B**``, ``[B]``) — and the LAST one to appear anywhere in the outputwins. Position, not form, decides: a model that boxes a scratch answer andthen self-corrects ("...\\boxed{A}... on reflection, the answer is (B)")chose B, while one that echoes the option list and then boxes its decision("(A) x (B) y. Answer: \\boxed{A}") chose A. Ranking the boxed FORM abovethe others would get the first of those backwards.- Only if none of the three appears does the bare tier apply: a- clause-terminating uppercase letter, taking the FIRST match (a model- answering without a cue leads with the letter, e.g. "C. I think ..."). A- bare letter only counts when it terminates a clause, so a prose opener- ("A cat sat ...") is not read as choosing option A.+ Only if none of the four appears (the wrapped-letter form counts as an+ explicit commitment too — ``**B**``/``[B]``/``"B"`` and friends, #1442)+ does the bare tier apply: a standalone uppercase letter leading the+ output followed by a line break or ``is``/``-`` (``B is the correct+ answer.``), else a clause-terminating uppercase letter, taking the FIRST+ match (a model answering without a cue leads with the letter, e.g. "C.+ I think ..."). A bare letter only counts when it terminates a clause or+ leads the output, so a prose opener ("A cat sat ...") is not read as+ choosing option A.Returns ``None`` when no option letter is present (e.g. a free-text answerlike "Berlin", or a boxed VALUE like ``\\boxed{4}``).@@ -128,12 +149,15 @@ def extract_mcq_letter(output: str) -> Optional[str]: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 regex in (_CUE_RE, _PAREN_RE, _WRAPPED_RE):for match in regex.finditer(output):if latest is None or match.end() > latest[0]:latest = (match.end(), match.group(1))if latest is not None:return latest[1].upper()+ leading = _LEADING_RE.match(output)+ if leading is not None:+ return leading.group(1)bare = _BARE_UPPER_RE.findall(output)if bare:return bare[0].upper()diff --git a/tests/test_issue1442_mcq_unboxed_letters.py b/tests/test_issue1442_mcq_unboxed_letters.pynew file mode 100644index 00000000..2eeed1b5--- /dev/null+++ b/tests/test_issue1442_mcq_unboxed_letters.py@@ -0,0 +1,119 @@+"""#1442: `extract_mcq_letter` rejected common UNBOXED answer spellings.++#1365 fixed the boxed spellings (`\\boxed{B.}`, `\\boxed{**B**}`), but the+unboxed set still read as no answer: markdown emphasis (`**B**`,+`Answer: **B**`), a letter followed by a line break and the explanation+(`B\\n\\nBecause ...`), and `B is the correct answer.`. On `MINI_MMLU` a+model that bolds every letter scored 0.000 while the same model writing+plain letters scored 1.000.++Two additions close it: a wrapped lone letter (`**B**`, `*B*`, `__B__`,+`` `B` ``, `"B"`, `'B'`, `[B]`) counts as an explicit commitment — same+last-wins tier as boxed/cue/paren — and a standalone uppercase letter that+LEADS the output counts when a line break or " is"/" -" follows.+"""++from __future__ import annotations++import pytest++from soup_cli.eval.forgetting import MINI_MMLU, extract_mcq_letter, score_answer+++class TestIssue1442SpellingsTable:+ """Every spelling in the issue's acceptance table, plus the extras it+ measured as None on main (`98905096`)."""++ @pytest.mark.parametrize(+ "completion",+ [+ "**B**",+ "The answer is **B**.",+ "Answer: **B**",+ "B\n\nExplanation: 2 + 2 = 4.",+ "B is the correct answer.",+ "Option **B**",+ "B\nBecause 2 + 2 = 4.",+ "B\r\nBecause 2 + 2 = 4.",+ "B - because 2 + 2 = 4.",+ "*B*",+ "__B__",+ "`B`",+ "[B]",+ '"B"',+ "'B'",+ "**B** (4)",+ "The correct choice is **B**, since 2 + 2 = 4.",+ ],+ )+ def test_unboxed_spelling_scores(self, completion):+ assert extract_mcq_letter(completion) == "B"+ assert score_answer(completion, "B") is True+++class TestIssue1442Controls:+ @pytest.mark.parametrize(+ "completion",+ [+ "B",+ "(B)",+ "The answer is B.",+ r"\boxed{B}",+ "**B.**",+ "**Answer:** B",+ ],+ )+ def test_existing_spellings_still_score(self, completion):+ assert score_answer(completion, "B") is True++ @pytest.mark.parametrize(+ "completion",+ [+ "A cat is an animal.", # the article "a" is not option A+ "the word 'a' is an article", # lowercase quoted prose is not option A+ "Berlin",+ r"\boxed{4}", # a boxed VALUE is not an option letter+ "I choose C", # a real but wrong letter earns no credit+ ],+ )+ def test_negatives_earn_no_credit(self, completion):+ assert score_answer(completion, "B") is False++ def test_lowercase_wrapped_letter_is_not_an_option(self):+ assert extract_mcq_letter("the word 'a' is an article") is None+++class TestIssue1442SuiteLevel:+ def test_mini_mmlu_all_bolded_scores_1_0(self):+ """The issue's headline metric: an always-correct model that bolds+ its letter scored 0.000 before this fix."""+ right = [item["answer"] for item in MINI_MMLU]+ score = sum(score_answer(f"**{a}**", a) for a in right) / len(right)+ assert score == pytest.approx(1.0)++ def test_wrapped_loses_to_a_later_explicit_commitment(self):+ """Last explicit commitment wins: a scratch ``**A**`` followed by a+ self-corrected ``\\boxed{B}`` reads B, not A."""+ assert extract_mcq_letter("first guess **A** ... on reflection \\boxed{B}") == "B"+++class TestIssue1442OrderingAndAnchor:+ """Pin the two behaviours the comments promise but the table above only+ exercises in one direction: a wrapped letter joins the last-wins tier+ (so it can override an earlier cue or box, and the later of two wrapped+ letters wins), and the leading form is anchored to the start (so a stray+ ``B is`` mid-prose is not read as an answer)."""++ def test_wrapped_letter_after_an_earlier_cue_wins(self):+ assert extract_mcq_letter("Answer: A. On reflection, **B**") == "B"+ assert score_answer("Answer: A. On reflection, **B**", "B") is True++ def test_wrapped_letter_after_an_earlier_boxed_wins(self):+ assert extract_mcq_letter(r"\boxed{A} ... on reflection **B**") == "B"++ def test_the_later_of_two_wrapped_letters_wins(self):+ assert extract_mcq_letter("first **A**, final **B**") == "B"++ def test_leading_form_is_anchored_to_the_start(self):+ assert extract_mcq_letter("Statement B is false") is None+ assert extract_mcq_letter("Statement B - false") is None