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: review follow-ups to #1310, #1275 and #1316 (#1332)

Alpamys Makazhan252e211be66f
diff --git a/benchmarks/README.md b/benchmarks/README.md
index 6b1b7234..121bc6f3 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -41,7 +41,7 @@ They are the evidence behind the preprint:
| [`gpu-test-runs.md`](gpu-test-runs.md) | Not a gate — every run of the CUDA-dependent tests (`pytest -m gpu`) on a real card, since CI has none ([#833](https://github.com/MakazhanAlpamys/Soup/issues/833)) | Two runs recorded, both before the marker existed, and **both found defects CI could not see**: 8x H100 (`9 failed, 419 passed` on the four streaming suites, three defects) and an RTX 5070 Laptop (sm_120, full suite `20709 passed, 2 failed`, #776) |
| [`gate-725-lorafa-operating-point.md`](gate-725-lorafa-operating-point.md) | PEFT LoRA-FA optimizer operating point ([#725](https://github.com/MakazhanAlpamys/Soup/issues/725)) | Measured 50.0% fewer trainable adapter parameters and 50.0% fewer AdamW state elements; analytic $r / d_{in}$ activation retention for adapted projections. Micro-benchmark only; explicitly not total LLM peak VRAM, throughput, or quality claim. |
| [`gate-836-bench-train-contract.md`](gate-836-bench-train-contract.md) | What `soup bench train` reports on a real card ([#836](https://github.com/MakazhanAlpamys/Soup/issues/836), shipped in [#1146](https://github.com/MakazhanAlpamys/Soup/pull/1146)) — the published reference run that acceptance item 7 asked for, on an RTX 5070 Laptop **on battery at a 50 W cap** | **The contract holds; the number does not repeat.** Over **thirteen runs of a byte-identical config** the config hash, token counts, `max_memory_allocated`, `max_memory_reserved` and all three checks are **identical to the byte**, while reported throughput spans **376.4–915.3 supervised tok/s, 2.43x** (CV 35.3%). The noise is **additive, not multiplicative**: across four shapes whose fast-mode step spans 26x (0.197–5.26 s) the fastest and slowest repeat differ by a near-constant **0.17–0.28 s per step** — 4.6% on a 5.3 s step, 1.9x on a 0.2 s one — and a longer window does **not** average it away (160 counted steps still spread 1.89x). Two explanations were tested and **both refuted by their own covariate** (peer processes; CPU frequency, where the highest-frequency run is in the slow half). Also: one shape **completed while allocating 1.51x the card's VRAM** (WDDM spill — `memory` is the allocator's truth, not a fit), `provenance.sm_clock_mhz_after_run` is an **idle reading** that cannot discriminate a 1.83x difference (since replaced by the busy-window `sm_clock_mhz_busy` in [#1177](https://github.com/MakazhanAlpamys/Soup/pull/1177); see the record's addendum), and `config_hash` changes with `--steps` because the tool's own `save_steps` override is inside it. Four refusals exercised verbatim; one **contaminated run** kept in |
-| [`gate-1227-ab-burn-in.md`](gate-1227-ab-burn-in.md) | The burn-in of `soup ab`'s two-sided mSPRT ([#1227](https://github.com/MakazhanAlpamys/Soup/issues/1227)): how many rows per arm before any verdict, so that re-running the test after every new pair keeps its false-positive rate at `--alpha` | **30 rows at alpha >= 0.05, 40 below**, calibrated over runs of up to 1000 rows per arm: worst Type-I **0.0512** at alpha 0.05 and **0.0109** at alpha 0.01 (bounds 0.0521 / 0.0109). A 200-row horizon had picked 20 rows, which reach 0.0534 by 1000 rows. Not calibrated below alpha 0.01 (0.0058 at 0.005). With the true variance the rate stays below alpha everywhere |
+| [`gate-1227-ab-burn-in.md`](gate-1227-ab-burn-in.md) | The burn-in of `soup ab`'s two-sided mSPRT ([#1227](https://github.com/MakazhanAlpamys/Soup/issues/1227)): how many rows per arm before any verdict, so that re-running the test after every new pair keeps its false-positive rate at `--alpha` | **30 rows at alpha >= 0.05, 40 below**, calibrated over runs of up to 1000 rows per arm: worst Type-I **0.0512** at alpha 0.05 (bound 0.0521). At alpha 0.01 the sweep's 0.01088 is inside its bound (0.01094) **only in this seed set**: two of three other seed sets reached 0.0113 and 0.0116, and pooled over seeds the worst case is near **0.0108, about 8% over nominal**, a floor set by the estimated variance that more rows do not lower ([#1265](https://github.com/MakazhanAlpamys/Soup/issues/1265)). A 200-row horizon had picked 20 rows, which reach 0.0534 by 1000 rows. Not calibrated below alpha 0.01 (0.0058 at 0.005). With the true variance the rate stays below alpha everywhere |
## Harnesses
diff --git a/changelog.d/0.75.1/1332.fixed.md b/changelog.d/0.75.1/1332.fixed.md
new file mode 100644
index 00000000..a43298e5
--- /dev/null
+++ b/changelog.d/0.75.1/1332.fixed.md
@@ -0,0 +1 @@
+- **GRPO's `accuracy` and verifiable `math` rewards now match a LaTeX matrix however its rows are spaced (#1226, follow-up to #1316 in #1332).** Answer normalisation read the second backslash of a row break followed by a space (`\\ `) as the LaTeX control space `\ ` and deleted it, so a gold such as MATH-500's `\begin{pmatrix} -2 \\ -14 \\ -7 \end{pmatrix}` scored 1.0 only against a completion that spaced its rows the same way, and 0.0 against the same matrix written `\begin{pmatrix}-2\\-14\\-7\end{pmatrix}`. A row break is now kept whole, while `\,`, `\!`, `\;`, `\:` and `\ ` are still dropped. After an answer phrase (`The answer is $...$.`), a LaTeX environment such as a matrix is now one answer, like `(3, 4)`: its entries used to count as separate values, so a matrix whose entries stood apart read as a hedge and scored 0.0 (and a gold written that way was refused), while one with a single stand-alone entry was read as that number and could pay a numeric gold equal to it. All 7 MATH-500 golds with a space after a row break are matrices, and each now matches its other spacings; across the 9,792 GSM8K and MATH-500 gold texts, only those 7 answers and their 7 solutions read differently, and no numeric reading changes.
diff --git a/docs/evaluation.md b/docs/evaluation.md
index c65015a3..9f77c12a 100644
--- a/docs/evaluation.md
+++ b/docs/evaluation.md
@@ -277,11 +277,10 @@ The values come from a simulation of that re-run-after-every-pair procedure: bet
The calibration has two limits, and `soup ab` prints a warning past either:
-- **At `--alpha 0.01` the rate sits slightly above the level asked for**, near 0.011 across seeds, because the variance is estimated from the rows; more rows do not lower it. A statistic without that floor is [#1265](https://github.com/MakazhanAlpamys/Soup/issues/1265).
- **Below `--alpha 0.01` it is not calibrated.** At `--alpha 0.005`, 40 rows leave a simulated rate slightly above the level asked for.
- **It holds up to 1000 rows per arm.** Past that, a test that keeps being re-run has not been measured.
-A variance-robust statistic, which would need no burn-in, is tracked in [#1265](https://github.com/MakazhanAlpamys/Soup/issues/1265).
+**At `--alpha 0.01` itself the rate sits slightly above the level asked for**, near 0.011 across seeds, because the variance is estimated from the rows; more rows do not lower it, and `soup ab` prints no warning for it. A variance-robust statistic, which would remove that floor and need no burn-in, is tracked in [#1265](https://github.com/MakazhanAlpamys/Soup/issues/1265).
```bash
soup ab --input ab.jsonl --metric latency --effect-size 0.5
diff --git a/docs/training.md b/docs/training.md
index 8b818082..fa0bfaf9 100644
--- a/docs/training.md
+++ b/docs/training.md
@@ -1245,17 +1245,19 @@ a hedge and states no answer: `The answer is either 41 or 42.`, `Answer: 41 or 4
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.
+answer (`(3, 4)`, `\begin{pmatrix} 3 \\ 4 \end{pmatrix}`, `\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`).
+also drop the trailing punctuation `. , ; : !`, LaTeX thousands separators such as `1{,}000`, the
+LaTeX spacing commands `\,` `\!` `\;` `\:` and `\ `, and a Unicode minus sign. A `\\` row break is
+kept whole, so a matrix matches however its rows are spaced. 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 as
keyword arguments. An Alpaca `output` or the final assistant turn in ShareGPT/ChatML is also
diff --git a/src/soup_cli/utils/final_answer.py b/src/soup_cli/utils/final_answer.py
index 1773094a..628eb61c 100644
--- a/src/soup_cli/utils/final_answer.py
+++ b/src/soup_cli/utils/final_answer.py
@@ -28,15 +28,16 @@ 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.
+from its clause: the stand-alone numbers outside brackets and LaTeX environments (the digits of
+``(3, 4)``, of a ``\\begin{pmatrix} 3 \\\\ 4 \\end{pmatrix}`` matrix, of ``\\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
@@ -45,12 +46,12 @@ last non-empty line, and its number is the last number anywhere in it, which is
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.
+``\\frac``; LaTeX spacing (``\\,``, ``\\!``, ``\\;``, ``\\:``, ``\\ ``, but never the second
+backslash of a ``\\\\`` line break) 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.
"""
@@ -87,7 +88,9 @@ _ANSWER_LABEL_RE = re.compile(r"[*_\s]*(?:final\s+)?answer[*_\s]*(?::[*_\s]*)?",
_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"\\[,!;: ]")
+# 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"\\\\|\\[,!;: ]")
_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])")
@@ -97,11 +100,12 @@ _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.
+# A bracket, or a LaTeX environment's "\begin{...}" / "\end{...}", which lets a scan track depth
+# (a matrix is one answer, not one value per entry); 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"[()\[\]{}]"
+ r"\\(?:begin|end)\{[A-Za-z*]*\}|[()\[\]{}]"
+ "|" + _STANDS_ALONE + "[-+]?" + _UNSIGNED_PATTERN + "(?::" + _UNSIGNED_PATTERN + ")+"
+ "|" + _STANDS_ALONE + r"(?<!\d:)(" + _NUMBER_PATTERN + r")(?![\w{}^/]|:\d)"
)
@@ -130,7 +134,7 @@ class FinalAnswer:
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)
+ return _LATEX_SPACING_RE.sub(lambda match: "\\\\" if match.group() == "\\\\" else "", text)
def normalize_answer(text: str) -> str:
@@ -193,8 +197,8 @@ def _split_clause(line: str) -> tuple[str, str]:
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."""
+ """The distinct values a clause names: the answer's stand-alone numbers outside brackets and
+ LaTeX environments, 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):
@@ -202,9 +206,9 @@ def _clause_values(answer: str, aside: str) -> frozenset[Decimal]:
if match.group(1) is not None:
if depth == 0:
values.add(_to_decimal(match.group(1)))
- elif token in _OPENERS:
+ elif token in _OPENERS or token.startswith("\\begin"):
depth += 1
- elif token in _CLOSERS:
+ elif token in _CLOSERS or token.startswith("\\end"):
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))
diff --git a/tests/test_issue1222_refuse_int8_qat.py b/tests/test_issue1222_refuse_int8_qat.py
index 7c5925f2..82481f93 100644
--- a/tests/test_issue1222_refuse_int8_qat.py
+++ b/tests/test_issue1222_refuse_int8_qat.py
@@ -14,8 +14,8 @@ The ruling is "refuse until real QAT exists". This file pins:
backend that accepted it (unsloth included, which supersedes #1248), and on
every entry point that builds a config (the string loader the Web UI uses,
direct construction, ``soup train`` and ``soup doctor --config``);
-* the message: it names the setting, says why, says what still works and
- points at the issue;
+* the message: it names the setting, says why, says what to do instead,
+ says what still works and points at the issue;
* that no other message recommends the refused value (``soup train``'s
unsloth refusal used to);
* the values that must NOT change -- ``fp8``, ``quest`` and every false
@@ -110,6 +110,8 @@ def test_the_message_names_the_setting_the_reason_what_still_works_and_the_issue
in message
)
assert "no run completed" not in message
+ # What to do instead.
+ assert "Remove the key or set it to false." in message
# What still works, and why it is unaffected.
assert "quantization_aware: fp8" in message
assert "quantization_aware: quest" in message
diff --git a/tests/test_issue1226_parser_edge_cases.py b/tests/test_issue1226_parser_edge_cases.py
index b9ea06a5..ab5829ac 100644
--- a/tests/test_issue1226_parser_edge_cases.py
+++ b/tests/test_issue1226_parser_edge_cases.py
@@ -12,6 +12,12 @@ r"""Edge cases of the #1226 final-answer parser, found while reviewing the fix.
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.
+5. **A LaTeX line break keeps both backslashes.** ``\\ -14`` is a row break followed by a space,
+ not the control space ``\ ``, so it must not normalise to ``\-14``. Every MATH-500 gold with a
+ space after a row break is a matrix (7 of 500), and each one matched only a completion that
+ spaced its rows identically. The spacing commands themselves are still dropped. After an
+ answer phrase a matrix is one answer: a LaTeX environment is a bracket to the value scan, so
+ entries that stand apart are not a hedge between several values.
The linear-time check of the clause scanner is in ``test_issue1226_clause_scanner_is_linear.py``.
"""
@@ -25,7 +31,13 @@ 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
+from soup_cli.utils.final_answer import (
+ FinalAnswer,
+ normalize_answer,
+ parse_completion,
+ parse_number,
+ parse_reference,
+)
_REWARDS = [("accuracy", None), ("verifiable", "math")]
@@ -219,3 +231,80 @@ class TestAMarkerHeadingIsNotAGold:
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)
+
+
+# ===========================================================================
+# 5. a LaTeX line break keeps both backslashes
+# ===========================================================================
+
+LINE_BREAK = "\\" * 2 # LaTeX's row break: two backslashes
+# The seven MATH-500 golds (HuggingFaceH4/MATH-500, test split) with a space after a row break.
+# Every one is a matrix.
+MATH500_MATRIX_GOLDS = [
+ r"\begin{pmatrix} -1/3 \\ 2/3 \\ 5/3 \end{pmatrix}",
+ r"\begin{pmatrix} -2 \\ -14 \\ -7 \end{pmatrix}",
+ r"\begin{pmatrix} -1 & 0 \\ 0 & -1 \end{pmatrix}",
+ r"\begin{pmatrix} -18 \\ -49 \\ 96 \end{pmatrix}",
+ r"\begin{pmatrix} 1/5 \\ -18/5 \end{pmatrix}",
+ r"\begin{pmatrix} -7 \\ 16 \\ 5 \end{pmatrix}",
+ r"\begin{pmatrix} 16/49 \\ 48/49 \\ 24/49 \end{pmatrix}",
+]
+
+
+def _row_spacings(gold: str) -> list[str]:
+ """The same matrix, with its rows spaced the ways a model writes them."""
+ no_space_after = gold.replace(LINE_BREAK + " ", LINE_BREAK)
+ return [
+ gold,
+ no_space_after,
+ no_space_after.replace(" " + LINE_BREAK, LINE_BREAK),
+ "".join(gold.split()),
+ ]
+
+
+MATRIX_SPELLINGS = [
+ (gold, spelling) for gold in MATH500_MATRIX_GOLDS for spelling in _row_spacings(gold)
+]
+
+
+class TestALatexLineBreakKeepsBothBackslashes:
+ @pytest.mark.parametrize(("gold", "spelling"), MATRIX_SPELLINGS)
+ def test_a_matrix_matches_however_its_rows_are_spaced(self, gold, spelling):
+ # Either side can carry either spacing, boxed or on a '####' line.
+ assert _scores(r"\boxed{" + spelling + "}", gold) == (1.0, 1.0)
+ assert _scores(r"\boxed{" + gold + "}", spelling) == (1.0, 1.0)
+ assert _scores("#### " + spelling, gold) == (1.0, 1.0)
+
+ def test_normalisation_keeps_a_row_break_whole(self):
+ assert normalize_answer(r"-2 \\ -14 \\ -7") == r"-2 \\ -14 \\ -7"
+
+ def test_a_different_matrix_still_scores_zero(self):
+ gold = MATH500_MATRIX_GOLDS[1]
+ assert _scores(r"\boxed{\begin{pmatrix}-2\\-14\\7\end{pmatrix}}", gold) == (0.0, 0.0)
+
+ def test_a_row_break_is_kept_not_dropped(self):
+ # The two entries 1 and 2 are not the one entry 12.
+ column = r"\begin{pmatrix} 1 \\ 2 \end{pmatrix}"
+ assert _scores(r"\boxed{\begin{pmatrix}1\\2\end{pmatrix}}", column) == (1.0, 1.0)
+ assert _scores(r"\boxed{\begin{pmatrix}12\end{pmatrix}}", column) == (0.0, 0.0)
+
+ @pytest.mark.parametrize(("gold", "spelling"), MATRIX_SPELLINGS)
+ def test_a_matrix_after_an_answer_phrase_is_one_answer(self, gold, spelling):
+ # A matrix's entries are one answer, not several values: no hedge, whatever the spacing.
+ assert _scores("The answer is $" + spelling + "$.", gold) == (1.0, 1.0)
+ assert _scores("Answer: $" + spelling + "$", gold) == (1.0, 1.0)
+
+ def test_a_phrased_matrix_is_one_text_answer_not_a_number(self):
+ column = r"\begin{pmatrix} 3 \\ 4 \end{pmatrix}"
+ phrased = "The answer is $" + column + "$."
+ assert _scores(phrased, column) == (1.0, 1.0)
+ assert _scores(phrased, "3") == (0.0, 0.0) # not its first entry
+ assert parse_reference(phrased) is not None # a gold written that way is readable
+ # The environment closes: a value on each side of the matrix is still a hedge.
+ assert _scores("The answer is 5 or $" + column + "$ or 6.", "5") == (0.0, 0.0)
+
+ @pytest.mark.parametrize("command", [r"\,", r"\!", r"\;", r"\:", "\\ "])
+ def test_the_spacing_commands_are_still_dropped(self, command):
+ # "\\ " here is one backslash and a space: the control space, which is still dropped.
+ assert normalize_answer("1" + command + "000") == "1000"
+ assert parse_number("1" + command + "000") == Decimal(1000)
diff --git a/tests/test_issue1227_ab_two_sided.py b/tests/test_issue1227_ab_two_sided.py
index bab2e6fa..2eb2f4d8 100644
--- a/tests/test_issue1227_ab_two_sided.py
+++ b/tests/test_issue1227_ab_two_sided.py
@@ -8,11 +8,14 @@ command said "No significant difference". On ``latency`` and ``retry_rate``
(lower is better) that made a real improvement look like no difference too.
The fix is the symmetric two-point mixture: average the likelihood RATIOS for
-``+effect_size`` and ``-effect_size`` (in log space, with logsumexp). Each point
-ratio is a martingale under H0 and so is their average, which is why the
-``log((1 - beta) / alpha)`` boundary keeps its meaning. Averaging the
-log-ratios, or substituting ``|z|``, does not have that property; the peeking
-simulations below are what catch the ``|z|`` shortcut.
+``+effect_size`` and ``-effect_size`` (in log space, with logsumexp). With a
+known variance each point ratio has expectation 1 under H0 at every step, and so
+does their average, which is why the ``log((1 - beta) / alpha)`` boundary keeps
+its meaning. Neither is exactly a martingale (the ``n_eff / (n_eff + 1)`` shrink
+moves the alternative with n), so the Type-I rate under peeking is measured, not
+derived. Averaging the log-ratios, or substituting ``|z|``, does not keep that
+expectation at 1; the peeking simulations below are what catch the ``|z|``
+shortcut.
That argument needs a known variance, and ``soup ab`` estimates it from the rows.
From a handful of rows the estimate is too noisy: without a burn-in, re-running
@@ -27,15 +30,18 @@ alpha 0.01. The simulations here stop at 200 rows per arm to stay CI-sized.
from __future__ import annotations
+import inspect
import json
import math
import re
import statistics
+from pathlib import Path
import pytest
from typer.testing import CliRunner
runner = CliRunner()
+_REPO_ROOT = Path(__file__).resolve().parents[1]
# Rich colours per character on Linux CI, and wraps; compare on plain text.
# Box-drawing characters go too, so a table row reads "direction worse" and a
@@ -294,6 +300,54 @@ class TestBurnIn:
assert verdict.log_likelihood_ratio >= _upper()
+class TestTheBurnInTextFollowsTheTable:
+ """The `--alpha` help and two docs pages state the burn-in in words.
+
+ Nothing else ties that text to ``BURN_IN_ROWS_BY_ALPHA``: change a value there (after
+ re-running the sweep) and these fail until the help and the docs say it too.
+ """
+
+ @staticmethod
+ def _tiers():
+ from soup_cli.utils.ab_test import BURN_IN_ROWS_BY_ALPHA, min_rows_per_arm
+
+ # The text names two calibrated tiers, and one "N below" covers both the lower tier
+ # and the uncalibrated range, so it is right only while those share a value.
+ assert len(BURN_IN_ROWS_BY_ALPHA) == 2, BURN_IN_ROWS_BY_ALPHA
+ (high_alpha, high_rows), (low_alpha, low_rows) = BURN_IN_ROWS_BY_ALPHA
+ assert min_rows_per_arm(low_alpha / 2) == low_rows
+ return f"{high_alpha:g}", high_rows, f"{low_alpha:g}", low_rows
+
+ def test_the_alpha_help_states_the_table(self):
+ from soup_cli.commands.ab import ab
+
+ high_alpha, high_rows, low_alpha, low_rows = self._tiers()
+ help_text = " ".join(inspect.signature(ab).parameters["alpha"].default.help.split())
+ expected = (
+ f"no verdict before {high_rows} rows per arm at {high_alpha} and above, "
+ f"{low_rows} below (not calibrated below {low_alpha})"
+ )
+ assert expected in help_text, help_text
+
+ def test_docs_commands_md_states_the_table(self):
+ high_alpha, high_rows, _, low_rows = self._tiers()
+ text = (_REPO_ROOT / "docs" / "commands.md").read_text(encoding="utf-8")
+ expected = (
+ f"continue until {high_rows} rows per arm, {low_rows} when --alpha < {high_alpha}"
+ )
+ assert expected in text
+
+ def test_docs_evaluation_md_table_states_the_table(self):
+ high_alpha, high_rows, low_alpha, low_rows = self._tiers()
+ text = (_REPO_ROOT / "docs" / "evaluation.md").read_text(encoding="utf-8")
+ for row in (
+ f"| {high_alpha} and above | {high_rows} |",
+ f"| from {low_alpha} to below {high_alpha} | {low_rows} |",
+ f"| below {low_alpha} | {low_rows}, **not calibrated** |",
+ ):
+ assert row in text, row
+
+
# ---------------------------------------------------------------------------
# The statistic itself: log of the AVERAGE of the two likelihood ratios
# ---------------------------------------------------------------------------