Type at least 2 letters. Enter opens the first result, Esc closes.

    Calculus for ML · Lesson 12 · Gradients of expectations and functionals

    Differentiating expectations: score-function and pathwise gradients

    Advanced 75 min 4 interactive figures 4 videos Colab notebook

    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=μ+σϵx = \mu + \sigma\epsilon). 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.


    Why this matters #

    Many objectives in ML are expectations over a distribution that depends on the parameters:

    F(θ)=Ex∼pθ[f(x)]=∫pθ(x) f(x) dx.F(\theta) = \mathbb E_{x \sim p_\theta}[f(x)] = \int p_\theta(x)\, f(x)\, dx .
    • In a VAE, the encoder parameters define the distribution qϕ(z∣x)q_\phi(z \mid 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.

    FF almost never has a closed form, so we need an unbiased Monte Carlo estimate of ∇F\nabla 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)]\mathbb E_{x \sim \text{data}}[\ell(\theta; x)], or with the noise in diffusion-model training. There the distribution does not depend on θ\theta, and you just average ∇θℓ\nabla_\theta \ell. The problem of this lesson starts when θ\theta changes the distribution.

    Notation. In this lesson ϵ\epsilon is the random noise of a sampling path (for example ϵ∼N(0,1)\epsilon \sim N(0, 1)). It is not the machine epsilon of lesson 07.

    1. Predict first #

    2. The picture #

    The function stays, the weights move. F(θ)F(\theta) is a weighted average of the values f(x)f(x), with weights pθ(x)p_\theta(x). The function ff does not depend on θ\theta. When θ\theta changes, the density moves under ff, and the average changes.

    Interactive figure: loading…

    Move θ. The density pθp_\theta of N(θ,1)N(\theta, 1) (aqua) slides under the fixed function ff (black). The lower chart shows F(θ)F(\theta) and its tangent. Choose the step function f(x)=1[x>1]f(x) = \mathbf 1[x > 1]: its slope is 00 everywhere except at the jump, but FF still has a positive slope. The slope of FF comes from the moving density, not from the slope of ff.

    Why you cannot backpropagate through a sample. Look at how a program computes an estimate of F(θ)F(\theta):

    1. Draw x1,…,xNx_1, \dots, x_N from pθp_\theta. The program receives NN numbers.
    2. Compute F^=1N∑nf(xn)\hat F = \frac1N \sum_n f(x_n).
    3. Call autodiff on F^\hat F.

    In step 1 the link between θ\theta and the numbers xnx_n is hidden inside the random number generator. Autodiff (lesson 05) differentiates only the operations it records. It sees f(xn)f(x_n) with constants xnx_n, so it returns 00 (or an error). The gradient of FF is not 00. We need another way to express how the samples depend on θ\theta. There are two ways.

    Way 1: change the weights (the score function). The simplest case is a coin: x∈{0,1}x \in \{0, 1\} with P(x=1)=θP(x = 1) = \theta. Then F(θ)=θf(1)+(1−θ)f(0)F(\theta) = \theta f(1) + (1 - \theta) f(0) and F′(θ)=f(1)−f(0)F'(\theta) = 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: ∂θlog⁡pθ(x)\partial_\theta \log p_\theta(x). It is 1/θ1/\theta for x=1x = 1 and −1/(1−θ)-1/(1-\theta) for x=0x = 0. Then

    F′(θ)=θ⋅f(1)⋅1θ+(1−θ)⋅f(0)⋅−11−θ=E[f(x) ∂θlog⁡pθ(x)].\begin{aligned} F'(\theta) &= \theta \cdot f(1) \cdot \frac{1}{\theta} + (1 - \theta) \cdot f(0) \cdot \frac{-1}{1 - \theta} \\ &= \mathbb E\big[f(x)\, \partial_\theta \log p_\theta(x)\big]. \end{aligned}

    The factor ∂θlog⁡pθ(x)\partial_\theta \log p_\theta(x) is the score. A one-sample estimate is: draw xx, report f(x)f(x) times the score. It uses only the value f(x)f(x).

    Way 2: move the points (the pathwise gradient). The simplest case is a Gaussian location. You can produce x∼N(μ,1)x \sim N(\mu, 1) as x=μ+ϵx = \mu + \epsilon with ϵ∼N(0,1)\epsilon \sim N(0, 1). Keep ϵ\epsilon fixed: a change of μ\mu moves the point xx by the same amount. So F(μ)=Eϵ[f(μ+ϵ)]F(\mu) = \mathbb E_\epsilon[f(\mu + \epsilon)] and F′(μ)=Eϵ[f′(μ+ϵ)]F'(\mu) = \mathbb E_\epsilon[f'(\mu + \epsilon)]. A one-sample estimate is: draw ϵ\epsilon, report f′(μ+ϵ)f'(\mu + \epsilon). It uses the slope of ff.

    Interactive figure: loading…

    Two pictures of the same samples. In "move the points", each sample is xi=μ+σϵix_i = \mu + \sigma\epsilon_i with fixed noise ϵi\epsilon_i: change μ\mu or σ\sigma and every sample slides along its own path (grey dots: the positions at μ=0\mu = 0, σ=1\sigma = 1). In "reweight the points", the samples stay where they were drawn at μ=0\mu = 0, σ=1\sigma = 1, and their weights pθ(xi)/pθ0(xi)p_\theta(x_i)/p_{\theta_0}(x_i) change. The derivative of the weight at θ0\theta_0 is the score. Notice that far from θ0\theta_0 a few weights become very large.

    Same mean, different noise. Take f(x)=xf(x) = x, so F(μ)=μF(\mu) = \mu and F′(μ)=1F'(\mu) = 1.

    • Pathwise: f′(x)=1f'(x) = 1 for every sample. The variance is 00.
    • Score function: the score of N(μ,1)N(\mu, 1) is x−μ=ϵx - \mu = \epsilon. The estimate is xϵ=(μ+ϵ)ϵ=μϵ+ϵ2x\epsilon = (\mu + \epsilon)\epsilon = \mu\epsilon + \epsilon^2. Its mean is 0+1=10 + 1 = 1, correct. Its variance is μ2Var⁡(ϵ)+Var⁡(ϵ2)=μ2+2\mu^2 \operatorname{Var}(\epsilon) + \operatorname{Var}(\epsilon^2) = \mu^2 + 2 (the cross term 2μ E[ϵ3]=02\mu\,\mathbb E[\epsilon^3] = 0).

    The score-function estimate multiplies the value of ff by a random factor with mean zero. The larger ∣f∣|f| is, the larger the noise, even when the slope of ff is the same everywhere.

    Quick check

    A coin gives x=1x = 1 with probability θ=0.3\theta = 0.3 and x=0x = 0 otherwise. The reward is f(1)=5f(1) = 5 and f(0)=2f(0) = 2. What is F′(θ)F'(\theta) for F(θ)=E[f(x)]F(\theta) = \mathbb E[f(x)]?

    Quick check

    You sample x=μ+σϵx = \mu + \sigma\epsilon with ϵ∼N(0,1)\epsilon \sim N(0, 1) and f(x)=x2f(x) = x^2. What is the one-sample pathwise estimate of ∂F/∂μ\partial F/\partial\mu?

    3. Definitions and main results #

    Setup. θ∈Rk\theta \in \R^k are the parameters. pθp_\theta is a density (or a probability mass function) on Rd\R^d. f:Rd→Rf: \R^d \to \R does not depend on θ\theta. F(θ)=Epθ[f(x)]F(\theta) = \mathbb E_{p_\theta}[f(x)].

    A gradient estimator is a random vector g^\hat g computed from samples. It is unbiased if E[g^]=∇F(θ)\mathbb E[\hat g] = \nabla F(\theta). The average of NN independent copies has the same mean and 1/N1/N times the covariance. So, at equal cost per sample, the number to compare is the per-sample variance: to reach a standard error ss you need about N=variance/s2N = \text{variance}/s^2 samples.

    The score is sθ(x)=∇θlog⁡pθ(x)∈Rks_\theta(x) = \nabla_\theta \log p_\theta(x) \in \R^k. It is a gradient with respect to the parameters.

    The score has mean zero #

    Lemma 1. If pθ(x)p_\theta(x) is differentiable in θ\theta and ∇θ\nabla_\theta can be moved inside the integral, then Epθ[sθ(x)]=0\mathbb E_{p_\theta}[s_\theta(x)] = 0.

    Proof.

    1. Where pθ(x)>0p_\theta(x) > 0, the derivative of the log gives ∇θpθ(x)=pθ(x) ∇θlog⁡pθ(x)\nabla_\theta p_\theta(x) = p_\theta(x)\, \nabla_\theta \log p_\theta(x). This is the log-derivative trick.
    2. So E[sθ]=∫pθ ∇θlog⁡pθ dx=∫∇θpθ dx\mathbb E[s_\theta] = \int p_\theta\, \nabla_\theta \log p_\theta\, dx = \int \nabla_\theta p_\theta\, dx.
    3. Swap ∇\nabla and ∫\int: this is ∇θ∫pθ dx=∇θ1=0\nabla_\theta \int p_\theta\, dx = \nabla_\theta 1 = 0. ■\blacksquare

    In words: the total probability is always 1, so the changes of the probabilities cancel on average. For the coin: θ⋅1θ+(1−θ)⋅−11−θ=1−1=0\theta \cdot \frac1\theta + (1-\theta) \cdot \frac{-1}{1-\theta} = 1 - 1 = 0. The covariance of sθs_\theta is the Fisher information I(θ)I(\theta).

    The score-function identity #

    Theorem 1 (score-function identity; also "likelihood ratio" or "REINFORCE"). Assume

    • (i) pθ(x)p_\theta(x) is differentiable in θ\theta for every xx;
    • (ii) the support {x:pθ(x)>0}\{x : p_\theta(x) > 0\} does not depend on θ\theta;
    • (iii) ∇θ\nabla_\theta and ∫\int can be swapped (for example, some integrable G(x)G(x) satisfies ∣f(x)∣ ∥∇θpθ(x)∥≤G(x)|f(x)|\, \|\nabla_\theta p_\theta(x)\| \le G(x) for all θ\theta near the current value).

    Then

    ∇θF(θ)=Epθ[f(x) sθ(x)]=Epθ[f(x) ∇θlog⁡pθ(x)].\begin{aligned} \nabla_\theta F(\theta) &= \mathbb E_{p_\theta}\big[f(x)\, s_\theta(x)\big] \\ &= \mathbb E_{p_\theta}\big[f(x)\, \nabla_\theta \log p_\theta(x)\big]. \end{aligned}

    Proof.

    1. ∇θF\nabla_\theta F =∇θ∫pθ(x)f(x) dx= \nabla_\theta \int p_\theta(x) f(x)\, dx =∫f(x) ∇θpθ(x) dx= \int f(x)\, \nabla_\theta p_\theta(x)\, dx, by (iii) and because ff does not depend on θ\theta.
    2. By (ii), every xx with ∇θpθ(x)≠0\nabla_\theta p_\theta(x) \ne 0 has pθ(x)>0p_\theta(x) > 0. There the log-derivative trick gives ∇θpθ=pθ ∇θlog⁡pθ\nabla_\theta p_\theta = p_\theta\, \nabla_\theta \log p_\theta.
    3. Hence ∇θF\nabla_\theta F =∫pθ(x) f(x) sθ(x) dx= \int p_\theta(x)\, f(x)\, s_\theta(x)\, dx =E[f(x) sθ(x)]= \mathbb E[f(x)\, s_\theta(x)]. ■\blacksquare

    The estimator is g^=1N∑nf(xn) sθ(xn)\hat g = \frac1N \sum_n f(x_n)\, s_\theta(x_n) with xn∼pθx_n \sim p_\theta. For discrete xx, replace the integral by a sum; the proof is the same.

    What it does not need: ff can be discontinuous, a black box, or a reward from a simulator, and xx can be discrete. What it needs: samples from pθp_\theta, and the gradient of the normalized log-density. If you only know p~θ=Z(θ) pθ\tilde p_\theta = Z(\theta)\, p_\theta, then ∇log⁡p~θ\nabla \log \tilde p_\theta is off by ∇log⁡Z(θ)\nabla \log Z(\theta).

    Why condition (ii) matters. Take x∼Uniform(0,θ)x \sim \mathrm{Uniform}(0, \theta) and f(x)=xf(x) = x. Then F=θ/2F = \theta/2 and F′=1/2F' = 1/2. On the support, log⁡pθ=−log⁡θ\log p_\theta = -\log \theta, so sθ=−1/θs_\theta = -1/\theta and E[fsθ]=−(θ/2)/θ=−1/2\mathbb E[f s_\theta] = -(\theta/2)/\theta = -1/2. This has the wrong sign. The Leibniz rule shows what is missing. Write F(θ)=∫0θx⋅1θ dxF(\theta) = \int_0^\theta x \cdot \frac1\theta\, dx. Its derivative has two parts:

    F′(θ)=f(θ) pθ(θ)⏟boundary: 1+∫0θx ∂θ(1θ) dx⏟interior: −1/2=12.F'(\theta) = \underbrace{f(\theta)\, p_\theta(\theta)}_{\text{boundary: } 1} + \underbrace{\int_0^\theta x\, \partial_\theta\Big(\frac1\theta\Big)\, dx}_{\text{interior: } -1/2} = \frac12 .

    The boundary term comes from the support that moves with θ\theta. The score only sees the interior term.

    Interactive figure: loading…

    Where does the probability go? When θ\theta grows by Δθ\Delta\theta, the density on [0,θ][0, \theta] goes down (magenta: the change of the weights, which the score sees) and a new strip [θ,θ+Δθ][\theta, \theta + \Delta\theta] gets probability (blue: the boundary term, which the score misses). Compare the two Monte Carlo estimates with the exact slope. Try f=1f = 1: the true slope is 00, but the score-function estimate is −1/θ-1/\theta.

    Baselines #

    Theorem 2 (baselines keep the estimator unbiased). Let bb not depend on xx: a constant, a function of θ\theta, or an average of other, independent samples. Then E[(f(x)−b) sθ(x)]=∇θF\mathbb E[(f(x) - b)\, s_\theta(x)] = \nabla_\theta F.

    Proof. E[b sθ(x)]=E[b] E[sθ(x)]=0\mathbb E[b\, s_\theta(x)] = \mathbb E[b]\, \mathbb E[s_\theta(x)] = 0, by independence and Lemma 1. ■\blacksquare

    So we may subtract any such bb from ff. The mean stays the same; the variance changes. A good bb makes f(x)−bf(x) - b small, so the random factor sθ(x)s_\theta(x) is multiplied by a smaller number.

    Best constant baseline (scalar θ\theta). The per-sample variance is V(b)=E[(f−b)2sθ2]−(F′)2V(b) = \mathbb E[(f - b)^2 s_\theta^2] - (F')^2. It is a parabola in bb. Set its derivative to zero, −2 E[(f−b) sθ2]=0-2\,\mathbb E[(f - b)\, s_\theta^2] = 0:

    b∗=E[f(x) sθ(x)2]E[sθ(x)2].b^* = \frac{\mathbb E[f(x)\, s_\theta(x)^2]}{\mathbb E[s_\theta(x)^2]} .

    In practice b≈E[f]b \approx \mathbb E[f] (a running mean, or the mean of the other samples) is close to b∗b^* when ff and sθ2s_\theta^2 are only weakly correlated. Each coordinate of θ\theta may have its own bb.

    A baseline built from the same samples

    With KK samples, a common choice is the mean fˉ\bar f of all KK values as the baseline of sample ii. This mean contains fif_i itself, so it depends on xix_i. A short computation gives fi−fˉ=K−1K(fi−fˉ−i)f_i - \bar f = \frac{K-1}{K}\big(f_i - \bar f_{-i}\big), where fˉ−i\bar f_{-i} is the mean of the other K−1K - 1 values. So this estimator is K−1K\frac{K-1}{K} times the leave-one-out estimator, and its mean is K−1K∇F\frac{K-1}{K}\nabla F: the direction is right, the length is not. The leave-one-out mean fˉ−i\bar f_{-i} keeps the estimator unbiased (this is the RLOO estimator in RL).

    Quick check

    You add a constant cc to ff in the score-function estimator f(x) sθ(x)f(x)\,s_\theta(x). What happens?

    The pathwise gradient #

    Theorem 3 (pathwise gradient; the reparameterization trick). Assume

    • (i) there is a base distribution p(ϵ)p(\epsilon) that does not depend on θ\theta, and a map g(ϵ,θ)g(\epsilon, \theta), such that x=g(ϵ,θ)x = g(\epsilon, \theta) with ϵ∼p(ϵ)\epsilon \sim p(\epsilon) has the distribution pθp_\theta (a sampling path);
    • (ii) θ↦g(ϵ,θ)\theta \mapsto g(\epsilon, \theta) is differentiable for each ϵ\epsilon, and ff is differentiable (continuously differentiable is enough; a Lipschitz ff also works when xx has a density, because such an ff is then differentiable at xx with probability 1);
    • (iii) ∇θ\nabla_\theta and Eϵ\mathbb E_\epsilon can be swapped.

    Then

    ∇θF(θ)=Eϵ[(∂g∂θ(ϵ,θ)) ⁣⊤∇xf(g(ϵ,θ))],\nabla_\theta F(\theta) = \mathbb E_\epsilon\Big[\Big(\frac{\partial g}{\partial \theta}(\epsilon, \theta)\Big)^{\!\top} \nabla_x f\big(g(\epsilon, \theta)\big)\Big],

    where ∂g/∂θ\partial g/\partial \theta is the d×kd \times k Jacobian of gg with respect to θ\theta.

    Proof.

    1. By (i), xx and g(ϵ,θ)g(\epsilon, \theta) have the same distribution, so F(θ)=Eϵ[f(g(ϵ,θ))]F(\theta) = \mathbb E_\epsilon[f(g(\epsilon, \theta))] (the expectation of a function of a random variable, lesson 10).
    2. The distribution of ϵ\epsilon does not depend on θ\theta. Now θ\theta appears only inside the integrand. By (iii), ∇θF=Eϵ[∇θf(g(ϵ,θ))]\nabla_\theta F = \mathbb E_\epsilon[\nabla_\theta f(g(\epsilon, \theta))].
    3. The chain rule (lesson 04) gives ∇θf(g(ϵ,θ))=(∂g/∂θ)⊤∇xf(x)\nabla_\theta f(g(\epsilon, \theta)) = (\partial g/\partial \theta)^\top \nabla_x f(x) at x=g(ϵ,θ)x = g(\epsilon, \theta). ■\blacksquare

    The trick moves the randomness into ϵ\epsilon, which does not depend on θ\theta. Then the sample is an ordinary differentiable function of θ\theta, and autodiff can follow it.

    Gaussian case. x=μ+σ⊙ϵx = \mu + \sigma \odot \epsilon with ϵ∼N(0,Id)\epsilon \sim N(0, I_d) and θ=(μ,σ)\theta = (\mu, \sigma): ∇μ=∇xf(x)\nabla_\mu = \nabla_x f(x) and ∇σ=∇xf(x)⊙ϵ\nabla_\sigma = \nabla_x f(x) \odot \epsilon. With a full covariance Σ=LL⊤\Sigma = LL^\top and x=μ+Lϵx = \mu + L\epsilon: ∇L=∇xf(x) ϵ⊤\nabla_L = \nabla_x f(x)\, \epsilon^\top. These are the sampling maps of lesson 10, but here gg need not be invertible.

    Why condition (ii) matters. Take x∼Exp(λ)x \sim \mathrm{Exp}(\lambda) (density λe−λx\lambda e^{-\lambda x} for x>0x > 0) and the step f(x)=1[x>1]f(x) = \mathbf 1[x > 1]. Then F(λ)=P(x>1)=e−λF(\lambda) = P(x > 1) = e^{-\lambda} and F′(λ)=−e−λF'(\lambda) = -e^{-\lambda}. The path is x=ϵ/λx = \epsilon/\lambda with ϵ∼Exp(1)\epsilon \sim \mathrm{Exp}(1). But f′(x)=0f'(x) = 0 for every x≠1x \ne 1, so the pathwise estimate is 00 with probability 1: it is biased. The jump at x=1x = 1 carries the whole gradient, and the chain rule does not see it. The score function works here: sλ=1/λ−xs_\lambda = 1/\lambda - x, and

    E[1[x>1] (1/λ−x)]=e−λλ−e−λ(1+1λ)=−e−λ.\mathbb E\big[\mathbf 1[x > 1]\,(1/\lambda - x)\big] = \frac{e^{-\lambda}}{\lambda} - e^{-\lambda}\Big(1 + \frac1\lambda\Big) = -e^{-\lambda}.

    The conditions side by side.

    Score function Pathwise
    Needs from ff values only the gradient ∇xf\nabla_x f; no jumps
    Needs from pθp_\theta ∇θlog⁡pθ\nabla_\theta \log p_\theta (normalized); support fixed a differentiable path x=g(ϵ,θ)x = g(\epsilon, \theta)
    Type of xx discrete or continuous continuous
    Cost per sample one evaluation of ff ff plus one backward pass through ff
    Variance grows with ∣f∣\lvert f \rvert and with the dimension; needs baselines controlled by the slope of ff

    Variance: why pathwise is usually better, and when it is not #

    Pathwise. For ∇μ\nabla_\mu the estimator is ∇xf(x)\nabla_x f(x). If ff is LL-Lipschitz, then ∥∇f∥≤L\|\nabla f\| \le L, so the total variance (the trace of the covariance) is at most E∥∇f(x)∥2≤L2\mathbb E\|\nabla f(x)\|^2 \le L^2. This bound does not depend on the dimension dd, and adding a constant to ff does not change it.

    Score function. Two effects make it noisy.

    • The size of ff. For a constant f=cf = c the true gradient is 00, but the estimator c sθ(x)c\, s_\theta(x) has covariance c2I(θ)c^2 I(\theta): pure noise that grows like c2c^2. The baseline b=cb = c removes it exactly.
    • The dimension. Take x∼N(μ,Id)x \sim N(\mu, I_d) at μ=0\mu = 0 and f(x)=∑jxjf(x) = \sum_j x_j, so ∂F/∂μ1=1\partial F/\partial \mu_1 = 1. The score estimate for μ1\mu_1 is f(x) ϵ1=ϵ12+∑j≥2ϵjϵ1f(x)\,\epsilon_1 = \epsilon_1^2 + \sum_{j \ge 2} \epsilon_j \epsilon_1, with variance d+1d + 1. Every coordinate of xx adds noise to every coordinate of the gradient. The pathwise estimate is exactly 11.

    When pathwise is worse. The pathwise variance follows the slope of ff. Take f(x)=cos⁡(kx)f(x) = \cos(kx) with x∼N(μ,1)x \sim N(\mu, 1). Then F′(μ)=−ksin⁡(kμ) e−k2/2F'(\mu) = -k \sin(k\mu)\, e^{-k^2/2}, which is tiny for large kk. The pathwise estimate −ksin⁡(kx)-k\sin(kx) has a variance close to k2/2k^2/2 (12.512.5 for k=5k = 5). The score estimate cos⁡(kx)(x−μ)\cos(kx)(x - \mu) has a variance of at most E[(x−μ)2]=1\mathbb E[(x - \mu)^2] = 1 (about 0.50.5 for k=5k = 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 xx, for ff with jumps, or without a differentiable path.

    Why the two estimators agree for a Gaussian: Stein's lemma

    For x∼N(μ,σ2)x \sim N(\mu, \sigma^2) the score for μ\mu is (x−μ)/σ2(x - \mu)/\sigma^2. Integration by parts (lesson 10, Stein's lemma) gives E[f(x) (x−μ)/σ2]=E[f′(x)]\mathbb E\big[f(x)\,(x - \mu)/\sigma^2\big] = \mathbb E[f'(x)] when f pθ→0f\,p_\theta \to 0 at ±∞\pm\infty. 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 ff. It does not keep the variance: the two random variables f(x)(x−μ)/σ2f(x)(x - \mu)/\sigma^2 and f′(x)f'(x) are different.

    Answers to section 1. (1) No useful gradient. sample() returns numbers that are not connected to μ\mu, so backward() fails with "element 0 of tensors does not require grad". torch.normal(mu, 1.0) gives the gradient 00 for the mean. FF depends on μ\mu 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 c sθ(x)c\, s_\theta(x). The mean does not change, because E[c sθ]=0\mathbb E[c\, s_\theta] = 0. The variance changes by 2c E[fsθ2]+c2 E[sθ2]2c\, \mathbb E[f s_\theta^2] + c^2\, \mathbb E[s_\theta^2], a quadratic in cc that is large for large ∣c∣|c|.

    4. Worked example #

    Take x∼N(μ,σ2)x \sim N(\mu, \sigma^2), f(x)=x2f(x) = x^2, at μ=2\mu = 2, σ=1\sigma = 1. The path is x=μ+σϵx = \mu + \sigma\epsilon with ϵ∼N(0,1)\epsilon \sim N(0, 1). We use the Gaussian moments E[ϵ]=E[ϵ3]=E[ϵ5]=0\mathbb E[\epsilon] = \mathbb E[\epsilon^3] = \mathbb E[\epsilon^5] = 0, E[ϵ2]=1\mathbb E[\epsilon^2] = 1, E[ϵ4]=3\mathbb E[\epsilon^4] = 3, E[ϵ6]=15\mathbb E[\epsilon^6] = 15.

    Step 1: exact gradient. F=E[x2]=μ2+σ2F = \mathbb E[x^2] = \mu^2 + \sigma^2, so ∂F/∂μ=2μ=4\partial F/\partial\mu = 2\mu = 4 and ∂F/∂σ=2σ=2\partial F/\partial\sigma = 2\sigma = 2.

    Step 2: pathwise. ∂x/∂μ=1\partial x/\partial\mu = 1 and ∂x/∂σ=ϵ\partial x/\partial\sigma = \epsilon, and f′(x)=2xf'(x) = 2x.

    • For μ\mu: the estimate is 2x=4+2ϵ2x = 4 + 2\epsilon. Mean 44. Variance 4 E[ϵ2]=44\,\mathbb E[\epsilon^2] = 4.
    • For σ\sigma: the estimate is 2xϵ=4ϵ+2ϵ22x\epsilon = 4\epsilon + 2\epsilon^2. Mean 0+2=20 + 2 = 2. Second moment 16 E[ϵ2]+16 E[ϵ3]+4 E[ϵ4]16\,\mathbb E[\epsilon^2] + 16\,\mathbb E[\epsilon^3] + 4\,\mathbb E[\epsilon^4] =16+0+12= 16 + 0 + 12 =28= 28. Variance 28−22=2428 - 2^2 = 24.

    Step 3: score function. The log-density is log⁡p=−(x−μ)22σ2−log⁡σ−12log⁡2π\log p = -\frac{(x - \mu)^2}{2\sigma^2} - \log\sigma - \frac12\log 2\pi. So sμ=(x−μ)/σ2=ϵs_\mu = (x - \mu)/\sigma^2 = \epsilon and sσ=(x−μ)2/σ3−1/σ=ϵ2−1s_\sigma = (x-\mu)^2/\sigma^3 - 1/\sigma = \epsilon^2 - 1 (at σ=1\sigma = 1).

    • For μ\mu: the estimate is x2ϵ=(2+ϵ)2ϵ=4ϵ+4ϵ2+ϵ3x^2 \epsilon = (2 + \epsilon)^2 \epsilon = 4\epsilon + 4\epsilon^2 + \epsilon^3. Mean 0+4+0=40 + 4 + 0 = 4.
    • Its square is 16ϵ2+16ϵ4+ϵ6+32ϵ3+8ϵ4+8ϵ516\epsilon^2 + 16\epsilon^4 + \epsilon^6 + 32\epsilon^3 + 8\epsilon^4 + 8\epsilon^5. The odd powers have mean 00, so the second moment is 16⋅1+16⋅3+15+8⋅3=10316 \cdot 1 + 16 \cdot 3 + 15 + 8 \cdot 3 = 103. Variance 103−16=87103 - 16 = 87.
    • For σ\sigma: the estimate is x2(ϵ2−1)x^2(\epsilon^2 - 1). Mean 22, variance 346346 (same method, more terms).

    Step 4: baselines for μ\mu. With b=E[f]=5b = \mathbb E[f] = 5: (x2−5)ϵ=ϵ3+4ϵ2−ϵ(x^2 - 5)\epsilon = \epsilon^3 + 4\epsilon^2 - \epsilon. Mean 44. Second moment E[ϵ6]+16 E[ϵ4]+E[ϵ2]−2 E[ϵ4]=15+48+1−6=58\mathbb E[\epsilon^6] + 16\,\mathbb E[\epsilon^4] + \mathbb E[\epsilon^2] - 2\,\mathbb E[\epsilon^4] = 15 + 48 + 1 - 6 = 58 (the other cross terms are odd). Variance 58−16=4258 - 16 = 42. The best constant is b∗b^* =E[x2ϵ2]/E[ϵ2]= \mathbb E[x^2 \epsilon^2]/\mathbb E[\epsilon^2] =E[(2+ϵ)2ϵ2]= \mathbb E[(2 + \epsilon)^2\epsilon^2] =4+3= 4 + 3 =7= 7, with variance 3838.

    Step 5: what the numbers mean. For a standard error of 0.10.1 on ∂F/∂μ\partial F/\partial\mu you need N=variance/0.01N = \text{variance}/0.01 samples: 400400 (pathwise), 8,7008{,}700 (score), 4,2004{,}200 (score with b=5b = 5). For other μ\mu the score variance is μ4+14μ2+15\mu^4 + 14\mu^2 + 15: it grows like μ4\mu^4 (the size of ff, squared). The pathwise variance stays 4σ24\sigma^2, independent of μ\mu.

    Estimator of ∂F/∂μ\partial F/\partial\mu Mean Per-sample variance NN for standard error 0.10.1
    pathwise 2x2x 4 4 400
    score x2(x−μ)x^2(x - \mu) 4 87 8,700
    score, b=5b = 5 4 42 4,200
    score, b∗=7b^* = 7 4 38 3,800
    Interactive figure: loading…

    Three estimators of the same gradient. Each histogram shows 4000 estimates of ∂F/∂μ\partial F/\partial\mu for x∼N(μ,1)x \sim N(\mu, 1), f=x2f = x^2: pathwise, score function and score function with baseline bb. All three have the same mean, the true value 2μ2\mu (black line), but the score-function histograms are wide and skewed. Move bb and find the narrowest violet histogram; the button b=b∗b = b^* sets b∗=μ2+3b^* = \mu^2 + 3. Increase NN: every histogram gets narrower by a factor N\sqrt N and more symmetric, but the order stays.

    Quick check

    The score-function estimator above has per-sample variance 8787. How many samples do you need for a standard error of 0.10.1?

    5. In code #

    NumPy checks every number of the worked example: exact moments by quadrature, then Monte Carlo with 400,000400{,}000 samples, then the moving-support example.

    import numpy as np
    from scipy import integrate
    
    # (a) exact mean and per-sample variance by quadrature over eps ~ N(0, 1)
    phi = lambda e: np.exp(-e**2 / 2) / np.sqrt(2 * np.pi)
    def mean_var(g):
        m = integrate.quad(lambda e: g(e) * phi(e), -np.inf, np.inf)[0]
        s = integrate.quad(lambda e: g(e)**2 * phi(e), -np.inf, np.inf)[0]
        return round(m, 4), round(s - m**2, 4)
    
    mu = 2.0                                    # x = mu + eps, f(x) = x^2, dF/dmu = 4
    for name, g in [("pathwise   ", lambda e: 2 * (mu + e)),
                    ("score      ", lambda e: (mu + e)**2 * e),
                    ("score, b=5 ", lambda e: ((mu + e)**2 - 5) * e),
                    ("score, b=7 ", lambda e: ((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 samples
    rng = np.random.default_rng(0)
    eps = rng.standard_normal(400_000)
    x = mu + eps
    g_path = 2 * x                  # f'(x) * dx/dmu, with dx/dmu = 1
    g_score = x**2 * eps            # f(x) * score, score = (x - mu) / sigma^2 = eps
    print(round(g_path.mean(), 2), round(g_path.var(), 1))     # 4.0 4.0
    print(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/2
    theta = 1.0
    u = rng.uniform(size=400_000)
    xu = theta * u
    print(round(np.mean(xu * (-1 / theta)), 3))   # -0.5: score function, d/dtheta log(1/theta) = -1/theta
    print(round(np.mean(1.0 * u), 3))             # 0.5: pathwise, f'(x) * dx/dtheta = 1 * u
    

    In PyTorch, rsample() keeps the path x=g(ϵ,θ)x = g(\epsilon, \theta) in the graph; sample() does not. The score-function estimator is the gradient of a surrogate f(x)log⁡pθ(x)f(x)\log p_\theta(x), where f(x)f(x) enters as a constant:

    import torch
    from torch.distributions import Normal
    
    torch.manual_seed(0)
    n = 400_000
    mu = torch.full((n,), 2.0, requires_grad=True)   # one copy of mu per sample
    dist = Normal(mu, 1.0)
    
    (dist.rsample() ** 2).sum().backward()         # rsample: x = mu + eps, a differentiable path
    g_path = mu.grad.clone()
    mu.grad = None
    
    xs = dist.sample()                              # sample: no path, xs carries no gradient
    (xs ** 2 * dist.log_prob(xs)).sum().backward()  # surrogate: f(x) enters as a constant weight
    g_score = mu.grad.clone()
    
    print(round(g_path.mean().item(), 2), round(g_path.var().item(), 1))    # 3.99 4.0
    print(round(g_score.mean().item(), 2), round(g_score.var().item(), 1))  # 3.99 86.2
    

    Two practical points. First, the surrogate f(x)log⁡pθ(x)f(x)\log p_\theta(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 ff also depends on θ\theta, add the ordinary term: ∇θEpθ[fθ(x)]=E[∇θfθ(x)]+E[fθ(x) sθ(x)]\nabla_\theta \mathbb E_{p_\theta}[f_\theta(x)] = \mathbb E[\nabla_\theta f_\theta(x)] + \mathbb E[f_\theta(x)\, s_\theta(x)].

    6. Where it shows up #

    • VAEs. The ELBO is Eqϕ(z∣x)[log⁡pθ(x∣z)]−KL(qϕ(z∣x) ∥ p(z))\mathbb E_{q_\phi(z \mid x)}[\log p_\theta(x \mid z)] - \mathrm{KL}(q_\phi(z \mid x)\,\|\,p(z)). The decoder parameters θ\theta appear only in ff: an ordinary gradient. The encoder parameters ϕ\phi define the distribution: pathwise, with z=μϕ(x)+σϕ(x)⊙ϵz = \mu_\phi(x) + \sigma_\phi(x) \odot \epsilon. 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: ∇θlog⁡pθ(τ)=∑t∇θlog⁡πθ(at∣st)\nabla_\theta \log p_\theta(\tau) = \sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t). The unknown dynamics of the environment do not depend on θ\theta, 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(μ+σϵ) ϵ]/σ\nabla_\mu \mathbb E_\epsilon[f(\mu + \sigma\epsilon)] = \mathbb E[f(\mu + \sigma\epsilon)\,\epsilon]/\sigma. This is the score-function estimator of N(μ,σ2I)N(\mu, \sigma^2 I). The antithetic form [f(μ+σϵ)−f(μ−σϵ)] ϵ/(2σ)[f(\mu + \sigma\epsilon) - f(\mu - \sigma\epsilon)]\,\epsilon/(2\sigma) 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;θ)C(x; \theta) as the standardizing map: from ϵ=C(x;θ)\epsilon = C(x; \theta) with ϵ∼Uniform(0,1)\epsilon \sim \mathrm{Uniform}(0, 1), implicit differentiation (lesson 09) gives ∇θx=−∇θC(x;θ)/pθ(x)\nabla_\theta x = -\nabla_\theta C(x; \theta)/p_\theta(x). PyTorch's Gamma, Beta and Dirichlet have rsample.

    7. Common mistakes #

    • 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=μ+σϵx = \mu + \sigma\epsilon.
    • A baseline that depends on the sample. b=f(xi)b = f(x_i), a group mean that includes xix_i, 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. ∇θlog⁡pθ(x)\nabla_\theta \log p_\theta(x) (parameters; this lesson) is not ∇xlog⁡p(x)\nabla_x \log p(x) (data; score matching and diffusion).
    • Forgetting the direct term. If ff depends on θ\theta too, E[∇θfθ]\mathbb E[\nabla_\theta f_\theta] 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 log⁡pθ\log p_\theta in the score. It misses −∇θlog⁡Z(θ)-\nabla_\theta \log Z(\theta).

    8. Check yourself #

    1. x∼N(μ,σ2)x \sim N(\mu, \sigma^2) and f(x)=xf(x) = x. Give the pathwise and score-function estimates of ∂F/∂μ\partial F/\partial\mu and their variances. What does the baseline b=μb = \mu do?
      AnswerPathwise: f′(x)=1f'(x) = 1, variance 00. Score: x(x−μ)/σ2=μϵ/σ+ϵ2x(x - \mu)/\sigma^2 = \mu\epsilon/\sigma + \epsilon^2 (with x=μ+σϵx = \mu + \sigma\epsilon), mean 11, variance μ2/σ2+2\mu^2/\sigma^2 + 2. With b=μb = \mu: (x−μ)2/σ2=ϵ2(x - \mu)^2/\sigma^2 = \epsilon^2, mean 11, variance 22 for every μ\mu.
    2. x∼Bernoulli(θ)x \sim \mathrm{Bernoulli}(\theta). Show that E[sθ]=0\mathbb E[s_\theta] = 0 and that E[f(x) sθ(x)]=f(1)−f(0)\mathbb E[f(x)\, s_\theta(x)] = f(1) - f(0). Why is there no pathwise estimator?
      Answersθ(1)=1/θs_\theta(1) = 1/\theta and sθ(0)=−1/(1−θ)s_\theta(0) = -1/(1-\theta). E[s]=θ/θ−(1−θ)/(1−θ)=0\mathbb E[s] = \theta/\theta - (1-\theta)/(1-\theta) = 0. E[fs]\mathbb E[f s] =θf(1)/θ−(1−θ)f(0)/(1−θ)= \theta f(1)/\theta - (1-\theta) f(0)/(1-\theta) =f(1)−f(0)= f(1) - f(0). Any path g(ϵ,θ)∈{0,1}g(\epsilon, \theta) \in \{0, 1\} (for example 1[u<θ]\mathbf 1[u < \theta] with u∼Uniform(0,1)u \sim \mathrm{Uniform}(0,1)) is piecewise constant in θ\theta. Where it is differentiable, its derivative is 00, so the chain rule gives 00 instead of f(1)−f(0)f(1) - f(0).
    3. x∼Exp(λ)x \sim \mathrm{Exp}(\lambda) (density λe−λx\lambda e^{-\lambda x}, x>0x > 0) and f(x)=xf(x) = x. Derive both estimates of dF/dλdF/d\lambda and their variances.
      AnswerF=1/λF = 1/\lambda, F′=−1/λ2F' = -1/\lambda^2. Pathwise: x=ϵ/λx = \epsilon/\lambda with ϵ∼Exp(1)\epsilon \sim \mathrm{Exp}(1), so ∂x/∂λ=−x/λ\partial x/\partial\lambda = -x/\lambda. Mean −1/λ2-1/\lambda^2, variance Var⁡(x)/λ2=1/λ4\operatorname{Var}(x)/\lambda^2 = 1/\lambda^4. Score: s=1/λ−xs = 1/\lambda - x, estimate x(1/λ−x)x(1/\lambda - x). Using E[xk]=k!/λk\mathbb E[x^k] = k!/\lambda^k: mean 1/λ2−2/λ2=−1/λ21/\lambda^2 - 2/\lambda^2 = -1/\lambda^2; second moment E[x2]/λ2−2E[x3]/λ+E[x4]\mathbb E[x^2]/\lambda^2 - 2\mathbb E[x^3]/\lambda + \mathbb E[x^4] =(2−12+24)/λ4= (2 - 12 + 24)/\lambda^4 =14/λ4= 14/\lambda^4; variance 13/λ413/\lambda^4, thirteen times larger.
    4. x∼N(μ,1)x \sim N(\mu, 1). Is the pathwise estimator of ∂F/∂μ\partial F/\partial\mu valid for f(x)=∣x∣f(x) = |x|? For f(x)=round(x)f(x) = \mathrm{round}(x) (the nearest integer)?
      Answer∣x∣|x|: yes. It is Lipschitz, and its kink at 00 has probability 00. The estimate is sign(x)\mathrm{sign}(x), with mean 2Φ(μ)−1=ddμE∣x∣2\Phi(\mu) - 1 = \frac{d}{d\mu}\mathbb E|x| (Φ\Phi is the standard normal CDF). round(x)\mathrm{round}(x): no. It jumps by 1 at every half-integer, so f′=0f' = 0 almost everywhere and the estimate is 00. The true gradient is ∑kφ(k+12−μ)≈1\sum_k \varphi(k + \tfrac12 - \mu) \approx 1 (φ\varphi 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.
    5. For each prompt you sample K=4K = 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ˉ=34(fi−fˉ−i)f_i - \bar f = \frac34(f_i - \bar f_{-i}), so the estimate is 34\frac34 times the unbiased leave-one-out estimate: its mean is 34∇F\frac34 \nabla F. The direction is right, but the length is off. The leave-one-out mean fˉ−i\bar 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.
    1. State the score-function (REINFORCE) identity.

    2. Why does the score ∇θlog⁡pθ(x)\nabla_\theta \log p_\theta(x) have mean zero?

    3. Write the pathwise (reparameterization) gradient for x=g(ϵ,θ)x = g(\epsilon, \theta).

    4. How do you reparameterize x∼N(μ,σ2)x \sim N(\mu, \sigma^2), and what are ∂x/∂μ\partial x/\partial\mu and ∂x/∂σ\partial x/\partial\sigma?

    5. Why does a baseline bb not change the mean of the score-function estimator?

    6. What is the best constant baseline for a scalar parameter?

    7. For x∼N(2,1)x \sim N(2, 1) and f=x2f = x^2, what are the per-sample variances of the pathwise and score-function estimators of ∂F/∂μ\partial F/\partial\mu?

    8. Why does the pathwise estimator fail for f(x)=1[x>1]f(x) = \mathbf 1[x > 1]?

    9. x∼Uniform(0,θ)x \sim \mathrm{Uniform}(0, \theta), f(x)=xf(x) = x. What does the score-function estimator give, and why?

    10. Which estimator does a VAE encoder use, and which does a policy gradient use?

    Open the review →

    9. Interview angle #

    • "What is the reparameterization trick, and why does it reduce variance?" Write x=g(ϵ,θ)x = g(\epsilon, \theta) with ϵ\epsilon independent of θ\theta and differentiate through ff. The variance follows the slope of ff, not the value of ff 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 ∇log⁡p]\nabla F = \mathbb E[f\,\nabla\log p]; E[∇log⁡p]=0\mathbb E[\nabla \log p] = 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(ϵ,θ)x = g(\epsilon, \theta) in the computational graph; sample() does not.

    10. Practice #

    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:

    1. Write pathwise_grad_samples and score_function_grad_samples for N(μ,σ2)N(\mu, \sigma^2) and check their means against the exact gradient of E[x2]\mathbb E[x^2] for μ\mu and σ\sigma.
    2. Measure the variance of the score-function estimator as a function of the baseline bb, and find b∗b^* from samples and from the formula.
    3. Discrete samples: the score of Bernoulli(sigmoid(θ))\mathrm{Bernoulli}(\mathrm{sigmoid}(\theta)) and the gradient of an expected reward, compared with the exact value.
    4. The moving support of Uniform(0,θ)\mathrm{Uniform}(0, \theta): measure the bias of the score-function estimator and recover the missing boundary term.
    5. Demo: minimize E[(x−3)2]\mathbb E[(x - 3)^2] over the mean μ\mu 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.

    11. Watch and read #

    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,θ)\mathrm{Uniform}(0, \theta) 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).
    • Schulman, Heess, Weber and Abbeel, Gradient Estimation Using Stochastic Computation Graphs (NeurIPS 2015): how autodiff frameworks combine score-function and pathwise terms with surrogate losses.
    • Sutton and Barto, Reinforcement Learning: An Introduction, 2nd edition, free PDF: §13.3 (REINFORCE) and §13.4 (REINFORCE with baseline).
    • PyTorch documentation, torch.distributions: the sections "Score function" and "Pathwise derivative".