The sample-size lesson ended on a cost: detecting 10% going to 12% takes 3,839 users per arm, and the metric's variance sets that number. CUPED cuts it with data the test already has, each user's history from before it started. The 2013 paper that introduced it, by a team at Microsoft, reports for Bing: "we can reduce variance by about 50%, effectively achieving the same statistical power with only half of the users, or half the duration." Our version of the practice reads like this:
Each user has y, their metric during the test, and x, the same metric over the weeks before it. Write cuped(y, x): return the adjusted metric, which keeps the mean of y and has the least variance any adjustment y - theta * (x - mean(x)) can give, and the theta it used. Then read a test with it.
The practice comes in four levels. Level 1 writes cuped. Level 2 writes cuped_effect(y, x, t): the difference in adjusted means and its standard error, from one call on both arms. Level 3 keeps the users with no history, whose x is missing. Level 4 writes lin_effect, with one theta per arm.
You don't write it yet. The lesson starts with what less variance buys, finds the best θ, shows why the estimate stays unbiased, then runs CUPED on a test and answers the follow-ups. At the end you solve the whole problem, level by level, in an interview simulation with a 40-minute timer.
This lesson builds on the A/B test lesson's comparison of two means and on the sample-size formula, where the variance sits on top. The cluster-randomized lesson comes next, for tests where the unit you randomize isn't the unit you measure.
Less variance buys a narrower interval and fewer users
Start with what a smaller variance buys, in interval width and in users.
Predict
Cut a metric's variance in half. How wide is the test's interval now?
One test read twice, the raw metric and one with half the variance
variance 1.0
variance 0.571% as wide
-2-1012
raw SEs
An A/B test compares two means and puts an interval on the difference. Take two equal groups of n users and a metric whose standard deviation per user is σ. The standard error of the difference is
SE=σn2
In words: the spread per user, times the square root of 2 over the users in each group.
The interval is ±1.96SE, so its width grows in step with σ. Halve the variance and σ falls to 0.5=0.71 of what it was. That's the narrower interval in the figure.
The users you need grow faster: with the variance itself. Power is the chance that a real effect comes out significant. To detect an effect δ with a two-sided 5% test at 80% power, each group needs
n=δ22(z0.975+z0.8)2σ2≈δ215.7σ2
In words: z0.975=1.96 is the bar a result has to clear. z0.8=0.84 adds the room so that, when the true effect is δ, 80% of tests clear it. Their sum, 2.80, squared and doubled, is 15.7. For a conversion rate, σ2=p(1−p). The sample-size lesson builds this formula.
The part to hold on to is σ2 on top. Cut the variance in half and you need half the users, or half the days.
In the editor, write savings(variance_kept): the share of the users and the share of the interval's width that a variance cut leaves.
Each user also brings a number from before the test
The variance CUPED removes is visible in a second number each user already has.
Predict
Which covariate usually cuts the most variance?
One user, two numbersInteractive
→
→
the weeks before the test = x is measured here.
Every user brings two numbers. Y is the metric during the test. X is a covariate: a number about the same user, measured before the test began. The usual X is the same metric over the weeks before, which the paper found tends to give the biggest reduction.
You can't make users less different from each other. But much of how they differ was visible before the test started. A user who was busy last month will probably be busy this month, in either group.
That part of the spread was settled before anyone was assigned, so it can't carry any of the effect. It can only hide it. CUPED, short for Controlled-experiment Using Pre-Experiment Data, predicts that part from X and subtracts it.
Pick an answer above to see the rest
Last week's sessions predict this week's
Here are eight users, the same eight as in the worked example. x is each user's sessions in the week before the test, and y their sessions in the test's first week.
import numpy as np# sessions, the week beforex = np.array([2.0, 4, 6, 8, 4, 6, 8, 10])# sessions, the test weeky = np.array([2.0, 4, 5, 7, 6, 8, 7, 9])print(np.corrcoef(x, y)[0, 1].round(3))
Predict
How strongly do the eight users' x and y move together?
Pick one to see what it prints.
That's the correlation of x and y: 1 for points on a rising straight line, 0 for no straight-line link at all. The correlation in a sample is written r. It estimates the true one, written ρ (rho). 0.866 is high. Here are the eight users, with the straight line that fits them best.
Pick an answer above to see the rest
Predict
The line expects 6 sessions from both users at x = 6. The treatment user did 8 and the control user 5. What does CUPED keep for each?
C4 and T3 both sit at (8, 7). The two users at x = 6 show their distance from the line.
The line is the least-squares line: the one that makes the sum of the squared vertical distances to the points as small as possible. It rises 0.75 test-week sessions for each extra session the week before.
The distances from the line are the surprises. The rest of each user's y, the part on the line, was predictable from x.
In the editor, write correlation(x, y) from sums, the 0.866 that np.corrcoef printed.
The adjusted metric keeps each user's distance from the line, plus the mean
Take 0.75, the line's slope, times each user's distance from the average x, and subtract it from y. adjust(y, x, theta) does that, and you write it at the end of this step:
Subtract 0.75 × (x - mean of x) from each y. What happens to the mean and the variance?
Pick one to see what it prints.
Each adjusted value is the mean, 6, plus that user's distance from the line: the treatment user at x=6 gets 6 + 2 = 8, and the control user there gets 6 - 1 = 5.
That's CUPED. It replaces Y with
Ycv=Y−θ(X−Xˉ)
In words: take each user's Y and subtract θ (theta) times how far their X sits from the average X, written Xˉ. θ is a number you choose. The best one is the line's slope, and the next chapter shows why. Then you run the same test on Ycv. The subscript stands for control variate, the Monte Carlo technique the paper borrows.
Here is the eight users' spread, before and after:
Each user's test-week sessions, raw and adjusted
mean 6
raw yvariance 4.5
adjustedvariance 1.125
246810
sessions
controltreatment
Read the formula as: keep only the surprise. The busy users came down and the quiet ones came up, so the eight values bunch around the same mean.
Three details decide whether it works, and each one is a line of the practice problem: the value of θ, centering X, and measuring X before the test.
In the editor, write adjust(y, x, theta): the formula, for any theta.
CheckpointSubtract the predictable part
Write adjust(y, x, theta): Ycv=Y−θ(X−Xˉ) for arrays y and x of the same length and a given theta.
Pick an answer above to see the rest
Part 1 done
Part 2 of 5about 15 min
The best θ
Search θ for the least variance
Try a range of θ on the eight users and print the variance each one leaves, with a bar to show its size:
for theta in [0, 0.25, 0.5, 0.75, 1, 1.25, 1.5]: v = (y - theta * (x - x.mean())).var() print(f"{theta:.2f} {'█' * round(8 * v):<36} {v:.3f}")
Predict
Try θ from 0 to 1.5 on the eight users. Where is the variance lowest?
Pick one to see what it prints.
'█' * k repeats the block k times, 8 blocks per unit of variance. θ=0 is no adjustment at all.
That U holds for any data. Write σX2 and σY2 for the variances of X and Y, and σXY for their covariance: the average, over users, of the product of their two distances from the means. Subtracting the constant θXˉ doesn't change a variance, so set it aside. What's left is
Var(Y−θX)=σY2−2θσXY+θ2σX2
In words: a parabola in θ that opens upward. Its lowest point is at
θ∗=σX2σXY=Var(X)Cov(X,Y)
the covariance over the variance of X. The star marks the best θ.
θ∗ is a number you already know. It's the least-squares slope of Y on X, the line in the scatter. On real data you don't know the true covariance and variance, so you estimate θ from the users in the test: their covariance over their variance of x, which is the fitted slope.
That's the whole practice problem in three lines. np.polyfit(x, y, 1)[0] is the slope of the least-squares line, as a check, and it agrees.
Read the theta line inside out. xc * (y - y.mean()) multiplies each user's two distances from the means, and .sum() adds them up. The bottom does the same with xc against itself. That's the covariance over the variance with the count left off both, since it would cancel. float makes the result a plain Python number.
In the editor, write lowest_theta(y, x, thetas): the bottom of the U, found by trying each value.
r² is 0.75 on the eight users. What share of the variance does CUPED leave?
Pick one to see what it prints.
On the eight users the squared correlation is 0.75, and the variance left is 0.25=1−0.75. That's no accident. Put θ∗ back into the parabola, with the correlation ρ=σXY/(σXσY), and what's left is
Var(Y−θ∗X)=σY2(1−ρ2)
In words: the line explains a share ρ2 of the variance of Y, and CUPED removes exactly that share.
Nothing about the shape of Y was assumed: no normality, no linear model. It's algebra on two variances and a covariance. In a sample, with θ fitted on that same sample, it holds exactly with the sample's r. That's the practice problem's third test.
How much it buys depends on ρ alone. With CUPED, the σ2 in the sample-size formula becomes σ2(1−ρ2):
ρ
Variance left
Users needed
Interval width
0.3
0.91
91%
95%
0.5
0.75
75%
87%
0.7
0.51
51%
71%
0.9
0.19
19%
44%
The interval shrinks with the square root of the variance. So at ρ=0.7, a test that needs half the users still shows an interval 71% as wide. Bing's cut of about 50% corresponds to ρ≈0.71.
A weak covariate buys little: at ρ=0.3 the variance only falls to 0.91. In the sample it can't go up, because θ=0 is a point on the same U and the fitted θ is its floor.
In the editor, write rho_for(variance_left): the correlation a cut needs, such as Bing's half.
A two-minute example of how CUPED uses each user's pre-experiment data to cut the noise in a test, from the experimentation platform Eppo.
What Exactly is CUPED? · Eppo by Datadog · Jul 2022YouTube
Pick an answer above to see the rest
Every wrong θ is a multiple of the right one
A wrong θ still sits somewhere on the same U.
Predict
Besides θ = 0, which θ leaves the variance exactly where it started?
Most bugs in this function leave θ off by some factor m. Put θ=mθ∗ into the parabola:
σY2Var(Y−mθ∗X)=1−ρ2m(2−m)
In words: the share of the variance left is 1 at m=0 and again at m=2, and lowest at m=1. At ρ=0.7:
θ
Variance left
0, no adjustment
1.00
0.5θ∗
0.63
θ∗, the slope
0.51
1.5θ∗
0.63
2θ∗
1.00
3θ∗
2.47
−θ∗, the flipped sign
2.47
Anything between 0 and 2θ∗ helps, and the floor is at the slope itself. At 2θ∗ the variance is back to the raw, as the eight users' bars showed, and past it the adjustment adds noise. Three of the practice problem's broken versions are points on this curve.
In the editor, adjust is ready. Write best_theta(y, x): the bottom of the U, exactly.
CheckpointThe best θ
Write best_theta(y, x), the θ that gives y - theta * (x - x.mean()) the smallest variance. adjust is in the editor. One test uses a two-week pre-period against a one-week metric, so x varies about three times as much as y.
Pick an answer above to see the rest
Part 2 done
Part 3 of 5about 17 min
Unbiased
The estimate stays unbiased when x comes from before assignment
Less variance is only worth having if the estimate still centers on the truth.
Predict
Treatment's users were already 2 sessions heavier before the test, and θ = 0.75. How much of the raw 3-session gap does CUPED take back?
Treatment's mean minus control's, in sessions
0123 sessions
x, the week before
2.0
y, the test week
3.0
y, in two parts
1.5
1.5
the gap in xthe raw gap in ythe head start, 0.75 × 2.0left for the change
A test has two arms, control and treatment: the two groups of the A/B test. On the eight users, treatment's four were already 2 sessions heavier in the week before the test. At θ=0.75, that head start is worth 0.75×2=1.5 sessions in the test week. CUPED takes it back from the raw gap of 3.0 and credits the change with the other 1.5.
In general the test compares arm means. With one θ shared by both arms, the CUPED difference is
Δ^cv=(Yˉt−Yˉc)−θ(Xˉt−Xˉc)
In words: the raw difference between treatment (t) and control (c), minus θ times the gap in their mean X.
The first term is the plain difference, unbiased already. The second has expected value zero, because X was fixed before anyone was assigned. Randomization then gives both arms the same distribution of X, so E[Xˉt−Xˉc]=0 whatever θ is. The paper names this as the reason to use pre-experiment data: it "is guaranteed to be independent of the experiment's effect, which is crucial to avoid biased results."
In any one test the gap isn't zero, and that's the point. Randomization balances X only on average. When treatment happens to draw heavier users, the raw difference overstates the effect, and CUPED takes back θ times the head start. When treatment draws lighter users, it gives the difference back.
In the editor, write head_start(y, x, t, theta): the raw difference, the gap in x, and what's left for the change.
Check the claim the way you'd check any function: simulate it.
rng = np.random.default_rng(0)raw, adj = [], []for _ in range(10_000): # before the test x = rng.normal(10, 1, 1_000) y = 5 + 0.7 * (x - 10) + rng.normal(0, np.sqrt(0.51), 1_000) # random assignment t = rng.random(1_000) < 0.5 # true effect: 0.1 y = y + 0.1 * t # one call, both arms y_adj, _ = cuped(y, x) raw.append(y[t].mean() - y[~t].mean()) adj.append(y_adj[t].mean() - y_adj[~t].mean())print(f"average, raw and CUPED: {np.mean(raw):.2f} {np.mean(adj):.2f}")print(f"variance, CUPED over raw: {np.var(adj) / np.var(raw):.2f}")
Predict
10,000 simulated tests at ρ = 0.7, true effect 0.10. Do the raw and CUPED estimates average the same?
Pick one to see what it prints.
t is an array of True and False, True for the treated users. So y[t] picks their values, and y[~t] picks the rest, since ~ flips every entry. 0.1 * t is 0.1 for the treated users and 0 for the others, because True counts as 1.
X and Y both have variance 1 and correlation 0.7 by construction. Here are the 10,000 estimates of each, on one scale:
The effect each simulated test estimated
true effect, 0.10
raw the middle 95% ran from -0.03 to 0.23
CUPED from 0.01 to 0.19
-0.0500.050.10.150.20.25
Same center, narrower.
Estimating θ from the same data adds a bias of order 1/n
One piece of fine print: you estimate θ from the same data, and that adds a bias of order 1/n, which shrinks in step with one over the number of users. In simulation with a true effect of 1, it was -0.05 at 20 users and -0.0008 at 1,000, where the estimate's standard error was 0.045.
Pick an answer above to see the rest
Center x, so the mean stays where it was
Two details decide whether the numbers on a dashboard still mean anything. The first is centering.
Each arm's mean of the adjusted metric, on the eight users
centered5.25 and 6.75: lift +28.6%
uncentered0.75 and 2.25: lift +200%
01234567
controltreatment
X−Xˉ averages to zero, so subtracting θ(X−Xˉ) leaves the mean of Y exactly where it was. The adjusted metric stays in the original units at the original level: sessions per user still read as sessions per user.
Skip the centering and every value drops by an extra θXˉ compared with the centered version. On the eight users that's 0.75×6=4.5. Both arms drop by the same amount, so the difference between them survives: 1.5 in the figure.
Everything that uses a level breaks: the arm means on a dashboard, and the relative lift, which divides by the control mean. On the eight users the lift jumps from +28.6% to +200%.
In the editor, write arm_readout(y_adj, t): each arm's level and the lift, on both versions of the eight users.
Three ways to compute θ on the eight users. The first two give the slope, 0.75. The third comes out 0.857, which is 8/7 times too big. np.cov(x, y) returns a 2 by 2 grid: the variance of x at [0, 0] and the covariance at [0, 1].
The reason is the divisor. θ is a ratio of two averages over the same users. Write Sxy=∑i(xi−xˉ)(yi−yˉ) for the sum of products and Sxx=∑i(xi−xˉ)2 for the sum of squares. Divide both by the same count and the count cancels:
θ=Sxx/(n−d)Sxy/(n−d)=SxxSxy
Here d is the ddof, short for delta degrees of freedom: the number taken off n in the divisor, 0 or 1. Use different ones on top and bottom and the count doesn't cancel. The defaults make that easy to do by accident:
Call
Divides by
np.cov(x, y)
n−1
np.var(x)
n
statistics.covariance(x, y)
n−1
statistics.variance(x)
n−1
statistics.pvariance(x)
n
The safest version never divides by a count at all: a sum of products over a sum of squares, as cuped does. On the practice data, that, np.cov for both, and statistics.linear_regression(x, y).slope all match np.polyfit(x, y, 1)[0] to within 10−15. The names aren't the point. Any one convention, used on both sides, works.
In the editor, write theta_numpy(y, x) with np.cov for both numbers.
Eight users: θ = 0.75, and a quarter of the variance left
Eight users: C1 to C4 in control and T1 to T4 in treatment. x is each user's sessions in the week before the test, y their sessions in the test's first week, and xc=x−xˉ.
User
x
y
xc
θxc
ycv
C1
2
2
-4
-3.0
5.0
C2
4
4
-2
-1.5
5.5
C3
6
5
0
0.0
5.0
C4
8
7
2
1.5
5.5
T1
4
6
-2
-1.5
7.5
T2
6
8
0
0.0
8.0
T3
8
7
2
1.5
5.5
T4
10
9
4
3.0
6.0
Means.xˉ=48/8=6 and yˉ=48/8=6.
θ. The distances of y from 6 are -4, -2, -1, 1, 0, 2, 1, 3. Multiply each by xc and add: Sxy=16+4+0+2+0+0+2+12=36. The squares of xc add up to Sxx=48. So θ=36/48=0.75.
Adjust.ycv=y−0.75xc, the last column.
Check. The ycv column still averages 6. Its squared distances from 6 add up to 9, against 36 for y, so a quarter is left. The squared correlation is 362/(48×36)=0.75, and 1−0.75=0.25. In the sample the identity is exact.
By arm: the head start takes 1.5 of the raw 3 sessions
xˉ
yˉ
yˉcv
Control
5
4.5
5.25
Treatment
7
7.5
6.75
Difference
2
3.0
1.5
This is the head start from the chapter on the unbiased estimate, worth 1.5 of the raw 3 sessions. Eight users are far too few for a real test. The point here is the arithmetic.
Each bug shows up in these eight users
Run the broken versions on the same eight users:
Dividing by var(y):θ=36/36=1.0. The difference comes out 1.0, and 12 of the 36 is left instead of 9.
Flipped sign: the difference comes out 4.5, the head start added instead of removed. The squares add up to 117, which is 36(1+3×0.75).
No centering: the difference stays 1.5, but the arm means become 0.75 and 2.25, a lift of +200% where the centered means give +28.6%.
Mixed ddof:θ=0.857, which is 8/7 times too big. On 8 users the n/(n−1) factor is easy to see.
In the editor, write sums(y, x): the worked example's three sums, which give θ and r².
On a real test you adjust every user, then compare the arms.
Predict
Why call the function once on all users, rather than once per arm?
Call the function once, on both arms together. Then run the A/B test lesson's test for means on the adjusted metric, with Welch's standard error: each arm's sample variance over its users, added, under one square root. welch_se is the function you write at the end of this step.
# both arms, one cally_adj, theta = cuped(y, x)d = y_adj[t].mean() - y_adj[~t].mean()se = welch_se(y_adj, t)lo, hi = d - 1.96 * se, d + 1.96 * se
One call gives both arms the same θ and the same center, which is what the argument for an unbiased estimate needs. The paper puts it the same way: "the same θ has to be used for both control and treatment," and "The simplest way to estimate it is from the pooled population of control and treatment." In 10,000 simulated tests like the ones in the simulation step, this interval covered the true effect 94.7% of the time.
In the editor, write welch_se(y_adj, t): the standard error that goes with the adjusted difference.
Called once per arm, it keeps the raw difference but shrinks the interval
The tempting shortcut is one call per arm, and it fails quietly.
Control's four users
Mean
x
2
4
6
8
5
from the pooled mean, 6
-4
-2
0
+2
-1
from control's own mean, 5
-3
-1
+1
+3
0
CUPED subtracts θ times these distances. From the pooled center, control's distances average -1, so its mean rises by 0.75×1, from 4.5 to 5.25. From its own center they average 0, and the mean stays at 4.5. Treatment mirrors it: 7.5 falls to 6.75 with the pooled center and stays at 7.5 with its own.
That's what one call per arm does. Each call centers its arm at that arm's own mean of x, so the adjustment sums to zero inside each arm. Each arm's adjusted mean equals its raw mean, and the difference doesn't move at all: 3.0 on the eight users.
The variances still shrink, though, and the standard error with them. So you report the raw estimate with a CUPED-sized interval. In 10,000 simulated A/A tests at ρ=0.7, where both arms got the same experience, that called 15.9% of them significant at a nominal 5%.
In the editor, adjust and best_theta are ready. Write cuped_readout(y, x, t): the difference and the lift from one call on all users.
CheckpointRead the test on the adjusted metric
Finish cuped_readout(y, x, t), where t is True for treated users. Adjust every user with one θ fitted on all of them, then return the difference in adjusted means, treatment minus control, and the relative lift, that difference over the control's adjusted mean.
Part 4 done
Part 5 of 5about 27 min
Follow-ups
What interviewers ask next
These are the questions that follow the practice problem: why the covariate must come from before the test, the link to regression, one θ or two, new users, CUPAC, and why not just subtract last month. Levels 3 and 4 of the practice code two of them.
A covariate measured after assignment can carry part of the effect away
Predict
You use week 1 of a two-week test as the covariate for week 2. What happens?
x measured in
y measured in
Can the treatment move x?
right
the weeks before assignment
the test
no
wrong
week 1 of the test
week 2
yes
The unbiased-estimate argument needs E[Xˉt−Xˉc]=0, and randomization only promises that for things fixed before it happened. A covariate measured after assignment can be moved by the treatment. Then CUPED subtracts part of the effect along with the noise.
Use week 1 of a two-week test as the covariate for week 2, as in the table. In simulation with a true effect of 0.1 in both weeks and θ=0.5, the estimate averaged 0.049. Half the effect was gone.
The paper's own example is a test that makes a search page load faster. Faster pages usually get more clicks, so with clicks as the covariate, "we will end up underestimating the experiment impact on the load-time." The rule is simple: the covariate's window closes before the first user is assigned.
In the editor, write post_period_estimate(effect, theta, effect_on_x): what that mistake costs, on average.
With one θ, CUPED is regression adjustment, up to how θ is fitted
Regress y on an intercept, the treatment flag and x. That model is usually called ANCOVA. Its coefficient on the flag is exactly (yˉt−yˉc)−β^(xˉt−xˉc), where β^, the coefficient on x, is the slope fitted within the arms.
That's CUPED with θ=β^. CUPED's pooled θ is fitted on all users at once, so it also picks up the gap between the arms. In 200 simulated tests of 1,000 users the two estimates never differed by more than 0.004, about 3% of a standard error.
In the editor, write ancova_effect(y, x, t): that regression, to see it part ways with CUPED on the eight users.
Lin (2013): with interactions, adjustment can't hurt precision in large samples
Regression adjustment had a famous critic. In the words of Winston Lin's 2013 reply, Freedman "argued that adjustment can lead to worsened asymptotic precision, invalid measures of precision, and small-sample bias." Lin's answer comes in two parts:
Add the treatment-by-covariate interactions. "OLS adjustment cannot hurt asymptotic precision when a full set of treatment-covariate interactions is included."
Use robust standard errors. "Asymptotically valid confidence intervals can be constructed with the Huber-White sandwich standard error estimator."
A sandwich standard error estimates the variance from the residuals themselves, instead of assuming every user's noise has the same size. The cluster-randomized lesson builds one.
In CUPED terms, the interacted regression is one θ per arm, with both arms centered at the same pooled mean xˉ. Its coefficient on the flag is exactly
(yˉt−θt(xˉt−xˉ))−(yˉc−θc(xˉc−xˉ))
In words: each arm's mean, minus that arm's own slope (θt or θc) times its head start from the pooled mean xˉ.
One pooled θ, or one per arm
Lin's version raises a practical question: one θ or two?
Predict
With a 50/50 split, does one pooled θ do as well as one θ per arm?
With a 50/50 split, the best single θ is the average of the two arms' slopes, which is what the pooled fit estimates. So one pooled θ does as well as two.
Separate ones pay off when the split is lopsided and the treatment changes how y depends on x. In a simulation with 90% of users treated, where x predicted y only under treatment, the pooled θ gave 1.55 times the raw variance, worse than no adjustment at all. The per-arm version gave 1.00. With milder differences the two stay close: 0.73 against 0.72 when the slopes were 0.6 and 0.8.
Per-arm θs need care with the center. Calling cuped once per arm centers each arm at its own mean, the trap from the chapter on running a test. Fit the slopes inside each arm, but measure every head start from the pooled mean. That's Lin's estimator: a slope fitted inside each arm, and one center for both. It matches the interacted regression's coefficient to within 10−13.
In the editor, cuped is ready. Write per_arm_effect(y, x, t): Lin's estimator, with one center for both arms.
Some users arrive in the test with no history at all.
Predict
Some users have no pre-period at all. What do you do with them?
User
x, sessions before
Has history
x as filled in
U1
12
1
12
U2
7
1
7
U3
none: a new user
0
0, or any constant
New users, and users whose cookie changed, have no pre-period, so x is missing. Don't drop them: they were randomized like everyone else, and the effect on them counts.
The paper's fix: "One way to address this is to define another covariate that indicates whether or not a user appeared in the pre-experiment period. With this additional binary covariate, we can set the missing covariate values to be any constant we like." That makes CUPED a regression on two covariates, the last two columns in the table. In NumPy it takes five moves:
np.isnan(x) is True where x is missing, and ~ flips it, so has = ~np.isnan(x) is the has-history flag.
np.where(has, x, 0.0) keeps x where the flag is True and puts the constant, 0, everywhere else.
Center both covariates, the filled x and the flag, by subtracting each one's mean. np.column_stack([a, b]) makes them the two columns of a matrix C.
np.linalg.lstsq(C, y - y.mean(), rcond=None)[0] gives the least-squares coefficients for predicting y's distance from its mean from those columns, one per column. The first is the slope on x.
C @ coefs is each user's predicted part. Subtract it from y.
The flag gives users without history their own level, like a separate stratum, and the slope on x is fitted on the users who have one. The constant really doesn't matter: fill with 0 or with 123 and the adjusted values agree to within 10−12.
Without the flag it does matter. In a simulation with 30% new users, the flag version cut the estimate's variance to 0.43 of raw, against 0.46 for zeros alone and 0.80 for filling in the returning users' mean.
In the editor, write cuped_new_users(y, x): the flag version, on eight users, three of them new.
Sometimes there's no past value of the metric at all.
Predict
There's no past value of the metric to use as x. What can serve instead?
CUPED needs a past value of the same thing, and sometimes there isn't one. DoorDash hit this in logistics experiments. Its engineers wrote that pre-experiment data doesn't exist at the level of a single delivery the way it does for a market-level or customer-level test.
Their answer was CUPAC, Control Using Predictions As Covariates. Train a model on pre-experiment data to predict y from features the treatment can't move. Then use the model's output as x, as a control variable.
Nothing else changes: the prediction goes into the same function, and the variance falls to 1−Corr(y^,y)2 of the raw, where y^ is the prediction. One model can fold many features, their curves and their interactions into a single covariate.
The rules carry over: features the treatment can't move, and a model trained on data from before the test, so it never sees the outcomes it adjusts. DoorDash reports that CUPAC let it shorten its switchback tests, which switch each region between control and treatment in random time windows, by more than 25% with the same power.
In the editor, write variance_left(pred, y): what a model's prediction buys as the covariate.
Subtracting last month's number is θ = 1, the best θ only when the slope is 1
The simplest adjustment of all is to subtract last month's number.
Predict
Subtracting last month's number is θ = 1. At ρ = 0.5, with x and y on the same scale, how much variance does it save?
θ=1, the change from the pre-period, is unbiased for the same reason CUPED is. But it's the best θ only when the slope happens to be 1. With X and Y on the same scale, its variance is 2(1−ρ) of the raw:
ρ
Variance left, θ=1
Variance left, fitted θ
0.3
1.40
0.91
0.5
1.00
0.75
0.7
0.60
0.51
0.9
0.20
0.19
At ρ=0.5 it saves nothing, and at ρ=0.3 it adds 40% while CUPED removes 9%. The fitted slope is never worse, because it's the bottom of the parabola and θ=1 is just another point on it.
In the editor, write left_at_theta_one(rho) and left_at_fitted(rho): the table's two columns.
That's every piece of the practice problem, and every follow-up it lists. The simulation asks for all three functions under a timer, so rehearse the order once.
Check yourself
5 questions
1.The pre-period metric has a correlation of 0.8 with the test-period metric. With CUPED, about what share of the original sample size does the test need for the same power?
2.On the practice data your adjusted metric comes out with 2.65 times the raw variance, while its mean and θ are both right. What did you write?
3.In a simulation, x is each user's sessions over the two weeks before the test and y their sessions in the test's one week, so var(x) is about 3 times var(y). You compute theta as cov(x, y) / var(y). What happens?
4.You compute theta = np.cov(x, y)[0, 1] / np.var(x) on the practice data's 1,000 users. Which test fails, and why?
5.Your function returns y - theta * x, with no centering, and you call it once on both arms. Which number is still right?
“CUPAC is inspired by the CUPED methodology pioneered at Microsoft (Deng, Xu, Kohavi, & Walker, 2013), extending it to leverage machine learning predictions built using inputs unaffected by experiment intervention.”