Skip to content
BIASED

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,

qφ(z∣x)=N(μφ(x), σφ2(x)),q_\varphi(z \mid x) = \mathcal N\big(\mu_\varphi(x),\ \sigma^2_\varphi(x)\big),

and the KL term pulls every such Gaussian toward the prior p(z)=N(0,I)p(z) = \mathcal N(0, I). In code, the encoder ends with two heads: one for μ\mu and one for log⁡σ2\log\sigma^2.

The ELBO's reconstruction term is an expectation over qφq_\varphi, 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:

Eqφ(z∣x)[log⁡pθ(x∣z)].\mathbb E_{q_\varphi(z \mid x)}\big[\log p_\theta(x \mid z)\big].

We estimate it with a single sample per input: draw z∼N(μ,σ2)z \sim \mathcal N(\mu, \sigma^2), decode, compare with xx. The loss clearly depends on μ\mu and σ\sigma — move μ\mu and the codes move with it.

But the computational graph has a hole in it. The step "draw a random number from N(μ,σ2)\mathcal N(\mu, \sigma^2)" returns a value with no derivative attached: the gradient of the loss arrives at zz and stops there. The decoder learns; the encoder, whose job is to produce μ\mu and σ\sigma, 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:

z=μ+σ⊙ε,ε∼N(0,I).z = \mu + \sigma \odot \varepsilon, \qquad \varepsilon \sim \mathcal N(0, I).

This is the affine sampling x=μ+Lεx = \mu + L\varepsilon from Multivariate Gaussians with a diagonal L=diag⁡(σ)L = \operatorname{diag}(\sigma), so zz has exactly the distribution N(μ,σ2)\mathcal N(\mu, \sigma^2) it had before. Nothing about the model changed; only where the randomness lives.

The encoder outputs log⁡σ2\log\sigma^2 rather than σ\sigma, so σ\sigma has to be recovered from it before the shift-and-scale. In PyTorch the noise comes from torch.randn_like, which draws ε\varepsilon with the same shape as its argument.

Gradients now flow

Now zz is an ordinary differentiable function of μ\mu and σ\sigma, with ε\varepsilon playing the role of a fixed input:

∂zj∂μj=1,∂zj∂σj=εj.\frac{\partial z_j}{\partial \mu_j} = 1, \qquad \frac{\partial z_j}{\partial \sigma_j} = \varepsilon_j .

Gradients of the reconstruction term flow through zz 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 zz is now an expectation over ε\varepsilon, and the distribution of ε\varepsilon does not depend on φ\varphi. So the gradient moves inside it:

∇φ Eqφ(z∣x)[f(z)]=Eε[∇φf(μ+σ⊙ε)].\nabla_\varphi\, \mathbb E_{q_\varphi(z \mid x)}\big[f(z)\big] = \mathbb E_{\varepsilon}\big[\nabla_\varphi f(\mu + \sigma \odot \varepsilon)\big].

The gradient for a single drawn ε\varepsilon 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, ∇φEqφ[f]=Eqφ[f(z) ∇φlog⁡qφ(z∣x)]\nabla_\varphi \mathbb E_{q_\varphi}[f] = \mathbb E_{q_\varphi}\big[f(z)\, \nabla_\varphi \log q_\varphi(z \mid x)\big]. It is unbiased too and works for any qq, but it never uses how ff changes with zz, and its variance is typically much higher. For the gradient in μ\mu of E[z2]\mathbb E[z^2] at μ=σ=1\mu = \sigma = 1, one score-function sample has variance 30; one reparameterized sample, 2(1+ε)2(1 + \varepsilon), has variance 4.

Why log σ² and not σ

Why does the encoder predict log⁡σ2\log\sigma^2 and not σ\sigma? 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:

σ=exp⁡(12log⁡σ2)>0for any output.\sigma = \exp\big(\tfrac12 \log\sigma^2\big) > 0 \quad \text{for any output}.

It also keeps very small variances on a comfortable numerical scale. Softplus is a common alternative; the trick itself works with any positive σ\sigma.

The KL needs no sampling

The other half of the loss, DKL(qφ(z∣x) ∥ p(z))D_{\mathrm{KL}}\big(q_\varphi(z \mid x) \,\|\, p(z)\big), needs no sampling at all. Between two Gaussians it has a closed form. Take one coordinate, q=N(μ,σ2)q = \mathcal N(\mu, \sigma^2) and p=N(0,1)p = \mathcal N(0, 1):

log⁡q(z)=−12log⁡(2πσ2)−(z−μ)22σ2,log⁡p(z)=−12log⁡(2π)−z22.\log q(z) = -\tfrac12 \log(2\pi\sigma^2) - \frac{(z - \mu)^2}{2\sigma^2}, \qquad \log p(z) = -\tfrac12 \log(2\pi) - \frac{z^2}{2}.

Under z∼qz \sim q, E[(z−μ)2]=σ2\mathbb E[(z - \mu)^2] = \sigma^2 and E[z2]=μ2+σ2\mathbb E[z^2] = \mu^2 + \sigma^2, so DKL=Eq[log⁡q−log⁡p]=12(μ2+σ2−1−log⁡σ2)D_{\mathrm{KL}} = \mathbb E_q[\log q - \log p] = \tfrac12\big(\mu^2 + \sigma^2 - 1 - \log\sigma^2\big). The diagonal qq 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:

LKL=−12∑j=1d(1+log⁡σj2−μj2−σj2).\mathcal L_{\mathrm{KL}} = -\frac12 \sum_{j=1}^{d} \big(1 + \log \sigma_j^2 - \mu_j^2 - \sigma_j^2\big).

It is zero exactly when μj=0\mu_j = 0 and σj=1\sigma_j = 1 in every dimension, that is, when the posterior equals the prior. In code it is one line, and it differentiates through μ\mu and log⁡σ2\log\sigma^2 directly.

Read it as a fine. Moving the mean away from 0 costs quadratically. Shrinking the standard deviation costs only logarithmically for small σ\sigma, about 4.1 nats at σ=0.01\sigma = 0.01, but without bound: as σ→0\sigma \to 0 the term −log⁡σ2-\log\sigma^2 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 s2=12s^2 = \tfrac12, 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.

    Open practice
  • 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).

    Open practice
  • 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.

Full notes

Answers are saved on the server and tied to this browser until you sign in.