22.7 Expectations and Their Gradients

Almost every loss we have minimized so far is an average: over a minibatch of examples, over random dropout masks, or over noise injected into an input. As long as the source of randomness does not depend on the model parameters, differentiating such an average is straightforward. The derivative of an average equals the average of the derivatives, so minibatch gradient descent computes it directly without any extra machinery. The difficulty arises when the parameters control the probability distribution itself. A variational autoencoder draws its latent code from a distribution whose mean and variance are produced by its encoder; a policy-gradient agent (Section 14.7) samples actions from the very policy it is trying to improve. In both cases, the objective is an expectation over samples whose distribution shifts with the parameters, yet a sample, once drawn, is just a number. It carries no memory of the parameter that generated it.

Consider the simplest problem of this kind. Let X∼N(θ,1)X\sim\mathcal N(\theta,1) be a normal random variable with mean θ\theta and unit variance, and take the expected squared loss

ℓ(θ)=E[X2]=θ2+1.\ell(\theta)=\mathbb{E}\bigl[X^2\bigr]=\theta^2+1 .

The closed form follows immediately by writing X=θ+ZX=\theta+Z with ZZ standard normal: E[(θ+Z)2]=θ2+2θ E[Z]+E[Z2]\mathbb{E}[(\theta+Z)^2]=\theta^2+2\theta\,\mathbb{E}[Z]+\mathbb{E}[Z^2], where E[Z]=0\mathbb{E}[Z]=0 by symmetry and E[Z2]=1\mathbb{E}[Z^2]=1 (Section 22.6.2.3). At θ=1.5\theta=1.5, the exact derivative is ℓ′(1.5)=3\ell'(1.5)=3. In practice, however, a model can draw samples of XX but cannot evaluate ℓ(θ)\ell(\theta) in closed form. How, then, can we estimate ℓ′(θ)\ell'(\theta) from samples alone?

Calculus offers two fundamentally different answers. Both express the expectation as an integral (Section 22.6) and pass the derivative inside it. From there they diverge: the score-function estimator differentiates the probability density while leaving the samples untouched, whereas the pathwise estimator differentiates the samples while leaving the noise density untouched. Neither method dominates in every setting, and comparing them (Section 22.7.3) is the central goal of this section. First, we briefly recall how expectations are written as integrals and establish when passing a derivative inside an integral is valid, because that step is where subtle errors can creep in.

22.7.1 Expectations as Integrals#

Before differentiating anything, let us fix our notation for densities and expectations. The probability chapter develops both notions in detail (Section 24.1); here we restate them in the integral language of the preceding section. A probability density on a domain X\mathcal X is a nonnegative function whose total integral equals 11:

p(x)≥0,∫Xp(x) dx=1.(22.7.1)p(x)\ge 0, \qquad \int_{\mathcal X} p(x)\,dx = 1 . \tag{22.7.1}

The probability that a random variable XX with density pp lands in an interval [a,b][a, b] is the area under pp over that interval, P(a≤X≤b)=∫abp(x) dxP(a\le X\le b)=\int_a^b p(x)\,dx (Section 24.1). Because a density measures probability per unit length rather than probability itself, its value can exceed 11; for example, the uniform density on [0,12][0,\tfrac12] equals 22 everywhere on its support. Our main running example is the standard normal distribution N(0,1)\mathcal N(0,1), whose density p(z)=e−z2/2/2πp(z)=e^{-z^2/2}/\sqrt{2\pi} is normalized by the Gaussian integral of Section 22.6.

An expectation computes the weighted average of XX, or of a function g(X)g(X), weighting each outcome by its probability density:

E[X]=∫Xx p(x) dx,E[g(X)]=∫Xg(x) p(x) dx.(22.7.2)\mathbb{E}[X] = \int_{\mathcal X} x\,p(x)\,dx, \qquad \mathbb{E}[g(X)] = \int_{\mathcal X} g(x)\,p(x)\,dx . \tag{22.7.2}

The expectation E[g(X)]\mathbb{E}[g(X)] is well defined whenever the integral converges absolutely, ∫X∣g(x)∣ p(x) dx<∞\int_{\mathcal X}|g(x)|\,p(x)\,dx\lt \infty. Heavy-tailed distributions can violate this condition; the Cauchy density in exercise 2, for instance, has no finite mean.

In deep learning, expectations rarely have closed-form expressions, and they often live in thousands of dimensions where numerical quadrature on a grid is out of the question. Instead, we draw independent samples x1,…,xnx_1,\ldots,x_n from pp and form the sample average 1n∑i=1ng(xi)\frac1n\sum_{i=1}^n g(x_i), known as the Monte Carlo estimate. If a single sample g(X)g(X) has standard deviation σ\sigma, the Monte Carlo average has root-mean-square error σ/n\sigma/\sqrt n, regardless of the dimension (Section 24.5.1.7). Both gradient estimators in this section are Monte Carlo averages of this form. Because both are unbiased for the same true gradient, they differ only in the spread of a single sample, making the single-sample standard deviation σ\sigma the natural yardstick for comparing them.

22.7.2 Differentiation under the Integral Sign#

22.7.2.1 The Swap#

Our toy loss ℓ(θ)=E[X2]\ell(\theta)=\mathbb{E}[X^2] is an integral that varies with a parameter θ\theta. In general, a parameter can affect an integral in two places: through the limits of integration, which the fundamental theorem of calculus (Section 22.6) handles, or through the integrand itself.

When the limits of integration are fixed and only the integrand depends on θ\theta, we differentiate by passing the derivative inside the integral:

ddθ∫f(x,θ) dx=∫∂f∂θ(x,θ) dx.(22.7.3)\frac{d}{d\theta} \int f(x, \theta)\,dx = \int \frac{\partial f}{\partial\theta}(x, \theta)\,dx . \tag{22.7.3}

