Expectations and Their Gradients

Dive into Deep Learning · §34.7

Expectations and Their Gradients
differentiation under the integral sign · Leibniz rule · score-function (REINFORCE) · pathwise reparameterization · variance trade-offs

When Parameters Govern the Sampling Distribution

Motivation

  • Where Parameterized Sampling Arises: VAEs sample latent codes \mathbf{x} \sim \mathcal{N}(\boldsymbol{\mu}_{\boldsymbol{\theta}}, \operatorname{diag}(\boldsymbol{\sigma}_{\boldsymbol{\theta}}^2)) and RL policies sample actions a \sim \pi_{\boldsymbol{\theta}}(a \mid s).
  • The Graph-Severing Obstacle: A raw sample x_i \sim p_{\boldsymbol{\theta}} is just a number with no computation graph linking it to \boldsymbol{\theta}.
  • Running Benchmark: For X \sim \mathcal{N}(\theta, 1) and \ell(\theta) = \mathbb{E}[X^2] = \theta^2 + 1, true slope at \theta = 1.5 is \ell'(1.5) = 2\theta = 3.

Expectations as Integrals and Monte Carlo Error

Foundations

  • Expectation as Integral: \mathbb{E}_{X \sim p}[g(X)] = \int_{\mathcal{X}} g(x)p(x)\,dx, approximated by \hat{\mu}_n = \frac{1}{n}\sum_{i=1}^n g(x_i).
  • Dimension-Free RMSE (\sigma/\sqrt{n}): Root-mean-square error scales as \sigma/\sqrt{n} regardless of dimension d.
  • The Yardstick: Sample efficiency of any unbiased gradient estimator is governed by its single-sample standard deviation \sigma.

Differentiating Under the Integral Sign: The Swap

Exchanging Limits

  • The Interior Swap: On fixed support \mathcal{X}, \frac{d}{d\theta}\int_{\mathcal{X}} f(x, \theta)\,dx = \int_{\mathcal{X}} \frac{\partial f}{\partial\theta}(x, \theta)\,dx.
  • Regularity Conditions: Joint continuity of \partial_\theta f on bounded [a, b], plus an integrable dominating bound |\partial_\theta f(x, \theta')| \le M(x) on unbounded \mathbb{R} (satisfied by Gaussian tails).

Log-Integral-Exp and Exponential Family Tilting

Continuous Softmax

  • Log-Partition Derivative: Differentiating \log\int e^{\theta x}p(x)\,dx via the swap yields the tilted expectation \mathbb{E}_{X \sim \tilde{p}_\theta}[X] under \tilde{p}_\theta(x) \propto e^{\theta x}p(x).
  • Standard Normal Check: For Z \sim \mathcal{N}(0, 1), \log\mathbb{E}[e^{\theta Z}] = \tfrac{1}{2}\theta^2 has derivative \theta, matching the mean of \tilde{p}_\theta = \mathcal{N}(\theta, 1).

The Leibniz Rule: Moving Integration Boundaries

Moving Support

\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)

  • Interior shift + sweeping boundaries: When a(\theta) and b(\theta) move with \theta, the total area changes both because the integrand roof shifts vertically (\int_a^b \partial_\theta f\,dx) and because the endpoints sweep horizontally (f(b,\theta)b' - f(a,\theta)a').
  • Proof via multivariable chain rule (§34.3): Set H(\alpha, \beta, \theta) = \int_\alpha^\beta f(x, \theta)\,dx. By FTC, \partial_\beta H = f(\beta, \theta) and \partial_\alpha H = -f(\alpha, \theta), while the bounded swap gives \partial_\theta H = \int_\alpha^\beta \partial_\theta f\,dx. Evaluating \frac{d}{d\theta}H(a(\theta), b(\theta), \theta) sums all three path products.

Why Ignoring Boundary Terms Flips the Sign

