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.

test: linear-growth timing checks measure above timer noise (#2069)

Alpamys Makazhan3779f97f6f81
diff --git a/tests/_growth_timing.py b/tests/_growth_timing.py
new file mode 100644
index 00000000..9ebe2a97
--- /dev/null
+++ b/tests/_growth_timing.py
@@ -0,0 +1,121 @@
+"""THE growth check for the "stays linear" tests. One definition.
+
+A wall-clock test of "linear, not quadratic" compares the time at ``scale * n`` with the time
+at ``n``: a linear scan grows about ``scale`` times, a quadratic one ``scale ** 2`` times. The
+tests that did this at a fixed ``n`` timed calls of 30 microseconds to a few milliseconds (most
+of them under a millisecond), so one scheduler stall on a loaded runner was larger than the
+whole signal: ``test_contains_grows_linearly[one-letter-run]`` read 69 microseconds against
+1.77 ms (25.6x, limit 24) and the email growth test "8N took 0.024s vs N 0.001s" on macOS,
+2026-10-20. A fixed bound flaked the same way before (#1932).
+
+Three things keep a loaded runner from deciding the test:
+
+* The reference run is calibrated to take at least ``MIN_BASE_SECONDS``: ``n`` doubles from a
+ small start until it does (capped at ``MAX_GROWTH`` times the start), so a slow machine needs
+ fewer doublings and a fast one more, and the signal is far above the timer and a stall.
+ Starting small also keeps a quadratic scan cheap to catch: its reference reaches the floor
+ at a small ``n``, so the larger run takes about ``scale ** 2`` times the floor, whatever the
+ start was.
+* Both sizes are the fastest of several runs, taken in alternation, so the same load phases
+ hit both. The check ends at the first round that shows the larger input is fast enough; only
+ a genuinely super-linear scan runs more than one, and it gives up after ``MIN_ROUNDS`` once
+ ``BUDGET_SECONDS`` are spent.
+* The collector is paused while timing, so one full collection cannot land on one size only.
+
+A call that truncates its input (``detect_pii`` reads the first 50,000 characters) would stop
+growing past that length and pass whatever it did before it: give ``cap`` the length it reads.
+
+``TIMER_SLACK_SECONDS`` is added to the bound for the case where the call is so fast that the
+cap is reached before the reference is long. A quadratic scan fails by a wide margin at either
+size: 64x against a 32x limit.
+"""
+
+from __future__ import annotations
+
+import gc
+import time
+from collections.abc import Callable
+from typing import Any
+
+SCALE = 8
+LIMIT = 4.0 * SCALE # 4x slack over linear (8x), as in #1932; a quadratic scan measures 64x
+MIN_BASE_SECONDS = 0.005
+MAX_GROWTH = 4096 # how far calibration may scale the starting size
+ROUNDS = 5
+MIN_ROUNDS = 2 # a failing scan still gets this many rounds, however slow
+BUDGET_SECONDS = 2.0 # ...and no more once the rounds have spent this long
+TIMER_SLACK_SECONDS = 0.002
+
+
+def _seconds(call: Callable[[Any], object], payload: Any) -> float:
+ start = time.perf_counter()
+ call(payload)
+ return time.perf_counter() - start
+
+
+def _calibrate(
+ call: Callable[[Any], object],
+ build: Callable[[int], Any],
+ size: int,
+ min_base: float,
+ max_size: int,
+) -> tuple[int, Any, float]:
+ """Double ``size`` until the best of three runs reaches ``min_base`` (or ``max_size``)."""
+ while True:
+ payload = build(size)
+ best = min(_seconds(call, payload) for _ in range(3))
+ if best >= min_base or size * 2 > max_size:
+ return size, payload, best
+ size *= 2
+
+
+def assert_grows_linearly(
+ call: Callable[[Any], object],
+ build: Callable[[int], Any],
+ size: int,
+ *,
+ label: str = "",
+ scale: int = SCALE,
+ limit: float = LIMIT,
+ min_base: float = MIN_BASE_SECONDS,
+ cap: int | None = None,
+) -> None:
+ """Fail unless ``call(build(scale * n))`` takes under ``limit`` times ``call(build(n))``.
+
+ ``n`` starts at ``size`` and is calibrated up so the reference run lasts ``min_base``.
+ ``build(k)`` returns an input that grows in proportion to ``k``; ``call`` takes it whole.
+ ``cap`` is the largest ``k`` the call still reads in full: past it the call truncates (or
+ refuses) its input, so a larger run would measure nothing. The larger input never exceeds
+ it, and the reference then stays shorter than ``min_base`` if it has to.
+ """
+ max_size = size * MAX_GROWTH
+ if cap is not None:
+ max_size = min(max_size, cap // scale)
+ if size > max_size:
+ raise ValueError(f"size {size} x {scale} is past the cap of {cap}")
+ reenable = gc.isenabled()
+ gc.collect()
+ gc.disable()
+ try:
+ used, small, t_small = _calibrate(call, build, size, min_base, max_size)
+ large = build(scale * used)
+ t_large = float("inf")
+ spent = 0.0
+ for round_number in range(1, ROUNDS + 1):
+ t_small = min(t_small, _seconds(call, small))
+ latest = _seconds(call, large)
+ t_large = min(t_large, latest)
+ if t_large <= limit * t_small + TIMER_SLACK_SECONDS:
+ return
+ spent += latest
+ if round_number >= MIN_ROUNDS and spent > BUDGET_SECONDS:
+ break
+ finally:
+ if reenable:
+ gc.enable()
+ prefix = f"{label}: " if label else ""
+ raise AssertionError(
+ f"{prefix}{scale}x the input took {t_large / t_small:.0f}x as long "
+ f"(limit {limit:.0f}x; n={used}: {t_small * 1e3:.2f} ms -> {t_large * 1e3:.2f} ms, "
+ f"best of {round_number} rounds)"
+ )
diff --git a/tests/test_issue1226_clause_scanner_is_linear.py b/tests/test_issue1226_clause_scanner_is_linear.py
index c335b889..b1103223 100644
--- a/tests/test_issue1226_clause_scanner_is_linear.py
+++ b/tests/test_issue1226_clause_scanner_is_linear.py
@@ -8,7 +8,8 @@ completion.
The test compares the time at N with the time at 8N instead of checking an absolute time, so it
holds on any machine and fails fast: a linear scan grows about 8x, the quadratic one grew
-61-66x, and at N = 1,000 the quadratic scan failed each case in 10-13 s. The absolute 2 s
+61-66x, and at N = 1,000 the quadratic scan failed each case in 10-13 s (before the reference
+was calibrated up; ``tests/_growth_timing.py``). The absolute 2 s
bound on 20,000 spaces is in ``TestAdversarialInputsStayLinear`` of
``test_issue1226_reward_gold_parsing.py``.
@@ -18,13 +19,13 @@ clauses continue a list.
from __future__ import annotations
-import time
from decimal import Decimal
import pytest
from soup_cli.trainer.rewards import accuracy_reward, math_verify_reward
from soup_cli.utils.final_answer import parse_completion
+from tests._growth_timing import assert_grows_linearly
def _msg(text: str) -> list[list[dict]]:
@@ -57,39 +58,18 @@ WHITESPACE_RUNS = {
"glued-because": lambda k: "The answer is 42 " + "x-because " * k + "x",
}
-_SCALE_N = 1_000
-# A linear scan takes about 8x as long on 8x the input: 6.5-7.4x measured, the fixed cost of a
-# call pulling it below 8. The quadratic scan took 61-66x. The limit leaves 3x of slack over
-# linear, and every time is a best of several runs, so a stall on a busy runner would have to
-# hit every run of the larger input to fail the test.
-_SCALE_LIMIT = 24.0
-
-
-def _best_time(text: str, repeats: int) -> float:
- best = float("inf")
- for _ in range(repeats):
- start = time.perf_counter()
- parse_completion(text)
- best = min(best, time.perf_counter() - start)
- return best
+_SCALE_N = 100 # the starting size; the helper doubles it until the run is long enough to time
class TestTheClauseScannerIsLinear:
@pytest.mark.parametrize("build", list(WHITESPACE_RUNS.values()), ids=list(WHITESPACE_RUNS))
def test_time_grows_linearly_with_a_whitespace_run(self, build):
- small, large = build(_SCALE_N), build(8 * _SCALE_N)
# The clause ends at the comma or semicolon, so the answer is 42 at every size.
- assert parse_completion(large).number == Decimal(42)
- t_small = max(_best_time(small, repeats=5), 1e-7)
- t_large = float("inf")
- for _ in range(5): # stop as soon as the larger input is shown to be fast enough
- t_large = min(t_large, _best_time(large, repeats=1))
- if t_large <= _SCALE_LIMIT * t_small:
- break
- assert t_large <= _SCALE_LIMIT * t_small, (
- f"8x the whitespace took {t_large / t_small:.0f}x as long "
- f"({t_small * 1e3:.2f} ms -> {t_large * 1e3:.2f} ms)"
- )
+ assert parse_completion(build(8_000)).number == Decimal(42)
+ # A linear scan takes about 8x as long on 8x the input (6.5-7.4x measured, the fixed
+ # cost of a call pulling it below 8); the quadratic scan took 61-66x. The helper's 32x
+ # limit leaves 4x of slack over linear, on a reference long enough to time.
+ assert_grows_linearly(parse_completion, build, _SCALE_N)
# After ", " or "; " a number continues the list in every spelling the look-ahead accepts: a
diff --git a/tests/test_issue1329_email_pattern_is_linear.py b/tests/test_issue1329_email_pattern_is_linear.py
index aca1323b..7bc168e3 100644
--- a/tests/test_issue1329_email_pattern_is_linear.py
+++ b/tests/test_issue1329_email_pattern_is_linear.py
@@ -4,7 +4,6 @@ from __future__ import annotations
import random
import re
-import statistics
import time
from pathlib import Path
@@ -13,6 +12,7 @@ from typer.testing import CliRunner
from soup_cli.cli import app
from soup_cli.utils import data_score
+from tests._growth_timing import assert_grows_linearly
_BASELINE_EMAIL_PATTERN = re.compile(r"\b[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}\b")
_PATHOLOGICAL_RUNS = ("1-", "1.", "a.", "a-", "a+")
@@ -30,34 +30,43 @@ def _email_snippets(text: str) -> list[str]:
]
+def _row(run: str, length: int) -> str:
+ return (run * ((length + len(run) - 1) // len(run)))[:length]
+
+
+def test_email_pattern_growth_is_linear() -> None:
+ """The pattern alone: an 8x longer row must not take 32x the time (linear 8x, quadratic 64x).
+
+ ``detect_pii`` reads only the first ``_PII_SCAN_CAP`` characters, so a row long enough to
+ time reliably is past what it scans. The compiled pattern has no such cap: the helper
+ doubles the row until one search lasts long enough to time, then compares it with 8x.
+ """
+ pattern = _email_pattern()
+ for run in _PATHOLOGICAL_RUNS:
+ assert_grows_linearly(
+ pattern.search, lambda length, run=run: _row(run, length), 500, label=repr(run)
+ )
+
+
def test_email_detection_growth_is_subquadratic(monkeypatch: pytest.MonkeyPatch) -> None:
- """An 8x longer row must not consume 64x the regex time."""
+ """``detect_pii`` end to end (all four patterns), within the rows it scans in full."""
monkeypatch.setattr(data_score, "_presidio_pii", lambda _text: None)
n = 5_000
for run in _PATHOLOGICAL_RUNS:
- smaller = (run * ((n + len(run) - 1) // len(run)))[:n]
- larger = (run * ((8 * n + len(run) - 1) // len(run)))[: 8 * n]
-
- small_samples = []
- large_samples = []
- for _ in range(3):
- start = time.perf_counter()
- small_hits = data_score.detect_pii(smaller)
- small_samples.append(time.perf_counter() - start)
-
- start = time.perf_counter()
- large_hits = data_score.detect_pii(larger)
- large_samples.append(time.perf_counter() - start)
-
- small_elapsed = statistics.median(small_samples)
- large_elapsed = statistics.median(large_samples)
-
- assert not any(hit["kind"] == "email" for hit in small_hits)
- assert not any(hit["kind"] == "email" for hit in large_hits)
- assert large_elapsed < small_elapsed * 32, (
- f"{run!r}: 8N took {large_elapsed:.3f}s vs N {small_elapsed:.3f}s"
+ # The growth check goes first: a quadratic pattern fails here in seconds, where
+ # scanning the 8n row for the no-hit check below would take it minutes. The cap keeps
+ # the larger row inside the 50,000 characters ``detect_pii`` reads (past it the time
+ # stops growing and the check would pass for any pattern).
+ assert_grows_linearly(
+ data_score.detect_pii,
+ lambda length, run=run: _row(run, length),
+ n // 10,
+ label=repr(run),
+ cap=data_score._PII_SCAN_CAP,
)
+ for text in (_row(run, n), _row(run, 8 * n)):
+ assert not any(hit["kind"] == "email" for hit in data_score.detect_pii(text))
def test_email_detection_matches_baseline_row_flags_on_seeded_texts() -> None:
diff --git a/tests/test_issue1346_rewrites_are_linear.py b/tests/test_issue1346_rewrites_are_linear.py
index 32b50817..140d93ed 100644
--- a/tests/test_issue1346_rewrites_are_linear.py
+++ b/tests/test_issue1346_rewrites_are_linear.py
@@ -2,19 +2,18 @@ r"""#1346: the four normalisation rewrites stay linear in a completion's length.
A completion is untrusted model output, so each rewrite gets an input aimed at it, and the time
at 8N is compared with the time at N, as in ``test_issue1226_clause_scanner_is_linear.py``: a
-linear scan grows about 8x, a quadratic one about 64x.
+linear scan grows about 8x, a quadratic one about 64x. ``tests/_growth_timing.py`` runs the
+comparison on a reference long enough to time.
"""
from __future__ import annotations
-import time
-
import pytest
from soup_cli.trainer.rewards import accuracy_reward, math_verify_reward
+from tests._growth_timing import assert_grows_linearly
-_SCALE_N = 1_000
-_SCALE_LIMIT = 24.0 # the same 3x slack over linear as the #1226 growth test
+_SCALE_N = 100 # the starting size; the helper doubles it until the run is long enough to time
REWRITE_INPUTS = {
"text-wrapper-never-closes": lambda k: "\\text{" * k,
@@ -37,23 +36,11 @@ def _msg(text: str) -> list[list[dict]]:
return [[{"role": "assistant", "content": text}]]
-def _best_time(text: str, repeats: int) -> float:
- best = float("inf")
- for _ in range(repeats):
- start = time.perf_counter()
- accuracy_reward(_msg(text), answer=["42"])
- math_verify_reward(_msg(text), answer=["42"])
- best = min(best, time.perf_counter() - start)
- return best
+def _score(text: str) -> None:
+ accuracy_reward(_msg(text), answer=["42"])
+ math_verify_reward(_msg(text), answer=["42"])
@pytest.mark.parametrize("build", list(REWRITE_INPUTS.values()), ids=list(REWRITE_INPUTS))
def test_each_rewrite_grows_linearly(build):
- small, large = build(_SCALE_N), build(8 * _SCALE_N)
- t_small = max(_best_time(small, repeats=5), 1e-7)
- t_large = float("inf")
- for _ in range(5): # stop as soon as the larger input is shown to be fast enough
- t_large = min(t_large, _best_time(large, repeats=1))
- if t_large / t_small < _SCALE_LIMIT:
- break
- assert t_large / t_small < _SCALE_LIMIT, (t_small, t_large)
+ assert_grows_linearly(_score, build, _SCALE_N)
diff --git a/tests/test_issue1347_boxed_scan.py b/tests/test_issue1347_boxed_scan.py
index 9ec78064..671256b7 100644
--- a/tests/test_issue1347_boxed_scan.py
+++ b/tests/test_issue1347_boxed_scan.py
@@ -14,27 +14,32 @@ 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
+from tests._growth_timing import assert_grows_linearly
+
+# The size the growth checks start from. ``tests/_growth_timing.py`` doubles it until one scan
+# lasts long enough to time, then compares it with a scan of 8x the input. It replaced a
+# 20,000-box input timed once per size and an absolute 30 s ceiling (3.0 s had flaked): the
+# ceiling cannot trip when the reference is calibrated, and the ratio is what pins linearity.
+# The start is small on purpose: a super-linear scan then costs about 64x the calibrated
+# reference to catch, not 64x a large start.
+_GROWTH_INPUT = 100
+
+
+def _scan(text: str) -> int:
+ return sum(1 for _ in iter_boxed_answers(text))
+
-# Long enough that the scan's own cost dominates the interpreter's.
-_GROWTH_INPUT = 20_000
-# An absolute ceiling only a scan that is not linear can reach. The growth ratio next to it
-# is what pins linearity; this catches a scan that is slow at every size. It was 3.0, and a
-# linear scan measured 3.01 on a four-core runner with coverage on and every core busy with
-# another test file, so it leaves ten times that.
-_CEILING_SECONDS = 30.0
+def _unclosed(count: int) -> str:
+ return r"\boxed{" * count
-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
+def _closed(count: int) -> str:
+ return r"\boxed{B} " * count
+
+
+def _nested(depth: int) -> str:
+ return r"\boxed{" * depth + "B" + "}" * depth
class TestIssue1347TheScanReadsEveryClosedBox:
@@ -72,29 +77,17 @@ class TestIssue1347TheScanReadsEveryClosedBox:
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
+ """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
+ assert _scan(_unclosed(8 * _GROWTH_INPUT)) == 0
- small_seconds = _best_seconds(small)
- large_seconds = _best_seconds(large)
- assert large_seconds < small_seconds * 20, (small_seconds, large_seconds)
- assert large_seconds < _CEILING_SECONDS, large_seconds
+ assert_grows_linearly(_scan, _unclosed, _GROWTH_INPUT)
def test_closed_boxes_cost_linear_time_too(self):
- small = r"\boxed{B} " * _GROWTH_INPUT
- large = r"\boxed{B} " * (_GROWTH_INPUT * 8)
+ assert _scan(_closed(8 * _GROWTH_INPUT)) == _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 < _CEILING_SECONDS, large_seconds
+ assert_grows_linearly(_scan, _closed, _GROWTH_INPUT)
class TestIssue1347NestedBoxes:
@@ -102,12 +95,7 @@ class TestIssue1347NestedBoxes:
"""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)
+ assert_grows_linearly(_scan, _nested, 100)
def test_a_box_inside_a_box_reads_the_inner_answer(self):
parsed = parse_completion(r"\boxed{\boxed{42}}")
diff --git a/tests/test_issue1528_contains_is_linear.py b/tests/test_issue1528_contains_is_linear.py
index af452ca7..70501072 100644
--- a/tests/test_issue1528_contains_is_linear.py
+++ b/tests/test_issue1528_contains_is_linear.py
@@ -2,22 +2,22 @@ r"""#1528: the custom-eval ``contains`` scorer stays linear in output and expect
#1490 made ``contains`` match ``expected`` only as a whole token. Its pattern started with a
lookbehind and ran under ``re.IGNORECASE``, so ``re`` tried it at every position: quadratic in
-``len(output) * len(expected)``. The time at 8N is compared with the time at N, as in
-``test_issue1346_rewrites_are_linear.py``: a linear scan grows about 8x, a quadratic one about 64x.
+``len(output) * len(expected)``. The time at 8N is compared with the time at N: a linear scan
+grows about 8x, a quadratic one about 64x. ``tests/_growth_timing.py`` runs the comparison on a
+reference long enough to time, so a loaded runner cannot decide it.
"""
from __future__ import annotations
import random
import re
-import time
import pytest
from soup_cli.eval.custom import score_contains
+from tests._growth_timing import assert_grows_linearly
-_SCALE_N = 2_500 # 5,000 output characters at N, 40,000 at 8N
-_SCALE_LIMIT = 24.0 # the same 3x slack over linear as the #1346 growth test
+_SCALE_N = 250 # the starting size; the helper doubles it until the run is long enough to time
SHAPES = {
"word-starts-never-match": lambda k: ("a " * k, "a " * (k // 2) + "b"),
@@ -27,25 +27,9 @@ SHAPES = {
}
-def _best_time(output: str, expected: str, repeats: int) -> float:
- best = float("inf")
- for _ in range(repeats):
- start = time.perf_counter()
- score_contains(output, expected)
- best = min(best, time.perf_counter() - start)
- return best
-
-
@pytest.mark.parametrize("build", list(SHAPES.values()), ids=list(SHAPES))
def test_contains_grows_linearly(build):
- small, large = build(_SCALE_N), build(8 * _SCALE_N)
- t_small = max(_best_time(*small, repeats=5), 1e-7)
- t_large = float("inf")
- for _ in range(5): # stop as soon as the larger input is shown to be fast enough
- t_large = min(t_large, _best_time(*large, repeats=1))
- if t_large / t_small < _SCALE_LIMIT:
- break
- assert t_large / t_small < _SCALE_LIMIT, (t_small, t_large)
+ assert_grows_linearly(lambda pair: score_contains(*pair), build, _SCALE_N)
def _contains_before_1528(output: str, expected: str) -> bool: