Algorithm Search⌘K

Algorithmresearch

CUPED

Also called controlled-experiment using pre-experiment data, regression adjustment for A/B tests.

Reduces the variance of an online experiment's estimate by subtracting theta times a pre-experiment covariate, with theta the regression coefficient, as in control variates.

Time
Θ(n) worst · best
Space
Θ(n) extra
Where
n = the number of units in both arms
Properties
deterministicequals ancova with within thetaneeds pre treatment covariateunbiased for fixed theta
Origin
Alex Deng, Ya Xu, Ron Kohavi, Toby Walker, 2013

CUPED (controlled-experiment using pre-experiment data) makes a randomized experiment more sensitive by removing from each unit's outcome the part that a covariate measured before the experiment already predicts. For a metric YY and a pre-experiment covariate XX, usually the same metric over an earlier period, it replaces YiY_i with Yi−θ(Xi−xˉ)Y_i - \theta(X_i - \bar x) and compares the arm means of the adjusted values. Because XX is fixed before the coin is tossed, the adjustment does not move the mean of the estimate, but with θ\theta the regression slope of YY on XX it cuts the variance by the factor 1−ρ21 - \rho^2, where ρ\rho is the correlation of XX and YY. It is the control variates method of Monte Carlo integration applied to an A/B test, and with the within-arm slope it gives exactly the analysis of covariance (ANCOVA) estimate. The cost is one pass over the data.

In plain words

Some users spend much more than others, week after week. In an A/B test this spread is noise: it hides the small change that the new version makes. But we already know how much each user spent last month, before the test started. CUPED takes away from each user's number the part that last month's number predicts, and compares what is left between the two groups.

Last month's spending cannot be affected by the new version, and the two groups were formed at random, so the subtraction takes away the same amount from both groups on average and the comparison stays fair. What it takes away is the spread that the two months share. If the months are strongly related, the remaining numbers are much less noisy, and the test needs fewer users or less time to detect the same change.

The problem

Identification. This is the identification of a randomized experiment. Each unit has potential outcomes Y(1)Y(1) and Y(0)Y(0), the observed outcome is Y=TY(1)+(1−T)Y(0)Y = TY(1) + (1 - T)Y(0) under SUTVA, and the treatment TT is assigned at random, so TT is independent of (Y(1),Y(0),X)(Y(1), Y(0), X). The estimand is the average treatment effect τ=E[Y(1)−Y(0)]\tau = \mathbb{E}[Y(1) - Y(0)], or its finite population version 1n∑i(Yi(1)−Yi(0))\frac1n\sum_i(Y_i(1) - Y_i(0)). It is identified by the difference of the arm means, τ=E[Y∣T=1]−E[Y∣T=0]\tau = \mathbb{E}[Y \mid T = 1] - \mathbb{E}[Y \mid T = 0]; no model is needed. The one extra assumption is that XX is a pre-treatment covariate: it is measured before the assignment, so the treatment cannot change it. This is checkable in part: the arms should have the same distribution of XX, and a test of xˉt=xˉc\bar x_t = \bar x_c is a test of the randomization and of this assumption.

Estimation. The input is the outcomes and covariates of the ntn_t treated units and the ncn_c control units, and a rule for θ\theta. The output is an estimate δ^\hat\delta of τ\tau, the coefficient θ\theta used, and an estimated variance. The estimator is

δ^(θ)=1nt∑Ti=1(Yi−θ(Xi−xˉ))−1nc∑Ti=0(Yi−θ(Xi−xˉ))=(yˉt−yˉc)−θ(xˉt−xˉc).\hat\delta(\theta) = \frac{1}{n_t}\sum_{T_i = 1}\big(Y_i - \theta(X_i - \bar x)\big) - \frac{1}{n_c}\sum_{T_i = 0}\big(Y_i - \theta(X_i - \bar x)\big) = (\bar y_t - \bar y_c) - \theta(\bar x_t - \bar x_c).

The second form shows what happens: if the treated arm happened to have a larger pre-period mean, the estimate is moved down by θ\theta times that chance difference. Three rules for θ\theta are common:

  • Fixed in advance, for example from an earlier experiment. Then δ^\hat\delta is exactly unbiased over the randomization.
  • Pooled: the slope of YY on XX over all units, ignoring the arms, θ^=∑i(Xi−xˉ)(Yi−yˉ)/∑i(Xi−xˉ)2\hat\theta = \sum_i(X_i - \bar x)(Y_i - \bar y)/\sum_i(X_i - \bar x)^2. This is the control variates formula Cov⁡(X,Y)/Var⁡(X)\operatorname{Cov}(X, Y)/\operatorname{Var}(X).
  • Within: the slope fitted inside each arm and pooled, which is the coefficient of XX in the regression of YY on (1,T,X)(1, T, X).

An estimated θ\theta makes δ^\hat\delta biased by a term of order 1/n1/n, which is negligible next to its standard error of order n−1/2n^{-1/2}. The variance estimate is the Welch form st2/nt+sc2/ncs_t^2/n_t + s_c^2/n_c computed on the adjusted values, with θ\theta treated as fixed, and a normal interval follows. Unlike the propensity weighted estimators of observational studies, nothing here can fail by positivity: the assignment probabilities are known and away from 0 and 1 by design.

