Monte Carlo: rejection sampling, importance sampling and variance reduction
Before this lesson: lesson 02 (expectation and inverse-CDF sampling), lesson 03 (the exponential and normal distributions), lesson 06 (the law of large numbers, the CLT and the Monte Carlo error bar), lesson 10 (posteriors known only up to a constant). From foundations: log-sum-exp. Time: about 75 minutes, plus the notebook.
Why this matters #
- Expectations everywhere. A Bayesian prediction is ; a VAE trains on a Monte Carlo estimate of the ELBO; a policy gradient is a Monte Carlo average over trajectories.
- Importance weights in modern ML. PPO's probability ratio, off-policy evaluation in reinforcement learning, the IWAE bound and particle filters are all importance sampling. Speculative decoding in LLM serving is a form of rejection sampling.
- Rare events in science and engineering. The probability that a flood, an earthquake or a structural load exceeds a design level is tiny. Plain sampling needs about draws for 10% accuracy on an event of probability ; importance sampling can cut this by orders of magnitude.
- The bridge to MCMC. When no good proposal exists (high dimension, complex posterior), Markov chain Monte Carlo takes over (lesson 15). Its error bars use the same ideas as here.
1. Predict first #
2. The picture #
Estimate with darts. Throw points uniformly into the square and count the fraction inside the unit disk. The disk covers of the square, so (fraction inside) estimates . Each dart is a coin flip with , so the estimate has standard error .
Press "+1,000" a few times, then "Play". Darts inside the disk are aqua, outside magenta. The blue path is the running estimate ; the orange lines are and the band . Switch the view to "error": on log–log axes the error follows a line of slope . Try "New seed": every path stays mostly inside the band.
The error formula has three levers. The standard error of an average of i.i.d. draws of is , where is the standard deviation of . To make it smaller you can:
- take more samples. This is slow: 4 times the work buys 2 times the accuracy.
- sample from somewhere else. Draw from a proposal that puts points where they matter, and correct with weights (importance sampling).
- make the integrand less variable. Subtract a correlated quantity with a known mean (control variates), or pair each draw with a mirrored twin (antithetic variables).
Weights correct the bias. Suppose the target is but we draw from a wider . Points far out are over-represented, so they get a small weight ; points near 0 are under-represented and get a weight above 1. The weighted average is then correct on average. But if is narrower than , a rare draw in the tail gets an enormous weight and dominates the whole average.
Try the four presets, and press "New seed" several times for each. The target is orange and the proposal is violet. The lower plot shows the normalised weight of each of the 200 draws as a blue stick; the largest is yellow, and the dashed line is the equal weight . The effective sample size (ESS) says how many equally weighted draws the weighted sample is worth. With the "too narrow" proposal, most runs look calm, and then one draw takes most of the weight.
You estimate with darts. About how large is the standard error, and how many darts do you need to make it 10 times smaller?
. The error falls like , so 10 times smaller needs 100 times more darts. The rate does not depend on the dimension; only the constant does.
3. Definitions and main results #
Simple Monte Carlo (recap of lesson 06) #
We want . Draw i.i.d. from and set
Then and with . The law of large numbers gives , and the CLT gives the error bar , where is the sample standard deviation of the (lesson 06).
Rare events. For a probability , take . Then and the relative standard error is
Here is the expected number of hits. For 10% relative error you need about 100 hits, so about draws. The error depends on how many times you see the event, not on alone.
Exact samplers: inverse CDF and rejection #
Importance sampling is easier to understand after two methods that produce exact draws.
Inverse CDF (lesson 02). If and is a CDF, then has CDF (with the generalised inverse for steps and flat parts). For the exponential with rate , . It needs a CDF you can invert; the Gaussian has none in closed form (use Box–Muller, lesson 05, or a numerical inverse).
Rejection sampling. Often you can evaluate the target only up to a constant: , where you know but not . A posterior is the typical case: likelihood times prior is , and is the evidence (lesson 10). Choose a proposal density that you can sample, and a constant with an envelope: for all .
Algorithm: draw and independently. Accept if ; otherwise try again.
Picture: the points are uniform under the graph of . We keep the ones under the graph of . Those are uniform under , so their -coordinate has density proportional to .
Theorem (rejection sampling is exact). An accepted has density . Each trial is accepted with probability , so the number of trials per accepted sample is geometric with mean .
Proof.
- Given , the acceptance probability is , a number in because of the envelope.
- For a set : .
- Take = everything: .
- Divide: . So the accepted has density .
- Trials are i.i.d. with success probability , so their number is geometric with mean .
Use the smallest valid . The supremum must be finite, so must have tails at least as heavy as : a Gaussian proposal can never envelope a Cauchy target. If is too small, the envelope dips below and the samples are silently wrong there. A too large is only slow.
Press "+500", then move below 1.65. The target () is orange, the envelope is violet. Proposals under are accepted (aqua), the others rejected (magenta); "Step" shows one proposal in yellow. The histogram compares the accepted samples with the target density. Below a magenta region appears where the envelope is too low, and the histogram misses mass near .
High dimension kills rejection. For the target and the proposal with , the ratio is largest at , so and the acceptance rate is . With and it is . Rejection sampling is a tool for low dimension.
Importance sampling #
Importance sampling keeps every draw from and fixes the bias with weights.
The identity. If wherever , then with the importance weight ,
Estimator. Draw i.i.d. from and set . It is unbiased by the identity. It is an average of i.i.d. terms, so
Estimate the standard error by the sample standard deviation of the terms , divided by .
The best proposal. minimises .
- Only depends on .
- By Jensen (or Cauchy–Schwarz), for every .
- Equality holds when is constant, that is when .
For the best proposal gives zero variance, but it needs the unknown . The practical lesson: put the proposal where is large. For the rare event , that region is just above , so shift the proposal there.
Press "Run again" several times, then move the threshold . The chart shows running estimates divided by the true value, so the target is the orange line at 1. Plain Monte Carlo (blue) is 0 until its first hit, then jumps. Importance sampling with (aqua) settles near 1 after a few hundred draws. Dashed lines are relative standard errors from the theory. At the variance ratio is about 7,000.
Why the proposal needs heavier tails. Take and . Then and
When , the weight grows without bound in the tails: rarely visits them, and a visit gets a huge weight. A heavier-tailed () has bounded weights, . In general the condition is .
Infinite variance is a silent failure. The estimator stays unbiased, and it still converges (the strong law of large numbers needs only ). But there is no CLT error bar, and the sample standard error is itself unreliable. Most runs miss the tail and look stable; for they are usually too small. A rare run jumps.
For you can choose the proposal . For which is the variance of the importance weights finite?
, and is integrable exactly when . So a slightly narrower proposal () still works, with ESS/; at the variance is infinite. Two Gaussians are not automatically a safe pair.
Self-normalised importance sampling #
Often you know only . Use unnormalised weights and
This is self-normalised importance sampling (SNIS).
- is unbiased for , because . For a Bayesian model this is the evidence . Its log is biased low: by Jensen.
- is consistent: the numerator over tends to and the denominator over to .
- is biased, because . With , with , so , not . The bias is , small next to the standard error .
- Its variance is approximately (normalised ; delta method). Estimate it with .
- Numerics. Work with log-weights and compute with , (log-sum-exp). Raw weights overflow or underflow.
The effective sample size #
Definition (Kish).
Where it comes from. Take i.i.d. with variance and fixed weights. The weighted mean has variance . An unweighted mean of draws has variance . Set the two equal and solve for .
Properties. for equal weights, and when one weight dominates. Scaling all weights by a constant does not change it, so is enough. Its population version is (normalised ). For and this is .
The curse of dimension. For and one finds , so the population ESS is . A shift of 0.1 standard deviations in each of coordinates gives and an ESS of . Small mismatches multiply over coordinates, and the weights collapse onto one draw.
A diagnostic, not a guarantee. The ESS uses only the weights, not . A small ESS proves a problem. A large ESS does not prove success: if misses a mode of entirely, all draws can have similar weights and the estimate is still wrong.
Five draws have importance weights . What is the effective sample size?
. The one heavy draw carries half of the total weight, so the five draws are worth about three equally weighted ones. 8 is , which changes when you rescale the weights; the ESS does not.
Variance reduction #
Control variates. Let be a function with a known mean . For any constant ,
is unbiased, because the subtracted term has mean 0.
- Its variance is , a parabola in .
- Set the derivative to zero: , the least-squares slope of on .
- Substitute: the minimum is , where .
With the variance falls to 19%; the sign of does not matter. In practice is estimated from the same draws, which adds a bias of order . It helps when is cheap, strongly correlated with , and has an exactly known mean. This is the same idea as CUPED in A/B testing, where a pre-experiment metric is the control (lesson 12), and as the baseline in a policy gradient.
Antithetic variables. Pair each uniform with (or a Gaussian with ). With evaluations of , use pairs and average .
- , with .
- So the estimator has variance , against for independent draws.
- It helps exactly when .
If is monotone, and move in opposite directions, so and antithetics never hurt. If (symmetric about ), then and the variance doubles. If is linear, the variance is 0.
Move the slider to the bottom of the parabola, then switch "Antithetic pairs" on. The problem is with the control . Top: draws in blue, the line with slope in yellow, the least-squares slope dashed in orange. Bottom: the variance factor of the control-variate estimator as a function of ; its minimum is at . The aqua line is the antithetic factor . Then try : the control is useless and the antithetic pairs double the variance. "Check by simulation" measures both factors.
Answers to section 1. (1) About 50%. The expected number of hits is , so the relative standard error is . With probability there is no hit at all. (2) Proposal A. Its variance is , so : the estimate is unbiased but has infinite variance. Proposal B has bounded weights and an ESS of about .
4. Worked example #
(a) Rejection: a half-normal from an exponential. Target on , with . Proposal (Exponential(1)).
- . Its exponent has derivative , so the maximum is at : .
- Accept with probability .
- Acceptance rate ; on average proposals per sample.
- Proposal with : , accept. Proposal with : , reject.
(b) Importance sampling by hand. Target , proposal , (true value 1). Then . Four draws from :
| 0.446 | 2.000 | 1.375 | 0.068 | |
| 1.785 | 0 | 1.375 | 0.616 |
- Plain IS: .
- SNIS: , so ; and (true ).
- ESS: , so of 4 draws. The draw at 0 alone carries 51% of the normalised weight.
(c) A rare event. for , . Proposal .
- The weight: , so . On the event it is small: .
- Second moment: , where is the standard normal density. Complete the square: , so the integral is .
- Variance per draw: IS ; plain MC .
- Ratio about 7,000. With , the relative standard error falls from 0.56 to 0.0067.
(d) Variance reduction for . Let .
- , so .
- Control (mean , variance ). , so . Then and . The variance falls by the factor 0.031: about 32 times fewer draws.
- Antithetic: , so and . The factor is : about 16 times fewer evaluations. is monotone, so was guaranteed.
You use antithetic pairs to estimate for . Compared with the same number of independent evaluations, the variance of the estimate is
, so each pair contains the same value twice: and the factor . You pay for two evaluations and get the information of one. Antithetic pairs help only when and are negatively correlated, for example for monotone .
5. In code #
The notebook asks you to write the samplers and estimators yourself. Here NumPy and SciPy check the numbers of sections 3 and 4 by simulation, with draws each.
import numpy as np
from scipy import stats
rng = np.random.default_rng(0)
n = 100_000
# Simple Monte Carlo: pi with a CLT error bar
u = rng.uniform(-1, 1, size=(n, 2))
f = 4 * (np.sum(u**2, axis=1) <= 1)
print(f"{f.mean():.4f} +- {2 * f.std(ddof=1) / np.sqrt(n):.4f}") # 3.1471 +- 0.0104
# Rejection: half-normal target exp(-x^2/2) on [0, inf), Exp(1) proposal, M = e^{1/2}
x = rng.exponential(size=n)
keep = rng.uniform(size=n) <= np.exp(-(x - 1)**2 / 2) # p~ / (M q)
print(round(keep.mean(), 3), round(stats.kstest(x[keep], stats.halfnorm.cdf).pvalue, 2)) # 0.757 0.62
# Importance sampling for P(X > 4) with q = N(4, 1)
mu = stats.norm.sf(4)
plain = (rng.standard_normal(n) > 4).astype(float)
xq = 4 + rng.standard_normal(n)
wf = np.exp(-4 * xq + 8) * (xq > 4) # w = p/q times the indicator
for name, v in [("plain", plain), ("IS", wf)]:
print(name, f"{v.mean():.3e} rel. SE {v.std(ddof=1) / np.sqrt(n) / mu:.4f}")
print(f"exact {mu:.3e}")
# plain 5.000e-05 rel. SE 0.7060 (5 hits)
# IS 3.176e-05 rel. SE 0.0067
# exact 3.167e-05
# Self-normalised IS with log-weights: E[X^2] = 1 under p = N(0, 1), q = N(0, 2^2)
xs = 2 * rng.standard_normal(n)
logw = stats.norm.logpdf(xs) - stats.norm.logpdf(xs, scale=2)
wbar = np.exp(logw - logw.max()); wbar /= wbar.sum()
print(round(np.sum(wbar * xs**2), 3), round(1 / np.sum(wbar**2) / n, 3)) # 0.997 0.661
# Control variate and antithetic pairs for ln 2 = E[1/(1+U)], same number of evaluations
U = rng.uniform(size=n)
h = 1 / (1 + U)
beta = np.cov(h, U)[0, 1] / np.var(U, ddof=1)
cv = h - beta * (U - 0.5)
anti = 0.5 * (1 / (1 + U[: n // 2]) + 1 / (2 - U[: n // 2])) # n/2 pairs = n evaluations
print(round(beta, 3), round(cv.var() / h.var(), 3), round(2 * anti.var() / h.var(), 3)) # -0.477 0.031 0.061
In this run plain Monte Carlo saw 5 hits instead of the expected 3.2, so its estimate is 58% too high; its sample standard error is itself noisy. Importance sampling is within 0.3% of the exact value.
6. Where it shows up #
- Speculative decoding in LLMs (ml-systems 12). A small draft model proposes a token ; the large model accepts it with probability . On rejection it samples once from the normalised residual . The accepted part has mass and the residual part ; they add up to , so the output distribution is exactly the large model's.
- Importance weights in reinforcement learning. Off-policy evaluation reweights returns by (RL 04). PPO's probability ratio is an importance weight that is clipped to control its variance (RL 09).
- Variational inference. The IWAE bound is with draws from the encoder: biased low by Jensen, and tighter as grows (generative models 01).
- Particle filters and data assimilation. A particle filter is sequential SNIS: weight the ensemble members by the likelihood of new observations, and resample when the ESS drops (a common rule is ). In high-dimensional weather models the weights collapse onto one member unless the ensemble grows exponentially with the effective dimension. This is one reason weather centres use ensemble Kalman and variational methods instead (ml-for-science 06).
- Rare events in science. Seismic hazard (the probability that ground motion at a site exceeds a design level), extreme rainfall, failure of a structure. A proposal shifted toward the event, as in (c), cuts the cost by orders of magnitude.
- Control variates. The baseline in REINFORCE (RL 07, calculus 12). Multi-fidelity Monte Carlo uses a cheap emulator, whose mean is known from many cheap runs, as the control for an expensive simulator.
- Antithetic sampling. Mirrored noise in evolution strategies and in finite-difference gradient estimators.
7. Common mistakes #
- A proposal with lighter tails than the target. The weights have infinite variance; the estimate looks stable for many runs and then jumps. Check , or use a heavy-tailed proposal (a Student , a wider Gaussian, or a mixture with a broad component).
- Forgetting the support condition. If where , plain IS is biased. SNIS needs wherever .
- Weights in linear space. overflows or underflows in high dimension. Use log-weights and log-sum-exp.
- Trusting a large ESS. It cannot see a mode that no draw visited.
- Using the plain-IS standard error for SNIS. Use , not the sample variance of .
- A rejection envelope that is too low. If somewhere, the samples are silently wrong there. A too high is only slow.
- Reporting a rare-event estimate with too few hits. With 3 expected hits, the estimate is often 0 or off by a factor 2. Count the hits; aim for at least 100, or use importance sampling.
- Antithetic pairs for a symmetric integrand. For they double the variance.
- A control variate whose mean is only estimated. The error of that estimate adds directly to the error of ; must be known exactly, or far more precisely than .
8. Check yourself #
- You sample by rejection from a standard Cauchy proposal . Find and the
acceptance rate. Can you sample a Cauchy target from a Gaussian proposal?
Answer
. The derivative of is , so the maximum is at : . Acceptance rate (normalised target, ). The reverse is impossible: Cauchy/Gaussian in the tails, so no finite exists. - How many plain Monte Carlo draws do you need to estimate for with
10% relative standard error?
Answer
Relative SE gives , so draws (the exact formula gives about 73,980). - Show that SNIS is biased with a one-line example. Why is it still used?
Answer
With , with , so in general. It is used because it needs only up to a constant (posteriors, energy-based models), it is consistent with an bias, and the same weights estimate . - For and , for which is the IS variance of the estimate of finite?
Answer
The second moment is with . This is integrable (also times ) exactly when , that is . - For which of , , do antithetic pairs help?
Answer
: , so the variance is 0. : monotone, so and it helps a lot (). : symmetric, , so the variance per evaluation doubles. - A control variate has correlation with . How many times fewer draws do you need? And if ?
Answer
The variance factor is , so about times fewer draws. The sign does not matter: takes the sign of the covariance.
What is the standard error of the plain Monte Carlo estimate of from i.i.d. draws?
, estimated by ; it does not depend on the dimension of .
What is the relative standard error of plain Monte Carlo for an event of probability ?
, one over the square root of the expected number of hits.
In rejection sampling, when do you accept a proposal , and what is the acceptance rate?
Accept if with ; the acceptance rate is .
Write the importance sampling estimator of .
with ; it is unbiased if wherever .
Why must an importance sampling proposal have heavier tails than the target?
The variance contains ; if decays faster than , the weights blow up in the tails and this integral is infinite.
What is the self-normalised IS estimator, and is it unbiased?
with ; it is biased () but consistent.
Define the effective sample size of importance weights.
: equal to for equal weights, close to 1 when one weight dominates.
What is the optimal coefficient of a control variate, and the resulting variance factor?
; the variance is multiplied by , .
When do antithetic variables reduce the variance, and when do they increase it?
The factor is : it helps for monotone (negative correlation) and doubles the variance for symmetric about .
9. Interview angle #
- "Estimate with a random number generator. How accurate is it?" — Fraction of points in the disk times 4; standard error .
- "You have a density up to a constant. How do you sample it?" — Inverse CDF in 1-D if you can integrate and invert; rejection with an envelope in low dimension; otherwise MCMC (lesson 15), or SNIS if you only need expectations.
- "Why does importance sampling fail in high dimension?" — The variance of the weights grows exponentially with the dimension (ESS for a mean shift ), so one weight dominates.
- "Why is speculative decoding exact?" — Accept with and, on rejection, sample from the normalised residual ; the two parts add up to .
- "Importance sampling or MCMC for a posterior?" — IS from a Laplace or variational approximation with heavier tails when the dimension is low and a good proposal exists: independent draws, the evidence and a weight diagnostic. MCMC when the posterior is high-dimensional or has a shape no simple proposal covers.
- "What is a baseline in policy gradients?" — A control variate: subtracting keeps the estimator unbiased because , and reduces the variance when is close to the optimal value; a bad can increase it.
10. Practice #
The notebook for this lesson has five exercises, each with a check cell and a folded solution:
log_sum_expandeffective_sample_sizefrom log-weights, stable for weights like .importance_samplingfor with its standard error, compared withscipy.stats.norm.sf.self_normalized_ison the unnormalised mixture (so ): the mean, and .- A rejection sampler for the half-normal with an Exp(1) proposal: the acceptance rate against the optimal .
control_variate_meanandantithetic_mean, with their variance-reduction factors for .
11. Watch and read #
- Art Owen, Monte Carlo theory, methods and examples (free chapters): ch. 2 (simple Monte Carlo), ch. 4 §4.1–4.4 (inversion) and §4.7 (acceptance–rejection), ch. 8 §8.2 (antithetics) and §8.9 (control variates), ch. 9 §9.1–9.3 (importance sampling, self-normalisation, the ESS).
- Kevin Murphy, Probabilistic Machine Learning: Advanced Topics (free PDF): ch. 11 (Monte Carlo methods: inverse CDF, rejection sampling, importance sampling, variance reduction).
- Yaniv Leviathan, Matan Kalman and Yossi Matias, Fast Inference from Transformers via Speculative Decoding (2023): rejection sampling at the scale of LLMs.
- Yuri Burda, Roger Grosse and Ruslan Salakhutdinov, Importance Weighted Autoencoders (2016): importance sampling inside a variational bound.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.