The reparameterization trick
Why gradients cannot pass through sampling, and how one line, z = μ + σ ⊙ ε, fixes it.
What the encoder outputs
The topic Latent variables and the ELBO gave the VAE (Kingma and Welling, 2014) its objective, the ELBO. Its encoder maps each input to a Gaussian, not a point,
and the KL term pulls every such Gaussian toward the prior . In code, the encoder ends with two heads: one for and one for .
The ELBO's reconstruction term is an expectation over , and we estimate it with a sampled code. To train the encoder, we have to differentiate through that sample. This topic shows how.
Where the gradient stops
Look closer at the reconstruction term, an expectation over codes:
We estimate it with a single sample per input: draw , decode, compare with . The loss clearly depends on and — move and the codes move with it.
But the computational graph has a hole in it. The step "draw a random number from " returns a value with no derivative attached: the gradient of the loss arrives at and stops there. The decoder learns; the encoder, whose job is to produce and , receives nothing from the reconstruction term.
Move the randomness outside
The fix is to move the randomness into an input of the graph. Draw noise that has nothing to do with the network, then shift and scale it:
This is the affine sampling from Multivariate Gaussians with a diagonal , so has exactly the distribution it had before. Nothing about the model changed; only where the randomness lives.
The encoder outputs rather than , so has to be recovered from it before the shift-and-scale. In PyTorch the noise comes from torch.randn_like, which draws with the same shape as its argument.
Gradients now flow
Now is an ordinary differentiable function of and , with playing the role of a fixed input:
Gradients of the reconstruction term flow through back into the encoder (Kingma and Welling, 2014, §2.4). Autograd does this for you; the point is that there is now something for it to differentiate.
Why is one sample enough? The expectation over is now an expectation over , and the distribution of does not depend on . So the gradient moves inside it:
The gradient for a single drawn is therefore an unbiased estimate of the gradient we want.
There is a quieter benefit too. The generic alternative, the score-function (REINFORCE) estimator, differentiates the density instead, . It is unbiased too and works for any , but it never uses how changes with , and its variance is typically much higher. For the gradient in of at , one score-function sample has variance 30; one reparameterized sample, , has variance 4.
Why log σ² and not σ
Why does the encoder predict and not ? A standard deviation must be positive, but the last linear layer of a network can output any real number. Predicting the logarithm removes the constraint for free:
It also keeps very small variances on a comfortable numerical scale. Softplus is a common alternative; the trick itself works with any positive .
The KL needs no sampling
The other half of the loss, , needs no sampling at all. Between two Gaussians it has a closed form. Take one coordinate, and :
Under , and , so . The diagonal and the prior both factorize over coordinates, so the log ratio is a sum of one-coordinate terms, and the KL is the sum of their KLs:
It is zero exactly when and in every dimension, that is, when the posterior equals the prior. In code it is one line, and it differentiates through and directly.
Read it as a fine. Moving the mean away from 0 costs quadratically. Shrinking the standard deviation costs only logarithmically for small , about 4.1 nats at , but without bound: as the term grows to infinity. A point code, as in a plain autoencoder, would pay an infinite fine.
Putting a training step together
Put together, one training step looks like this:
mu, logvar = encoder(x)
std = torch.exp(0.5 * logvar)
eps = torch.randn_like(std)
z = mu + std * eps
x_hat = decoder(z)
recon = ((x - x_hat) ** 2).sum(dim=1)
kl = -0.5 * (1 + logvar - mu**2 - logvar.exp()).sum(dim=1)
loss = (recon + kl).mean()
loss.backward()The squared error corresponds to a Gaussian decoder with fixed variance , which makes it the negative ELBO up to a constant. A different fixed variance reweights the KL term — the idea behind β-VAE.
This VAE trains end to end, but two weaknesses remain. Its samples come out blurry, and the codes fill the prior only loosely, so some prior samples still land where the decoder was barely trained. The extension topic β-VAE and VQ-VAE works on both inside the VAE family; beyond it, GANs as a two-player game tries a different idea altogether.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Go deeper — optional
Code and labs do not count toward the main percentage or the certificate.
- KL term in codeoptional
Write the element-wise KL between N(μ, σ²) and N(0, 1) from encoder outputs mu and logvar.
~15 min · easier on a computer · The Reparameterization topic read; closed-form KL for diagonal Gaussians.
- Reparameterization in codeoptional
Finish sampling z = μ + σ ⊙ ε so gradients reach the encoder.
~15 min · easier on a computer · The Reparameterization topic read; basic PyTorch (tensors, element-wise ops).
- Reparameterization — derivation and CPU demooptional
Detailed derivation of z=μ+σ⊙ε, a NumPy distribution/gradient demo, and links to the code exercises. Self-check in the notebook.
~30 min · easier on a computer · The Reparameterization topic read; code exercises optional after the notebook.
Self-check in the notebook — not part of mastery or the certificate.
Answers are saved on the server and tied to this browser until you sign in.