Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.Sending gradients through a dice roll
A VAE’s encoder does not output one code but a cloud of possible codes, and training samples from that cloud. Sampling is like rolling dice, and you cannot take the derivative of a dice roll. The reparameterization trick moves the dice outside the network: roll standard noise first, then shift it by the encoder’s mean and stretch it by its standard deviation. Now the sample is an ordinary function of the encoder’s outputs, and backpropagation works. The older alternative, the score-function estimator, also gives correct gradients on average but is much noisier, and the noise grows with the number of latent dimensions. The demo shows the two variances.
Reparameterised gradients train VAEs, world models for robot planning, stochastic policies in SAC and Bayesian neural networks; score-function estimators remain the fallback for discrete choices and non-differentiable simulators.
- 1. The reparameterization trick writes z as…
- 2. Its main benefit is…
- 3. The score-function estimator is also called…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.By hand
- VAE objective per example: L(θ, φ; x) = E_q(z|x)[log p_θ(x | z)] − KL(q_φ(z | x) ‖ N(0, I)), maximised over decoder θ and encoder φ.
- Encoder output: μ(x) and log σ²(x); sample: z = μ + exp(½ log σ²)·ε. For μ = 1, log σ² = ln 4, ε = 0.5: z = 1 + 2 × 0.5 = 2.
- Pathwise estimator: ∇_μ E[f(z)] = E[f′(μ + σε)], ∇_σ E[f(z)] = E[f′(μ + σε)·ε].
- Score-function estimator: ∇ E_q[f(z)] = E_q[f(z) ∇ log q(z)]; for a Gaussian, ∇_μ log q = (z − μ)/σ² = ε/σ.
- Worked example: f(z) = z², z ~ N(μ, σ²). E[f] = μ² + σ², so the true gradient in μ is 2μ.
- Pathwise sample: 2(μ + σε), variance 4σ².
- At μ = 0, σ = 1 in D dimensions with f = Σ z_i², the score-function sample f·ε₁ has variance (D + 2)(D + 4): 15 at D = 1, 168 at D = 10.
- Subtracting the baseline E[f] = D gives variance 2D + 8.
- Samples for a given accuracy: n = variance / (target standard error)²: 400 samples for error 0.1 at variance 4.
- Decoder likelihoods: Gaussian N(x̂, σ_x²) gives squared error / (2σ_x²) + ½ D ln(2πσ_x²); Bernoulli gives binary cross-entropy; discretised logistic mixtures suit 8-bit images.
- 1. z for μ = 0, σ = 3, ε = −1:
- 2. Score-function variance for f = Σ z² at D = 1:
- 3. Subtracting a baseline from f…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.Training a VAE
Exercise 1.
- The reparameterised sample and the diagonal-Gaussian KL.
- Pathwise and score-function gradient estimators for E[f(z)].
- A check that both are unbiased while their variances differ.
Practice.
- Output log σ² (or a softplus scale) from the encoder, never σ directly; clamp log σ² to about [−10, 10] early in training.
- One sample of z per example is enough with reparameterisation; average the loss over the batch, sum over dimensions.
- Use rsample() in torch.distributions (reparameterised) rather than sample(), which blocks gradients.
- For discrete latents use Gumbel-softmax relaxations (Jang et al.; Maddison et al., 2017) or score-function estimators with control variates (REINFORCE with baselines, RELAX).
- Gamma, Beta and von Mises latents can use implicit reparameterisation gradients (Figurnov et al., 2018).
import torch, torch.nn as nn, torch.nn.functional as F
class VAE(nn.Module):
def __init__(s, D=784, h=400, d=16):
super().__init__(); s.enc = nn.Sequential(nn.Linear(D, h), nn.ReLU(), nn.Linear(h, 2 * d))
s.dec = nn.Sequential(nn.Linear(d, h), nn.ReLU(), nn.Linear(h, D))
def forward(s, x):
mu, logvar = s.enc(x).chunk(2, -1)
z = mu + torch.exp(0.5 * logvar) * torch.randn_like(mu) # reparameterisation
rec = F.binary_cross_entropy_with_logits(s.dec(z), x, reduction="none").sum(-1)
kl = 0.5 * (mu ** 2 + logvar.exp() - 1 - logvar).sum(-1)
return (rec + kl).mean() # negative ELBO- 1. To keep gradients through a sample in PyTorch use…
- 2. For discrete latents a common choice is…
- 3. The encoder should output…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.Theory
Why both estimators are unbiased.
- Pathwise: E_q[f(z)] = E_ε[f(μ + σε)]. The distribution of ε does not depend on (μ, σ), so the gradient moves inside the expectation: ∇_μ = E[f′(z)], ∇_σ = E[f′(z) ε].
- Score function: ∇ ∫ q(z) f(z) dz = ∫ q(z) ∇ log q(z) f(z) dz, using ∇q = q ∇ log q. It needs only values of f, not derivatives, so it works for discrete z and black-box f.
- Baselines: E_q[∇ log q] = ∇ ∫ q = 0, so f can be replaced by f − b for any b not depending on z.
Why the pathwise estimator usually wins. It uses the local slope of f; the score function correlates f with the noise and must average away everything else f depends on. For f = Σ z_i², the other D − 1 coordinates add variance to the μ₁ estimate: E[ε₁²(Σ ε_i²)²] = (D + 2)(D + 4), against 4 for the pathwise one. The pathwise estimator can be worse when f is very wiggly (large, oscillating f′), but for smooth decoders it is far better.
The full VAE gradient. With the KL in closed form, only the reconstruction term needs sampling: ∇_φ E_ε[log p_θ(x | μ_φ(x) + σ_φ(x) ε)]. The decoder gradient ∇_θ needs no trick, since q does not depend on θ. Kingma and Welling call this the SGVB estimator; with the analytic KL it is their “second” estimator, which has lower variance than sampling the KL too.
Beyond Gaussians. Location-scale families reparameterise directly. Others need tricks: inverse-CDF sampling, implicit reparameterisation (differentiate the CDF), rejection-sampler reparameterisation, or continuous relaxations (Concrete / Gumbel-softmax) for categorical latents.
- 1. E_q[∇ log q(z)] equals…
- 2. The score-function estimator needs…
- 3. The decoder gradient in a VAE needs…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.How much noisier is the score-function gradient, and does it matter for training?
History.
- R. J. Williams, “Simple statistical gradient-following algorithms for connectionist reinforcement learning” (REINFORCE, 1992).
- D. P. Kingma and M. Welling, “Auto-encoding variational Bayes” (ICLR 2014); D. J. Rezende, S. Mohamed and D. Wierstra, “Stochastic backpropagation and approximate inference in deep generative models” (ICML 2014).
- S. Mohamed, M. Rosca, M. Figurnov and A. Mnih, “Monte Carlo gradient estimation in machine learning” (JMLR 2020), a survey.
Exercise 2.
- Part A (variance): single-sample estimates of d/dμ₁ E[Σ z_i²] at μ = 0, σ = 1 (true value 0), from 10000 draws, in D = 1, 10 and 100 dimensions.
- Part B (training): a linear VAE with 8 latents on 300 points in 20 dimensions drawn from an 8-factor model with noise variance 0.1 (known to the decoder). The KL term is analytic; the encoder’s reconstruction gradient uses one sample per point, either pathwise or score-function with a batch-mean baseline. 1000 Adam steps; the exact ELBO is computed in closed form and compared with the best possible log-likelihood of any such linear model (−25.063).
| D | pathwise | score function | score function with baseline | theory (score / baseline) |
|---|---|---|---|---|
| 1 | 4.0 | 14.3 | 9.4 | 15 / 10 |
| 10 | 4.0 | 169.8 | 28.1 | 168 / 28 |
| 100 | 4.0 | 10806.9 | 212.0 | 10608 / 208 |
| estimator | final ELBO, learning rate 0.01 | final ELBO, learning rate 0.02 |
|---|---|---|
| pathwise | −27.563 | −27.141 |
| score function + baseline | −30.965 | −152.211 (diverged) |
- The variance gap is structural: pathwise variance did not change with dimension; the score function’s matched (D + 2)(D + 4) and a baseline only reduced it to 2D + 8.
- Training followed suit: at the same learning rate the pathwise run ended 2.5 nats below the optimum and the score-function run 5.9 nats below. At 0.02 the pathwise run improved further, while the score-function ELBO had collapsed to −461 by step 750.
- Seeds 1 and 2 gave the same ordering: pathwise −25.899 and −26.725 against score function −29.346 and −30.168 at rate 0.01. At 0.02 the score function reached −123.144 on seed 1 and degraded to −32.053 on seed 2 (from −30.433 midway), so the instability varies but recurs.
- Caveat: a linear model with a known noise level; with deep decoders the score function’s disadvantage is usually larger.
Reparameterised gradients in AI, robotics and aerospace
- VAEs and world models: Dreamer-style agents learn latent dynamics for planning with reparameterised (and straight-through) gradients.
- Stochastic policies: soft actor-critic trains Gaussian policies with the same trick; REINFORCE-type estimators remain for discrete actions and black-box simulators.
- Bayesian deep learning: Bayes-by-backprop and variational dropout use reparameterised weight noise for uncertainty estimates in perception.
References
- R. J. Williams (1992). “Simple statistical gradient-following algorithms for connectionist reinforcement learning.” Machine Learning.
- D. P. Kingma and M. Welling (2014). “Auto-encoding variational Bayes.” ICLR.
- D. J. Rezende, S. Mohamed and D. Wierstra (2014). “Stochastic backpropagation and approximate inference in deep generative models.” ICML.
- E. Jang, S. Gu and B. Poole (2017). “Categorical reparameterization with Gumbel-softmax.” ICLR.
- M. Figurnov, S. Mohamed and A. Mnih (2018). “Implicit reparameterization gradients.” NeurIPS.
- S. Mohamed, M. Rosca, M. Figurnov and A. Mnih (2020). “Monte Carlo gradient estimation in machine learning.” JMLR.
- D. P. Kingma and M. Welling (2019). “An introduction to variational autoencoders.” Foundations and Trends in ML.