Simple Algorithm
Deep Learning · Representation · 24 min

Autoencoders & Variational Autoencoders

Compressing to a latent code, and making that code a distribution you can sample.

An autoencoder learns to squeeze data through a narrow code and rebuild it. That makes a compressor, not a generator: nobody knows which codes are valid. The variational autoencoder turns the code into a probability distribution, and one inequality, the evidence lower bound, turns training it into ordinary gradient descent.

What you’ll learn

  • Build an autoencoder, explain why a linear one with squared error learns the principal subspace, and why a plain autoencoder's code space cannot be sampled.
  • Derive the evidence lower bound log⁡pθ(x)≥Eq[log⁡pθ(x∣z)]−DKL(qϕ(z∣x) ∥ p(z))\log p_{\boldsymbol\theta}(\mathbf x)\ge\E_q[\log p_{\boldsymbol\theta}(\mathbf x\mid\mathbf z)]-\KL(q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x)\,\|\,p(\mathbf z)) and identify its gap.
  • Derive the Gaussian KL term in closed form and implement a VAE training step with the reparameterization trick.
  • Explain why VAE samples blur, how β\beta trades reconstruction against the KL term, and how conditional VAEs model p(x∣c)p(\mathbf x\mid c).

Autoencoders: learning by copying

An autoencoder has two parts: an encoder z=eϕ(x)\mathbf z=e_{\boldsymbol\phi}(\mathbf x) that maps an input x∈Rd\mathbf x\in\R^d to a code z∈Rk\mathbf z\in\R^k, and a decoder x^=gθ(z)\hat{\mathbf x}=g_{\boldsymbol\theta}(\mathbf z) that maps it back. In this lesson z\mathbf z always denotes a latent variable, not a pre-activation. Both networks are trained together to minimize a reconstruction loss, usually the squared error:

L(ϕ,θ)=1n∑i=1n∥xi−gθ(eϕ(xi))∥2.\loss(\boldsymbol\phi,\boldsymbol\theta)=\frac1n\sum_{i=1}^n\norm{\mathbf x_i-g_{\boldsymbol\theta}(e_{\boldsymbol\phi}(\mathbf x_i))}^2.

Copying is trivial if the code is as large as the input, so the architecture blocks it. An undercomplete autoencoder makes k≪dk\ll d, a bottleneck; others keep kk large and penalize the code instead (sparse or contractive autoencoders).

Two caveats keep this honest. The subspace is determined but the coordinates are not: replacing AA by CACA and BB by BC−1BC^{-1} for any invertible k×kk\times k matrix CC leaves BABA unchanged, so the code units are generally mixtures of the principal components, not the components themselves. And with nonlinear encoders and decoders the autoencoder can learn curved low-dimensional structure that no linear projection captures; that is the point of making them deep.

Denoising autoencoders (Vincent et al., 2008) corrupt the input, for example by adding noise or zeroing random pixels, and train the network to output the clean version. The network can no longer copy, so even a wide code must capture structure. The idea returns in force later: for Gaussian noise, the optimal denoiser moves a noisy point along the gradient of the log-density of the noise-blurred data, so learning to denoise is learning that gradient (Vincent, 2011). Diffusion models are built on exactly this.

None of this yields a generator. The encoder maps the training set to some cloud of codes whose shape nobody specified. Decode a code from outside that cloud and the output is meaningless, and there is no rule for drawing codes from inside it.

A latent-variable model and its lower bound

The variational autoencoder (Kingma & Welling, 2014; Rezende, Mohamed & Wierstra, 2014) starts from the generative side. Fix a simple prior over codes, p(z)=N(0,I)p(\mathbf z)=\mathcal N(\mathbf 0,I), and let the decoder define a distribution over data given a code, pθ(x∣z)p_{\boldsymbol\theta}(\mathbf x\mid\mathbf z): a Gaussian centered at gθ(z)g_{\boldsymbol\theta}(\mathbf z), or independent Bernoulli pixels with probabilities gθ(z)g_{\boldsymbol\theta}(\mathbf z). Sampling is then trivial: draw z∼p(z)\mathbf z\sim p(\mathbf z), then x∼pθ(x∣z)\mathbf x\sim p_{\boldsymbol\theta}(\mathbf x\mid\mathbf z). Training by maximum likelihood needs the marginal

