Overview
A variational autoencoder compresses each input into a small random code and then rebuilds the input from it. Two things are wanted at once. The rebuilt output should match the input, which is the reconstruction term. And the codes should fill the latent space in a regular way, so that sampling a code at random gives a sensible output, which is the KL term. The KL term measures how far the encoder's distribution for one input is from a standard normal. Their sum is the negative of the evidence lower bound, a quantity that is never above the log-probability the model gives the data.
A short history
The bound comes from variational inference, developed for graphical models in the 1990s by Michael Jordan and others as a way to approximate distributions that cannot be computed exactly. Diederik Kingma and Max Welling turned it into a loss for neural networks in the 2013 paper 'Auto-Encoding Variational Bayes', and Rezende, Mohamed and Wierstra published a similar method in 2014. Their reparameterisation trick let the bound be optimised by ordinary backpropagation.
How it works
- The encoder gives a mean and a log-variance for each latent dimension. The decoder gives a reconstruction. Both come from your model.
- Compute the reconstruction negative log-likelihood per sample: Bernoulli from logits, or Gaussian with fixed
sigma. - Compute the KL divergence from the encoder distribution to the standard normal in closed form, summed over latent dimensions.
- Add them: reconstruction plus
betatimes KL, per sample. - Average or sum over the batch with
reduction. - In
backward, return the direct gradients for the reconstruction, and the log-variance. The path through the sampled code is added by the model.
Watch out for
- If the KL term dominates, the encoder outputs the prior for every input and the decoder ignores the code. This posterior collapse shows as a KL near zero.
- The two terms must be summed over dimensions, not averaged, before they are added. Averaging one and not the other changes their balance by a large factor.
- With
betadifferent from 1 the loss is no longer a bound on the log-likelihood, so its value cannot be compared across settings ofbeta. - The template computes the loss terms only. Sampling the code with the reparameterisation trick and running the decoder are the model's job.
- The Bernoulli option expects logits and data in . Passing probabilities gives a wrong reconstruction term with no error.
Use cases
When to use it
Training variational autoencoders and related latent-variable models. Set beta above 1 for more disentangled codes, or anneal it from 0 to avoid the KL term winning too early.
In industry
- Image generation
- Latent diffusion image generators first compress images with an autoencoder trained with a KL term, and run the diffusion process in that latent space.
- Drug discovery
- Variational autoencoders trained on molecule strings give a continuous space in which chemists search for new candidate structures.
- Anomaly detection
- A variational autoencoder trained on normal sensor or transaction data flags inputs that it reconstructs poorly or finds unlikely.
Choosing it: what must hold
- A goal of learning a latent representation or generating new samples, not predicting a label.
- A reconstruction likelihood that suits the data: Gaussian for real values, Bernoulli or categorical for discrete ones.
- A plan for balancing the two terms, such as KL warm-up, so the model does not ignore its latent code.
When to choose something else
| If | Use instead |
|---|---|
| You only need a compressed representation, not a generative model | A plain autoencoder with mean squared error |
| You want the sharpest possible generated images | A diffusion model or a GAN |
| You want representations for retrieval or downstream classifiers | InfoNCE on augmented pairs |
Math foundations
The bound
The right side is the evidence lower bound. The first term rewards codes from which the decoder can rebuild . The second penalises an encoder distribution far from the prior.
The loss
The negative bound, estimated with one sampled code . With minimising it maximises the bound.
The KL term in closed form
For a diagonal Gaussian encoder and a standard normal prior no sampling is needed. Each dimension contributes zero exactly when and , which means unit variance.
Bernoulli reconstruction from logits
Binary cross-entropy between the data and , written on the logits so it is stable. Used for data in such as pixel intensities.
Gaussian reconstruction
Squared error scaled by a fixed variance, plus a constant. A smaller weights reconstruction more heavily against the KL term.
Direct gradients of the KL term
The KL term pulls every mean toward 0 and every log-variance toward 0. The reconstruction term, through the decoder, pulls the other way.
Symbols
- one data sample,
target - the latent code sampled from the encoder distribution
- the encoder distribution, a diagonal Gaussian with mean mu and log-variance v
- the decoder likelihood of the data given the code
- the prior over codes, a standard normal
- encoder mean and log-variance for latent dimension j;
muandlogvar - decoder output for data element k,
recon(logits or means) - weight on the KL term,
betain the config, default 1 - fixed standard deviation of the Gaussian likelihood,
sigma - the number of latent dimensions
- the Kullback-Leibler divergence
- the loss for one sample, the negative ELBO
Worked by hand
One sample with a single latent dimension, and , and a single data element with decoder logit . Bernoulli likelihood, . Use and .
The loss is 0.8108 nats, most of it KL. The encoder is paying 0.6839 to place this input away from the origin with a narrow variance.
Visual example
Loading the example.
Try this
- Move across the curve: the height is what the model is charged.
- Move each control and watch which part of the curve it changes.
Code sample
import numpy as np
from impl import ELBO
from config import ELBOConfig
loss = ELBO(ELBOConfig(likelihood="bernoulli", beta=1.0))
rng = np.random.default_rng(0)
x = (rng.uniform(size=(4, 784)) > 0.5).astype(float) # a batch of binary images, flattened
mu, logvar = rng.normal(size=(4, 16)), np.zeros((4, 16)) # encoder outputs
z = mu + np.exp(0.5 * logvar) * rng.normal(size=mu.shape) # the sampling step, in your model
recon_logits = rng.normal(size=(4, 784)) # decoder output for z
print(loss.forward(recon_logits, x, mu, logvar)) # negative ELBO, nats per sample
recon_nll, kl = loss.components(recon_logits, x, mu, logvar)
g_recon, g_mu, g_logvar = loss.backward(recon_logits, x, mu, logvar)Read the implementation (72 lines)
"""Negative ELBO of a VAE with a diagonal Gaussian encoder and a standard normal prior: reconstruction negative log-
likelihood plus beta times the closed-form KL term.
NumPy only. `forward` returns the loss, `components` its two parts, `backward` the gradients with respect to the
reconstruction, mu and logvar.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import ELBOConfig
except ImportError: # run from the template's own folder
from config import ELBOConfig
class ELBO:
"""reconstruction NLL + beta * KL(N(mu, exp(logvar)) || N(0, I)), per sample, then reduced over the batch."""
def __init__(self, config: ELBOConfig | None = None) -> None:
self.config = config or ELBOConfig()
@staticmethod
def _check(recon, target, mu, logvar) -> tuple[np.ndarray, ...]:
"""All four as float arrays; recon and target share a shape (N, ...), mu and logvar a shape (N, ...)."""
recon, target, mu, logvar = (np.asarray(x, dtype=float) for x in (recon, target, mu, logvar))
if recon.shape != target.shape or mu.shape != logvar.shape or recon.ndim < 1 or mu.ndim < 1:
raise ValueError("recon and target must share a shape, and mu and logvar must share a shape")
if recon.shape[0] != mu.shape[0]:
raise ValueError(f"batch sizes differ: {recon.shape[0]} and {mu.shape[0]}")
return recon, target, mu, logvar
def components(self, recon, target, mu, logvar) -> tuple[np.ndarray, np.ndarray]:
"""The two parts of the loss for every sample, before weighting and reduction.
recon: (N, ...) decoder output (logits for "bernoulli", means for "gaussian"). target: same shape,
the data. mu, logvar: (N, latent) encoder outputs. Returns (reconstruction NLL (N,), KL (N,)), in nats.
"""
recon, target, mu, logvar = self._check(recon, target, mu, logvar)
n = recon.shape[0]
if self.config.likelihood == "bernoulli":
nll = np.logaddexp(0.0, recon) - target * recon # -[x log p + (1 - x) log(1 - p)], p = sigmoid(recon)
else:
var = self.config.sigma**2
nll = 0.5 * (target - recon) ** 2 / var + 0.5 * math.log(2.0 * math.pi * var)
kl = -0.5 * (1.0 + logvar - mu**2 - np.exp(logvar))
return nll.reshape(n, -1).sum(axis=1), kl.reshape(n, -1).sum(axis=1)
def forward(self, recon, target, mu, logvar) -> float:
"""Negative ELBO as a float: reconstruction + beta * KL, averaged (or summed) over the batch."""
nll, kl = self.components(recon, target, mu, logvar)
per_sample = nll + self.config.beta * kl
return float(per_sample.mean() if self.config.reduction == "mean" else per_sample.sum())
def backward(self, recon, target, mu, logvar) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Gradients of the loss with respect to recon, mu and logvar, each in the shape it was given.
These are the direct gradients of the two terms. The gradient that flows from recon back through the
decoder and the sampled code into mu and logvar is the model's job and adds to the ones returned here.
"""
recon, target, mu, logvar = self._check(recon, target, mu, logvar)
scale = 1.0 / recon.shape[0] if self.config.reduction == "mean" else 1.0
if self.config.likelihood == "bernoulli":
g_recon = np.exp(-np.logaddexp(0.0, -recon)) - target # sigmoid(recon) - x
else:
g_recon = (recon - target) / self.config.sigma**2
g_mu = self.config.beta * mu
g_logvar = self.config.beta * 0.5 * (np.exp(logvar) - 1.0)
return g_recon * scale, g_mu * scale, g_logvar * scale
__call__ = forward- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Build ELBO(ELBOConfig(likelihood="bernoulli", beta=1.0)). With random recon and target of shape (4, 10), call components once with mu and logvar all zero and once with mu all 2. Confirm the KL is 0 in the first case, compute by hand what it should be in the second, then compare forward at beta of 1 and 4.
Check on learning
- After training, the KL term is nearly zero for every input and reconstructions all look like the dataset average. What happened, and what would you try?
A way to think about it
A zero KL means the code carries no information about the input. Think about ways to make using the code worthwhile early on: a smaller at first, or a weaker decoder.
- Why can the KL term be computed exactly while the reconstruction term needs a sampled code?
A way to think about it
The KL is between two Gaussians, which has a formula. The reconstruction passes the code through a neural network, and no closed form exists for an expectation through that.
- With the Gaussian likelihood, what happens to the balance between the two terms when
sigmais halved?A way to think about it
Look at the factor . Compare the effect with changing , and ask whether the two settings are really independent.
- The KL term pulls every code toward the standard normal. Why is that useful for generating new samples?
A way to think about it
To generate, you draw a code from the prior and decode it. Consider what the decoder has seen during training if the encoder's codes lie nowhere near the prior.
backwardreturns as the gradient for the mean. Why is that not the full gradient the encoder needs?A way to think about it
The mean also shifts the sampled code, which changes the reconstruction. Trace that second path through the decoder and decide who is responsible for it.