The encoder in a variational autoencoder predicts a distribution over a latent (a mean and a variance), and you'd like to train it on a likelihood you can't compute.
The encoder outputs a mean and a variance
You build a VAE from three pieces: a prior \(p(z) = \mathcal{N}(0, I)\) over a latent variable \(z\), a decoder \(p(x \mid z)\) that turns a latent back into data, and an encoder \(q(z \mid x)\) that maps data to a distribution over latents. The encoder is the neural network, so start by pinning down its output.
Hand the encoder an input \(x\) and you get back the parameters of a Gaussian over \(z\): a mean \(\mu(x)\) and a variance \(\sigma^2(x)\) (in practice a log-variance, so it stays unconstrained). Read "the VAE predicts" as mean and variance:
To get a latent you have to sample from that Gaussian, and you can't differentiate through a sampling step, so you would get no gradient for \(\mu\) and \(\sigma\). You fix this with the reparameterization trick: draw the randomness from a fixed standard Gaussian and push it through the predicted parameters,
Now \(z\) is a deterministic, differentiable function of \(\mu\) and \(\sigma\), with all the noise in \(\varepsilon\). I derive this "standard Gaussian to latent" map and the closed form of the KL term in the side note at the end.
The likelihood is intractable
You'd like to train by maximum likelihood: maximize \(\log p(x)\). Write out the marginal,
and you're staring at an integral over the entire latent space. With a neural-network decoder, that integral has no closed form. You can't enumerate it either, because \(z\) is continuous and high-dimensional. Now write the posterior with Bayes' rule,
and its denominator is the intractable \(p(x)\), so the true posterior is out of reach too. You brought in \(q(z \mid x)\) to approximate that posterior, and now you need a way to measure how good the approximation is.
Forward and reverse KL
You measure the gap between \(q(z \mid x)\) and \(p(z \mid x)\) with a KL divergence. KL is not symmetric, so you have to pick an order:
- Forward, \(D_{\mathrm{KL}}\big(p(z \mid x) \,\|\, q(z \mid x)\big)\): an expectation over the true posterior \(p(z \mid x)\), the thing I said you can't sample from, which makes this direction a non-starter.
- Reverse, \(D_{\mathrm{KL}}\big(q(z \mid x) \,\|\, p(z \mid x)\big)\): an expectation over your encoder \(q(z \mid x)\), which you built and can sample from for cheap with the reparameterization trick.
You minimize the reverse KL. It's the tractable direction, and it's the direction you can rearrange into a quantity you can optimize. (Reverse KL is also mode-seeking: the KL penalty is smaller for concentrating \(q\) on one mode of the posterior than for smearing probability where the posterior has none. For a sampler, that's the well-behaved failure mode.)
KL from information content
I like seeing where KL comes from before I use it. The information content of an outcome under a density is \(I(x) = -\log p(x)\): rarer outcomes have more bits. Say you're using the distribution \(q\) and \(p\) is the true one. The excess information per sample for using the wrong distribution is:
and you average that surprise gap over the true distribution to get the Kullback-Leibler divergence,
and it equals zero only when the two distributions agree almost everywhere. You'll lean on that one non-negativity for the rest of the derivation.
Deriving the bound
Write the reverse KL between your encoder and the true posterior, then substitute Bayes' rule for \(p(z \mid x)\):
Replace \(p(z \mid x) = \dfrac{p(x \mid z)\, p(z)}{p(x)}\) and you get the ratio \(\dfrac{q(z \mid x)\, p(x)}{p(x \mid z)\, p(z)}\) inside the log:
Split the logarithm and pull \(\log p(x)\) out of the integral, since it has no dependence on \(z\) and \(\int q(z \mid x)\, dz = 1\):
Maximizing the ELBO
Call that integral \(\mathcal{L}\). Rearrange the line above and you have an exact identity:
The KL term is non-negative, so \(\mathcal{L} \le \log p(x)\): \(\mathcal{L}\) is a lower bound on the log evidence, the evidence lower bound. Expand it into its two pieces,
The ELBO
\( \mathcal{L} = \mathbb{E}_{q(z \mid x)}\!\big[\log p(x \mid z)\big] - D_{\mathrm{KL}}\!\big(q(z \mid x) \,\|\, p(z)\big) \le \log p(x). \)
You maximize \(\mathcal{L}\) because \(\log p(x)\), the thing you want, is fixed and unreachable, and the gap to it is \(D_{\mathrm{KL}}(q \,\|\, p(z \mid x)) \ge 0\). Push \(\mathcal{L}\) up and you do two jobs at once: you drive a proxy for the likelihood upward and you shrink that gap, pulling \(q(z \mid x)\) toward the true posterior. You get a tight bound if and only if the encoder recovers \(p(z \mid x)\).
The training loss
Optimizers minimize, so you take the negative ELBO as your training loss:
You can read the two terms as the two halves of the autoencoder. The first is reconstruction: you sample \(z\) with the reparameterization trick, decode it, and penalize a decoder that gives the original \(x\) low probability. A Gaussian decoder gives you mean-squared error, and a Bernoulli decoder gives you binary cross-entropy. The second is regularization: you pull the predicted \(\mu, \sigma\) toward the standard-normal prior so the latent space stays smooth and samplable. Minimize this loss and you maximize the ELBO, the lower bound on \(\log p(x)\).
Side note: the Gaussian encoder
The reparameterization trick
You can't backprop through a coin flip, so you pull the randomness out into a fixed standard Gaussian, sample that, and push it through your predicted mean and variance. You keep the noise separate and your gradients flow. It takes one product and one sum, and it still feels like magic to me.
You need samples \(z \sim \mathcal{N}(\mu, \sigma^2)\), and you need gradients to flow back into \(\mu\) and \(\sigma\). With a location-scale Gaussian, you have both: if \(\varepsilon \sim \mathcal{N}(0, I)\), then
The stochastic part is the fixed, parameter-free \(\varepsilon\), and \(\mu\) and \(\sigma\) appear only in deterministic, smooth operations. That gives you \(\partial z / \partial \mu = 1\) and \(\partial z / \partial \sigma = \varepsilon\), and the expectation \(\mathbb{E}_{q}[\,\cdot\,]\) becomes \(\mathbb{E}_{\varepsilon \sim \mathcal{N}(0,I)}[\,\cdot\,]\), which you estimate by Monte Carlo and differentiate term by term. You have transported the Gaussian noise into the latent, in the literal sense of a map from one to the other.
Closed form of the KL term
The encoder \(q = \mathcal{N}(\mu, \sigma^2)\) and the prior \(p = \mathcal{N}(0, 1)\) are both Gaussian, so you can compute the regularizer without sampling. In one dimension,
Plug in \(\mathbb{E}_q[(z-\mu)^2] = \sigma^2\) and \(\mathbb{E}_q[z^2] = \mu^2 + \sigma^2\):
Sum over a diagonal latent of dimension \(J\) and you have the term that appears in the loss,
a closed-form function of the same mean and variance the network predicts, the two quantities I started this note with.
It took me over ten tries to derive this from memory.