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 be a normal random variable with mean and unit variance, and take the expected squared loss
The closed form follows immediately by writing with standard normal: , where by symmetry and (Section 22.6.2.3). At , the exact derivative is . In practice, however, a model can draw samples of but cannot evaluate in closed form. How, then, can we estimate 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 is a nonnegative function whose total integral equals :
The probability that a random variable with density lands in an interval is the area under over that interval, (Section 24.1). Because a density measures probability per unit length rather than probability itself, its value can exceed ; for example, the uniform density on equals everywhere on its support. Our main running example is the standard normal distribution , whose density is normalized by the Gaussian integral of Section 22.6.
An expectation computes the weighted average of , or of a function , weighting each outcome by its probability density:
The expectation is well defined whenever the integral converges absolutely, . 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 from and form the sample average , known as the Monte Carlo estimate. If a single sample has standard deviation , the Monte Carlo average has root-mean-square error , 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 the natural yardstick for comparing them.
22.7.2 Differentiation under the Integral Sign#
22.7.2.1 The Swap#
Our toy loss is an integral that varies with a parameter . 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 , we differentiate by passing the derivative inside the integral:
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 , continuity of in both variables is enough. On an unbounded domain, we also need an integrable function of that dominates for all near (an immediate consequence of the dominated convergence theorem, quoted without proof from (Folland, 1999)). For our running example 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 , 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 and be continuous on a region containing for in an open interval, and let and be differentiable. Then
Proof. Define . By the fundamental theorem of calculus, and , while the swap on the bounded interval gives . Since all three partial derivatives are continuous, the multivariable chain rule (Section 22.3) applies to the composition and combines the three terms weighted by , , and .
The Leibniz rule for on , the uniform example. When increases by , the integrand curve shifts to (dashed; here it drops, so the hatched region represents lost area), while the right boundary moves outward and sweeps in a strip of height and width .
Ignoring the boundary term is not a minor inaccuracy; it can flip the sign of the derivative. Suppose is uniform on , with density on that interval. Its mean is , whose derivative is . Differentiating only the integrand gives , which has the wrong sign. Adding the upper boundary contribution restores the true derivative, . Whenever the support of a distribution depends on the parameter, the plain swap alone is not valid (exercise 1 works out ).
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 yields
The right-hand side is the mean of under the exponentially tilted density proportional to . For the standard normal density, completing the square via shows that the tilted density is and that , whose derivative 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 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 . Unfortunately, we cannot estimate this integral directly by Monte Carlo sampling: 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 be a density parameterized by . Applying the chain rule to yields the log-derivative identity:
In words, the gradient of a density equals the density itself multiplied by the gradient of its logarithm, a vector known as the score . Whenever the swap is valid and the support of does not move with , the score has expectation zero: . The uniform density on shows why fixed support is essential: its score is , whose expectation is , because differentiating also picks up the boundary term . 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 that does not depend on and integrating gives the score-function identity:
This identity turns the gradient of an expected loss back into an expectation under : each sample's loss is weighted by how strongly increases that sample's log-probability. To estimate it by Monte Carlo, we draw samples and average . In reinforcement learning, this is the REINFORCE estimator of policy-gradient methods (Section 14.7) (Williams, 1992). (If also depends directly on , the product rule simply adds the term .)
Because the score has mean zero, we may subtract any constant baseline (independent of ) from without biasing the estimator (Section 14.8): . Choosing 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 . Often, a sample from can be generated by applying a deterministic transformation to an auxiliary noise variable whose distribution does not depend on . A normal random variable , for instance, is simply with . Rewriting the expectation as an integral over removes from the density entirely, so the swap yields the pathwise identity:
Instead of differentiating the density, this estimator differentiates right through the sample: automatic differentiation traces the path from through into . 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 to be differentiable in , to be differentiable along the path (a Lipschitz suffices when has a continuous density), and an integrable dominating bound for the swap. Notice that no boundary term ever appears, even if the support of moves with , because the integral is taken over whose density stays fixed.
The differentiability requirement on is not a technicality we can ignore. Consider the step function , which equals for positive and otherwise, with . The true expectation has derivative , which evaluates to about at . Yet the pathwise sample is for every except the single point (an event of probability zero), so the pathwise estimator returns with probability . By contrast, the score-function sample has expectation , recovering the exact derivative. Because the score-function estimator never differentiates through 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 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 with is simple enough to compute the variance of both by hand. For the pathwise estimator, a single sample contributes , whose variance is . For the score-function estimator, the score of the normal location family is , so one sample contributes , or when using a baseline . To find the variance of , we use the standard normal moments , , and , all of which follow from Stein's identity (Section 22.6.2.3). By symmetry, all odd powers of vanish in the second moment:
Subtracting the squared mean leaves a variance of . The variance-minimizing constant baseline turns out to be , reducing the variance to (exercise 2). At , the three single-sample standard deviations are for the pathwise estimator, for the plain score-function estimator, and for the score-function estimator with the optimal baseline. Although the baseline helps noticeably, it cannot close the gap for this loss, since for every .
Let us test all three closed-form predictions in a single Monte Carlo simulation. Because the pathwise derivative is simply , we do not even need automatic differentiation here. If our algebra is right, the three sample standard deviations should land near , , and , and each sample mean should fall within a few standard errors of the true derivative .
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 , 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 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 , for which the true derivative of the expectation is . The pathwise sample scales with the frequency and has standard deviation close to , whereas the score-function sample has standard deviation at most because . Whenever an integrand oscillates rapidly, its derivative can be huge even while its values remain bounded. Let us compare the two estimators at and , 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 , the score-function estimator already has the smaller spread (about versus ), and at it wins by a factor of three (about versus ). Both sample means agree with the exact derivatives within a few standard errors.
Neither estimator dominates in every problem. The pathwise estimator differentiates , so its variance grows whenever is large; the score-function estimator multiplies by the score, so its variance grows whenever itself is large. In both cases, the single-sample standard deviation governs how many samples are needed for a given accuracy. Because also depends on the distribution from which we draw samples, choosing a proposal distribution that makes 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 and discrete random variables, though its samples scale with the magnitude of and can be noisy without a good baseline. The pathwise identity differentiates through a reparameterized sample; it requires a differentiable and often, though not always, achieves much lower variance. Because both estimators have root-mean-square error (Section 24.5.1.7), the single-sample standard deviation decides which one is preferable for a given problem.
22.7.5 Exercises#
-
A moving support. Let be uniform on with , so that and .
- Differentiate 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?
- On the support, . Compute the expectation of the score-function estimator of (22.7.6). Then let be continuous on . Show that the mean of equals the plain swap (22.7.3) applied to . What is its bias as an estimate of , in terms of and ?
- Write with uniform on and compute the expectation of the pathwise estimator of (22.7.7). Why does it need no boundary term, although the support of moves with ?
-
[code] Estimator variance for a quartic. ● Let , write , and let be the score.
- Take , so that . 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 .
- For a constant baseline , show that the variance of is minimized by . For show that , and use , , to derive the three variances , and that the text quotes.
- Evaluate for . With samples at , estimate the standard deviations of the pathwise estimator, the score-function estimator, and the score-function estimator with the baseline. For which is the baseline's gain largest, and does it ever close the gap to the pathwise estimator? Explain the ordering from the sizes of and of .
- Take at . The text shows that the pathwise estimator is for almost every sample, while the score-function estimator has the correct mean . Verify both by simulation.
-
[extended] Gradients through a coin flip. ●● When is a discrete choice there is no differentiable path from 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 has for a logit , and the objective is with target . Let be uniform on , let , and, for a temperature , let , the two-class case of the Gumbel-softmax relaxation.
- Compute and in closed form. Which probability minimizes , and does a finite attain it?
- Show that satisfies for every .
- Implement three single-sample estimators of : REINFORCE (22.7.6) with the baseline ; the relaxed estimator ; and the straight-through estimator , 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 for and . How does the bias of each estimator depend on and ?
- Run stochastic gradient descent on from with step size for steps with REINFORCE and with the relaxed and straight-through estimators at each , replacing the REINFORCE baseline by an exponential moving average of past losses. Plot along each run. Compute the relaxed objective by quadrature over , and compare its minimizer with the values of at which the relaxed runs settle. How does lowering trade the bias of the relaxed estimator against its variance?