Geometrically, the rate of change of the total area equals the integral of the pointwise rate of change of the height. We will refer to this exchange of derivative and integral as the swap; both gradient estimators depend on it. At first glance the identity looks harmless, since a derivative is a limit of difference quotients, an integral is a limit of sums, and finite sums and differences always commute. Yet exchanging two limits is never automatic and requires regularity conditions. On a bounded interval of xx, continuity of ∂θf\partial_\theta f in both variables is enough. On an unbounded domain, we also need an integrable function of xx that dominates ∣∂θf(x,θ′)∣|\partial_\theta f(x,\theta')| for all θ′\theta' near θ\theta (an immediate consequence of the dominated convergence theorem, quoted without proof from (Folland, 1999)). For our running example f(x,θ)=x2pθ(x)f(x,\theta)=x^2p_\theta(x) with a normal density, such a dominating bound always exists because the Gaussian tail decays faster than any polynomial grows.

22.7.2.2 The Leibniz Rule#

When the limits of integration also move with θ\theta, the plain swap is incomplete and gives the wrong answer. The Leibniz rule supplies the missing boundary terms: the interior change and the sweeping boundaries simply add (Figure 22.7.1).

Proposition (Leibniz rule). Let ff and ∂θf\partial_\theta f be continuous on a region containing {(x,θ):x∈[a(θ),b(θ)]}\{(x,\theta):x\in[a(\theta),b(\theta)]\} for θ\theta in an open interval, and let aa and bb be differentiable. Then

ddθ∫a(θ)b(θ)f(x,θ) dx=∫a(θ)b(θ)∂f∂θ(x,θ) dx+f(b(θ),θ) b′(θ)−f(a(θ),θ) a′(θ).(22.7.4)\frac{d}{d\theta} \int_{a(\theta)}^{b(\theta)} f(x, \theta)\,dx = \int_{a(\theta)}^{b(\theta)} \frac{\partial f}{\partial\theta}(x,\theta)\,dx + f\bigl(b(\theta), \theta\bigr)\,b'(\theta) - f\bigl(a(\theta), \theta\bigr)\,a'(\theta) . \tag{22.7.4}

Proof. Define H(α,β,θ)=∫αβf(x,θ) dxH(\alpha,\beta,\theta)=\int_\alpha^\beta f(x,\theta)\,dx. By the fundamental theorem of calculus, ∂βH=f(β,θ)\partial_\beta H=f(\beta,\theta) and ∂αH=−f(α,θ)\partial_\alpha H=-f(\alpha,\theta), while the swap on the bounded interval [α,β][\alpha,\beta] gives ∂θH=∫αβ∂θf dx\partial_\theta H=\int_\alpha^\beta\partial_\theta f\,dx. Since all three partial derivatives are continuous, the multivariable chain rule (Section 22.3) applies to the composition θ↦H(a(θ),b(θ),θ)\theta\mapsto H(a(\theta),b(\theta),\theta) and combines the three terms weighted by a′(θ)a'(\theta), b′(θ)b'(\theta), and 11. ■\blacksquare

Figure 22.7.1:

The Leibniz rule for f(x,θ)=x/θf(x,\theta)=x/\theta on [0,θ][0,\theta], the uniform example. When θ\theta increases by dθd\theta, the integrand curve shifts to f(⋅,θ+dθ)f(\cdot,\theta+d\theta) (dashed; here it drops, so the hatched region represents lost area), while the right boundary moves outward and sweeps in a strip of height f(b,θ)f(b,\theta) and width b′ dθb'\,d\theta.

Ignoring the boundary term is not a minor inaccuracy; it can flip the sign of the derivative. Suppose XX is uniform on [0,θ][0,\theta], with density 1/θ1/\theta on that interval. Its mean is E[X]=∫0θxθ dx=θ2\mathbb{E}[X]=\int_0^\theta\frac x\theta\,dx=\frac\theta2, whose derivative is +12+\tfrac12. Differentiating only the integrand gives ∫0θ−xθ2 dx=−12\int_0^\theta-\frac{x}{\theta^2}\,dx=-\tfrac12, which has the wrong sign. Adding the upper boundary contribution f(θ,θ) b′(θ)=θθ⋅1=1f(\theta,\theta)\,b'(\theta)=\frac\theta\theta\cdot1=1 restores the true derivative, −12+1=+12-\tfrac12+1=+\tfrac12. Whenever the support of a distribution depends on the parameter, the plain swap alone is not valid (exercise 1 works out E[X2]\mathbb{E}[X^2]).

22.7.2.3 Log-Integral-Exp#

The swap also produces the continuous counterpart of the log-sum-exp function. Applying the chain rule and (22.7.3) to log⁡∫eθxp(x) dx\log\int e^{\theta x}p(x)\,dx yields

ddθlog⁡∫eθxp(x) dx=∫x eθxp(x) dx∫eθxp(x) dx.\frac{d}{d\theta}\log\int e^{\theta x}p(x)\,dx=\frac{\int x\,e^{\theta x}p(x)\,dx}{\int e^{\theta x}p(x)\,dx}.

The right-hand side is the mean of xx under the exponentially tilted density proportional to eθxp(x)e^{\theta x}p(x). For the standard normal density, completing the square via θz−12z2=12θ2−12(z−θ)2\theta z-\tfrac12z^2=\tfrac12\theta^2-\tfrac12(z-\theta)^2 shows that the tilted density is N(θ,1)\mathcal N(\theta,1) and that log⁡E[eθZ]=θ2/2\log\mathbb{E}[e^{\theta Z}]=\theta^2/2, whose derivative θ\theta is indeed the tilted mean. Just as the gradient of log-sum-exp is the softmax vector, the gradient of log-integral-exp is an expectation. We will encounter this identity again as the derivative A′(η)A'(\eta) of the log-partition function in Section 24.4.

22.7.3 Score-Function and Pathwise Gradients#

Applying the swap to an expected loss gives the integral ∫g(x) ∂θpθ(x) dx\int g(x)\,\partial_\theta p_\theta(x)\,dx. Unfortunately, we cannot estimate this integral directly by Monte Carlo sampling: ∂θpθ\partial_\theta p_\theta is not a probability density (it takes both positive and negative values and integrates to zero), so we cannot draw samples from it. Two simple identities rewrite this integral back into an expectation that samples can estimate.

22.7.3.1 The Score-Function Estimator#

Let pθp_{\boldsymbol\theta} be a density parameterized by θ\boldsymbol\theta. Applying the chain rule to log⁡pθ(x)\log p_{\boldsymbol\theta}(x) yields the log-derivative identity:

∇θ pθ(x)=pθ(x) ∇θlog⁡pθ(x).(22.7.5)\nabla_{\boldsymbol\theta}\,p_{\boldsymbol\theta}(x)=p_{\boldsymbol\theta}(x)\,\nabla_{\boldsymbol\theta}\log p_{\boldsymbol\theta}(x). \tag{22.7.5}

In words, the gradient of a density equals the density itself multiplied by the gradient of its logarithm, a vector known as the score ∇θlog⁡pθ\nabla_{\boldsymbol\theta}\log p_{\boldsymbol\theta}. Whenever the swap is valid and the support of pθp_{\boldsymbol\theta} does not move with θ\boldsymbol\theta, the score has expectation zero: E[∇θlog⁡pθ(X)]=∫∇θpθ dx=∇θ∫pθ dx=∇θ1=0\mathbb{E}[\nabla_{\boldsymbol\theta}\log p_{\boldsymbol\theta}(X)]=\int\nabla_{\boldsymbol\theta}p_{\boldsymbol\theta}\,dx=\nabla_{\boldsymbol\theta}\int p_{\boldsymbol\theta}\,dx=\nabla_{\boldsymbol\theta}1=\mathbf 0. The uniform density on [0,θ][0,\theta] shows why fixed support is essential: its score is ∂θlog⁡(1/θ)=−1/θ\partial_\theta\log(1/\theta)=-1/\theta, whose expectation is −1/θ≠0-1/\theta\ne0, because differentiating ∫0θpθ(x) dx=1\int_0^\theta p_\theta(x)\,dx=1 also picks up the boundary term pθ(θ)=1/θp_\theta(\theta)=1/\theta. The mean-zero property of the score is also the starting point for Fisher information (Section 24.6).

Multiplying (22.7.5) by a function g(x)g(x) that does not depend on θ\boldsymbol\theta and integrating gives the score-function identity:

∇θ EX∼pθ[g(X)]=∫g(x) ∇θpθ(x) dx=E[g(X) ∇θlog⁡pθ(X)].(22.7.6)\nabla_{\boldsymbol{\theta}}\,\mathbb{E}_{X\sim p_{\boldsymbol{\theta}}}[g(X)] =\int g(x)\,\nabla_{\boldsymbol\theta}p_{\boldsymbol\theta}(x)\,dx = \mathbb{E}\bigl[g(X)\,\nabla_{\boldsymbol{\theta}}\log p_{\boldsymbol{\theta}}(X)\bigr]. \tag{22.7.6}

This identity turns the gradient of an expected loss back into an expectation under pθp_{\boldsymbol\theta}: each sample's loss g(x)g(x) is weighted by how strongly θ\boldsymbol\theta increases that sample's log-probability. To estimate it by Monte Carlo, we draw samples xi∼pθx_i\sim p_{\boldsymbol\theta} and average g(xi)∇θlog⁡pθ(xi)g(x_i)\nabla_{\boldsymbol\theta}\log p_{\boldsymbol\theta}(x_i). In reinforcement learning, this is the REINFORCE estimator of policy-gradient methods (Section 14.7) (Williams, 1992). (If gg also depends directly on θ\boldsymbol\theta, the product rule simply adds the term E[∇θg(X,θ)]\mathbb{E}[\nabla_{\boldsymbol\theta}g(X,\boldsymbol\theta)].)

Because the score has mean zero, we may subtract any constant baseline bb (independent of xx) from g(X)g(X) without biasing the estimator (Section 14.8): E[(g(X)−b)∇θlog⁡pθ(X)]=E[g(X)∇θlog⁡pθ(X)]\mathbb{E}[(g(X)-b)\nabla_{\boldsymbol\theta}\log p_{\boldsymbol\theta}(X)]=\mathbb{E}[g(X)\nabla_{\boldsymbol\theta}\log p_{\boldsymbol\theta}(X)]. Choosing bb well can substantially reduce the variance of the estimate.

22.7.3.2 The Pathwise Estimator#

The second identity restores the sample's memory of θ\boldsymbol\theta. Often, a sample from pθp_{\boldsymbol\theta} can be generated by applying a deterministic transformation x=Tθ(z)x=T_{\boldsymbol\theta}(\mathbf z) to an auxiliary noise variable z∼q\mathbf z\sim q whose distribution does not depend on θ\boldsymbol\theta. A normal random variable N(μ,σ2)\mathcal N(\mu,\sigma^2), for instance, is simply μ+σz\mu+\sigma z with z∼N(0,1)z\sim\mathcal N(0,1). Rewriting the expectation as an integral over z\mathbf z removes θ\boldsymbol\theta from the density entirely, so the swap yields the pathwise identity:

∇θ EX∼pθ[g(X)]=∇θ∫g(Tθ(z)) q(z) dz=Ez∼q[∇θ g(Tθ(z))].(22.7.7)\nabla_{\boldsymbol\theta}\, \mathbb{E}_{X\sim p_{\boldsymbol\theta}}[g(X)] =\nabla_{\boldsymbol\theta}\int g\bigl(T_{\boldsymbol\theta}(\mathbf z)\bigr)\,q(\mathbf z)\,d\mathbf z =\mathbb{E}_{\mathbf z\sim q} \Bigl[\nabla_{\boldsymbol\theta}\, g\bigl(T_{\boldsymbol\theta}(\mathbf z)\bigr)\Bigr]. \tag{22.7.7}

Instead of differentiating the density, this estimator differentiates right through the sample: automatic differentiation traces the path from θ\boldsymbol\theta through TθT_{\boldsymbol\theta} into gg. Known as the reparameterization trick, this is how variational autoencoders backpropagate through Gaussian latent variables (Kingma and Welling, 2014; Rezende et al., 2014). The estimator itself is older: the simulation literature had long used it under the names pathwise and infinitesimal-perturbation derivative (Mohamed et al., 2020). Valid use requires TθT_{\boldsymbol\theta} to be differentiable in θ\boldsymbol\theta, gg to be differentiable along the path (a Lipschitz gg suffices when XX has a continuous density), and an integrable dominating bound for the swap. Notice that no boundary term ever appears, even if the support of XX moves with θ\boldsymbol\theta, because the integral is taken over z\mathbf z whose density qq stays fixed.

The differentiability requirement on gg is not a technicality we can ignore. Consider the step function g(x)=1(x>0)g(x)=\mathbf{1}(x>0), which equals 11 for positive xx and 00 otherwise, with X=θ+zX=\theta+z. The true expectation E[g(X)]=P(z>−θ)\mathbb{E}[g(X)]=P(z>-\theta) has derivative φ(θ)=e−θ2/2/2π\varphi(\theta)=e^{-\theta^2/2}/\sqrt{2\pi}, which evaluates to about 0.130.13 at θ=1.5\theta=1.5. Yet the pathwise sample ∂θ1(θ+z>0)\partial_\theta\mathbf{1}(\theta+z>0) is 00 for every zz except the single point z=−θz=-\theta (an event of probability zero), so the pathwise estimator returns 00 with probability 11. By contrast, the score-function sample 1(x>0) z\mathbf{1}(x>0)\,z has expectation ∫−θ∞z φ(z) dz=[−φ(z)]−θ∞=φ(θ)\int_{-\theta}^\infty z\,\varphi(z)\,dz=\bigl[-\varphi(z)\bigr]_{-\theta}^\infty=\varphi(\theta), recovering the exact derivative. Because the score-function estimator never differentiates through gg or the sampling step, it applies equally well to discontinuous losses and to discrete distributions such as Bernoulli or categorical choices, where no differentiable path from θ\boldsymbol\theta to the sample exists.

22.7.3.3 The Two Estimators Compared#

We now have two unbiased estimators of the same derivative, and our running example ℓ(θ)=E[X2]\ell(\theta)=\mathbb{E}[X^2] with X=θ+zX=\theta+z is simple enough to compute the variance of both by hand. For the pathwise estimator, a single sample contributes ∂θ(θ+z)2=2X\partial_\theta(\theta+z)^2 = 2X, whose variance is Var(2X)=4\textrm{Var}(2X)=4. For the score-function estimator, the score of the normal location family is ∂θlog⁡pθ(X)=X−θ=z\partial_\theta\log p_\theta(X)=X-\theta=z, so one sample contributes X2zX^2z, or (X2−b)z(X^2-b)z when using a baseline bb. To find the variance of X2zX^2z, we use the standard normal moments E[z2]=1\mathbb{E}[z^2]=1, E[z4]=3\mathbb{E}[z^4]=3, and E[z6]=15\mathbb{E}[z^6]=15, all of which follow from Stein's identity E[g′(Z)]=E[Z g(Z)]\mathbb{E}[g'(Z)]=\mathbb{E}[Z\,g(Z)] (Section 22.6.2.3). By symmetry, all odd powers of zz vanish in the second moment:

E[(θ+z)4z2]=θ4 E[z2]+6θ2 E[z4]+E[z6]=θ4+18θ2+15.\mathbb{E}\bigl[(\theta+z)^4z^2\bigr]=\theta^4\,\mathbb{E}[z^2]+6\theta^2\,\mathbb{E}[z^4]+\mathbb{E}[z^6]=\theta^4+18\theta^2+15.

Subtracting the squared mean (2θ)2(2\theta)^2 leaves a variance of θ4+14θ2+15\theta^4+14\theta^2+15. The variance-minimizing constant baseline turns out to be b⋆=θ2+3b^\star=\theta^2+3, reducing the variance to 8θ2+68\theta^2+6 (exercise 2). At θ=1.5\theta=1.5, the three single-sample standard deviations are 22 for the pathwise estimator, 7.187.18 for the plain score-function estimator, and 4.904.90 for the score-function estimator with the optimal baseline. Although the baseline helps noticeably, it cannot close the gap for this loss, since 8θ2+6>48\theta^2+6>4 for every θ\theta.

Let us test all three closed-form predictions in a single Monte Carlo simulation. Because the pathwise derivative is simply 2xi2x_i, we do not even need automatic differentiation here. If our algebra is right, the three sample standard deviations should land near 22, 7.187.18, and 4.904.90, and each sample mean should fall within a few standard errors sd/n\mathrm{sd}/\sqrt n of the true derivative 33.