The algorithm

  1. CUPED(Yt, Xt, Yc, Xc, rule) ▷ X measured before the experiment
  2. 1θ ← the value given by rule: fixed, pooled slope of Y on X, or within-arm slope
  3. 2x̄ ← mean of X over all n_t + n_c units
  4. 3for every unit i: A_i ← Y_i - θ (X_i - x̄)
  5. 4δ ← mean of A over the treated - mean of A over the controls
  6. 5v ← s²(A over treated) / n_t + s²(A over controls) / n_c
  7. 6return (δ, θ, v)

Line L1 is one pass of sums for the slope. Line L2 only centres the adjusted values; by the second form of δ^\hat\delta it does not change δ\delta, but it keeps the adjusted values on the scale of YY so that the per-arm means can be reported. Line L5 is the usual Welch variance of a difference in means, applied to the adjusted metric, and the interval is δ±z1−α/2v\delta \pm z_{1 - \alpha/2}\sqrt v.

Example

Six users, three per arm. The covariate is last month's spending and the outcome is this month's.

arm XX YY
treated 2, 4, 6 5, 8, 11
control 1, 3, 5 2, 6, 7

The plain difference in means is 8−5=38 - 5 = 3, with Welch variance 9/3+7/3=16/39/3 + 7/3 = 16/3. But the treated users also spent more last month: xˉt=4\bar x_t = 4 against xˉc=3\bar x_c = 3.

Within-arm θ\theta. About the arm means, the treated deviations are X:−2,0,2X: -2, 0, 2 and Y:−3,0,3Y: -3, 0, 3, and the control deviations are X:−2,0,2X: -2, 0, 2 and Y:−3,1,2Y: -3, 1, 2. So ∑(X−xˉarm)(Y−yˉarm)=12+10=22\sum(X - \bar x_{\text{arm}})(Y - \bar y_{\text{arm}}) = 12 + 10 = 22 and ∑(X−xˉarm)2=8+8=16\sum(X - \bar x_{\text{arm}})^2 = 8 + 8 = 16, and θ=11/8\theta = 11/8. With xˉ=7/2\bar x = 7/2, the adjusted values Y−118(X−72)Y - \frac{11}{8}(X - \frac72) are

arm adjusted values mean s2s^2
treated 113/16, 117/16, 121/16 117/16 1/16
control 87/16, 107/16, 79/16 91/16 13/16

so δ=26/16=13/8=3−118(4−3)\delta = 26/16 = 13/8 = 3 - \frac{11}{8}(4 - 3), and v=1/163+13/163=7/24v = \frac{1/16}{3} + \frac{13/16}{3} = 7/24, against 16/316/3 before. The least squares fit of YY on (1,T,X)(1, T, X) is Y=7/8+13/8 T+11/8 XY = 7/8 + 13/8\,T + 11/8\,X: the coefficient of TT is the CUPED estimate, as the theory says.

Pooled θ\theta. Over all six users, ∑(X−72)(Y−132)=26.5\sum(X - \frac72)(Y - \frac{13}{2}) = 26.5 and ∑(X−72)2=17.5\sum(X - \frac72)^2 = 17.5, so θ=53/35\theta = 53/35 and δ=3−53/35=52/35≈1.486\delta = 3 - 53/35 = 52/35 \approx 1.486. The pooled slope is larger because the treated users are both higher in XX and, through the treatment, higher in YY, so part of the effect looks like slope. In a sample this small the two rules differ by 0.14; in the simulation below, with 500 users per arm, they never differed by more than 0.0013.

Simulation. X∼N(0,1)X \sim N(0, 1), Y=2+0.1T+X+0.75εY = 2 + 0.1T + X + 0.75\varepsilon, so ρ2=0.64\rho^2 = 0.64 and the predicted factor is 0.360.36. Over 400 experiments with 500 users per arm (seed 2026), measured:

estimator mean SD 95% coverage
difference in means 0.1065 0.0831 0.935
CUPED, pooled θ\theta 0.1029 0.0499 0.930
CUPED, within θ\theta 0.1030 0.0499 0.930

The ratio of the two Monte Carlo variances was 0.360, and the mean of the per-experiment ratio v/vnaivev/v_{\text{naive}} was also 0.360. The same precision without CUPED would need about 1/0.36≈2.81/0.36 \approx 2.8 times as many users.

Correctness

The full proofs are in the correctness proof. The key facts:

  • The form. δ^(θ)=(yˉt−yˉc)−θ(xˉt−xˉc)\hat\delta(\theta) = (\bar y_t - \bar y_c) - \theta(\bar x_t - \bar x_c), whatever value is used for centring.
  • Unbiased for a fixed θ\theta. Under complete randomization each unit is treated with probability nt/nn_t/n, so E[xˉt]=E[xˉc]=xˉ\mathbb{E}[\bar x_t] = \mathbb{E}[\bar x_c] = \bar x and E[yˉt−yˉc]=τ\mathbb{E}[\bar y_t - \bar y_c] = \tau. Hence E[δ^(θ)]=τ\mathbb{E}[\hat\delta(\theta)] = \tau exactly for any θ\theta chosen without the assignment. The tests check this by listing all 20 assignments of 6 units with exact fractions.
  • Estimated θ\theta. Under the sharp null Yi(1)=Yi(0)Y_i(1) = Y_i(0) the pooled slope does not depend on the assignment, so the estimate is exactly unbiased there. With a real effect, E[δ^]=τ−E[θ^(xˉt−xˉc)]\mathbb{E}[\hat\delta] = \tau - \mathbb{E}[\hat\theta(\bar x_t - \bar x_c)], which is not 0 in general; the tests show a case. Freedman (2008) shows the bias is of order 1/n1/n.
  • The factor 1−ρ21 - \rho^2. Var⁡(Y−θX)=Var⁡(Y)−2θCov⁡(X,Y)+θ2Var⁡(X)\operatorname{Var}(Y - \theta X) = \operatorname{Var}(Y) - 2\theta\operatorname{Cov}(X, Y) + \theta^2\operatorname{Var}(X) is smallest at θ∗=Cov⁡(X,Y)/Var⁡(X)\theta^* = \operatorname{Cov}(X, Y)/\operatorname{Var}(X), where it equals Var⁡(Y)(1−ρ2)\operatorname{Var}(Y)(1 - \rho^2). If both arms have the same variance and the same covariance with XX (for example a constant effect), the variance of δ^\hat\delta falls by the same factor. The identity holds exactly for sample moments too, which the tests check.
  • ANCOVA. In the regression of YY on (1,T,X)(1, T, X), the residuals sum to 0 in each arm, which gives the coefficient of TT as δ^(g)\hat\delta(g) with gg the coefficient of XX; the normal equation for XX then makes gg the within-arm slope.