pθ(x)=∫pθ(x∣z) p(z) dz,pθ(z∣x)=pθ(x∣z) p(z)pθ(x)p_{\boldsymbol\theta}(\mathbf x)=\int p_{\boldsymbol\theta}(\mathbf x\mid\mathbf z)\,p(\mathbf z)\,d\mathbf z,\qquad p_{\boldsymbol\theta}(\mathbf z\mid\mathbf x)=\frac{p_{\boldsymbol\theta}(\mathbf x\mid\mathbf z)\,p(\mathbf z)}{p_{\boldsymbol\theta}(\mathbf x)}
With a neural decoder the integral has no closed form, and so neither does the posterior. Sampling z\mathbf z from the prior to estimate the integral fails in practice: almost no prior sample explains a given x\mathbf x.

The fix is amortized variational inference: train an encoder qϕ(z∣x)=N(μϕ(x),diag⁡σϕ2(x))q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x)=\mathcal N\big(\boldsymbol\mu_{\boldsymbol\phi}(\mathbf x),\diag\boldsymbol\sigma^2_{\boldsymbol\phi}(\mathbf x)\big) to propose codes that explain x\mathbf x, and use it to bound the likelihood from below.

DerivationThe evidence lower bound
  1. log⁡pθ(x)=log⁡Eqϕ(z∣x)[pθ(x∣z) p(z)qϕ(z∣x)]\log p_{\boldsymbol\theta}(\mathbf x)=\log\E_{q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x)}\Big[\frac{p_{\boldsymbol\theta}(\mathbf x\mid\mathbf z)\,p(\mathbf z)}{q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x)}\Big]

    Multiply and divide inside the integral by qϕ(z∣x)q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x), which turns the integral into an expectation under the encoder:

  2. log⁡pθ(x) ≥ Eqϕ[log⁡pθ(x∣z)+log⁡p(z)−log⁡qϕ(z∣x)]\log p_{\boldsymbol\theta}(\mathbf x)\ \ge\ \E_{q_{\boldsymbol\phi}}\big[\log p_{\boldsymbol\theta}(\mathbf x\mid\mathbf z)+\log p(\mathbf z)-\log q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x)\big]

    The logarithm is concave, so by Jensen's inequality the log of an expectation is at least the expectation of the log:

  3. L(θ,ϕ;x)=Eqϕ(z∣x)[log⁡pθ(x∣z)]⏟reconstruction−DKL(qϕ(z∣x) ∥ p(z))⏟regularizer\mathcal L(\boldsymbol\theta,\boldsymbol\phi;\mathbf x)=\underbrace{\E_{q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x)}\big[\log p_{\boldsymbol\theta}(\mathbf x\mid\mathbf z)\big]}_{\text{reconstruction}}-\underbrace{\KL\big(q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x)\,\|\,p(\mathbf z)\big)}_{\text{regularizer}}

    Group the last two terms into a KL divergence. The result is the evidence lower bound: a reconstruction term minus a regularizer that keeps each input's code distribution close to the prior.

  4. log⁡pθ(x)=L(θ,ϕ;x)+DKL(qϕ(z∣x) ∥ pθ(z∣x))\log p_{\boldsymbol\theta}(\mathbf x)=\mathcal L(\boldsymbol\theta,\boldsymbol\phi;\mathbf x)+\KL\big(q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x)\,\|\,p_{\boldsymbol\theta}(\mathbf z\mid\mathbf x)\big)

    To see exactly what was lost, write log⁡pθ(x)=Eq[log⁡pθ(x,z)−log⁡pθ(z∣x)]\log p_{\boldsymbol\theta}(\mathbf x)=\E_q[\log p_{\boldsymbol\theta}(\mathbf x,\mathbf z)-\log p_{\boldsymbol\theta}(\mathbf z\mid\mathbf x)], which holds for any qq, and add and subtract log⁡q\log q:

  5. The gap is the KL divergence from the encoder to the true posterior, which is never negative. Maximizing L\mathcal L over ϕ\boldsymbol\phi pulls the encoder toward the posterior and tightens the bound; maximizing over θ\boldsymbol\theta raises the likelihood itself (or makes the posterior easier to match).