theta, n = 1.5, 200_000
z = np.random.default_rng().standard_normal(n)     # noise, independent of theta
x = theta + z                                      # samples of N(theta, 1)
pathwise = 2 * x                                   # d/dtheta (theta + z_i)^2
score = x**2 * z                                   # g(x) times the score x - theta
baseline = (x**2 - (theta**2 + 3)) * z             # with the optimal baseline
exact_sd = {'pathwise': 2, 'score': math.sqrt(theta**4 + 14 * theta**2 + 15),
            'score+baseline': math.sqrt(8 * theta**2 + 6)}
print(f'true derivative 2*theta = {2 * theta}')
for name, s in zip(exact_sd, [pathwise, score, baseline]):
    print(f'{name:15s} mean={s.mean():.4f}  sd={s.std():.3f} '
          f'(exact {exact_sd[name]:.3f})  se={s.std() / math.sqrt(n):.4f}')
true derivative 2*theta = 3.0
pathwise        mean=3.0041  sd=2.000 (exact 2.000)  se=0.0045
score           mean=3.0068  sd=7.146 (exact 7.181)  se=0.0160
score+baseline  mean=2.9961  sd=4.858 (exact 4.899)  se=0.0109

In typical runs, all three means lie within a couple of standard errors of 33, and the empirical standard deviations match the closed-form predictions to within a few percent. For a fixed sample budget, the pathwise estimate is about 3.63.6 times more accurate than the plain score-function estimate; equivalently, the plain score-function estimator needs roughly thirteen times as many samples to reach the same precision.