Proved: these exact statements. Cited, not proved: that an estimated θ\theta leaves the large-sample distribution unchanged and that the interval has its nominal level (Deng et al. 2013; Lin 2013).

Proof: CUPED with a fixed coefficient is unbiased, the best coefficient cuts the variance by 1 - rho^2, and the within-arm coefficient gives the ANCOVA estimatefull

There are nn units. Unit ii has a covariate XiX_i measured before the experiment and an outcome YiY_i; the treated arm T\mathcal T has nt≥2n_t \ge 2 units and the control arm C\mathcal C has nc≥2n_c \ge 2 units. Write yˉt,xˉt\bar y_t, \bar x_t for the means over T\mathcal T, yˉc,xˉc\bar y_c, \bar x_c for the means over C\mathcal C, and xˉ\bar x for the mean of XX over all nn units. CUPED returns

δ^(θ)=1nt∑i∈T(Yi−θ(Xi−xˉ))−1nc∑i∈C(Yi−θ(Xi−xˉ)).\hat\delta(\theta) = \frac{1}{n_t}\sum_{i \in \mathcal T}\big(Y_i - \theta(X_i - \bar x)\big) - \frac{1}{n_c}\sum_{i \in \mathcal C}\big(Y_i - \theta(X_i - \bar x)\big).

Lemma 1 (the form of the estimate). δ^(θ)=(yˉt−yˉc)−θ(xˉt−xˉc)\hat\delta(\theta) = (\bar y_t - \bar y_c) - \theta(\bar x_t - \bar x_c).

Proof. The mean of Yi−θ(Xi−xˉ)Y_i - \theta(X_i - \bar x) over T\mathcal T is yˉt−θxˉt+θxˉ\bar y_t - \theta\bar x_t + \theta\bar x, and over C\mathcal C it is yˉc−θxˉc+θxˉ\bar y_c - \theta\bar x_c + \theta\bar x. The θxˉ\theta\bar x terms cancel in the difference. □\square

So centring by xˉ\bar x does not change δ^\hat\delta; it only keeps the adjusted values on the scale of YY, which makes the per-arm means readable.

Unbiased under randomization

Theorem 2 (fixed theta). Take the finite population view: each unit has fixed potential outcomes Yi(1),Yi(0)Y_i(1), Y_i(0) and a fixed XiX_i, and the treated set is a uniformly random subset of size ntn_t (complete randomization). Let τ=1n∑i(Yi(1)−Yi(0))\tau = \frac1n\sum_i(Y_i(1) - Y_i(0)). If θ\theta does not depend on the assignment, then E[δ^(θ)]=τ\mathbb{E}[\hat\delta(\theta)] = \tau.

Proof. Each unit is treated with probability nt/nn_t/n, so E[yˉt]=1nt∑intnYi(1)=1n∑iYi(1)\mathbb{E}[\bar y_t] = \frac{1}{n_t}\sum_i \frac{n_t}{n}Y_i(1) = \frac1n\sum_i Y_i(1), and in the same way E[yˉc]=1n∑iYi(0)\mathbb{E}[\bar y_c] = \frac1n\sum_i Y_i(0) and E[xˉt]=E[xˉc]=xˉ\mathbb{E}[\bar x_t] = \mathbb{E}[\bar x_c] = \bar x. By Lemma 1 and linearity, E[δ^(θ)]=τ−θ⋅0\mathbb{E}[\hat\delta(\theta)] = \tau - \theta\cdot 0. □\square

The covariate must be measured before the treatment starts. If the treatment can change XX, then XiX_i is not fixed in the sense of the theorem, and E[xˉt−xˉc]\mathbb{E}[\bar x_t - \bar x_c] is the effect of the treatment on XX, which leaks into δ^\hat\delta.

Theorem 3 (pooled theta under the sharp null). If Yi(1)=Yi(0)Y_i(1) = Y_i(0) for every unit, the pooled coefficient θ^=∑i(Xi−xˉ)(Yi−yˉ)/∑i(Xi−xˉ)2\hat\theta = \sum_i(X_i - \bar x)(Y_i - \bar y)/\sum_i(X_i - \bar x)^2 does not depend on the assignment, and E[δ^(θ^)]=0\mathbb{E}[\hat\delta(\hat\theta)] = 0.

Proof. Under the sharp null the observed YiY_i equals Yi(0)Y_i(0) whatever the assignment, and θ^\hat\theta uses all units without their arm labels. So θ^\hat\theta is a constant, and Theorem 2 applies with τ=0\tau = 0. □\square