Moving-Support Pitfall

  • Uniform(0, \theta) Mean: \mathbb{E}[X] = \int_0^\theta \frac{x}{\theta}\,dx = \frac{\theta}{2} has true derivative +\frac{1}{2}.
  • Naive Swap Gives Wrong Sign: Differentiating only inside gives \int_0^\theta -\frac{x}{\theta^2}\,dx = -\frac{1}{2}.
  • Leibniz Boundary Term: Adding the upper wall sweep f(\theta, \theta)b'(\theta) = 1 \cdot 1 = +1 restores -\frac{1}{2} + 1 = +\frac{1}{2}.

Why Raw Density Derivatives Cannot Be Sampled

The Monte Carlo Obstacle

  • \nabla_{\boldsymbol{\theta}}p_{\boldsymbol{\theta}}(x) Is Not a Density: In \int g(x)\nabla_{\boldsymbol{\theta}}p_{\boldsymbol{\theta}}(x)\,dx, \nabla_{\boldsymbol{\theta}}p_{\boldsymbol{\theta}} takes negative values and integrates to \mathbf{0}.
  • Two Escape Routes Back to an Expectation:
    1. Score function: Multiply and divide by p_{\boldsymbol{\theta}}(x) (\nabla_{\boldsymbol{\theta}}\log p_{\boldsymbol{\theta}}).
    2. Pathwise: Change variables to X = T_{\boldsymbol{\theta}}(\mathbf{z}) with \mathbf{z} \sim q(\mathbf{z}).

The Log-Derivative Trick and the Score Function

Score-Function Identity

  • REINFORCE Identity: Using \nabla_{\boldsymbol{\theta}}p_{\boldsymbol{\theta}} = p_{\boldsymbol{\theta}}\nabla_{\boldsymbol{\theta}}\log p_{\boldsymbol{\theta}} gives \nabla_{\boldsymbol{\theta}}\mathbb{E}_{p_{\boldsymbol{\theta}}}[g(X)] = \mathbb{E}_{p_{\boldsymbol{\theta}}}[g(X)\nabla_{\boldsymbol{\theta}}\log p_{\boldsymbol{\theta}}(X)].
  • Zero-Mean Score: On fixed support, \mathbb{E}[\nabla_{\boldsymbol{\theta}}\log p_{\boldsymbol{\theta}}(X)] = \mathbf{0} (for \mathcal{N}(\theta, 1), s_\theta(X) = X - \theta = Z).
  • Generality: Never differentiates g(x), so it works for discrete actions and black-box rewards.

Variance Reduction via Control-Variate Baselines

Baseline Subtraction

  • Unbiased Baseline Subtraction: Since \mathbb{E}[s_\theta(X)] = 0, replacing g(X) by g(X) - b leaves the mean unchanged for any constant b.
  • Optimal Constant Baseline: b^\star = \frac{\mathbb{E}[g(X)s_\theta(X)^2]}{\mathbb{E}[s_\theta(X)^2]} (= \theta^2 + 3 for g(X) = X^2), cutting variance from O(\theta^4) to 8\theta^2 + 6 = O(\theta^2).

The Pathwise (Reparameterization) Estimator

Differentiating Through Samples

  • Reparameterization (X = T_{\boldsymbol{\theta}}(\mathbf{z}), \mathbf{z} \sim q): Changing variables to parameter-free noise \mathbf{z} gives \nabla_{\boldsymbol{\theta}}\mathbb{E}_{p_{\boldsymbol{\theta}}}[g(X)] = \mathbb{E}_{\mathbf{z} \sim q}[\nabla_{\boldsymbol{\theta}}g(T_{\boldsymbol{\theta}}(\mathbf{z}))].
  • Direct Chain Rule Through g: For \mathbf{x} = \boldsymbol{\mu} + \boldsymbol{\sigma}\odot\mathbf{z}, backprop differentiates g(\boldsymbol{\mu} + \boldsymbol{\sigma}\odot\mathbf{z}) directly with low variance.

When Pathwise Fails: Step Losses & Discrete Choices

Differentiability Boundary

  • Step Loss g(x) = \mathbf{1}(x > 0) at \theta = 1.5: True derivative of \Phi(\theta) is \varphi(1.5) \approx 0.1295.
  • Pathwise Returns 0 Almost Surely: The step \theta \mapsto \mathbf{1}(\theta + z > 0) is flat everywhere except the zero-probability jump z = -\theta.
  • Score Function Succeeds: \mathbb{E}[\mathbf{1}(\theta + Z > 0)Z] = \varphi(\theta) \approx 0.1295.