Check your understanding

For one training example, when does the ELBO equal log⁡pθ(x)\log p_{\boldsymbol\theta}(\mathbf x) exactly?

  1. When the encoder's distribution matches the prior, qϕ(z∣x)=p(z)q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x)=p(\mathbf z)
  2. When the reconstruction is perfect
  3. When the encoder's distribution equals the true posterior, qϕ(z∣x)=pθ(z∣x)q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x)=p_{\boldsymbol\theta}(\mathbf z\mid\mathbf x)
  4. Never: Jensen's inequality is always strict
Show the answer

C. When the encoder's distribution equals the true posterior, qϕ(z∣x)=pθ(z∣x)q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x)=p_{\boldsymbol\theta}(\mathbf z\mid\mathbf x)

The gap is DKL(qϕ(z∣x) ∥ pθ(z∣x))\KL(q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x)\,\|\,p_{\boldsymbol\theta}(\mathbf z\mid\mathbf x)), which is zero exactly when the two distributions agree. A diagonal Gaussian encoder usually cannot match a neural decoder's posterior exactly, so in practice a gap remains.

The KL term in closed form

With a diagonal Gaussian encoder and a standard normal prior, the regularizer needs no sampling at all. Both distributions factor over the kk latent dimensions, so the KL is a sum of one-dimensional terms. Derive one of them:

DerivationKL between N(μ, σ²) and N(0, 1)
  1. DKL(q ∥ p)=Ez∼q[−12log⁡σ2−(z−μ)22σ2+z22]\KL(q\,\|\,p)=\E_{z\sim q}\Big[-\tfrac12\log\sigma^2-\frac{(z-\mu)^2}{2\sigma^2}+\frac{z^2}{2}\Big]

    Write the KL as an expectation under q=N(μ,σ2)q=\mathcal N(\mu,\sigma^2) of the log-ratio of the two densities. The log⁡2π\log2\pi terms cancel:

  2. DKL(q ∥ p)=−12log⁡σ2−12+12(μ2+σ2)\KL(q\,\|\,p)=-\tfrac12\log\sigma^2-\tfrac12+\tfrac12(\mu^2+\sigma^2)

    Under qq, E[(z−μ)2]=σ2\E[(z-\mu)^2]=\sigma^2 and E[z2]=μ2+σ2\E[z^2]=\mu^2+\sigma^2:

  3. DKL(N(μ,diag⁡σ2) ∥ N(0,I))=12∑j=1k(μj2+σj2−log⁡σj2−1)\KL\big(\mathcal N(\boldsymbol\mu,\diag\boldsymbol\sigma^2)\,\|\,\mathcal N(\mathbf 0,I)\big)=\frac12\sum_{j=1}^{k}\big(\mu_j^2+\sigma_j^2-\log\sigma_j^2-1\big)

    Collect the terms and sum over the dimensions:

  4. Each term is zero only at μj=0\mu_j=0, σj=1\sigma_j=1. The μj2\mu_j^2 part pulls codes toward the origin; σj2−log⁡σj2\sigma_j^2-\log\sigma_j^2, minimized at σj=1\sigma_j=1, stops the encoder from shrinking its noise to zero, which would turn the VAE back into a plain autoencoder with isolated points in code space.

Predict before you look

One latent dimension has encoder mean μ=1\mu=1 and standard deviation σ=0.5\sigma=0.5. What is its KL divergence from N(0,1)\mathcal N(0,1), in nats?