With a real effect, the pooled θ^\hat\theta and the within-arm θ^\hat\theta both depend on the assignment, and E[δ^(θ^)]=τ−E[θ^(xˉt−xˉc)]\mathbb{E}[\hat\delta(\hat\theta)] = \tau - \mathbb{E}[\hat\theta(\bar x_t - \bar x_c)], which is not 0 in general. The tests find a population of 6 units where the mean over all 20 assignments differs from τ\tau. Freedman (2008) shows the bias is of order 1/n1/n; it is not proved here.

The variance

Theorem 4 (the best coefficient). Let XX and YY be random variables with finite variances, Var⁡(X)>0\operatorname{Var}(X) > 0, and correlation ρ\rho. Then Var⁡(Y−θX)\operatorname{Var}(Y - \theta X) is smallest at θ∗=Cov⁡(X,Y)/Var⁡(X)\theta^* = \operatorname{Cov}(X, Y)/\operatorname{Var}(X), and

Var⁡(Y−θ∗X)=Var⁡(Y)(1−ρ2).\operatorname{Var}(Y - \theta^* X) = \operatorname{Var}(Y)(1 - \rho^2).

The same identity holds for sample moments: with sxx,syy,sxys_{xx}, s_{yy}, s_{xy} the sums of squares and cross products about the means, and θ^=sxy/sxx\hat\theta = s_{xy}/s_{xx}, the sum of squares of Yi−θ^XiY_i - \hat\theta X_i about its mean is syy(1−sxy2/(sxxsyy))s_{yy}(1 - s_{xy}^2/(s_{xx}s_{yy})).

Proof. Var⁡(Y−θX)=Var⁡(Y)−2θCov⁡(X,Y)+θ2Var⁡(X)\operatorname{Var}(Y - \theta X) = \operatorname{Var}(Y) - 2\theta\operatorname{Cov}(X, Y) + \theta^2\operatorname{Var}(X), a quadratic in θ\theta with positive leading coefficient, smallest where its derivative −2Cov⁡(X,Y)+2θVar⁡(X)-2\operatorname{Cov}(X, Y) + 2\theta\operatorname{Var}(X) is 0. Putting θ∗\theta^* in gives Var⁡(Y)−Cov⁡(X,Y)2/Var⁡(X)=Var⁡(Y)(1−ρ2)\operatorname{Var}(Y) - \operatorname{Cov}(X, Y)^2/\operatorname{Var}(X) = \operatorname{Var}(Y)(1 - \rho^2), since ρ2=Cov⁡(X,Y)2/(Var⁡(X)Var⁡(Y))\rho^2 = \operatorname{Cov}(X, Y)^2/(\operatorname{Var}(X)\operatorname{Var}(Y)). The sample version is the same algebra with sxx,syy,sxys_{xx}, s_{yy}, s_{xy} in place of the moments. □\square

Theorem 5 (the variance of the estimate). Take the sampling view: the units of each arm are independent, the treated units are draws of (X,Y(1))(X, Y(1)) and the control units are draws of (X,Y(0))(X, Y(0)) from one population, so XX has the same law in both arms. Let σa2=Var⁡(Y(a))\sigma_a^2 = \operatorname{Var}(Y(a)), ca=Cov⁡(X,Y(a))c_a = \operatorname{Cov}(X, Y(a)) and v=Var⁡(X)>0v = \operatorname{Var}(X) > 0. For a fixed θ\theta,

Var⁡(δ^(θ))=σ12−2θc1+θ2vnt+σ02−2θc0+θ2vnc.\operatorname{Var}(\hat\delta(\theta)) = \frac{\sigma_1^2 - 2\theta c_1 + \theta^2 v}{n_t} + \frac{\sigma_0^2 - 2\theta c_0 + \theta^2 v}{n_c}.

It is smallest at θ∗=(c1/nt+c0/nc)/(v(1/nt+1/nc))\theta^* = (c_1/n_t + c_0/n_c)/(v(1/n_t + 1/n_c)). If c1=c0c_1 = c_0 and σ1=σ0\sigma_1 = \sigma_0, which holds for example when the effect is the same for every unit, the smallest value is (1−ρ2)(1 - \rho^2) times the variance of yˉt−yˉc\bar y_t - \bar y_c, where ρ\rho is the correlation of XX and Y(0)Y(0).

Proof. By Lemma 1, δ^(θ)\hat\delta(\theta) is the difference of the arm means of Yi−θXiY_i - \theta X_i; the two arms are independent and each mean averages independent terms, so the variance is the sum of Var⁡(Y(a)−θX)/na\operatorname{Var}(Y(a) - \theta X)/n_a, and each of these expands as in Theorem 4. The sum is a quadratic in θ\theta with leading coefficient v(1/nt+1/nc)>0v(1/n_t + 1/n_c) > 0, smallest at θ∗\theta^*. If c1=c0=cc_1 = c_0 = c and σ1=σ0=σ\sigma_1 = \sigma_0 = \sigma, then θ∗=c/v\theta^* = c/v, and each arm term is σ2(1−ρ2)/na\sigma^2(1 - \rho^2)/n_a by Theorem 4, while the unadjusted variance is σ2(1/nt+1/nc)\sigma^2(1/n_t + 1/n_c). □\square

When c1≠c0c_1 \ne c_0, the pooled coefficient estimates a weighted slope that need not be θ∗\theta^*, and the variance can even rise when the arm sizes differ. This is the case that Freedman (2008) studied; Lin (2013) shows that fitting a separate slope in each arm removes the problem in large samples. The plug-in variance that CUPED reports (line L5) treats θ^\hat\theta as fixed; its validity in large samples is cited from Deng et al. (2013) and Lin (2013).