Analytical Variance Comparison on E[X²]

Exact Moment Calculation

  • Exact Variances on \ell(\theta) = \mathbb{E}[X^2] at \theta = 1.5:
    • Pathwise (2X): \operatorname{Var} = 4 \implies \sigma = 2.000.
    • Score + Baseline (b^\star = \theta^2+3): \operatorname{Var} = 8\theta^2+6 \implies \sigma = 4.899.
    • Plain REINFORCE (X^2 Z): \operatorname{Var} = \theta^4+14\theta^2+15 \implies \sigma = 7.181 (12.9\times higher variance).

Monte Carlo Verification: Pathwise vs. REINFORCE

Empirical Benchmark

Drawing n = 200{,}000 samples at \theta = 1.5 confirms that all three estimators are unbiased for \ell'(1.5) = 3.0000 and reproduces the exact theoretical standard deviations 2.000, 7.181, and 4.899:

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

When Score Beats Pathwise: Rapidly Oscillating Losses

High-Frequency Regime

Does the pathwise estimator always have lower variance than the score-function estimator? No. Consider the oscillating loss g(x) = \sin(\omega x), where \frac{d}{d\theta}\mathbb{E}[\sin(\omega X)] = \omega\cos(\omega\theta)e^{-\omega^2/2}:

  • Pathwise variance scales with |g'|^2 = O(\omega^2): One pathwise sample is \omega\cos(\omega X), whose standard deviation grows linearly with frequency as \approx \omega/\sqrt{2}.
  • Score-function variance is bounded by |g|^2 \le 1: One score sample is \sin(\omega X)\,Z; since |\sin(\omega X)| \le 1, its second moment is at most \mathbb{E}[Z^2] = 1 regardless of how large \omega grows.
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)

Decision Guide: Choosing a Gradient Estimator

Design Trade-Offs

Property / Requirement Score-Function (REINFORCE) Pathwise (Reparameterization) Relaxed / Straight-Through (e.g. Gumbel-Softmax)
Core Formula g(X)\,\nabla_{\boldsymbol{\theta}}\log p_{\boldsymbol{\theta}}(X) \nabla_{\boldsymbol{\theta}}g(T_{\boldsymbol{\theta}}(\mathbf{z})) = \mathbf{J}_{T}^\top \nabla_x g Differentiate smooth surrogate z_\tau = \sigma((\theta+\zeta)/\tau)
Requires Differentiable g? No (works on steps & black-box rewards) Yes (g must be differentiable/Lipschitz) Yes (surrogate loss must be differentiable)
Handles Discrete X? Yes (Bernoulli, categorical actions) No (no continuous path T_{\boldsymbol{\theta}}(\mathbf{z})) Yes (approximates discrete choice at temperature \tau)
Bias Unbiased (on fixed support) Unbiased (for smooth g) Biased (bias shrinks as \tau \to 0, variance blows up)
Single-Sample Variance Scales with \|g(X)\|^2 (needs baseline b) Scales with \|\nabla_x g(X)\|^2 (low for smooth g) Controlled by temperature \tau (bias–variance trade-off)

Concept Check: Differentiating Expectations

Review & Practice

Work out these three questions on the Leibniz rule, score function, and pathwise estimators:

  1. Moving support bias: For X \sim \mathrm{Uniform}(0, \theta) with density p_\theta(x) = 1/\theta on [0, \theta], the score is \partial_\theta \log(1/\theta) = -1/\theta. What does the score-function estimator X^2 \partial_\theta \log p_\theta(X) give in expectation for \ell(\theta) = \mathbb{E}[X^2] = \theta^2/3, and why does it miss \ell'(\theta) = 2\theta/3?
  2. Reparameterizing Uniform(0, \theta): How can you reparameterize X \sim \mathrm{Uniform}(0, \theta) using U \sim \mathrm{Uniform}(0, 1) so the pathwise estimator gives the exact unbiased derivative \ell'(\theta) = 2\theta/3 without a boundary term?
  3. Variance comparison in high dimensions: If g(\mathbf{x}) = \|\mathbf{x}\|_2^2 for \mathbf{X} \sim \mathcal{N}(\boldsymbol{\theta}, \mathbf{I}_d), how do the magnitudes of g(\mathbf{X}) (entering REINFORCE) and \nabla_{\mathbf{x}} g(\mathbf{X}) = 2\mathbf{X} (entering pathwise) scale with dimension d?

