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): refuse alpha + beta >= 1 and an overflowing standardised effect (#1339) (#1378)
qwist1233-cpu57dd91b301d5
diff --git a/changelog.d/0.75.1/1378.fixed.md b/changelog.d/0.75.1/1378.fixed.mdnew file mode 100644index 00000000..04747c9d--- /dev/null+++ b/changelog.d/0.75.1/1378.fixed.md@@ -0,0 +1,2 @@+- **`soup ab` now refuses `--alpha` + `--beta` at or above 1, where two identical arms could "reject" H0 (#1339 by @qwist1233-cpu in #1378).** Each rate was checked in (0, 1) on its own, but the reject boundary `log((1 - beta) / alpha)` stays above the accept boundary `log(beta / (1 - alpha))` only while their sum is below 1. Past that there is no `continue` band left, and because reject is tested first, every verdict in the gap rejected: `--alpha 0.6 --beta 0.5` reported `reject_h0` with `direction worse` on two byte-identical arms, and `--beta 0.95` (a power of 0.95 typed as beta) rejected a true H0 in a quarter of single looks. The command now exits 2 naming both values, and the `--beta` help plus the evaluation guide state the bound and that beta is the Type-II error rate, not the power.+- **`soup ab` names `--effect-size` instead of exiting on a bare `OverflowError` (#1339 by @qwist1233-cpu in #1378).** The drift term squares the standardised effect `--effect-size / pooled standard error`, and `**` raises `OverflowError` where `*` would return infinity, so a huge `--effect-size` ended the run on `Error: OverflowError: (34, 'Result too large')` with no flag named. The ratio is now bounded before it is squared, and the message carries the flag, the ratio and the standard error measured. Because it is the ratio that overflows, a near-constant metric column reached this at the default `--effect-size` too, and is named as well.diff --git a/docs/evaluation.md b/docs/evaluation.mdindex 9f77c12a..af7cfb1b 100644--- a/docs/evaluation.md+++ b/docs/evaluation.md@@ -288,6 +288,10 @@ soup ab --input ab.jsonl --metric latency --effect-size 0.5soup ab --input ab.jsonl --metric judge_score --alpha 0.01 --beta 0.10 --effect-size 0.1```+`--alpha` and `--beta` are each in (0, 1), and their sum must stay below 1. At or above 1 the reject boundary `log((1 - beta) / alpha)` is no longer above the accept boundary `log(beta / (1 - alpha))`, so there is no `continue` band left and any verdict between them rejects — two identical arms included. `soup ab` exits `2` naming both values. `--beta` is the Type-II error rate, not the power: a power of 0.95 is `--beta 0.05`, not `--beta 0.95`.++A `--effect-size` that is more than about 1.3e154 pooled standard errors overflows the test statistic; `soup ab` exits `1` naming the flag and the standard error it measured. Because it is the ratio that overflows, a near-constant metric column reaches it at the default `--effect-size` too.+Input rows look like `{"arm": "control", "latency": 1.23}` or `{"arm": "treatment", "judge_score": 0.91}`. Decision is one of `continue` (keep collecting samples), `reject_h0` (real difference detected, in either direction), `accept_h0` (no significant difference). A `reject_h0` also reports a `direction`, `better` or `worse`, read through the metric's polarity: `judge_score` is higher-is-better, `latency` and `retry_rate` are lower-is-better. Composes with `soup loop canary` (v0.58): the panel recommends promoting a `better` treatment and a rollback only for a `worse` one.`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.diff --git a/src/soup_cli/commands/ab.py b/src/soup_cli/commands/ab.pyindex 9961b79d..757dcede 100644--- a/src/soup_cli/commands/ab.py+++ b/src/soup_cli/commands/ab.py@@ -41,7 +41,12 @@ def ab(),),beta: float = typer.Option(- 0.20, "--beta", help="Type-II error (false negative) rate (0, 1).",+ 0.20, "--beta",+ help=(+ "Type-II error (false negative) rate (0, 1). Not the power: a power "+ "of 0.95 is --beta 0.05. alpha + beta must stay below 1, or the "+ "reject and accept boundaries cross and every verdict rejects."+ ),),effect_size: float = typer.Option(0.1, "--effect-size",diff --git a/src/soup_cli/utils/ab_test.py b/src/soup_cli/utils/ab_test.pyindex 1e94297f..442dff87 100644--- a/src/soup_cli/utils/ab_test.py+++ b/src/soup_cli/utils/ab_test.py@@ -41,6 +41,7 @@ from __future__ import annotationsimport jsonimport mathimport os+import sysfrom dataclasses import dataclassfrom types import MappingProxyTypefrom typing import Mapping, Sequence@@ -87,6 +88,12 @@ _BURN_IN_ROWS_UNCALIBRATED = 40# The sweep followed runs up to this many rows per arm; past it the Type-I# figures above are not established, and `soup ab` says so.CALIBRATED_HORIZON_ROWS = 1000++# #1339 - the largest standardised effect whose square is still a float. The+# drift term in _verdict_from_summary squares mu_h1, and ** raises+# OverflowError where * would have returned inf, so the bound is checked+# rather than the result.+MAX_STANDARDISED_EFFECT = math.sqrt(sys.float_info.max)_MAX_METRIC_NAME_LEN = 32_MAX_SAMPLES_PER_ARM = 1_000_000_VALID_DECISIONS: frozenset[str] = frozenset(@@ -177,6 +184,23 @@ class MsprtConfig:object.__setattr__(self, "metric", validate_metric_name(self.metric))object.__setattr__(self, "alpha", _require_unit_open(self.alpha, field="alpha"))object.__setattr__(self, "beta", _require_unit_open(self.beta, field="beta"))+ # #1339 - each rate is in (0, 1) on its own, but the reject boundary+ # log((1 - beta) / alpha) stays above the accept boundary+ # log(beta / (1 - alpha)) only while alpha + beta < 1. At or past 1+ # there is no continue band, and because reject is tested first every+ # verdict in the gap rejects: alpha 0.6 / beta 0.5 rejects on two+ # identical arms, and alpha 0.05 / beta 0.95 (a power typed as beta)+ # rejects a true H0 in a quarter of single looks.+ if self.alpha + self.beta >= 1.0:+ raise ValueError(+ f"alpha + beta must be < 1.0, got alpha={self.alpha} + "+ f"beta={self.beta} = {self.alpha + self.beta}. At or above 1.0 "+ "the reject boundary log((1 - beta) / alpha) is no longer above "+ "the accept boundary log(beta / (1 - alpha)), so there is no "+ "continue band left and any verdict between them rejects. "+ "beta is the Type-II error rate, not the power: a power of "+ "0.95 is beta 0.05."+ )object.__setattr__(self,"effect_size",@@ -303,6 +327,19 @@ def _verdict_from_summary(# the LLR positive under H0 as n grew → unbounded Type-I error.)n_eff = (n_control * n_treatment) / (n_control + n_treatment)mu_h1 = config.effect_size / pooled_se # in standardised units+ # #1339 - drift squares mu_h1 below, and ** raises OverflowError instead+ # of returning inf, which left `soup ab` exiting on a bare+ # "OverflowError: (34, 'Result too large')" that names no flag. It is the+ # RATIO that overflows, so a near-constant metric column reaches it at the+ # default --effect-size too; the message therefore names both sides.+ if mu_h1 > MAX_STANDARDISED_EFFECT:+ raise ValueError(+ f"--effect-size {config.effect_size!r} is {mu_h1:.3g} standard "+ f"errors at a pooled standard error of {pooled_se:.3g}, and the "+ f"test statistic overflows above {MAX_STANDARDISED_EFFECT:.3g}. "+ f"Lower --effect-size, or check the {config.metric!r} column: a "+ "near-constant column reaches this at any --effect-size."+ )n_ratio = n_eff / (n_eff + 1.0)shift = z * mu_h1 * math.sqrt(n_ratio)drift = 0.5 * mu_h1**2 * n_ratio@@ -451,6 +488,7 @@ __all__ = ["BURN_IN_ROWS_BY_ALPHA","CALIBRATED_HORIZON_ROWS","HIGHER_IS_BETTER",+ "MAX_STANDARDISED_EFFECT","MsprtConfig","MsprtVerdict","SUPPORTED_METRICS",diff --git a/tests/test_issue1339_ab_boundary_and_overflow.py b/tests/test_issue1339_ab_boundary_and_overflow.pynew file mode 100644index 00000000..2b4a1c10--- /dev/null+++ b/tests/test_issue1339_ab_boundary_and_overflow.py@@ -0,0 +1,175 @@+"""#1339 — `soup ab` refuses `alpha + beta >= 1` and an overflowing standardised effect.++Two gaps listed as pre-existing in #1310's description and left out of it.++**The boundaries cross.** ``MsprtConfig`` checked ``alpha`` and ``beta`` in+(0, 1) one at a time. The reject boundary ``log((1 - beta) / alpha)`` stays above+the accept boundary ``log(beta / (1 - alpha))`` only while ``alpha + beta < 1``;+past that there is no ``continue`` band, and since reject is tested first, the+gap between them rejects. ``--alpha 0.6 --beta 0.5`` rejected on two identical+arms, and ``--alpha 0.05 --beta 0.95`` (a power of 0.95 typed as beta) put both+boundaries at 0 and rejected a true H0 in 255 of 1000 single looks.++**The statistic overflows.** ``drift = 0.5 * mu_h1**2 * n_ratio`` raises+``OverflowError`` rather than returning ``inf``, and ``commands/ab.py`` catches+only ``FileNotFoundError`` / ``TypeError`` / ``ValueError``, so the run ended on+a bare ``Error: OverflowError: (34, 'Result too large')`` that named no flag. It+is the ratio ``effect_size / pooled_se`` that overflows, so a near-constant+column reaches it at the default ``--effect-size`` too.+"""++from __future__ import annotations++import math+import sys++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, _write_ab++runner = CliRunner()++# Rows around 0.80 with real noise, 40 per arm — past the 30-row burn-in at+# alpha 0.05 and the 40-row one below it, so a verdict is actually reached.+_H0_CONTROL = [0.80, 0.82, 0.78, 0.81, 0.79] * 8++# The same, spread wider (SD 0.095): at alpha 0.6 / beta 0.5 and+# --effect-size 0.01 these land the LLR of two IDENTICAL arms at -0.129, inside+# the inverted band (reject at -0.182, accept at +0.223). Measured on main:+# "decision reject_h0 / direction worse / mean_control 0.8000 /+# mean_treatment 0.8000", exit 0.+_WIDE_CONTROL = [0.68, 0.92, 0.74, 0.86, 0.80] * 8+++def _run_cli(tmp_path, monkeypatch, control, treatment, extra=()):+ from soup_cli.cli import app++ monkeypatch.chdir(tmp_path)+ _write_ab(tmp_path / "ab.jsonl", "judge_score", control, treatment)+ return runner.invoke(+ app, ["ab", "--input", "ab.jsonl", "--metric", "judge_score", *extra]+ )+++class TestAlphaPlusBeta:+ @pytest.mark.parametrize(+ ("alpha", "beta"),+ [+ (0.6, 0.5), # reject at -0.182, accept at +0.223: the gap rejects+ (0.05, 0.95), # a power of 0.95 typed as beta: both boundaries at 0+ (0.5, 0.5), # exactly 1.0, the degenerate edge+ ],+ )+ def test_config_refuses_a_crossed_pair(self, alpha, beta):+ with pytest.raises(ValueError) as exc:+ MsprtConfig(metric="judge_score", alpha=alpha, beta=beta)+ message = str(exc.value)+ assert "alpha + beta" in message+ # Both values named, so the operator sees which one to move.+ assert str(alpha) in message and str(beta) in message++ @pytest.mark.parametrize(+ ("alpha", "beta"),+ [+ (0.05, 0.20), # the defaults+ (0.01, 0.10), # the docs/evaluation.md example+ (0.6, 0.39), # just below 1.0: still allowed+ ],+ )+ def test_config_accepts_a_usable_pair(self, alpha, beta):+ cfg = MsprtConfig(metric="judge_score", alpha=alpha, beta=beta)+ assert (cfg.alpha, cfg.beta) == (alpha, beta)+ # The band the refusal is about: reject stays strictly above accept.+ upper = math.log((1.0 - cfg.beta) / cfg.alpha)+ lower = math.log(cfg.beta / (1.0 - cfg.alpha))+ assert upper > lower++ def test_identical_arms_no_longer_reject_at_alpha_0_6_beta_0_5(self):+ """The reported symptom, now unreachable: refused before the step runs.++ On main this pair reaches ``msprt_step`` and returns ``reject_h0`` with+ ``direction worse`` on two byte-identical arms.+ """+ with pytest.raises(ValueError):+ msprt_step(+ MsprtConfig(+ metric="judge_score", alpha=0.6, beta=0.5, effect_size=0.01+ ),+ control=_WIDE_CONTROL,+ treatment=_WIDE_CONTROL,+ )++ def test_cli_exits_2_naming_alpha_and_beta(self, tmp_path, monkeypatch):+ result = _run_cli(+ tmp_path, monkeypatch, _H0_CONTROL, _H0_CONTROL,+ extra=["--alpha", "0.05", "--beta", "0.95"],+ )+ assert result.exit_code == 2, (result.output, repr(result.exception))+ out = _plain(result.output)+ assert "alpha + beta" in out+ assert "0.95" in out++ def test_cli_still_runs_the_documented_pair(self, tmp_path, monkeypatch):+ result = _run_cli(+ tmp_path, monkeypatch, _H0_CONTROL, _H0_CONTROL,+ extra=["--alpha", "0.01", "--beta", "0.10"],+ )+ assert result.exit_code == 0, (result.output, repr(result.exception))++ def test_beta_help_states_the_bound(self):+ from soup_cli.cli import app++ result = runner.invoke(app, ["ab", "--help"])+ assert result.exit_code == 0, (result.output, repr(result.exception))+ out = _plain(result.output)+ assert "alpha + beta" in out+++class TestStandardisedEffectOverflow:+ def test_bound_is_the_largest_squarable_float(self):+ # Imported here, not at module scope, so the rest of the file still+ # collects against a tree without the constant.+ from soup_cli.utils.ab_test import MAX_STANDARDISED_EFFECT++ assert MAX_STANDARDISED_EFFECT == math.sqrt(sys.float_info.max)+ # The premise: ** raises where * returns inf, which is why the bound is+ # checked instead of the result.+ with pytest.raises(OverflowError):+ (MAX_STANDARDISED_EFFECT * 2.0) ** 2++ @pytest.mark.parametrize("rows_per_arm", [2, 40])+ def test_cli_exits_1_naming_effect_size(self, tmp_path, monkeypatch, rows_per_arm):+ """At 2 rows per arm too: the statistic runs before the burn-in check."""+ control = _H0_CONTROL[:rows_per_arm]+ result = _run_cli(+ tmp_path, monkeypatch, control, control,+ extra=["--effect-size", "1e200"],+ )+ assert result.exit_code == 1, (result.output, repr(result.exception))+ out = _plain(result.output)+ assert "--effect-size" in out+ assert "OverflowError" not in out++ def test_near_constant_column_overflows_at_the_default_effect_size(self):+ """It is the ratio, not the flag: values 0 and 1e-160 reach it at 0.1."""+ near_constant = [0.0, 1e-160] * 20+ with pytest.raises(ValueError) as exc:+ msprt_step(+ MsprtConfig(metric="judge_score"),+ control=near_constant,+ treatment=near_constant,+ )+ message = str(exc.value)+ assert "--effect-size" in message+ assert "judge_score" in message++ def test_a_workable_effect_size_still_decides(self):+ verdict = msprt_step(+ MsprtConfig(metric="judge_score", effect_size=0.03),+ control=_H0_CONTROL,+ treatment=_H0_CONTROL,+ )+ assert verdict.decision in {"continue", "accept_h0", "reject_h0"}+ assert math.isfinite(verdict.log_likelihood_ratio)