The within-arm coefficient is ANCOVA

Theorem 6. Let θ^w=(∑T(Xi−xˉt)(Yi−yˉt)+∑C(Xi−xˉc)(Yi−yˉc))/(∑T(Xi−xˉt)2+∑C(Xi−xˉc)2)\hat\theta_w = \big(\sum_{\mathcal T}(X_i - \bar x_t)(Y_i - \bar y_t) + \sum_{\mathcal C}(X_i - \bar x_c)(Y_i - \bar y_c)\big)/\big(\sum_{\mathcal T}(X_i - \bar x_t)^2 + \sum_{\mathcal C}(X_i - \bar x_c)^2\big), with a positive denominator. In the least squares fit of YY on (1,T,X)(1, T, X), the coefficient of XX is θ^w\hat\theta_w and the coefficient of TT is δ^(θ^w)\hat\delta(\hat\theta_w).

Proof. Let (a,b,g)(a, b, g) be the coefficients of (1,T,X)(1, T, X) and ri=Yi−a−bTi−gXir_i = Y_i - a - bT_i - gX_i the residuals. The normal equations for the columns 11 and TT say ∑iri=0\sum_i r_i = 0 and ∑Tri=0\sum_{\mathcal T} r_i = 0, so the residuals sum to 0 in each arm:

yˉt=a+b+gxˉt,yˉc=a+gxˉc.\bar y_t = a + b + g\bar x_t, \qquad \bar y_c = a + g\bar x_c.

Subtracting, b=(yˉt−yˉc)−g(xˉt−xˉc)=δ^(g)b = (\bar y_t - \bar y_c) - g(\bar x_t - \bar x_c) = \hat\delta(g) by Lemma 1. Substituting a+bTi=yˉ(i)−gxˉ(i)a + bT_i = \bar y_{(i)} - g\bar x_{(i)}, where (i)(i) is the arm of unit ii, gives ri=(Yi−yˉ(i))−g(Xi−xˉ(i))r_i = (Y_i - \bar y_{(i)}) - g(X_i - \bar x_{(i)}). The normal equation for the column XX, ∑iXiri=0\sum_i X_ir_i = 0, becomes ∑i(Xi−xˉ(i))ri=0\sum_i (X_i - \bar x_{(i)})r_i = 0 because ∑armri=0\sum_{\text{arm}} r_i = 0 in each arm. That is ∑i(Xi−xˉ(i))(Yi−yˉ(i))=g∑i(Xi−xˉ(i))2\sum_i (X_i - \bar x_{(i)})(Y_i - \bar y_{(i)}) = g\sum_i (X_i - \bar x_{(i)})^2, so g=θ^wg = \hat\theta_w. The denominator is positive, so the design has full rank and the solution is unique. □\square

What is proved and what is measured

Proved here: the form of the estimate (Lemma 1), exact unbiasedness over the randomization for any coefficient fixed in advance (Theorem 2) and for the pooled coefficient under the sharp null (Theorem 3), the factor 1−ρ21 - \rho^2 for the best coefficient (Theorems 4 and 5), and the equality with the ANCOVA coefficient (Theorem 6). The tests check Lemma 1 and Theorems 2, 3, 4 and 6 exactly with fractions. Not proved: that the estimated coefficient changes the large-sample distribution by a negligible amount and that the interval has its nominal level; these come from Deng et al. (2013) and Lin (2013). The variance ratio 0.360 and the coverage on the page are measured in a simulation.

Complexity