It would be a mistake, however, to conclude that the pathwise estimator always has lower variance. Consider an oscillating loss g(x)=sin⁡(ωx)g(x)=\sin(\omega x), for which the true derivative of the expectation is ωcos⁡(ωθ)e−ω2/2\omega\cos(\omega\theta)e^{-\omega^2/2}. The pathwise sample ωcos⁡(ωX)\omega\cos(\omega X) scales with the frequency ω\omega and has standard deviation close to ω/2\omega/\sqrt2, whereas the score-function sample sin⁡(ωX) z\sin(\omega X)\,z has standard deviation at most E[z2]=1\sqrt{\mathbb{E}[z^2]}=1 because ∣sin⁡∣≤1|\sin|\le1. Whenever an integrand oscillates rapidly, its derivative can be huge even while its values remain bounded. Let us compare the two estimators at ω=1\omega=1 and ω=3\omega=3, reusing the samples already drawn.

for omega in [1, 3]:
    true = omega * math.cos(omega * theta) * math.exp(-omega**2 / 2)
    path, score = omega * np.cos(omega * x), np.sin(omega * x) * z
    print(f'omega={omega}  true={true:+.4f}  pathwise {path.mean():+.4f} '
          f'(sd {path.std():.2f})  score {score.mean():+.4f} (sd {score.std():.2f})')
