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(ab): name a metric column whose spread a float cannot carry (#1384) (#1392)
Mohammad Hijjawidc0292c758f1
diff --git a/changelog.d/0.75.1/1392.fixed.md b/changelog.d/0.75.1/1392.fixed.mdnew file mode 100644index 00000000..1194f0fd--- /dev/null+++ b/changelog.d/0.75.1/1392.fixed.md@@ -0,0 +1,11 @@+- **`soup ab` names a metric column whose spread a float cannot carry, instead of+ exiting on a bare `ZeroDivisionError` or `OverflowError` (#1384 by @MohammadHijjawi97 in #1392).**+ A near-constant column (`0` and `1e-161`) has a positive pooled variance that still+ underflows to a standard error of `0.0` once divided by the row counts, and the+ z-statistic divided by it. A column spread past about `1.3e154` (`0` and `1e200`)+ overflowed while its variance was squared, and an arm whose values summed past the+ largest float gave an infinite mean and a silent `continue` with a `nan`+ log-likelihood ratio. All three now exit 1 with a message that names the column,+ says whether its spread is below or above what the statistic can represent or its+ values are so large that an arm's sum overflows (an arm of `1e308` values), and+ says to rescale the metric.diff --git a/docs/evaluation.md b/docs/evaluation.mdindex af7cfb1b..feec8398 100644--- a/docs/evaluation.md+++ b/docs/evaluation.md@@ -296,6 +296,8 @@ Input rows look like `{"arm": "control", "latency": 1.23}` or `{"arm": "treatmen`soup ab` exits `0` on every decision, including a `worse` one; to gate a pipeline on a regression, read `direction` from the output or the webhook payload.+`soup ab` exits `1`, naming the metric column, when its values are outside what a float can carry: so close together that the standard error of the difference underflows to 0 (a column of `0` and `1e-161`), so far apart that their variance overflows (a column of `0` and `1e200`), or so large that an arm's sum overflows (an arm of `1e308` values). Rescale the metric and re-run.+`soup ab` accepts `--slack-url` / `--discord-url` (v0.71.5) and pings the webhook **only when the test actually decides** (`reject_h0` / `accept_h0`) — a still-running `continue` stays quiet so you're not paged on every peek. The payload carries `decision` and `direction` (`null` on `accept_h0`). Same SSRF-hardened validator as `soup drift-alarm`.diff --git a/src/soup_cli/utils/ab_test.py b/src/soup_cli/utils/ab_test.pyindex 442dff87..5753fd0a 100644--- a/src/soup_cli/utils/ab_test.py+++ b/src/soup_cli/utils/ab_test.py@@ -299,6 +299,18 @@ def _verdict_from_summary(``continue``."""pooled_se = math.sqrt(pooled_variance * (1.0 / n_control + 1.0 / n_treatment))+ # #1384 - a positive but subnormal pooled variance can still underflow to+ # 0.0 once scaled by 1/n (values 0 and 1e-161 at 40 rows per arm), and the+ # z below then divides by zero. The square root of the smallest positive+ # float is about 2.2e-162, so an underflow shows here as exactly 0.0.+ if pooled_se == 0.0:+ raise ValueError(+ f"The {config.metric!r} column's spread is below what the test "+ f"statistic can represent: its pooled variance {pooled_variance:.3g} "+ f"over {n_control} + {n_treatment} rows gives a standard error that "+ "underflows to 0. Rescale the metric (multiply its values by a large "+ "constant) and re-run."+ )# Standardised effect size (z-statistic of the difference of means).diff = mean_treatment - mean_control@@ -403,10 +415,31 @@ def msprt_step(mean_treatment=mean_t,)- # Pooled variance with Bessel correction.- var_c = sum((x - mean_c) ** 2 for x in ctrl) / (n_c - 1)- var_t = sum((x - mean_t) ** 2 for x in treat) / (n_t - 1)+ # #1384 - an arm whose values sum past the largest float has an infinite+ # mean however little they spread: name their size, not their spread.+ if not (math.isfinite(mean_c) and math.isfinite(mean_t)):+ values = ctrl + treat+ raise ValueError(+ f"The {config.metric!r} column's values are too large for the test "+ f"statistic: they run from {min(values):.3g} to {max(values):.3g}, "+ "and an arm's sum overflows a float. Rescale the metric (divide its "+ "values by a large constant) and re-run."+ )++ # Pooled variance with Bessel correction. Squared as d * d, not d ** 2:+ # ** raises OverflowError where * returns inf, and inf is refused below.+ var_c = sum((x - mean_c) * (x - mean_c) for x in ctrl) / (n_c - 1)+ var_t = sum((x - mean_t) * (x - mean_t) for x in treat) / (n_t - 1)raw_pooled_var = ((n_c - 1) * var_c + (n_t - 1) * var_t) / (n_c + n_t - 2)+ # #1384 - deviations past about 1.3e154 square past the largest float.+ if not math.isfinite(raw_pooled_var):+ values = ctrl + treat+ raise ValueError(+ f"The {config.metric!r} column's spread is above what the test "+ f"statistic can represent: its values run from {min(values):.3g} to "+ f"{max(values):.3g}, and their variance overflows a float. Rescale "+ "the metric (divide its values by a large constant) and re-run."+ )# Degenerate (zero variance) — both arms are constant. If the means# are also identical, defer to ``continue`` (no information). If the# means differ, fall back to ``continue`` as well: with zero observeddiff --git a/tests/test_issue1384_ab_degenerate_spread.py b/tests/test_issue1384_ab_degenerate_spread.pynew file mode 100644index 00000000..e065bf09--- /dev/null+++ b/tests/test_issue1384_ab_degenerate_spread.py@@ -0,0 +1,164 @@+"""#1384 — `soup ab` names a column whose spread a float cannot carry.++Two crashes found while reviewing #1378, on ``main`` and on #1378's head alike.++**Too little spread.** A metric column of ``0`` and ``1e-161`` has a positive+pooled variance (``2.5e-323``, a subnormal), but ``var * (1/n_c + 1/n_t)``+underflows to ``0.0`` at 40 rows per arm, and ``z = diff / pooled_se`` raised a+bare ``ZeroDivisionError``. The square root of the smallest positive float is+about ``2.2e-162``, so an underflow shows as a standard error of exactly ``0.0``.++**Too much spread.** A column of ``0`` and ``1e200``: ``(x - mean) ** 2`` raised+``OverflowError`` while the variance was being computed (``**`` raises where+``*`` returns ``inf``). An arm whose values sum past the largest float had an+infinite mean, and ``soup ab`` quietly reported ``continue`` with a ``nan``+log-likelihood ratio.++All three are now refused with a ``ValueError`` naming the column (the+overflowing sum with its own message, since its spread may be 0), which+``commands/ab.py`` turns into exit 1 and a message, not a traceback.+"""++from __future__ import annotations++import json+import math++import pytest+from typer.testing import CliRunner++from soup_cli.utils.ab_test import MsprtConfig, msprt_step+from tests.test_issue1227_ab_two_sided import _plain++runner = CliRunner()++# The issue's inputs, 40 rows per arm, at the issue's --alpha 0.1.+_TINY = [0.0, 1e-161] * 20+_HUGE = [0.0, 1e200] * 20+++def _write_rows(path, metric, control, treatment):+ # Not test_issue1227's _write_ab: it rounds treatment values to 6 places,+ # which would turn 1e-161 into 0.+ rows = [{"arm": "control", metric: x} for x in control]+ rows += [{"arm": "treatment", metric: x} for x in treatment]+ path.write_text("\n".join(json.dumps(r) for r in rows), encoding="utf-8")+++def _run_cli(tmp_path, monkeypatch, control, treatment, extra=()):+ from soup_cli.cli import app++ monkeypatch.chdir(tmp_path)+ _write_rows(tmp_path / "ab.jsonl", "latency", control, treatment)+ return runner.invoke(+ app,+ ["ab", "--input", "ab.jsonl", "--metric", "latency", "--alpha", "0.1", *extra],+ )+++class TestSpreadBelowAFloat:+ def test_premise_the_standard_error_underflows(self):+ """Without this the tests below would not be exercising the underflow."""+ mean = sum(_TINY) / len(_TINY)+ var = sum((x - mean) * (x - mean) for x in _TINY) / (len(_TINY) - 1)+ assert var > 0.0+ assert var * (1.0 / 40 + 1.0 / 40) == 0.0++ def test_step_refuses_naming_the_column(self):+ with pytest.raises(ValueError) as exc:+ msprt_step(+ MsprtConfig(metric="latency", alpha=0.1),+ control=_TINY,+ treatment=_TINY,+ )+ message = str(exc.value)+ assert "'latency'" in message+ assert "below what the test statistic can represent" in message+ assert "Rescale" in message++ def test_cli_exits_1_with_a_message_not_a_traceback(self, tmp_path, monkeypatch):+ result = _run_cli(tmp_path, monkeypatch, [0.0] * 40, _TINY)+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert isinstance(result.exception, SystemExit), repr(result.exception)+ out = _plain(result.output)+ assert "'latency' column's spread is below" in out+ assert "ZeroDivisionError" not in out+ assert "Traceback" not in out++ def test_the_same_values_still_run_where_the_error_does_not_underflow(self):+ """At 2 rows per arm the standard error is about 5e-162, not 0: the+ refusal is keyed on the underflow, not on how small the values are."""+ verdict = msprt_step(+ MsprtConfig(metric="latency", alpha=0.1, effect_size=1e-162),+ control=[0.0, 1e-161],+ treatment=[0.0, 1e-161],+ )+ assert verdict.decision == "continue" # burn-in+ assert math.isfinite(verdict.log_likelihood_ratio)+++class TestSpreadAboveAFloat:+ @pytest.mark.parametrize(+ ("control", "treatment"),+ [+ (_HUGE, _HUGE), # the issue's input: (x - mean) ** 2 overflowed+ ([1.0, 2.0] * 20, _HUGE), # the treatment arm alone+ ],+ ids=["deviation-overflows", "treatment-only"],+ )+ def test_step_refuses_naming_the_column(self, control, treatment):+ with pytest.raises(ValueError) as exc:+ msprt_step(+ MsprtConfig(metric="latency", alpha=0.1),+ control=control,+ treatment=treatment,+ )+ message = str(exc.value)+ assert "'latency'" in message+ assert "above what the test statistic can represent" in message+ assert "Rescale" in message++ def test_cli_exits_1_with_a_message_not_a_traceback(self, tmp_path, monkeypatch):+ result = _run_cli(tmp_path, monkeypatch, _HUGE, _HUGE)+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert isinstance(result.exception, SystemExit), repr(result.exception)+ out = _plain(result.output)+ assert "'latency' column's spread is above" in out+ assert "1e+200" in out+ assert "OverflowError" not in out+ assert "Traceback" not in out++ def test_large_values_whose_variance_fits_still_decide(self):+ """0 and 1e153, 40 rows per arm: a variance near 2.6e305 is a float."""+ values = [0.0, 1e153] * 20+ verdict = msprt_step(+ MsprtConfig(metric="latency", alpha=0.1, effect_size=1e152),+ control=values,+ treatment=values,+ )+ assert verdict.decision in {"continue", "accept_h0"}+ assert math.isfinite(verdict.log_likelihood_ratio)+++class TestValuesTooLargeToSum:+ @pytest.mark.parametrize(+ ("control", "treatment"),+ [+ ([1e308] * 40, [1.0, 2.0] * 20), # one arm's sum overflows: mean inf+ ([1e308] * 40, [1e308] * 40), # no spread at all, yet the sums overflow+ ([1.0, 2.0] * 20, [1e308] * 40), # the treatment arm's sum alone+ ],+ ids=["arm-sum-overflows", "constant-column", "treatment-sum-overflows"],+ )+ def test_step_names_the_size_not_the_spread(self, control, treatment):+ with pytest.raises(ValueError) as exc:+ msprt_step(+ MsprtConfig(metric="latency", alpha=0.1),+ control=control,+ treatment=treatment,+ )+ message = str(exc.value)+ assert "'latency'" in message+ assert "sum overflows a float" in message+ assert "spread" not in message+ assert "Rescale" in message