Show the answer

0.82 nats

12(1+0.25−log⁡0.25−1)=12(0.25+1.386)≈0.82\tfrac12\big(1+0.25-\log0.25-1\big)=\tfrac12(0.25+1.386)\approx0.82 nats. Most of it comes from the narrow spread: −log⁡σ2=1.386-\log\sigma^2=1.386. The same dimension with σ=1\sigma=1 would cost only 12μ2=0.5\tfrac12\mu^2=0.5.

The KL term has an information-theoretic reading: averaged over the data, it upper-bounds how many nats of information the code carries about the input. Every nat the encoder spends to make a code more specific is charged against the bound, and it pays only if the decoder's reconstruction improves by more. That bargain explains both the strengths and the failures you will meet next.

The reparameterization trick and a training step

The reconstruction term Eqϕ[log⁡pθ(x∣z)]\E_{q_{\boldsymbol\phi}}[\log p_{\boldsymbol\theta}(\mathbf x\mid\mathbf z)] has no closed form, so it is estimated by sampling, usually with a single z\mathbf z per example. But a sample drawn from qϕq_{\boldsymbol\phi} is not a differentiable function of ϕ\boldsymbol\phi: how should the gradient reach the encoder? The reparameterization trick moves the randomness into a parameter-free variable:

z=μϕ(x)+σϕ(x)⊙ϵ,ϵ∼N(0,I)⟹∇ϕEqϕ[f(z)]=Eϵ[∇ϕf(μϕ+σϕ⊙ϵ)]\mathbf z=\boldsymbol\mu_{\boldsymbol\phi}(\mathbf x)+\boldsymbol\sigma_{\boldsymbol\phi}(\mathbf x)\odot\boldsymbol\epsilon,\quad\boldsymbol\epsilon\sim\mathcal N(\mathbf 0,I)\qquad\Longrightarrow\qquad\nabla_{\boldsymbol\phi}\E_{q_{\boldsymbol\phi}}[f(\mathbf z)]=\E_{\boldsymbol\epsilon}\big[\nabla_{\boldsymbol\phi}f(\boldsymbol\mu_{\boldsymbol\phi}+\boldsymbol\sigma_{\boldsymbol\phi}\odot\boldsymbol\epsilon)\big]
Now z\mathbf z is an ordinary differentiable function of ϕ\boldsymbol\phi and the noise, and backpropagation does the rest. The alternative, the score-function (REINFORCE) estimator, needs only values of ff but typically has much higher variance.

The decoder's likelihood decides the reconstruction loss. Independent Bernoulli pixels give the binary cross-entropy. A Gaussian pθ(x∣z)=N(gθ(z),s2I)p_{\boldsymbol\theta}(\mathbf x\mid\mathbf z)=\mathcal N(g_{\boldsymbol\theta}(\mathbf z),s^2I) with fixed variance gives −log⁡p=∥x−gθ(z)∥2/(2s2)+const-\log p=\norm{\mathbf x-g_{\boldsymbol\theta}(\mathbf z)}^2/(2s^2)+\text{const}: squared error, with s2s^2 setting its exchange rate against the KL term. Here is a complete training step for binarized 28×2828\times28 digits:

python
import torch
import torch.nn as nn
import torch.nn.functional as F

class VAE(nn.Module):
    def __init__(self, d=784, h=400, k=20):
        super().__init__()
        self.enc = nn.Sequential(nn.Linear(d, h), nn.ReLU(), nn.Linear(h, 2 * k))
        self.dec = nn.Sequential(nn.Linear(k, h), nn.ReLU(), nn.Linear(h, d))

    def forward(self, x):
        mu, logvar = self.enc(x).chunk(2, dim=-1)
        z = mu + torch.exp(0.5 * logvar) * torch.randn_like(mu)  # reparameterization
        return self.dec(z), mu, logvar                           # decoder outputs logits