Concept Check: Differentiating Expectations (cont.)

Review & Practice

Answers:

  1. \mathbb{E}[X^2(-1/\theta)] = -\frac{1}{\theta}\frac{\theta^2}{3} = -\frac{\theta}{3}—which equals the naive interior swap \int_0^\theta x^2 \partial_\theta(1/\theta)\,dx and misses the Leibniz upper-boundary term f(\theta, \theta)b'(\theta) = \theta^2(1/\theta)(1) = +\theta (-\frac{\theta}{3} + \theta = +\frac{2\theta}{3}).
  2. Write X = T_\theta(U) = \theta U on fixed support U \in [0, 1]: the pathwise estimator is \partial_\theta(\theta U)^2 = 2\theta U^2, whose expectation is 2\theta\mathbb{E}[U^2] = 2\theta(\tfrac{1}{3}) = \frac{2\theta}{3}.
  3. The scalar loss g(\mathbf{X}) = \sum_{j=1}^d X_j^2 = O(d) multiplies all d coordinates of the score vector, making REINFORCE variance grow as O(d^2) (or O(d) with a baseline), whereas the pathwise derivative of coordinate k is simply 2X_k with O(1) variance independent of d.

Summary: Expectation Gradients Toolkit

Key Takeaways

Rule / Estimator Mathematical Identity Conditions & Variance Behavior
Interior Swap \frac{d}{d\theta}\int f(x,\theta)\,dx = \int \frac{\partial f}{\partial \theta}(x,\theta)\,dx Fixed limits; continuous \partial_\theta f + integrable dominating bound
Leibniz Boundary Rule \frac{d}{d\theta}\int_{a(\theta)}^{b(\theta)} f\,dx = \int_a^b \partial_\theta f\,dx + f(b,\theta)b' - f(a,\theta)a' Required whenever integration limits / support move with \theta
Log-Integral-Exp \frac{d}{d\theta}\log\int e^{\theta x}p(x)\,dx = \mathbb{E}_{\tilde{p}_\theta}[X] (\tilde{p}_\theta \propto e^{\theta x}p) Continuous counterpart of \nabla\operatorname{LSE}(\mathbf{z}) = \operatorname{softmax}(\mathbf{z})
Score Function (REINFORCE) \nabla_{\boldsymbol{\theta}}\mathbb{E}_{p_{\boldsymbol{\theta}}}[g(X)] = \mathbb{E}_{p_{\boldsymbol{\theta}}}\bigl[(g(X)-b)\nabla_{\boldsymbol{\theta}}\log p_{\boldsymbol{\theta}}(X)\bigr] Works for discontinuous g & discrete X; variance scales with \|g-b\|^2
Optimal Baseline b^\star b^\star = \mathbb{E}[g(X)s_\theta(X)^2] / \mathbb{E}[s_\theta(X)^2] Unbiased because \mathbb{E}[\nabla_{\boldsymbol{\theta}}\log p_{\boldsymbol{\theta}}(X)] = \mathbf{0} on fixed support
Pathwise (Reparameterized) \nabla_{\boldsymbol{\theta}}\mathbb{E}_{p_{\boldsymbol{\theta}}}[g(X)] = \mathbb{E}_{\mathbf{z}\sim q}\bigl[\nabla_{\boldsymbol{\theta}}g(T_{\boldsymbol{\theta}}(\mathbf{z}))\bigr] Requires smooth g & continuous X = T_{\boldsymbol{\theta}}(\mathbf{z}); variance scales with \|\nabla g\|^2