omega=1  true=+0.0429  pathwise +0.0414 (sd 0.66)  score +0.0432 (sd 0.54)
omega=3  true=-0.0070  pathwise -0.0067 (sd 2.12)  score -0.0080 (sd 0.71)

Even at ω=1\omega=1, the score-function estimator already has the smaller spread (about 0.50.5 versus 0.70.7), and at ω=3\omega=3 it wins by a factor of three (about 0.70.7 versus 2.12.1). Both sample means agree with the exact derivatives within a few standard errors.

Neither estimator dominates in every problem. The pathwise estimator differentiates gg, so its variance grows whenever g′g' is large; the score-function estimator multiplies gg by the score, so its variance grows whenever gg itself is large. In both cases, the single-sample standard deviation σ\sigma governs how many samples are needed for a given accuracy. Because σ\sigma also depends on the distribution from which we draw samples, choosing a proposal distribution that makes σ\sigma small leads directly to importance sampling, which we take up in Section 24.8.

22.7.4 Summary#

When a model's parameters govern the distribution of its samples, the gradient of an expected loss must be rewritten as an expectation before Monte Carlo sampling can estimate it. Both ways of doing so pass the derivative inside the integral, a step that requires an integrable dominating bound and, whenever the limits of integration move with the parameter, the boundary terms of the Leibniz rule. The score-function identity differentiates the log-density; it works for arbitrary losses gg and discrete random variables, though its samples scale with the magnitude of gg and can be noisy without a good baseline. The pathwise identity differentiates through a reparameterized sample; it requires a differentiable gg and often, though not always, achieves much lower variance. Because both estimators have root-mean-square error σ/n\sigma/\sqrt n (Section 24.5.1.7), the single-sample standard deviation σ\sigma decides which one is preferable for a given problem.