def neg_elbo(x, logits, mu, logvar):
    rec = F.binary_cross_entropy_with_logits(logits, x, reduction='sum')  # -log p(x|z)
    kl = 0.5 * (mu.pow(2) + logvar.exp() - logvar - 1).sum()              # closed form
    return (rec + kl) / x.shape[0]

model = VAE()
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
for x in loader:                          # x: (B, 784) binarized pixels in {0, 1}
    loss = neg_elbo(x, *model(x))
    opt.zero_grad(); loss.backward(); opt.step()

The encoder predicts log⁡σ2\log\boldsymbol\sigma^2 rather than σ\boldsymbol\sigma, so any real output is a valid variance. To generate, skip the encoder: torch.sigmoid(model.dec(torch.randn(16, 20))) gives 16 grids of pixel probabilities.

Think first The loss above uses one sample of ϵ\boldsymbol\epsilon per example. Is the gradient biased?

No. For each fixed ϵ\boldsymbol\epsilon the gradient of f(μ+σ⊙ϵ)f(\boldsymbol\mu+\boldsymbol\sigma\odot\boldsymbol\epsilon) is exact, and averaging over ϵ\boldsymbol\epsilon gives the true gradient, so one sample is an unbiased, if noisy, estimate. The mini-batch already averages over many examples, which is why one sample per example is enough in practice.

Blur, β and conditions

Why samples blur. With a Gaussian decoder, the reconstruction term is a squared error, which is minimized by the conditional mean: the decoder outputs the average of all images consistent with a code. Because the encoder is noisy, nearby codes from many slightly different images get mixed, and their average is soft. Two further effects add to it. Sampling uses the prior p(z)p(\mathbf z), but the decoder was trained on codes from the aggregate posterior qϕ(z)=1n∑iqϕ(z∣xi)q_{\boldsymbol\phi}(\mathbf z)=\frac1n\sum_iq_{\boldsymbol\phi}(\mathbf z\mid\mathbf x_i), which never matches the prior exactly, so some prior samples land in regions the decoder rarely saw. And the per-pixel noise of pθ(x∣z)p_{\boldsymbol\theta}(\mathbf x\mid\mathbf z) is usually dropped when sampling, since it would only add static.

The β trade-off. Weighting the regularizer by β\beta gives the objective Eq[log⁡pθ(x∣z)]−β DKL(qϕ(z∣x) ∥ p(z))\E_q[\log p_{\boldsymbol\theta}(\mathbf x\mid\mathbf z)]-\beta\,\KL(q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x)\,\|\,p(\mathbf z)). Larger β\beta squeezes the information in the code, giving blurrier reconstructions but codes closer to the prior; smaller β\beta gives sharper reconstructions and a less regular code space. With a Gaussian decoder, β\beta is equivalent to rescaling the fixed decoder variance s2s^2. The β-VAE (Higgins et al., 2017) chose β>1\beta>1 and found that on simple images varying in a few independent factors (position, scale, rotation), individual code units tended to align with single factors: "disentanglement". Locatello et al. (2019) later proved that without inductive biases or some supervision, such disentanglement is not identifiable from the data alone.

Conditional VAEs. To model p(x∣c)p(\mathbf x\mid c), for a class cc or for a whole input image when the target x\mathbf x is, say, its segmentation, give cc to every part of the model: an encoder qϕ(z∣x,c)q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x,c), a decoder pθ(x∣z,c)p_{\boldsymbol\theta}(\mathbf x\mid\mathbf z,c) and possibly a learned prior pψ(z∣c)p_{\boldsymbol\psi}(\mathbf z\mid c). The same derivation bounds log⁡pθ(x∣c)\log p_{\boldsymbol\theta}(\mathbf x\mid c) by Eq[log⁡pθ(x∣z,c)]−DKL(qϕ(z∣x,c) ∥ pψ(z∣c))\E_q[\log p_{\boldsymbol\theta}(\mathbf x\mid\mathbf z,c)]-\KL(q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x,c)\,\|\,p_{\boldsymbol\psi}(\mathbf z\mid c)). Sohn, Lee & Yan (2015) used this for structured prediction: different samples of z\mathbf z give different plausible outputs for one input, where a deterministic network would average them.