Each step is a constant number of sums over the units, so the time is Θ(n)\Theta(n). The code keeps the adjusted values, Θ(n)\Theta(n) space; a streaming version that keeps the sums of XX, YY, X2X^2, XYXY and Y2Y^2 per arm needs Θ(1)\Theta(1) space, at the cost of the cancellation risk of the textbook variance formula (use Welford's updates for large values). The real cost is in data engineering: joining each unit to its pre-period metric.

Properties

  • No bias from the adjustment. The covariate is fixed before assignment, so the adjustment only removes noise. With a fixed θ\theta this is exact; with an estimated θ\theta the bias is of order 1/n1/n.
  • Gain set by the correlation. The variance falls by 1−ρ21 - \rho^2. For ρ=0.5\rho = 0.5 that is only 25%; for ρ=0.9\rho = 0.9 it is 81%. Metrics that are stable per user over time, such as sessions or spend, gain the most.
  • Any θ\theta is valid. A poor θ\theta only loses precision; with θ=0\theta = 0 the estimate is the plain difference in means.
  • Same as regression. With the within-arm slope it is the ANCOVA coefficient exactly, so standard regression software gives the same point estimate.
  • Missing pre-period data. New users have no XX. A common fix is to set XX to a constant and add an indicator of missingness as a second covariate; this is valid because the indicator is also pre-treatment.

Variants and improvements

  • Separate slopes (Lin's estimator). Fit θt\theta_t in the treated arm and θc\theta_c in the control arm, and adjust each arm with its own slope around the overall xˉ\bar x. This is the regression with a T×XT \times X interaction. Lin (2013) shows that it is never less precise than the unadjusted estimate in large samples, which is not true of a common slope when the arms differ in size and the effect varies with XX.
  • Several covariates. Replace θX\theta X by θ⊤X\theta^\top X with θ\theta from a multiple regression; the factor becomes 1−R21 - R^2, with R2R^2 the coefficient of determination of YY on XX.
  • Machine-learning predictions. Use as the covariate a prediction of YY from any model trained on pre-experiment data. As long as the model never sees the experiment's outcomes or assignments, the prediction is a pre-treatment covariate and the method stays valid. Cross-fitting as in double machine learning lets the model use the experiment's own covariates.
  • Stratification. Post-stratifying by a discrete pre-period variable, when every stratum has units in both arms, is exactly the separate-slopes adjustment with the stratum indicators as covariates: in each arm the regression on the indicators fits the stratum means, and the adjusted arm mean weights them by the stratum shares.
  • Ratio metrics. For metrics like clicks per session, apply CUPED to the linearized metric from the delta method.

When to use it

Use CUPED in every A/B test where a pre-experiment version of the metric exists, which is most tests on returning users. It costs one join and one pass, and the gain is free power: the same sensitivity with fewer users or a shorter test. It helps little for metrics with weak memory (one-off conversions), for new users without history, and for very short pre-periods. In an observational study, where XX is also needed to remove confounding, use an adjustment estimator such as AIPW instead: CUPED relies on randomization for its unbiasedness.

Pitfalls

  • A covariate affected by the treatment. If XX is measured after exposure starts, even partly, the treatment's effect on XX is subtracted out. The pre-period must end before the first exposure.
  • Choosing θ\theta or the covariate after looking at the effect. Trying several covariates and reporting the one with the best p-value inflates the type I error. Fix the rule in advance.
  • Common slope with unequal arms. With very unbalanced arms and heterogeneous effects, the pooled or within slope can make the estimate less precise (Freedman 2008). Use separate slopes.
  • Reporting the pooled theta as the ANCOVA answer. They agree only in large samples; in small samples, as in the example, they differ. Say which rule was used.
  • Variance of the wrong unit. If users are randomized but the metric is per page view, the units are not independent; compute the variance at the randomization unit (see cluster-robust standard errors).
  • Missing XX dropped. Dropping units without pre-period data changes the population. Keep them with an imputed constant and an indicator.

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.

cuped.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cuped/. The authors are listed in prov/Y9J2V9.jsonl.

"""CUPED: variance reduction for a randomized experiment with a pre-experiment covariate.

Each unit has a metric y measured during the experiment and a covariate x measured
before it (often the same metric in an earlier period). The adjusted metric is

    y_cv = y - theta (x - mean of x over all units),

and the effect estimate is the difference of the arm means of y_cv:

    delta = (ybar_t - ybar_c) - theta (xbar_t - xbar_c).

theta can be a number fixed in advance, "pooled" (the slope of y on x over all units,
ignoring the arms) or "within" (the pooled within-arm slope). With "within", delta is
exactly the treatment coefficient of the regression of y on (1, T, x) (ANCOVA).
All functions are exact for Fraction inputs, except the interval.
"""

import math
from collections.abc import Sequence
from statistics import NormalDist
from typing import NamedTuple


class CupedResult(NamedTuple):
    delta: object  # the adjusted difference in means
    theta: object  # the coefficient used
    var: object  # the estimated variance of delta (Welch form, divisors n_t - 1 and n_c - 1)
    naive_delta: object  # ybar_t - ybar_c
    naive_var: object  # its estimated variance


def _mean(v):
    return sum(v) / len(v)


def _svar(v):
    m = _mean(v)
    return sum((a - m) ** 2 for a in v) / (len(v) - 1)


def theta_pooled(y: Sequence, x: Sequence) -> object:
    """Slope of y on x over all units: sum (x - xbar)(y - ybar) / sum (x - xbar)^2."""
    mx, my = _mean(x), _mean(y)
    sxx = sum((a - mx) ** 2 for a in x)
    if sxx == 0:
        raise ValueError("the covariate is constant")
    return sum((a - mx) * (b - my) for a, b in zip(x, y)) / sxx


def theta_within(yt, xt, yc, xc) -> object:
    """Pooled within-arm slope: the coefficient of x in the regression of y on (1, T, x)."""
    mxt, myt, mxc, myc = _mean(xt), _mean(yt), _mean(xc), _mean(yc)
    sxx = sum((a - mxt) ** 2 for a in xt) + sum((a - mxc) ** 2 for a in xc)
    if sxx == 0:
        raise ValueError("the covariate is constant within both arms")
    sxy = sum((a - mxt) * (b - myt) for a, b in zip(xt, yt)) + sum((a - mxc) * (b - myc) for a, b in zip(xc, yc))
    return sxy / sxx


def cuped(yt: Sequence, xt: Sequence, yc: Sequence, xc: Sequence, theta="pooled") -> CupedResult:
    """CUPED estimate of the treatment effect. Cost: Theta(n) time, Theta(n) space for the adjusted values."""
    if len(yt) != len(xt) or len(yc) != len(xc):
        raise ValueError("each arm needs one covariate per outcome")
    if len(yt) < 2 or len(yc) < 2:
        raise ValueError("each arm needs at least two units")
    if theta == "pooled":  # @line L1
        th = theta_pooled(list(yt) + list(yc), list(xt) + list(xc))
    elif theta == "within":
        th = theta_within(yt, xt, yc, xc)
    else:
        th = theta
    xbar = _mean(list(xt) + list(xc))  # @line L2
    at = [b - th * (a - xbar) for a, b in zip(xt, yt)]  # @line L3
    ac = [b - th * (a - xbar) for a, b in zip(xc, yc)]
    delta = _mean(at) - _mean(ac)  # @line L4
    var = _svar(at) / len(at) + _svar(ac) / len(ac)  # @line L5
    naive = _mean(yt) - _mean(yc)
    nvar = _svar(yt) / len(yt) + _svar(yc) / len(yc)
    return CupedResult(delta, th, var, naive, nvar)  # @line L6


def interval(res: CupedResult, alpha: float = 0.05) -> tuple[float, float]:
    """Normal interval delta +- z sqrt(var), approximate level 1 - alpha."""
    z = NormalDist().inv_cdf(1 - alpha / 2)
    se = math.sqrt(float(res.var))
    return float(res.delta) - z * se, float(res.delta) + z * se


# ----------------------------------------------------------------- reference: ANCOVA by least squares


def solve(a: list[list], b: list) -> list:
    """Solve a x = b by Gaussian elimination with partial pivoting (exact for Fractions)."""
    k = len(b)
    m = [list(row) + [bi] for row, bi in zip(a, b)]
    for c in range(k):
        p = max(range(c, k), key=lambda r: abs(m[r][c]))
        if m[p][c] == 0:
            raise ValueError("singular system")
        m[c], m[p] = m[p], m[c]
        for r in range(c + 1, k):
            f = m[r][c] / m[c][c]
            if f != 0:
                for j in range(c, k + 1):
                    m[r][j] -= f * m[c][j]
    out = [0] * k
    for c in range(k - 1, -1, -1):
        out[c] = (m[c][k] - sum(m[c][j] * out[j] for j in range(c + 1, k))) / m[c][c]
    return out


def ancova(yt, xt, yc, xc) -> list:
    """Coefficients (intercept, T, x) of the least squares regression of y on (1, T, x)."""
    one = xt[0] * 0 + 1  # 1 in the number type of the input, so Fractions stay exact
    zero = one - one
    rows = [[one, one, a] for a in xt] + [[one, zero, a] for a in xc]
    y = list(yt) + list(yc)
    xtx = [[sum(r[i] * r[j] for r in rows) for j in range(3)] for i in range(3)]
    xty = [sum(r[i] * v for r, v in zip(rows, y)) for i in range(3)]
    return solve(xtx, xty)
test_cuped.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cuped/. The authors are listed in prov/Y9J2V9.jsonl.

import itertools
import math
import random
import statistics
from fractions import Fraction as Fr

import pytest

from cuped import ancova, cuped, interval, theta_pooled


def test_worked_example():
    xt, yt = [Fr(2), Fr(4), Fr(6)], [Fr(5), Fr(8), Fr(11)]
    xc, yc = [Fr(1), Fr(3), Fr(5)], [Fr(2), Fr(6), Fr(7)]
    w = cuped(yt, xt, yc, xc, "within")
    assert (w.naive_delta, w.theta, w.delta) == (3, Fr(11, 8), Fr(13, 8))
    p = cuped(yt, xt, yc, xc, "pooled")
    assert (p.theta, p.delta) == (Fr(53, 35), Fr(52, 35))
    assert ancova(yt, xt, yc, xc) == [Fr(7, 8), Fr(13, 8), Fr(11, 8)]


def test_within_theta_equals_ancova_coefficient_exactly():
    rng = random.Random(1)
    for _ in range(200):
        nt, nc = rng.randint(2, 7), rng.randint(2, 7)
        xt = [Fr(rng.randint(-9, 9), rng.randint(1, 4)) for _ in range(nt)]
        xc = [Fr(rng.randint(-9, 9), rng.randint(1, 4)) for _ in range(nc)]
        yt = [Fr(rng.randint(-20, 20)) for _ in range(nt)]
        yc = [Fr(rng.randint(-20, 20)) for _ in range(nc)]
        try:
            res = cuped(yt, xt, yc, xc, "within")
        except ValueError:
            continue
        b = ancova(yt, xt, yc, xc)
        assert res.delta == b[1] and res.theta == b[2]


def test_zero_theta_is_difference_in_means():
    yt, xt, yc, xc = [Fr(3), Fr(5)], [Fr(1), Fr(2)], [Fr(1), Fr(4)], [Fr(0), Fr(7)]
    r = cuped(yt, xt, yc, xc, 0)
    assert r.delta == r.naive_delta == Fr(3, 2) and r.var == r.naive_var


def enumerate_designs(y1, y0, x, n_t):
    """All assignments of n_t of the n units to treatment, each equally likely (complete randomization)."""
    n = len(x)
    for tr in itertools.combinations(range(n), n_t):
        s = set(tr)
        yield ([y1[i] for i in tr], [x[i] for i in tr], [y0[i] for i in range(n) if i not in s], [x[i] for i in range(n) if i not in s])


def test_fixed_theta_is_exactly_unbiased_over_the_randomization():
    """n = 6 units with fixed potential outcomes, 3 treated: averaging over all 20 assignments,
    CUPED with any theta fixed in advance has mean equal to the sample average treatment effect."""
    rng = random.Random(2)
    for _ in range(30):
        x = [Fr(rng.randint(0, 9)) for _ in range(6)]
        y0 = [xi + Fr(rng.randint(-3, 3)) for xi in x]
        y1 = [v + Fr(rng.randint(-2, 6)) for v in y0]
        tau = sum(a - b for a, b in zip(y1, y0)) / 6
        for theta in (Fr(0), Fr(1), Fr(7, 3), Fr(-2)):
            ests = [cuped(*d, theta).delta for d in enumerate_designs(y1, y0, x, 3)]
            assert len(ests) == 20 and sum(ests) / 20 == tau


def test_estimated_theta_bias():
    """With theta estimated from the same data the estimate is not exactly unbiased, but under the sharp
    null (Y(1) = Y(0)) the pooled theta does not depend on the assignment, so the mean is exactly 0."""
    x = [Fr(v) for v in (0, 1, 2, 3, 4, 9)]
    y0 = [Fr(v) for v in (1, 0, 4, 3, 7, 8)]
    y1 = [Fr(v) for v in (1, 6, 4, 3, 7, 20)]  # effects 0, 6, 0, 0, 0, 12: tau = 3
    within = [cuped(*d, "within").delta for d in enumerate_designs(y1, y0, x, 3)]
    assert sum(within) / 20 != 3
    null = [cuped(*d, "pooled").delta for d in enumerate_designs(y0, y0, x, 3)]
    assert sum(null) == 0


def test_variance_identity_exact():
    """With theta the pooled slope, the sample variance of y - theta x is var(y) (1 - r^2) exactly."""
    rng = random.Random(3)
    for _ in range(100):
        n = rng.randint(3, 12)
        x = [Fr(rng.randint(-9, 9)) for _ in range(n)]
        y = [Fr(rng.randint(-9, 9)) for _ in range(n)]
        mx, my = sum(x) / n, sum(y) / n
        sxx = sum((a - mx) ** 2 for a in x)
        syy = sum((b - my) ** 2 for b in y)
        sxy = sum((a - mx) * (b - my) for a, b in zip(x, y))
        if sxx == 0 or syy == 0:
            continue
        th = theta_pooled(y, x)
        z = [b - th * a for a, b in zip(x, y)]
        mz = sum(z) / n
        szz = sum((c - mz) ** 2 for c in z)
        assert szz == syy * (1 - sxy * sxy / (sxx * syy))


def test_monte_carlo_variance_reduction_and_coverage():
    """X ~ N(0, 1), Y = 2 + X + 0.75 noise, so rho^2 = 1/1.5625 = 0.64 and the variance factor is 0.36.
    Effect 0.1, 500 units per arm, r = 400 replicates (seed 2026). Checks: the CUPED and naive estimates
    are unbiased within 4 SE; the ratio of the Monte Carlo variances is within 0.36 +- 0.08 (the ratio of
    two sample variances of 400 draws has relative SE about 0.07 each, and they are positively correlated);
    the mean of the per-sample variance ratio is within 0.36 +- 0.01; the 95% interval covers in at least
    0.92 of runs (4 SE below 0.95 is 0.906)."""
    rng = random.Random(2026)
    r, m, tau = 400, 500, 0.1
    cu, nv, ratios, cover = [], [], [], 0
    for _ in range(r):
        def arm(eff):
            xs = [rng.gauss(0, 1) for _ in range(m)]
            return [2 + eff + v + 0.75 * rng.gauss(0, 1) for v in xs], xs
        yt, xt = arm(tau)
        yc, xc = arm(0.0)
        res = cuped(yt, xt, yc, xc, "pooled")
        cu.append(res.delta)
        nv.append(res.naive_delta)
        ratios.append(res.var / res.naive_var)
        lo, hi = interval(res)
        cover += lo <= tau <= hi
    for est in (cu, nv):
        assert abs(statistics.mean(est) - tau) < 4 * statistics.stdev(est) / math.sqrt(r)
    assert abs(statistics.variance(cu) / statistics.variance(nv) - 0.36) < 0.08
    assert abs(statistics.mean(ratios) - 0.36) < 0.01
    assert cover / r >= 0.92


def test_input_checks():
    with pytest.raises(ValueError):
        cuped([1, 2], [1], [1, 2], [1, 2])
    with pytest.raises(ValueError):
        cuped([1], [1], [1, 2], [1, 2])
    with pytest.raises(ValueError):
        cuped([1, 2], [5, 5], [3, 4], [5, 5], "pooled")

History

Analysis of covariance, the regression of an experiment's outcome on the treatment and a covariate measured beforehand, is part of classical experimental design and goes back to Fisher. The control variates method of Monte Carlo integration subtracts a correlated quantity with known mean in the same way. Deng, Xu, Kohavi and Walker (2013) brought the idea to online controlled experiments at Microsoft Bing, with the same metric over the pre-experiment period as the covariate, and named it CUPED; it became standard in the experimentation platforms of large web companies. Freedman (2008) had criticized regression adjustment of experiments for its finite sample bias and possible loss of precision, and Lin (2013) answered that the adjustment with treatment by covariate interactions and robust standard errors is safe in large samples.

References

  1. Alex Deng, Ya Xu, Ron Kohavi and Toby Walker, Improving the sensitivity of online controlled experiments by utilizing pre-experiment data, Proceedings of the Sixth ACM International Conference on Web Search and Data Mining (WSDM), 2013, pp. 123 to 132 (the control variates estimator, the optimal theta and the factor 1 - rho^2)
  2. Winston Lin, Agnostic notes on regression adjustments to experimental data, reexamining Freedman's critique, The Annals of Applied Statistics 7(1), 2013, pp. 295 to 318 (regression adjustment with treatment by covariate interactions cannot hurt asymptotic precision, and the sandwich variance is valid)
  3. David A. Freedman, On regression adjustments to experimental data, Advances in Applied Mathematics 40(2), 2008, pp. 180 to 193 (under randomization, ANCOVA has a bias of order 1/n and can lose precision when arm sizes differ)

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example