22.7.5 Exercises#

  1. A moving support. Let XX be uniform on [0,θ][0,\theta] with θ>0\theta>0, so that ℓ(θ)=E[X2]=∫0θx2θ dx=θ23\ell(\theta)=\mathbb{E}[X^2]=\int_0^\theta \tfrac{x^2}{\theta}\,dx=\tfrac{\theta^2}{3} and ℓ′(θ)=2θ3\ell'(\theta)=\tfrac{2\theta}{3}.

    1. Differentiate ℓ\ell with the Leibniz rule (22.7.4). Which part of the result does the plain swap (22.7.3) produce, and which part does it miss?
    2. On the support, log⁡pθ(x)=−log⁡θ\log p_\theta(x)=-\log\theta. Compute the expectation of the score-function estimator X2 ∂θlog⁡pθ(X)X^2\,\partial_\theta\log p_\theta(X) of (22.7.6). Then let gg be continuous on [0,∞)[0,\infty). Show that the mean of g(X) ∂θlog⁡pθ(X)g(X)\,\partial_\theta\log p_\theta(X) equals the plain swap (22.7.3) applied to E[g(X)]=∫0θg(x) pθ(x) dx\mathbb{E}[g(X)]=\int_0^\theta g(x)\,p_\theta(x)\,dx. What is its bias as an estimate of ddθE[g(X)]\frac{d}{d\theta}\mathbb{E}[g(X)], in terms of g(θ)g(\theta) and θ\theta?
    3. Write X=θUX=\theta U with UU uniform on [0,1][0,1] and compute the expectation of the pathwise estimator of (22.7.7). Why does it need no boundary term, although the support of XX moves with θ\theta?
  2. [code] Estimator variance for a quartic. ● Let X∼N(θ,1)X\sim\mathcal N(\theta,1), write X=θ+zX=\theta+z, and let s(X)=∂θlog⁡pθ(X)=zs(X)=\partial_\theta\log p_\theta(X)=z be the score.

    1. Take g(X)=X4g(X)=X^4, so that ddθE[X4]=4θ3+12θ\frac{d}{d\theta}\mathbb{E}[X^4]=4\theta^3+12\theta. Derive the single-sample pathwise estimator from (22.7.7) and the single-sample score-function estimator from (22.7.6). Use the identity of exercise 5 (b) to show that both have mean 4θ3+12θ4\theta^3+12\theta.
    2. For a constant baseline bb, show that the variance of (g(X)−b) s(X)(g(X)-b)\,s(X) is minimized by b⋆=E[g(X)s(X)2]/E[s(X)2]b^\star=\mathbb{E}[g(X)s(X)^2]/\mathbb{E}[s(X)^2]. For g(X)=X2g(X)=X^2 show that b⋆=θ2+3b^\star=\theta^2+3, and use E[z2]=1\mathbb{E}[z^2]=1, E[z4]=3\mathbb{E}[z^4]=3, E[z6]=15\mathbb{E}[z^6]=15 to derive the three variances 44, θ4+14θ2+15\theta^4+14\theta^2+15 and 8θ2+68\theta^2+6 that the text quotes.
    3. Evaluate b⋆b^\star for g(X)=X4g(X)=X^4. With 10610^6 samples at θ∈{0,1,2}\theta\in\{0,1,2\}, estimate the standard deviations of the pathwise estimator, the score-function estimator, and the score-function estimator with the baseline. For which θ\theta is the baseline's gain largest, and does it ever close the gap to the pathwise estimator? Explain the ordering from the sizes of g′g' and of gg.
    4. Take g(x)=1(x>0)g(x)=\mathbf{1}(x>0) at θ=1.5\theta=1.5. The text shows that the pathwise estimator is 00 for almost every sample, while the score-function estimator 1(x>0) z\mathbf{1}(x>0)\,z has the correct mean φ(θ)=0.1295\varphi(\theta)=0.1295. Verify both by simulation.
  3. [extended] Gradients through a coin flip. ●● When xx is a discrete choice there is no differentiable path from θ\theta to the sample, so the pathwise estimator does not exist. Continuous relaxations such as Gumbel-softmax (Jang et al., 2017; Maddison et al., 2017) create a differentiable surrogate, and straight-through estimators (Bengio et al., 2013) use the hard sample in the forward pass and the surrogate in the backward pass; both are biased for the original objective. This problem measures that bias. Tucker et al. (2017) illustrate it on a toy problem. A single Bernoulli variable b∈{0,1}b\in\{0,1\} has P(b=1)=σ(θ)P(b=1)=\sigma(\theta) for a logit θ\theta, and the objective is ℓ(θ)=E[(b−t)2]\ell(\theta)=\mathbb{E}[(b-t)^2] with target t=0.45t=0.45. Let UU be uniform on (0,1)(0,1), let ζ=log⁡U−log⁡(1−U)\zeta=\log U-\log(1-U), and, for a temperature τ>0\tau>0, let z=σ((θ+ζ)/τ)z=\sigma\bigl((\theta+\zeta)/\tau\bigr), the two-class case of the Gumbel-softmax relaxation.

    1. Compute ℓ(θ)\ell(\theta) and ℓ′(θ)\ell'(\theta) in closed form. Which probability σ(θ)\sigma(\theta) minimizes ℓ\ell, and does a finite θ\theta attain it?
    2. Show that b=1(z>12)b=\mathbf{1}(z>\tfrac12) satisfies P(b=1)=σ(θ)P(b=1)=\sigma(\theta) for every τ\tau.
    3. Implement three single-sample estimators of ℓ′(θ)\ell'(\theta): REINFORCE (22.7.6) with the baseline ℓ(θ)\ell(\theta); the relaxed estimator ddθ(z−t)2\frac{d}{d\theta}(z-t)^2; and the straight-through estimator 2(b−t)dzdθ2(b-t)\frac{dz}{d\theta}, which uses the hard sample in the loss and the relaxed sample in the derivative. Tabulate the mean and the standard deviation of each estimator against ℓ′(θ)\ell'(\theta) for θ∈{−2,0,2}\theta\in\{-2,0,2\} and τ∈{1,0.5,0.1}\tau\in\{1,0.5,0.1\}. How does the bias of each estimator depend on θ\theta and τ\tau?
    4. Run stochastic gradient descent on θ\theta from θ=0\theta=0 with step size 11 for 50005000 steps with REINFORCE and with the relaxed and straight-through estimators at each τ\tau, replacing the REINFORCE baseline by an exponential moving average of past losses. Plot ℓ(θ)\ell(\theta) along each run. Compute the relaxed objective Rτ(θ)=E[(z−t)2]R_\tau(\theta)=\mathbb{E}[(z-t)^2] by quadrature over UU, and compare its minimizer with the values of θ\theta at which the relaxed runs settle. How does lowering τ\tau trade the bias of the relaxed estimator against its variance?

Discussions