Check your understanding

You raise β\beta from 11 to 88 in a VAE trained on faces. What do you expect?

  1. Sharper reconstructions, because the regularizer is stronger
  2. Codes that carry less information about each face, blurrier reconstructions, and per-input code distributions closer to the prior
  3. No change, because β\beta only rescales the loss
  4. Posterior collapse is now impossible
Show the answer

B. Codes that carry less information about each face, blurrier reconstructions, and per-input code distributions closer to the prior

A larger weight on the KL makes every nat of information in the code more expensive, so the encoder keeps less detail and the decoder reconstructs a blurrier average. The flip side is a code space that matches the prior more closely.

Key takeaways

  • An autoencoder compresses x\mathbf x to a code and reconstructs it; with linear maps and squared error it learns the principal subspace (Baldi & Hornik, 1989). Its code space has no distribution, so it cannot generate.
  • A VAE defines pθ(x)=∫pθ(x∣z)p(z) dzp_{\boldsymbol\theta}(\mathbf x)=\int p_{\boldsymbol\theta}(\mathbf x\mid\mathbf z)p(\mathbf z)\,d\mathbf z and maximizes the ELBO Eq[log⁡pθ(x∣z)]−DKL(qϕ(z∣x) ∥ p(z))\E_q[\log p_{\boldsymbol\theta}(\mathbf x\mid\mathbf z)]-\KL(q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x)\,\|\,p(\mathbf z)), whose gap is DKL(qϕ ∥ pθ(z∣x))\KL(q_{\boldsymbol\phi}\,\|\,p_{\boldsymbol\theta}(\mathbf z\mid\mathbf x)).
  • For diagonal Gaussians the regularizer is 12∑j(μj2+σj2−log⁡σj2−1)\tfrac12\sum_j(\mu_j^2+\sigma_j^2-\log\sigma_j^2-1), and the reparameterization z=μ+σ⊙ϵ\mathbf z=\boldsymbol\mu+\boldsymbol\sigma\odot\boldsymbol\epsilon makes the reconstruction term differentiable.
  • Gaussian decoders output conditional means, so samples blur; β\beta trades reconstruction against the KL term, and expressive decoders can make ignoring z\mathbf z optimal (posterior collapse).
  • Conditional VAEs bound log⁡p(x∣c)\log p(\mathbf x\mid c) with an encoder, decoder and prior that all see cc, giving several plausible outputs for one input.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

You train the same linear autoencoder, with a 3-unit code and squared error, twice from different random initializations. The data are centered and their covariance has distinct positive eigenvalues, and both runs reach the global minimum. How do the two runs' codes z1=A1x\mathbf z_1=A_1\mathbf x and z2=A2x\mathbf z_2=A_2\mathbf x compare?

  1. They are identical, because the global minimum is unique
  2. They span the same principal subspace, and one is an invertible linear function of the other: z2=Mz1\mathbf z_2=M\mathbf z_1
  3. They span unrelated three-dimensional subspaces, one per initialization
  4. They agree up to reordering the code units and flipping their signs
Show the answer

B. They span the same principal subspace, and one is an invertible linear function of the other: z2=Mz1\mathbf z_2=M\mathbf z_1

Both runs have BiAiB_iA_i equal to the projection onto the top-3 principal subspace, so each Ai=CiU⊤A_i=C_iU^\top for an orthonormal basis UU of that subspace and some invertible CiC_i. Then z2=C2C1−1z1\mathbf z_2=C_2C_1^{-1}\mathbf z_1: the same information, in a basis that depends on the run.

Question 2

