Before this lesson:lesson 04 (the chain rule),
lesson 05 (what autodiff can and cannot see),
lesson 10 (expectations as integrals, Monte Carlo,
sampling paths such as x=μ+σϵ). It helps to know Monte Carlo estimates and their
variance from the probability and statistics track; we repeat what we need.
Time: about 75 minutes, plus the notebook.
Many objectives in ML are expectations over a distribution that depends on the parameters:
F(θ)=Ex∼pθ[f(x)]=∫pθ(x)f(x)dx.
In a VAE, the encoder parameters define the distribution qϕ(z∣x) of the latent code.
In reinforcement learning, the policy parameters define the distribution of actions and
trajectories. RL fine-tuning of language models samples tokens from the model itself.
Variational inference, the tuning of a stochastic simulator, and every discrete choice
(a token, an architecture, a molecule) have the same form.
F almost never has a closed form, so we need an unbiased Monte Carlo estimate of ∇F. The
two basic estimators can differ in variance by orders of magnitude, and each one needs different
conditions. This choice often decides whether training works at all.
Note the contrast with an ordinary training loss Ex∼data[ℓ(θ;x)], or with the
noise in diffusion-model training. There the distribution does not depend on θ, and you just
average ∇θℓ. The problem of this lesson starts when θ changes the distribution.
Notation. In this lesson ϵ is the random noise of a sampling path (for example
ϵ∼N(0,1)). It is not the machine epsilon of lesson 07.
The function stays, the weights move.F(θ) is a weighted average of the values f(x),
with weights pθ(x). The function f does not depend on θ. When θ changes, the density
moves under f, and the average changes.
Interactive figure: loading…
Move θ. The density pθ of N(θ,1) (aqua) slides under the fixed
function f (black). The lower chart shows F(θ) and its tangent. Choose the
step function f(x)=1[x>1]: its slope is 0 everywhere except at the jump, but F still
has a positive slope. The slope of F comes from the moving density, not from the slope of f.
Why you cannot backpropagate through a sample. Look at how a program computes an estimate of
F(θ):
Draw x1,…,xN from pθ. The program receives N numbers.
Compute F^=N1∑nf(xn).
Call autodiff on F^.
In step 1 the link between θ and the numbers xn is hidden inside the random number
generator. Autodiff (lesson 05) differentiates only the
operations it records. It sees f(xn) with constants xn, so it returns 0 (or an error). The
gradient of F is not 0. We need another way to express how the samples depend on θ. There
are two ways.
Way 1: change the weights (the score function). The simplest case is a coin: x∈{0,1} with
P(x=1)=θ. Then F(θ)=θf(1)+(1−θ)f(0) and F′(θ)=f(1)−f(0). The samples are
0 or 1. They cannot move; only their probabilities change. Write the change of each probability
relative to the probability itself: ∂θlogpθ(x). It is 1/θ for x=1 and
−1/(1−θ) for x=0. Then
The factor ∂θlogpθ(x) is the score. A one-sample estimate is: draw x, report
f(x) times the score. It uses only the valuef(x).
Way 2: move the points (the pathwise gradient). The simplest case is a Gaussian location. You
can produce x∼N(μ,1) as x=μ+ϵ with ϵ∼N(0,1). Keep ϵ fixed: a change
of μ moves the point x by the same amount. So F(μ)=Eϵ[f(μ+ϵ)] and
F′(μ)=Eϵ[f′(μ+ϵ)]. A one-sample estimate is: draw ϵ, report
f′(μ+ϵ). It uses the slope of f.
Interactive figure: loading…
Two pictures of the same samples. In "move the points", each sample is
xi=μ+σϵi with fixed noise ϵi: change μ or σ and every
sample slides along its own path (grey dots: the positions at μ=0,σ=1).
In "reweight the points", the samples stay where they were drawn at μ=0,σ=1, and their
weightspθ(xi)/pθ0(xi) change. The derivative of the weight at θ0 is
the score. Notice that far from θ0 a few weights become very large.
Same mean, different noise. Take f(x)=x, so F(μ)=μ and F′(μ)=1.
Pathwise: f′(x)=1 for every sample. The variance is 0.
Score function: the score of N(μ,1) is x−μ=ϵ. The estimate is
xϵ=(μ+ϵ)ϵ=μϵ+ϵ2. Its mean is 0+1=1, correct. Its variance is
μ2Var(ϵ)+Var(ϵ2)=μ2+2 (the cross term 2μE[ϵ3]=0).
The score-function estimate multiplies the value of f by a random factor with mean zero. The
larger ∣f∣ is, the larger the noise, even when the slope of f is the same everywhere.
Quick check
A coin gives x=1 with probability θ=0.3 and x=0 otherwise. The reward is f(1)=5 and f(0)=2. What is F′(θ) for F(θ)=E[f(x)]?
Why.
F(θ)=5θ+2(1−θ), so F′(θ)=5−2=3 for every θ.(2.9 is F(0.3), the value, not the slope.) The samples cannot move, but their probabilities change, and the score function captures exactly this: 0.3⋅5⋅0.31+0.7⋅2⋅0.7−1=5−2=3.
Quick check
You sample x=μ+σϵ with ϵ∼N(0,1) and f(x)=x2. What is the one-sample pathwise estimate of ∂F/∂μ?
Why.
The chain rule along the path gives f′(x)∂x/∂μ=2x⋅1.2xϵ is the pathwise estimate for σ (because ∂x/∂σ=ϵ).x2ϵ/σ is the score-function estimate. 2μ is the exact gradient, which is the mean of 2x, not a sample.
Setup.θ∈Rk are the parameters. pθ is a density (or a probability mass function)
on Rd.f:Rd→R does not depend on θ.F(θ)=Epθ[f(x)].
A gradient estimator is a random vector g^ computed from samples. It is unbiased if
E[g^]=∇F(θ). The average of N independent copies has the same mean and 1/N
times the covariance. So, at equal cost per sample, the number to compare is the per-sample
variance: to reach a standard error s you need about N=variance/s2 samples.
The score is sθ(x)=∇θlogpθ(x)∈Rk. It is a gradient with respect to the
parameters.
Lemma 1. If pθ(x) is differentiable in θ and ∇θ can be moved inside the integral,
then Epθ[sθ(x)]=0.
Proof.
Where pθ(x)>0, the derivative of the log gives ∇θpθ(x)=pθ(x)∇θlogpθ(x).
This is the log-derivative trick.
So E[sθ]=∫pθ∇θlogpθdx=∫∇θpθdx.
Swap ∇ and ∫: this is ∇θ∫pθdx=∇θ1=0.■
In words: the total probability is always 1, so the changes of the probabilities cancel on average.
For the coin: θ⋅θ1+(1−θ)⋅1−θ−1=1−1=0. The covariance of sθ is the
Fisher informationI(θ).
∇θF=∇θ∫pθ(x)f(x)dx=∫f(x)∇θpθ(x)dx, by (iii) and because f
does not depend on θ.
By (ii), every x with ∇θpθ(x)=0 has pθ(x)>0. There the log-derivative trick
gives ∇θpθ=pθ∇θlogpθ.
Hence ∇θF=∫pθ(x)f(x)sθ(x)dx=E[f(x)sθ(x)].■
The estimator is g^=N1∑nf(xn)sθ(xn) with xn∼pθ. For discrete x, replace
the integral by a sum; the proof is the same.
What it does not need:f can be discontinuous, a black box, or a reward from a simulator, and
x can be discrete. What it needs: samples from pθ, and the gradient of the normalized
log-density. If you only know p~θ=Z(θ)pθ, then ∇logp~θ is off by
∇logZ(θ).
Why condition (ii) matters. Take x∼Uniform(0,θ) and f(x)=x. Then F=θ/2 and
F′=1/2. On the support, logpθ=−logθ, so sθ=−1/θ and
E[fsθ]=−(θ/2)/θ=−1/2. This has the wrong sign. The Leibniz rule shows what is
missing. Write F(θ)=∫0θx⋅θ1dx. Its derivative has two parts:
The boundary term comes from the support that moves with θ. The score only sees the interior
term.
Interactive figure: loading…
Where does the probability go? When θ grows by Δθ, the density on [0,θ] goes down
(magenta: the change of the weights, which the score sees) and a new strip
[θ,θ+Δθ] gets probability (blue: the boundary term, which the score
misses). Compare the two Monte Carlo estimates with the exact slope. Try f=1: the true slope is
0, but the score-function estimate is −1/θ.
Theorem 2 (baselines keep the estimator unbiased). Let b not depend on x: a constant, a
function of θ, or an average of other, independent samples. Then
E[(f(x)−b)sθ(x)]=∇θF.
Proof.E[bsθ(x)]=E[b]E[sθ(x)]=0, by independence and Lemma 1. ■
So we may subtract any such b from f. The mean stays the same; the variance changes. A good b
makes f(x)−b small, so the random factor sθ(x) is multiplied by a smaller number.
Best constant baseline (scalar θ). The per-sample variance is
V(b)=E[(f−b)2sθ2]−(F′)2. It is a parabola in b. Set its derivative to zero,
−2E[(f−b)sθ2]=0:
b∗=E[sθ(x)2]E[f(x)sθ(x)2].
In practice b≈E[f] (a running mean, or the mean of the other samples) is close to b∗
when f and sθ2 are only weakly correlated. Each coordinate of θ may have its own b.
A baseline built from the same samples
With K samples, a common choice is the mean fˉ of all K values as the baseline of sample i.
This mean contains fi itself, so it depends on xi. A short computation gives
fi−fˉ=KK−1(fi−fˉ−i), where fˉ−i is the mean of the other K−1
values. So this estimator is KK−1 times the leave-one-out estimator, and its mean is
KK−1∇F: the direction is right, the length is not. The leave-one-out mean fˉ−i
keeps the estimator unbiased (this is the RLOO estimator in RL).
Quick check
You add a constant c to f in the score-function estimator f(x)sθ(x). What happens?
Why.
The new estimate is fsθ+csθ. Its mean changes by cE[sθ]=0 (Lemma 1). The variance changes by 2cE[fsθ2]+c2E[sθ2], which is large for large ∣c∣. A baseline uses this freedom in the other direction: it picks c=−b to make the variance small.
Theorem 3 (pathwise gradient; the reparameterization trick). Assume
(i) there is a base distribution p(ϵ) that does not depend on θ, and a map g(ϵ,θ), such
that x=g(ϵ,θ) with ϵ∼p(ϵ) has the distribution pθ (a sampling path);
(ii) θ↦g(ϵ,θ) is differentiable for each ϵ, and f is differentiable
(continuously differentiable is enough; a Lipschitz f also works when x has a density,
because such an f is then differentiable at x with probability 1);
(iii) ∇θ and Eϵ can be swapped.
Then
∇θF(θ)=Eϵ[(∂θ∂g(ϵ,θ))⊤∇xf(g(ϵ,θ))],
where ∂g/∂θ is the d×k Jacobian of g with respect to θ.
Proof.
By (i), x and g(ϵ,θ) have the same distribution, so F(θ)=Eϵ[f(g(ϵ,θ))]
(the expectation of a function of a random variable, lesson 10).
The distribution of ϵ does not depend on θ. Now θ appears only inside the integrand.
By (iii), ∇θF=Eϵ[∇θf(g(ϵ,θ))].
The chain rule (lesson 04) gives
∇θf(g(ϵ,θ))=(∂g/∂θ)⊤∇xf(x) at x=g(ϵ,θ).■
The trick moves the randomness into ϵ, which does not depend on θ. Then the sample is an
ordinary differentiable function of θ, and autodiff can follow it.
Gaussian case.x=μ+σ⊙ϵ with ϵ∼N(0,Id) and θ=(μ,σ):∇μ=∇xf(x) and ∇σ=∇xf(x)⊙ϵ. With a full covariance Σ=LL⊤ and
x=μ+Lϵ:∇L=∇xf(x)ϵ⊤. These are the sampling maps of lesson 10, but here
g need not be invertible.
Why condition (ii) matters. Take x∼Exp(λ) (density λe−λx for x>0) and the
step f(x)=1[x>1]. Then F(λ)=P(x>1)=e−λ and F′(λ)=−e−λ. The path
is x=ϵ/λ with ϵ∼Exp(1). But f′(x)=0 for every x=1, so the pathwise
estimate is 0 with probability 1: it is biased. The jump at x=1 carries the whole gradient,
and the chain rule does not see it. The score function works here: sλ=1/λ−x, and
E[1[x>1](1/λ−x)]=λe−λ−e−λ(1+λ1)=−e−λ.
The conditions side by side.
Score function
Pathwise
Needs from f
values only
the gradient ∇xf; no jumps
Needs from pθ
∇θlogpθ (normalized); support fixed
a differentiable path x=g(ϵ,θ)
Type of x
discrete or continuous
continuous
Cost per sample
one evaluation of f
f plus one backward pass through f
Variance
grows with ∣f∣ and with the dimension; needs baselines
controlled by the slope of f
Variance: why pathwise is usually better, and when it is not #
Pathwise. For ∇μ the estimator is ∇xf(x). If f is L-Lipschitz, then ∥∇f∥≤L, so
the total variance (the trace of the covariance) is at most E∥∇f(x)∥2≤L2. This bound does
not depend on the dimension d, and adding a constant to f does not change it.
Score function. Two effects make it noisy.
The size of f. For a constant f=c the true gradient is 0, but the estimator csθ(x)
has covariance c2I(θ): pure noise that grows like c2. The baseline b=c removes it exactly.
The dimension. Take x∼N(μ,Id) at μ=0 and f(x)=∑jxj, so ∂F/∂μ1=1. The
score estimate for μ1 is f(x)ϵ1=ϵ12+∑j≥2ϵjϵ1, with variance d+1. Every
coordinate of x adds noise to every coordinate of the gradient. The pathwise estimate is exactly 1.
When pathwise is worse. The pathwise variance follows the slope of f. Take f(x)=cos(kx)
with x∼N(μ,1). Then F′(μ)=−ksin(kμ)e−k2/2, which is tiny for large k. The
pathwise estimate −ksin(kx) has a variance close to k2/2(12.5 for k=5). The score estimate
cos(kx)(x−μ) has a variance of at most E[(x−μ)2]=1 (about 0.5 for k=5). Large slopes
appear in chaotic simulators and in long unrolled computations with exploding gradients. And the
pathwise estimator is not usable at all for discrete x, for f with jumps, or without a
differentiable path.
Why the two estimators agree for a Gaussian: Stein's lemma
For x∼N(μ,σ2) the score for μ is (x−μ)/σ2. Integration by parts
(lesson 10, Stein's lemma) gives
E[f(x)(x−μ)/σ2]=E[f′(x)] when fpθ→0 at ±∞. The left side is the mean of
the score-function estimator; the right side is the mean of the pathwise estimator. So the two
estimators have the same mean, as they must. Integration by parts moves the derivative from the
density to f. It does not keep the variance: the two random variables f(x)(x−μ)/σ2 and f′(x)
are different.
Answers to section 1.
(1) No useful gradient. sample() returns numbers that are not connected to μ, so backward()
fails with "element 0 of tensors does not require grad". torch.normal(mu, 1.0) gives the gradient
0 for the mean. F depends on μ through the distribution, and this computation never
differentiates the distribution. Use rsample() (pathwise) or a score-function surrogate (section 5).
(2) The single-sample value changes by csθ(x). The mean does not change, because
E[csθ]=0. The variance changes by 2cE[fsθ2]+c2E[sθ2], a quadratic in
c that is large for large ∣c∣.
Take x∼N(μ,σ2),f(x)=x2, at μ=2,σ=1. The path is x=μ+σϵ with
ϵ∼N(0,1). We use the Gaussian moments
E[ϵ]=E[ϵ3]=E[ϵ5]=0,E[ϵ2]=1,E[ϵ4]=3,E[ϵ6]=15.
Step 1: exact gradient.F=E[x2]=μ2+σ2, so ∂F/∂μ=2μ=4 and
∂F/∂σ=2σ=2.
Step 2: pathwise.∂x/∂μ=1 and ∂x/∂σ=ϵ, and f′(x)=2x.
For μ: the estimate is 2x=4+2ϵ. Mean 4. Variance 4E[ϵ2]=4.
For σ: the estimate is 2xϵ=4ϵ+2ϵ2. Mean 0+2=2. Second moment
16E[ϵ2]+16E[ϵ3]+4E[ϵ4]=16+0+12=28. Variance 28−22=24.
Step 3: score function. The log-density is
logp=−2σ2(x−μ)2−logσ−21log2π. So
sμ=(x−μ)/σ2=ϵ and sσ=(x−μ)2/σ3−1/σ=ϵ2−1 (at σ=1).
For μ: the estimate is x2ϵ=(2+ϵ)2ϵ=4ϵ+4ϵ2+ϵ3. Mean 0+4+0=4.
Its square is 16ϵ2+16ϵ4+ϵ6+32ϵ3+8ϵ4+8ϵ5. The odd powers have mean 0, so the
second moment is 16⋅1+16⋅3+15+8⋅3=103. Variance 103−16=87.
For σ: the estimate is x2(ϵ2−1). Mean 2, variance 346 (same method, more terms).
Step 4: baselines for μ. With b=E[f]=5:(x2−5)ϵ=ϵ3+4ϵ2−ϵ. Mean 4.
Second moment E[ϵ6]+16E[ϵ4]+E[ϵ2]−2E[ϵ4]=15+48+1−6=58 (the
other cross terms are odd). Variance 58−16=42. The best constant is
b∗=E[x2ϵ2]/E[ϵ2]=E[(2+ϵ)2ϵ2]=4+3=7, with variance 38.
Step 5: what the numbers mean. For a standard error of 0.1 on ∂F/∂μ you need
N=variance/0.01 samples: 400 (pathwise), 8,700 (score), 4,200 (score with b=5).
For other μ the score variance is μ4+14μ2+15: it grows like μ4 (the size of f, squared).
The pathwise variance stays 4σ2, independent of μ.
Estimator of ∂F/∂μ
Mean
Per-sample variance
N for standard error 0.1
pathwise 2x
4
4
400
score x2(x−μ)
4
87
8,700
score, b=5
4
42
4,200
score, b∗=7
4
38
3,800
Interactive figure: loading…
Three estimators of the same gradient. Each histogram shows 4000 estimates of ∂F/∂μ
for x∼N(μ,1),f=x2:pathwise, score function
and score function with baseline b. All three have the same mean, the
true value 2μ (black line), but the score-function histograms are wide and skewed. Move b and
find the narrowest violet histogram; the button b=b∗ sets b∗=μ2+3. Increase N: every
histogram gets narrower by a factor N and more symmetric, but the order stays.
Quick check
The score-function estimator above has per-sample variance 87. How many samples do you need for a standard error of 0.1?
Why.
The standard error of an average of N samples is 87/N. Setting 87/N=0.1 gives N=87/0.01=8,700. The pathwise estimator needs only 4/0.01=400. The standard error falls like 1/N, so halving it costs four times as many samples.
NumPy checks every number of the worked example: exact moments by quadrature, then Monte Carlo
with 400,000 samples, then the moving-support example.
importnumpyasnpfromscipyimportintegrate# (a) exact mean and per-sample variance by quadrature over eps ~ N(0, 1)phi=lambdae:np.exp(-e**2/2)/np.sqrt(2*np.pi)defmean_var(g):m=integrate.quad(lambdae:g(e)*phi(e),-np.inf,np.inf)[0]s=integrate.quad(lambdae:g(e)**2*phi(e),-np.inf,np.inf)[0]returnround(m,4),round(s-m**2,4)mu=2.0# x = mu + eps, f(x) = x^2, dF/dmu = 4forname,gin[("pathwise ",lambdae:2*(mu+e)),("score ",lambdae:(mu+e)**2*e),("score, b=5 ",lambdae:((mu+e)**2-5)*e),("score, b=7 ",lambdae:((mu+e)**2-7)*e)]:print(name,*mean_var(g))# pathwise 4.0 4.0# score 4.0 87.0# score, b=5 4.0 42.0# score, b=7 4.0 38.0# (b) the same estimators from samplesrng=np.random.default_rng(0)eps=rng.standard_normal(400_000)x=mu+epsg_path=2*x# f'(x) * dx/dmu, with dx/dmu = 1g_score=x**2*eps# f(x) * score, score = (x - mu) / sigma^2 = epsprint(round(g_path.mean(),2),round(g_path.var(),1))# 4.0 4.0print(round(g_score.mean(),2),round(g_score.var(),1))# 4.01 87.0# (c) a support that moves: x ~ Uniform(0, theta), f(x) = x, true gradient 1/2theta=1.0u=rng.uniform(size=400_000)xu=theta*uprint(round(np.mean(xu*(-1/theta)),3))# -0.5: score function, d/dtheta log(1/theta) = -1/thetaprint(round(np.mean(1.0*u),3))# 0.5: pathwise, f'(x) * dx/dtheta = 1 * u
In PyTorch, rsample() keeps the path x=g(ϵ,θ) in the graph; sample() does not. The
score-function estimator is the gradient of a surrogatef(x)logpθ(x), where f(x) enters as
a constant:
importtorchfromtorch.distributionsimportNormaltorch.manual_seed(0)n=400_000mu=torch.full((n,),2.0,requires_grad=True)# one copy of mu per sampledist=Normal(mu,1.0)(dist.rsample()**2).sum().backward()# rsample: x = mu + eps, a differentiable pathg_path=mu.grad.clone()mu.grad=Nonexs=dist.sample()# sample: no path, xs carries no gradient(xs**2*dist.log_prob(xs)).sum().backward()# surrogate: f(x) enters as a constant weightg_score=mu.grad.clone()print(round(g_path.mean().item(),2),round(g_path.var().item(),1))# 3.99 4.0print(round(g_score.mean().item(),2),round(g_score.var().item(),1))# 3.99 86.2
Two practical points. First, the surrogate f(x)logpθ(x) is not a loss you can read; only its
gradient means something. This is the line loss = -m.log_prob(action) * reward in the REINFORCE
example of the PyTorch documentation. Second, rsample() exists only for distributions with a
differentiable path (has_rsample; true for Normal, Uniform, Gamma, Beta, Dirichlet, false for
Bernoulli and Categorical). If f also depends on θ, add the ordinary term:
∇θEpθ[fθ(x)]=E[∇θfθ(x)]+E[fθ(x)sθ(x)].
VAEs. The ELBO is Eqϕ(z∣x)[logpθ(x∣z)]−KL(qϕ(z∣x)∥p(z)). The
decoder parameters θ appear only in f: an ordinary gradient. The encoder parameters ϕ
define the distribution: pathwise, with z=μϕ(x)+σϕ(x)⊙ϵ. The Gaussian KL term
has a closed form and needs no estimator. See the generative models track.
Reinforcement learning, and RL for language models. The policy gradient is the score-function
estimator on trajectories: ∇θlogpθ(τ)=∑t∇θlogπθ(at∣st). The unknown
dynamics of the environment do not depend on θ, so they drop out. This is why RL uses the
score function. REINFORCE uses a baseline; RLOO uses the leave-one-out mean (unbiased); GRPO
subtracts the group mean, which includes the sample itself, and also divides by the group standard
deviation. See the reinforcement learning track.
Discrete latent variables and discrete choices (tokens, architectures, molecules). There is no
differentiable path. Options: the score function with control variates (leave-one-out baselines,
VIMCO), or a continuous relaxation (Gumbel-softmax) or the straight-through estimator. The last two
have lower variance but are biased.
Black-box simulators in science. To tune a climate-model parameterization or a seismic source
model whose code has no adjoint, use Gaussian smoothing (evolution strategies):
∇μEϵ[f(μ+σϵ)]=E[f(μ+σϵ)ϵ]/σ. This is the score-function estimator of
N(μ,σ2I). The antithetic form [f(μ+σϵ)−f(μ−σϵ)]ϵ/(2σ) acts like a baseline.
With a differentiable simulator or emulator, use pathwise gradients and adjoints
(ML for science track).
Probabilistic forecasts. An ensemble model that maps noise to members and is trained with the
CRPS (a proper scoring rule) gets its gradient through the noise path: a pathwise estimator.
Gamma, Beta, Dirichlet. These have no simple path. Implicit reparameterization uses the
CDF C(x;θ) as the standardizing map: from ϵ=C(x;θ) with ϵ∼Uniform(0,1),
implicit differentiation (lesson 09) gives
∇θx=−∇θC(x;θ)/pθ(x). PyTorch's Gamma, Beta and Dirichlet have rsample.
Sampling without a path.sample() gives no gradient, and torch.normal(mu, ...) gives a zero
gradient for the mean. Use rsample() or an explicit x=μ+σϵ.
A baseline that depends on the sample.b=f(xi), a group mean that includes xi, or an
action-dependent baseline in RL changes the mean of the estimator. Use constants, running means
or leave-one-out means.
Two different scores.∇θlogpθ(x) (parameters; this lesson) is not ∇xlogp(x)
(data; score matching and diffusion).
Forgetting the direct term. If f depends on θ too, E[∇θfθ] must be added.
Score function with a moving support (uniform bounds, truncation points). It misses the
boundary term and is biased.
Pathwise through a jump (thresholds, argmax, rounding, an indicator such as "rain above 10 mm").
The gradient is zero almost everywhere, not the true gradient.
An unnormalized logpθ in the score. It misses −∇θlogZ(θ).
x∼N(μ,σ2) and f(x)=x. Give the pathwise and score-function estimates of ∂F/∂μ
and their variances. What does the baseline b=μ do?AnswerPathwise: f′(x)=1, variance 0. Score: x(x−μ)/σ2=μϵ/σ+ϵ2 (with x=μ+σϵ), mean 1, variance μ2/σ2+2. With b=μ:(x−μ)2/σ2=ϵ2, mean 1, variance 2 for every μ.
x∼Bernoulli(θ). Show that E[sθ]=0 and that E[f(x)sθ(x)]=f(1)−f(0).
Why is there no pathwise estimator?Answersθ(1)=1/θ and sθ(0)=−1/(1−θ).E[s]=θ/θ−(1−θ)/(1−θ)=0.E[fs]=θf(1)/θ−(1−θ)f(0)/(1−θ)=f(1)−f(0). Any path g(ϵ,θ)∈{0,1} (for example 1[u<θ] with u∼Uniform(0,1)) is piecewise constant in θ. Where it is differentiable, its derivative is 0, so the chain rule gives 0 instead of f(1)−f(0).
x∼Exp(λ) (density λe−λx,x>0) and f(x)=x. Derive both estimates of
dF/dλ and their variances.AnswerF=1/λ,F′=−1/λ2. Pathwise: x=ϵ/λ with ϵ∼Exp(1), so ∂x/∂λ=−x/λ. Mean −1/λ2, variance Var(x)/λ2=1/λ4. Score: s=1/λ−x, estimate x(1/λ−x). Using E[xk]=k!/λk: mean 1/λ2−2/λ2=−1/λ2; second moment E[x2]/λ2−2E[x3]/λ+E[x4]=(2−12+24)/λ4=14/λ4; variance 13/λ4, thirteen times larger.
x∼N(μ,1). Is the pathwise estimator of ∂F/∂μ valid for f(x)=∣x∣? For
f(x)=round(x) (the nearest integer)?Answer∣x∣: yes. It is Lipschitz, and its kink at 0 has probability 0. The estimate is sign(x), with mean 2Φ(μ)−1=dμdE∣x∣(Φ is the standard normal CDF). round(x): no. It jumps by 1 at every half-integer, so f′=0 almost everywhere and the estimate is 0. The true gradient is ∑kφ(k+21−μ)≈1(φ is the standard normal density; each jump adds the density at the jump). The score-function estimator is unbiased for both. Kinks are fine; jumps are not.
For each prompt you sample K=4 answers and use as baseline the mean reward of all 4 answers,
including the answer itself. Is the policy-gradient estimate unbiased?AnswerNo. fi−fˉ=43(fi−fˉ−i), so the estimate is 43 times the unbiased leave-one-out estimate: its mean is 43∇F. The direction is right, but the length is off. The leave-one-out mean fˉ−i fixes it.
Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
State the score-function (REINFORCE) identity.
∇θEpθ[f(x)]=Epθ[f(x)∇θlogpθ(x)], valid when the support of pθ does not depend on θ and ∇ and ∫ can be swapped.
Why does the score ∇θlogpθ(x) have mean zero?
E[∇θlogpθ]=∫∇θpθdx=∇θ∫pθdx=∇θ1=0.
Write the pathwise (reparameterization) gradient for x=g(ϵ,θ).
∇θE[f(x)]=Eϵ[(∂g/∂θ)⊤∇xf(g(ϵ,θ))], where ϵ has a distribution that does not depend on θ.
How do you reparameterize x∼N(μ,σ2), and what are ∂x/∂μ and ∂x/∂σ?
x=μ+σϵ with ϵ∼N(0,1);∂x/∂μ=1 and ∂x/∂σ=ϵ.
Why does a baseline b not change the mean of the score-function estimator?
If b does not depend on x, then E[bsθ(x)]=bE[sθ(x)]=0. A baseline that depends on x itself can add bias.
What is the best constant baseline for a scalar parameter?
b∗=E[f(x)sθ(x)2]/E[sθ(x)2]; it minimizes the parabola E[(f−b)2sθ2] in b.
For x∼N(2,1) and f=x2, what are the per-sample variances of the pathwise and score-function estimators of ∂F/∂μ?
Pathwise 2x: variance 4. Score x2(x−μ): variance 87. Both have mean 4.
Why does the pathwise estimator fail for f(x)=1[x>1]?
f′=0 almost everywhere, so every pathwise estimate is 0. The whole gradient comes from the jump, which the chain rule does not see.
x∼Uniform(0,θ),f(x)=x. What does the score-function estimator give, and why?
−1/2 instead of +1/2. The support moves with θ, so the Leibniz rule has a boundary term f(θ)pθ(θ)=1 that the score misses.
Which estimator does a VAE encoder use, and which does a policy gradient use?
VAE encoder: pathwise, z=μϕ+σϕ⊙ϵ. Policy gradient: score function, because actions can be discrete and the environment is not differentiable.
"What is the reparameterization trick, and why does it reduce variance?" Write x=g(ϵ,θ)
with ϵ independent of θ and differentiate through f. The variance follows the slope of
f, not the value of f times a zero-mean score.
"Derive REINFORCE. Why does a baseline not add bias? Can it depend on the action?" The
log-derivative trick gives ∇F=E[f∇logp];E[∇logp]=0 makes a constant baseline
harmless. An action-dependent baseline adds bias (unless you correct for it).
"How do you backpropagate through sampling a discrete token?" Score function with a baseline
(unbiased, noisy), or Gumbel-softmax and straight-through (biased, lower variance).
"Your simulator is not differentiable. How do you tune its parameters with gradients?" Gaussian
smoothing (evolution strategies, a score-function estimator), or train a differentiable emulator.
"What is the difference between sample() and rsample()?" rsample() keeps the path
x=g(ϵ,θ) in the computational graph; sample() does not.
The notebook for this lesson runs in Colab. It has four exercises, each with a check cell
and a folded solution, and a final demo:
Write pathwise_grad_samples and score_function_grad_samples for N(μ,σ2) and check
their means against the exact gradient of E[x2] for μ and σ.
Measure the variance of the score-function estimator as a function of the baseline b, and find
b∗ from samples and from the formula.
Discrete samples: the score of Bernoulli(sigmoid(θ)) and the gradient of an
expected reward, compared with the exact value.
The moving support of Uniform(0,θ): measure the bias of the score-function estimator
and recover the missing boundary term.
Demo: minimize E[(x−3)2] over the mean μ of a Gaussian with SGD, using the pathwise
estimator, the score function, and the score function with a running-mean baseline, and compare
the training curves.
The part on variational inference compares the REINFORCE (likelihood-ratio) and reparameterization gradient estimators and explains which distributions can be reparameterized.
Open on YouTube · the player loads from youtube-nocookie.com when you press play
Why the sampling step of a VAE blocks backpropagation, and how the reparameterization trick moves the noise out of the way.
Open on YouTube · the player loads from youtube-nocookie.com when you press play
The policy gradient derived with the log-derivative trick; the unknown dynamics drop out of the gradient.
Open on YouTube · the player loads from youtube-nocookie.com when you press play
REINFORCE with a baseline, and why the baseline reduces the variance without adding bias.
Open on YouTube · the player loads from youtube-nocookie.com when you press play
Mohamed, Rosca, Figurnov and Mnih, Monte Carlo Gradient Estimation in Machine Learning
(JMLR 2020): §3 (an intuitive comparison), §4 (score function: derivation, conditions, the
Uniform(0,θ) example, variance), §5 (pathwise: sampling paths, implicit
reparameterization, the Lipschitz variance bound), §7.4 (control variates and baselines), §10.1
(how to choose an estimator).
Kingma and Welling, An Introduction to Variational Autoencoders:
§2.3 (why the gradient with respect to the encoder is the hard part) and §2.4 (the
reparameterization trick).