Algorithmresearch
Mixture sequential probability ratio test
Also called mSPRT, always valid p-value.
An SPRT whose alternative is a mixture over effect sizes. Its likelihood ratio is a test martingale, so its test and its p-values stay valid at any stopping time.
- Time
- Θ(n) worst
- Space
- Θ(1) extra
- Where
- n = the number of observations read before the test stops or the stream ends
- Model
- Real RAM
- Properties
- anytime validdeterministiconlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Herbert Robbins, Ramesh Johari, Pete Koomen, Leonid Pekelis, David Walsh, 1970
The mixture sequential probability ratio test (mSPRT) tests a point null hypothesis against the composite alternative while the data arrive. Where the SPRT needs one alternative value, the mSPRT averages the likelihood ratio over a mixing distribution of alternatives that is fixed in advance. The mixture is a test martingale under the null, so by Ville's inequality the rule "reject when the mixture reaches " has type I error at most for every way the analyst may look at the data and stop. The reciprocal of its running maximum is an always valid p-value, which online experiment platforms show to users who check their results every day.
In plain words
In an online experiment people look at the results every day and stop as soon as the effect looks significant. A normal test assumes that you look only once, at a size fixed in advance. Each extra look is a new chance for noise to look like an effect, so the false alarm rate grows well above the stated level. The mSPRT keeps a single running score that compares "there is some effect, of a size from a range fixed in advance" with "there is no effect". If there is truly no effect, the score is a fair game that cannot go below zero, so it seldom gets large. You may look after every new data point and stop when you like. The false alarm rate stays below the level you chose. The price is that a real effect needs somewhat more data to show.
The problem
Observations are i.i.d. with density from a parametric family. Test against , with a rule that may stop at any stopping time , chosen by the analyst while the data arrive, such that
and such that the test rejects eventually under every alternative. Also produce p-values with for every stopping time and every . These are the always valid p-values of Johari, Koomen, Pekelis and Walsh.
Given a mixing distribution on the parameters, the mixture likelihood ratio is
For normal data with known and , with , the integral has the closed form
The algorithm
MSPRT(x_1, x_2, ..., θ_0, σ, τ, α) ▷ σ, τ > 0 and 0 < α < 1- 1
S ← 0, n ← 0, p ← 1 - 2
for each new observation x do - 3
n ← n + 1, S ← S + (x - θ_0) - 4
Λ ← sqrt(σ² / (σ² + nτ²)) · exp(τ² S² / (2σ²(σ² + nτ²))) - 5
p ← min(p, 1 / Λ) ▷ always valid p-value p_n - 6
if Λ ≥ 1/α then return (reject H_0, n, p) - 7
return (no rejection, n, p)
Line L3 keeps the centred sum, which is a sufficient statistic. Line L4 evaluates the closed-form mixture. Line L5 keeps , which never increases, so a p-value once shown can only go down. Line L6 rejects at the first time the mixture reaches ; this is the same event as . There is no lower threshold: the test never accepts , and if the analyst stops for another reason, line L7 reports that the test did not reject and gives the current p-value.
Example
Let , and , so the threshold is . On the data :
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | |
|---|---|---|---|---|---|---|---|---|
| 0.8 | 2.2 | 2.0 | 3.1 | 4.0 | 5.6 | 5.9 | 7.1 | |
| 0.830 | 1.294 | 0.824 | 1.169 | 1.549 | 3.550 | 3.114 | 5.485 | |
| always valid | 1 | 0.7731 | 0.7731 | 0.7731 | 0.6457 | 0.2817 | 0.2817 | 0.1823 |
| fixed- z-test p-value | 0.4237 | 0.1198 | 0.2482 | 0.1211 | 0.0736 | 0.0222 | 0.0257 | 0.0121 |
The mSPRT does not reject: its largest value is 5.485, far below 20. The two-sided z-test p-value falls below 0.05 at , so an analyst who reruns the fixed-sample test after every observation would stop at and claim an effect. That p-value is valid only if was fixed in advance.
The difference matters under the null. In 2000 simulated streams of data with a horizon of 500 observations (seed 5, as in the tests), the mSPRT with rejected in 2.55% of the streams, while the z-test at level 0.05 repeated after every observation rejected at some time in 49.35% of them.
Correctness
The proofs are in full below; this is a summary.
- Closed form. With , the product of normal likelihood ratios is . Integrating it against the density of is a Gaussian integral and gives the formula of line L4.
- Test martingale. For each fixed , the product is a nonnegative martingale with mean 1 under . By Tonelli's theorem, , so is a test martingale.
- Level at every stopping time. The test rejects at or before only if for some . By Ville's inequality this has probability at most under , whatever is, including .
- Always valid p-values. For , , which has probability at most by Ville's inequality. So is a valid p-value for every stopping time .
- Power one. If , then almost surely, the exponent in line L4 grows like , and the prefactor shrinks only like . So almost surely, and the test rejects in finite time with probability 1.
Proof: The mSPRT has level alpha at every stopping time and its p-values are always validfull
Notation is that of the page. are i.i.d. with density with respect to a measure , with trivial, and is a probability measure on the parameters, fixed before the data. We assume that every is positive wherever is, and that is jointly measurable. Write
All probabilities and expectations below are under , written and .
Lemma 1 (closed form for the normal model). If is the density and , then with ,
Proof. Let . Expanding the squares in the normal densities,
Let and . Then
Here , and .
Lemma 2 (test martingale). is a nonnegative martingale under with .
Proof. since it is an integral of a nonnegative function, and it is -measurable by the joint measurability. For each and , is independent of and
with equality because is positive only where is. Hence . For a nonnegative jointly measurable integrand, Tonelli's theorem lets us exchange the conditional expectation and the integral over : for every bounded nonnegative -measurable ,
With and induction, , so is integrable, and the identity for all such is the statement .
Theorem 1 (level at every stopping time). Let be any stopping time with respect to , possibly infinite. The probability that the mSPRT rejects at some is at most .
Proof. The test rejects at some only if for some . By Lemma 2 and Ville's inequality applied to the nonnegative martingale ,
Theorem 2 (always valid p-values). Let for , the value kept by line L5, and , which exists because never increases. For every stopping time , possibly infinite, and every ,
Proof. For there is nothing to prove, and for the event is contained in , which has probability at most for every by Ville's inequality at level . Let . If and , then . If and , then . In both cases , so by Ville's inequality the probability is at most .
Lemma 3 (the procedure). After iteration of the loop of line L2, , and ; the procedure rejects exactly at if that is reached before the stream ends.
Proof. By induction on . Line L1 sets , and . Line L3 adds to , line L4 evaluates the formula of Lemma 1, and line L5 sets , which is because makes the outer with 1 automatic. Line L6 returns at the first with .
Theorem 3 (power one, normal model). If the data are with , then almost surely, so the mSPRT rejects at a finite time with probability 1.
Proof. Let . By the strong law of large numbers almost surely. Then
and the bracket tends to . So almost surely.
Theorems 1 and 2 with Lemma 3 give the guarantees of the page: the procedure has type I error at most whenever and however the analyst stops it, and the p-value it reports at that time is valid.
Complexity
Each observation costs one update of , one exponential and one square root, so the time is for the observations read and the extra space is . Under an alternative with effect , setting in line L4 shows that the test rejects at about the where
so the expected sample size grows like plus a term of order . A one-sided SPRT that knows needs about ; the extra logarithm is the cost of not knowing .
Properties
- Anytime valid. The type I error bound holds for continuous monitoring, for stopping when the data look good, and for never stopping.
- One threshold. The test never accepts . A study that must end at a fixed horizon reports "no rejection" and the p-value at that point.
- Monotone p-values. never increases, so a result that was significant stays significant.
- Conservative. Ville's inequality has slack because the mixture jumps over , and because a stream that stops early has no chance to cross later. The realized level is below , 2.55% in the simulation above.
- Inverts to a confidence sequence. The set of that the mSPRT has not rejected by time is the normal mixture confidence sequence.
Variants and improvements
- Other mixing distributions. Any fixed before the data works. A normal gives the closed form above; a one-sided mixture on gives a one-sided test with more power on that side. The mixing scale chooses the effect sizes at which the test is fastest; Johari et al. (2022) discuss how to choose it from the effect sizes seen in earlier experiments.
- Bernoulli data. For coin flips with null and a mixture, the ratio is after heads and tails. It is a Bayes factor and a test martingale for the same reason.
- Two-sample A/B tests. With large samples, the difference of the arm means is close to normal with known variance, and the normal mSPRT is applied to it; this is the setting of Johari et al.
- Multiple tests. Always valid p-values can be fed into Bonferroni or Benjamini-Hochberg procedures for many metrics at once; the multiple comparisons problem remains.
- E-processes. For composite nulls, an infimum of test martingales over the null gives an e-process, which still gives anytime-valid tests (see test martingale).
- Group sequential designs. When the number of looks is small and fixed in advance, a group sequential design with alpha spending gives more power than the mSPRT.
When to use it
Use the mSPRT when analysts will look at the results continuously, the stopping rule is not fixed, and the null is a point such as "no difference between the arms". It fits online A/B tests, monitoring dashboards and adaptive data collection. When the looks are few and planned, a group sequential design has more power. When there are only two simple hypotheses, the SPRT is faster.
Pitfalls
- Choosing the mixture after seeing the data. The guarantee needs fixed in advance. Tuning on the same data voids it.
- Unknown variance. The closed form assumes known. Plugging in an estimate is an approximation that is accurate only for large .
- Dependent data. Daily or weekly cycles in traffic break the i.i.d. assumption, and with it the martingale property.
- Reading as a fixed-sample p-value. It is larger than the fixed-sample p-value at the same , as the example shows; that is the price of validity at all times.
- Effect estimates at the stopping time. The sample mean when the test stops is biased away from zero. Report a confidence sequence instead.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mixture-sequential-probability-ratio-test/. The authors are listed in prov/7K0XX7.jsonl.
"""The mixture sequential probability ratio test (mSPRT) for a normal mean.
Data x_1, x_2, ... are i.i.d. N(theta, sigma^2) with sigma known. H0 is
theta = theta0. The likelihood ratio of N(theta, sigma^2) to N(theta0,
sigma^2) is mixed over theta ~ N(theta0, tau^2), which gives the closed form
Lambda_n = sqrt(sigma^2 / (sigma^2 + n tau^2))
* exp(tau^2 S_n^2 / (2 sigma^2 (sigma^2 + n tau^2))),
with S_n = sum (x_i - theta0). Lambda_n is a nonnegative martingale with mean 1
under H0, so rejecting at the first n with Lambda_n >= 1/alpha has level alpha
at every stopping time (Ville's inequality). The always valid p-value is
p_n = min(1, 1 / max_(k <= n) Lambda_k). Cost O(1) time and memory per item.
"""
import math
from collections.abc import Iterable
from fractions import Fraction
def msprt_ratio(n: int, s: float, sigma: float, tau: float) -> float:
"""Lambda_n from n and the centred sum s = sum (x_i - theta0)."""
v = sigma * sigma + n * tau * tau
return math.sqrt(sigma * sigma / v) * math.exp(tau * tau * s * s / (2.0 * sigma * sigma * v))
def msprt(stream: Iterable[float], theta0: float, sigma: float, tau: float,
alpha: float) -> tuple[bool, int, float]:
"""Run the normal mSPRT. Returns (rejected, n, always valid p-value at stop).
Precondition: sigma > 0, tau > 0, 0 < alpha < 1. The test stops at the
first n with Lambda_n >= 1/alpha, or at the end of the stream.
"""
if sigma <= 0 or tau <= 0 or not 0.0 < alpha < 1.0:
raise ValueError("need sigma > 0, tau > 0, 0 < alpha < 1")
s = 0.0 # @line L1
n = 0 # @line L1
p = 1.0 # @line L1
for x in stream: # @line L2
n += 1 # @line L3
s += x - theta0 # @line L3
lam = msprt_ratio(n, s, sigma, tau) # @line L4
p = min(p, 1.0 / lam) # @line L5
if lam >= 1.0 / alpha: # @line L6
return True, n, p # @line L6
return False, n, p # @line L7
def always_valid_p_values(xs: Iterable[float], theta0: float, sigma: float, tau: float) -> list[float]:
"""The sequence p_1, p_2, ... with p_n = min(1, 1 / max_(k <= n) Lambda_k)."""
out = []
s = 0.0
p = 1.0
for n, x in enumerate(xs, 1):
s += x - theta0
p = min(p, 1.0 / msprt_ratio(n, s, sigma, tau))
out.append(p)
return out
def _beta_fn(a: int, b: int) -> Fraction:
return Fraction(math.factorial(a - 1) * math.factorial(b - 1), math.factorial(a + b - 1))
def beta_bernoulli_ratio(heads: int, tails: int, a: int, b: int, p0: Fraction) -> Fraction:
"""Exact mixture ratio for coin flips: Beta(a, b) mixture over p against the point p0.
Lambda = B(a + heads, b + tails) / B(a, b) / (p0^heads (1 - p0)^tails).
Precondition: a, b positive integers, 0 < p0 < 1.
"""
return _beta_fn(a + heads, b + tails) / _beta_fn(a, b) / (p0 ** heads * (1 - p0) ** tails)
mixture_sequential_probability_ratio_test.py 8 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mixture-sequential-probability-ratio-test/. The authors are listed in prov/7K0XX7.jsonl.
"""Entry point named after the slug. The code lives in msprt_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""
from msprt_core import always_valid_p_values, beta_bernoulli_ratio, msprt, msprt_ratio
__all__ = ["always_valid_p_values", "beta_bernoulli_ratio", "msprt", "msprt_ratio"]
test_mixture_sequential_probability_ratio_test.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mixture-sequential-probability-ratio-test/. The authors are listed in prov/7K0XX7.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
from mixture_sequential_probability_ratio_test import (
always_valid_p_values,
beta_bernoulli_ratio,
msprt,
msprt_ratio,
)
EXAMPLE = [0.8, 1.4, -0.2, 1.1, 0.9, 1.6, 0.3, 1.2]
def mixture_by_quadrature(xs: list[float], theta0: float, sigma: float, tau: float, m: int = 4000) -> float:
"""Integral over theta of prod f_theta(x_i) / f_theta0(x_i) times the N(theta0, tau^2) density."""
lo, hi = theta0 - 12 * tau, theta0 + 12 * tau
h = (hi - lo) / m
acc = 0.0
for i in range(m + 1):
t = lo + i * h
w = 1.0 if i in (0, m) else (4.0 if i % 2 else 2.0)
log_lr = sum(((x - theta0) ** 2 - (x - t) ** 2) / (2 * sigma * sigma) for x in xs)
prior = math.exp(-0.5 * ((t - theta0) / tau) ** 2) / (tau * math.sqrt(2 * math.pi))
acc += w * math.exp(log_lr) * prior
return acc * h / 3.0
def test_worked_example():
p = always_valid_p_values(EXAMPLE, 0.0, 1.0, 1.0)
want = [1.0, 0.7731, 0.7731, 0.7731, 0.6457, 0.2817, 0.2817, 0.1823]
assert all(abs(a - b) < 1e-4 for a, b in zip(p, want))
assert msprt(EXAMPLE, 0.0, 1.0, 1.0, 0.05) == (False, 8, p[-1])
assert abs(msprt_ratio(6, 5.6, 1.0, 1.0) - 3.550) < 1e-3
def test_p_values_never_increase_and_reject_matches():
rng = random.Random(3)
xs = [rng.gauss(0.6, 1.0) for _ in range(200)]
p = always_valid_p_values(xs, 0.0, 1.0, 0.5)
assert all(a >= b for a, b in zip(p, p[1:]))
rejected, n, pn = msprt(xs, 0.0, 1.0, 0.5, 0.05)
first = next(i for i, v in enumerate(p, 1) if v <= 0.05)
assert rejected and n == first and pn == p[n - 1]
def test_closed_form_matches_quadrature():
rng = random.Random(8)
for _ in range(20):
sigma = rng.uniform(0.5, 2.0)
tau = rng.uniform(0.2, 2.0)
theta0 = rng.uniform(-1.0, 1.0)
xs = [rng.gauss(theta0 + rng.uniform(-1, 1), sigma) for _ in range(rng.randint(1, 12))]
s = sum(x - theta0 for x in xs)
want = mixture_by_quadrature(xs, theta0, sigma, tau)
assert abs(msprt_ratio(len(xs), s, sigma, tau) - want) < 1e-8 * max(1.0, want)
def test_beta_bernoulli_martingale_mean_one_exact():
for a, b in ((1, 1), (2, 3), (5, 1)):
for p0 in (Fraction(1, 2), Fraction(1, 3), Fraction(7, 10)):
for n in range(0, 11):
mean = sum(p0 ** sum(s) * (1 - p0) ** (n - sum(s)) * beta_bernoulli_ratio(sum(s), n - sum(s), a, b, p0)
for s in itertools.product((0, 1), repeat=n))
assert mean == 1
def test_beta_bernoulli_stopped_mean_at_most_one_exact():
# Stop when Lambda >= 1/alpha or after 12 flips: E0[Lambda_T] = 1 exactly for a bounded stopping time.
p0, alpha = Fraction(1, 2), Fraction(1, 10)
alive = {(0, 0): Fraction(1)}
stopped = Fraction(0)
reject = Fraction(0)
for n in range(1, 13):
nxt: dict[tuple[int, int], Fraction] = {}
for (h, t), m in alive.items():
for h2, t2, q in ((h + 1, t, p0), (h, t + 1, 1 - p0)):
lam = beta_bernoulli_ratio(h2, t2, 1, 1, p0)
if lam >= 1 / alpha or n == 12:
stopped += m * q * lam
reject += m * q * (lam >= 1 / alpha)
else:
nxt[(h2, t2)] = nxt.get((h2, t2), Fraction(0)) + m * q
alive = nxt
assert stopped == 1
assert reject <= alpha
def test_optional_stopping_size_against_naive_z_test():
rng = random.Random(5)
reps, horizon, alpha = 2000, 500, 0.05
msprt_rej = naive_rej = 0
for _ in range(reps):
s = 0.0
hit_m = hit_z = False
for n in range(1, horizon + 1):
s += rng.gauss(0.0, 1.0)
hit_m = hit_m or msprt_ratio(n, s, 1.0, 1.0) >= 1 / alpha
hit_z = hit_z or abs(s) / math.sqrt(n) >= 1.959964
if hit_m and hit_z:
break
msprt_rej += hit_m
naive_rej += hit_z
se = math.sqrt(alpha * (1 - alpha) / reps)
assert msprt_rej / reps < alpha
assert naive_rej / reps > alpha + 10 * se
def test_power_one():
rng = random.Random(12)
for _ in range(50):
xs = (rng.gauss(0.3, 1.0) for _ in range(5000))
assert msprt(xs, 0.0, 1.0, 1.0, 0.05)[0]
def test_random_streams_against_direct_formula():
rng = random.Random(77)
for _ in range(500):
sigma, tau = rng.uniform(0.3, 3), rng.uniform(0.1, 3)
theta0 = rng.uniform(-2, 2)
xs = [rng.gauss(theta0 + rng.uniform(-1, 1), sigma) for _ in range(rng.randint(1, 15))]
p = 1.0
for n in range(1, len(xs) + 1):
mean = sum(xs[:n]) / n
v = sigma ** 2 + n * tau ** 2
lam = math.sqrt(sigma ** 2 / v) * math.exp(n * n * tau ** 2 * (mean - theta0) ** 2 / (2 * sigma ** 2 * v))
p = min(p, 1 / lam)
assert abs(always_valid_p_values(xs, theta0, sigma, tau)[-1] - p) < 1e-9 * max(1.0, p)
def test_bad_input():
with pytest.raises(ValueError):
msprt([1.0], 0.0, 0.0, 1.0, 0.05)
with pytest.raises(ValueError):
msprt([1.0], 0.0, 1.0, 1.0, 1.5)
History
Robbins (1970) introduced the method of mixtures: average the likelihood ratio over a distribution of alternatives and apply the maximal inequality for nonnegative martingales to bound the probability of ever crossing a boundary. He used it to build tests of power one and confidence sequences. Johari, Koomen, Pekelis and Walsh (2017, 2022) named the test the mSPRT, defined always valid p-values and confidence intervals, and deployed them in a commercial A/B testing platform. Ramdas, Grünwald, Vovk and Shafer (2023) place it within the theory of test martingales and e-values.
References
- Herbert Robbins, Statistical methods related to the law of the iterated logarithm, Annals of Mathematical Statistics 41(5) (1970), pages 1397 to 1409, the method of mixtures, which mixes the likelihood ratio over a prior on the alternative and bounds the crossing probability of the mixture
- Ramesh Johari, Pete Koomen, Leonid Pekelis and David Walsh, Peeking at A/B tests, why it matters, and what to do about it, Proceedings of KDD 2017, pages 1517 to 1525, the mSPRT with a normal mixing distribution and the always valid p-values used in an online experimentation platform
- Ramesh Johari, Pete Koomen, Leonid Pekelis and David Walsh, Always valid inference, continuous monitoring of A/B tests, Operations Research 70(3) (2022), pages 1806 to 1821, the definition of always valid p-values and confidence intervals, their construction from the mSPRT, and the choice of the mixing distribution
- Aaditya Ramdas, Peter Grünwald, Vladimir Vovk and Glenn Shafer, Game-theoretic statistics and safe anytime-valid inference, Statistical Science 38(4) (2023), pages 576 to 601, mixture likelihood ratios as test martingales and the resulting anytime-valid p-values
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 7K0XX7 Edit this page History Report an error Markdown