Which identity holds for any encoder qϕq_{\boldsymbol\phi}?

  1. log⁡pθ(x)=L+DKL(qϕ(z∣x) ∥ p(z))\log p_{\boldsymbol\theta}(\mathbf x)=\mathcal L+\KL(q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x)\,\|\,p(\mathbf z))
  2. log⁡pθ(x)=L\log p_{\boldsymbol\theta}(\mathbf x)=\mathcal L
  3. log⁡pθ(x)=L−DKL(qϕ(z∣x) ∥ pθ(z∣x))\log p_{\boldsymbol\theta}(\mathbf x)=\mathcal L-\KL(q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x)\,\|\,p_{\boldsymbol\theta}(\mathbf z\mid\mathbf x))
  4. log⁡pθ(x)=L+DKL(qϕ(z∣x) ∥ pθ(z∣x))\log p_{\boldsymbol\theta}(\mathbf x)=\mathcal L+\KL(q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x)\,\|\,p_{\boldsymbol\theta}(\mathbf z\mid\mathbf x))
Show the answer

D. log⁡pθ(x)=L+DKL(qϕ(z∣x) ∥ pθ(z∣x))\log p_{\boldsymbol\theta}(\mathbf x)=\mathcal L+\KL(q_{\boldsymbol\phi}(\mathbf z\mid\mathbf x)\,\|\,p_{\boldsymbol\theta}(\mathbf z\mid\mathbf x))

The likelihood exceeds the ELBO by the KL from the encoder to the true posterior. Because a KL is never negative, L\mathcal L is a lower bound, tight exactly when qq is the posterior.

Question 3

Why do VAEs write z=μϕ(x)+σϕ(x)⊙ϵ\mathbf z=\boldsymbol\mu_{\boldsymbol\phi}(\mathbf x)+\boldsymbol\sigma_{\boldsymbol\phi}(\mathbf x)\odot\boldsymbol\epsilon with ϵ∼N(0,I)\boldsymbol\epsilon\sim\mathcal N(\mathbf 0,I) instead of sampling z\mathbf z directly?

  1. So that the randomness no longer depends on ϕ\boldsymbol\phi, and backpropagation can carry the reconstruction gradient through μ\boldsymbol\mu and σ\boldsymbol\sigma to the encoder
  2. To make the KL term computable in closed form
  3. To make sampling faster at test time
  4. To make the code discrete
Show the answer

A. So that the randomness no longer depends on ϕ\boldsymbol\phi, and backpropagation can carry the reconstruction gradient through μ\boldsymbol\mu and σ\boldsymbol\sigma to the encoder

A sample drawn from qϕq_{\boldsymbol\phi} is not a differentiable function of ϕ\boldsymbol\phi. Moving the randomness into ϵ\boldsymbol\epsilon makes z\mathbf z a deterministic, differentiable function of ϕ\boldsymbol\phi and ϵ\boldsymbol\epsilon, giving low-variance gradient estimates of the reconstruction term.

Question 4

A VAE with a Gaussian decoder of fixed variance produces blurry samples. Which explanation is the main one?

  1. Adam's gradient noise smears the decoder's weights
  2. The prior N(0,I)\mathcal N(\mathbf 0,I) is too narrow to hold many images
  3. The latent space has too many dimensions
  4. The squared-error reconstruction term is minimized by the conditional mean, so the decoder outputs an average of the images consistent with a noisy code
Show the answer

D. The squared-error reconstruction term is minimized by the conditional mean, so the decoder outputs an average of the images consistent with a noisy code

Under a Gaussian likelihood the best prediction is the mean, and the mean of several slightly different images is soft. Sharper models change the likelihood or the decoder (autoregressive or adversarial decoders, perceptual losses) or add latent structure.

Go deeper

Further reading

  • D. P. Kingma & M. Welling, "Auto-encoding variational Bayes," ICLR (2014).
  • D. J. Rezende, S. Mohamed & D. Wierstra, "Stochastic backpropagation and approximate inference in deep generative models," ICML (2014).
  • D. P. Kingma & M. Welling, "An introduction to variational autoencoders," Foundations and Trends in Machine Learning (2019).
  • S. J. D. Prince, Understanding Deep Learning, ch. 17 "Variational autoencoders" (MIT Press, 2023).