Overview
An ordinary autoencoder squeezes each input into a short code and rebuilds the input from it. Its codes can be scattered anywhere, with empty regions between them that decode to nonsense, so it cannot be used to generate new data. A variational autoencoder changes two things. The encoder outputs a small cloud of possible codes, a mean and a spread, and a code is drawn from the cloud at random. A penalty also pulls every cloud toward one shared standard bell curve centred at zero. The clouds therefore overlap and fill the space, and decoding a random draw from that bell curve yields a plausible new example.
A short history
Diederik Kingma and Max Welling introduced the variational autoencoder in a paper posted in 2013, and Danilo Rezende, Shakir Mohamed and Daan Wierstra published closely related work in 2014. The reparameterisation trick let a network with random latent variables be trained by ordinary backpropagation, joining deep learning with variational inference. VAEs give a smooth latent space, and a VAE compresses images in latent diffusion systems such as Stable Diffusion.
How it works
- The encoder maps an input to a mean and a log-variance for each latent dimension.
- Draw standard normal noise and form the code . This is the reparameterisation step.
- The decoder maps back to data space: a mean for the gaussian likelihood, or a logit per feature for the bernoulli likelihood.
- Compute the reconstruction loss, which measures how far the decoder output is from the input.
- Compute the KL term, which measures how far the encoder's cloud is from the standard normal, and add it with weight beta.
- Backpropagate through decoder, sampling step and encoder, and update with Adam. To generate, decode draws from the standard normal with the sample method.
Watch out for
- If the KL term dominates, the encoder outputs the prior for every input and the decoder ignores the code. This is called posterior collapse. Lower beta or strengthen the encoder.
- Reconstructions are blurry, because the decoder outputs the average of everything consistent with an uncertain code.
- The loss is noisy since it depends on random draws, so compare runs with a fixed seed and look at the reconstruction and KL parts separately.
- The bernoulli likelihood expects data in the range 0 to 1 and the template raises an error otherwise. The gaussian likelihood assumes unit variance, so scale your features accordingly.
Use cases
When to use it
Learning a smooth low-dimensional representation of data that you can also sample from, for example to generate variations, interpolate between examples or flag unusual inputs by their low ELBO.
In industry
- Generative imaging
- Compressing images into a small latent grid in which a diffusion model works, then decoding the result back to pixels.
- Chemistry and pharma
- Molecule design: encoding molecules into a continuous space and searching it for candidates with desired properties.
- Operations and security
- Anomaly detection: inputs the model reconstructs poorly, or to which it assigns low likelihood, are flagged for review.
Choosing it: what must hold
- Plenty of unlabelled examples of the data to model.
- A need for a smooth latent space that can be sampled or interpolated.
- Tolerance for somewhat blurry samples compared with GANs or diffusion models.
- A weight on the KL term chosen with care, so the decoder does not ignore the latent code.
When to choose something else
| If | Use instead |
|---|---|
| You only need compression or features, not sampling | A plain autoencoder or PCA |
| You need the sharpest possible samples | A diffusion model or a GAN |
| You have labels and want predictions | A supervised model such as an MLP or a CNN |
Math foundations
The encoder's distribution
For each input the encoder gives a Gaussian over codes rather than one code. Predicting the log of the variance lets the network output any real number while the variance stays positive.
The evidence lower bound
The true log-likelihood of the data cannot be computed, but this lower bound, the ELBO, can. The first term rewards good reconstruction and the second keeps the codes close to the prior .
The reparameterisation
A random draw written as a deterministic function of , and outside noise. The randomness no longer blocks the gradient, so the encoder can be trained by backpropagation.
The KL term in closed form
The distance from the encoder's Gaussian to the standard normal. It is zero only when and in every dimension.
The training loss
The negative ELBO with one sample per row, for the gaussian likelihood and up to a constant. For bernoulli the first term is the cross-entropy summed over features. is the standard VAE.
Gradients of the KL term
The KL term pulls each mean toward 0 and each variance toward 1. These are added to the gradients that arrive from the decoder through .
Symbols
- an input row and the decoder's reconstruction of it
- latent code with k dimensions
- mean and variance of the encoder's distribution, per latent dimension
- standard normal noise
- the encoder's distribution over codes for input x
- the prior over codes: a standard normal
- the decoder's distribution over data given a code
- Kullback-Leibler divergence: a measure of how one distribution differs from another
- weight of the KL term
- latent dimensions and number of rows
Worked by hand
One latent dimension. Compute the KL term for an encoder output of , , and then for , . Then draw a code for the first case with .
Shifting the mean by one unit costs 0.5, and doubling the standard deviation costs about 0.81. Both are paid only if they improve reconstruction by more than that.
Visual example
Loading the example.
Try this
- Move the noise ε from -2.5 to 2.5: the code slides across the point's cloud and the reconstruction slides along the curve.
- Raise β to 2 and watch every mean tick fall onto 0 while the decoder's curve shrinks to a single point.
- Set β to 0 and compare the ticks with the dashed prior.
Code sample
import numpy as np
from impl import VAE
from config import VAEConfig
rng = np.random.default_rng(0)
latent = rng.normal(size=(500, 2))
X = 3.0 * np.tanh(latent @ rng.normal(size=(2, 8))) + 0.05 * rng.normal(size=(500, 8)) # 8 features, 2 real dimensions
model = VAE(VAEConfig(latent_dim=2, epochs=100)).fit(X)
mu, logvar = model.encode(X) # each (500, 2)
print(np.mean((model.reconstruct(X) - X) ** 2)) # reconstruction error, far below the data variance
print(model.sample(3).shape) # (3, 8): new rows decoded from z ~ N(0, I)
print(model.elbo(X)) # mean ELBO per row (higher is better)Read the implementation (174 lines)
"""Variational autoencoder: encoder, reparameterisation, decoder and ELBO, with manual backpropagation and Adam.
NumPy only. For a row x of d features and a latent code z of k dimensions:
encoder h = tanh(x W1 + b1), mu = h Wmu + bmu, logvar = h Wlv + blv
sample z = mu + exp(0.5 * logvar) * eps, eps ~ N(0, I)
decoder g = tanh(z W3 + b3), out = g W4 + b4 (out is the mean, or the logit for `bernoulli`)
loss = reconstruction(x, out) + beta * KL(q(z | x) || N(0, I)), averaged over rows (the negative ELBO)
"""
from __future__ import annotations
import numpy as np
try:
from .config import VAEConfig
except ImportError: # run from the template's own folder
from config import VAEConfig
class _Adam:
"""Adam optimizer over a dict of NumPy arrays; `step` updates the arrays in place."""
def __init__(self, params: dict, lr: float, beta1: float = 0.9, beta2: float = 0.999, eps: float = 1e-8) -> None:
self.params, self.lr, self.beta1, self.beta2, self.eps = params, lr, beta1, beta2, eps
self.m = {k: np.zeros_like(v) for k, v in params.items()}
self.v = {k: np.zeros_like(v) for k, v in params.items()}
self.t = 0
def step(self, grads: dict) -> None:
"""Apply one update. grads: same keys and shapes as the parameters."""
self.t += 1
for k, g in grads.items():
self.m[k] = self.beta1 * self.m[k] + (1 - self.beta1) * g
self.v[k] = self.beta2 * self.v[k] + (1 - self.beta2) * g * g
m_hat = self.m[k] / (1 - self.beta1**self.t)
v_hat = self.v[k] / (1 - self.beta2**self.t)
self.params[k] -= self.lr * m_hat / (np.sqrt(v_hat) + self.eps)
def _sigmoid(z: np.ndarray) -> np.ndarray:
e = np.exp(-np.abs(z))
return np.where(z >= 0, 1.0 / (1.0 + e), e / (1.0 + e))
def kl_divergence(mu: np.ndarray, logvar: np.ndarray) -> np.ndarray:
"""KL( N(mu, diag(exp(logvar))) || N(0, I) ) for each row. mu, logvar: (n, k). Returns (n,)."""
return -0.5 * np.sum(1.0 + logvar - mu**2 - np.exp(logvar), axis=1)
def reparameterize(mu: np.ndarray, logvar: np.ndarray, eps: np.ndarray) -> np.ndarray:
"""z = mu + sigma * eps with sigma = exp(0.5 * logvar). All arguments (n, k). Returns (n, k)."""
return mu + np.exp(0.5 * logvar) * eps
class VAE:
"""Variational autoencoder for vector data. After `fit`: `params`, `loss_history_` (negative ELBO per epoch)."""
def __init__(self, config: VAEConfig | None = None) -> None:
self.config = config or VAEConfig()
self.params: dict[str, np.ndarray] = {}
self.loss_history_: list[float] = []
def initialize(self, n_features: int) -> None:
"""Create the encoder and decoder weights for rows with `n_features` columns."""
rng = np.random.default_rng(self.config.seed)
d, h, k = n_features, self.config.hidden_dim, self.config.latent_dim
def weight(fan_in: int, fan_out: int) -> np.ndarray:
return np.sqrt(1.0 / fan_in) * rng.normal(size=(fan_in, fan_out))
self.params = {
"W1": weight(d, h), "b1": np.zeros(h),
"Wmu": weight(h, k), "bmu": np.zeros(k),
"Wlv": 0.1 * weight(h, k), "blv": np.zeros(k),
"W3": weight(k, h), "b3": np.zeros(h),
"W4": weight(h, d), "b4": np.zeros(d),
}
def _check_ready(self) -> None:
if not self.params:
raise RuntimeError("call fit (or initialize) first")
def encode(self, X: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Parameters of q(z | x). X: (n, d). Returns (mu, logvar), each of shape (n, latent_dim)."""
self._check_ready()
p = self.params
h = np.tanh(np.asarray(X, dtype=float) @ p["W1"] + p["b1"])
return h @ p["Wmu"] + p["bmu"], h @ p["Wlv"] + p["blv"]
def decode(self, Z: np.ndarray) -> np.ndarray:
"""Decoder mean. Z: (n, latent_dim). Returns (n, d): real values, or probabilities for `bernoulli`."""
self._check_ready()
p = self.params
out = np.tanh(np.asarray(Z, dtype=float) @ p["W3"] + p["b3"]) @ p["W4"] + p["b4"]
return _sigmoid(out) if self.config.likelihood == "bernoulli" else out
def loss_and_grads(self, X: np.ndarray, eps: np.ndarray) -> tuple[float, dict]:
"""Negative ELBO on a batch for the given latent noise, and its gradient for every parameter.
X: (n, d). eps: standard normal noise, shape (n, latent_dim).
"""
p = self.params
n = len(X)
h = np.tanh(X @ p["W1"] + p["b1"])
mu = h @ p["Wmu"] + p["bmu"]
logvar = h @ p["Wlv"] + p["blv"]
sigma = np.exp(0.5 * logvar)
z = mu + sigma * eps
g = np.tanh(z @ p["W3"] + p["b3"])
out = g @ p["W4"] + p["b4"]
if self.config.likelihood == "bernoulli":
recon = np.sum(np.logaddexp(0.0, out) - X * out, axis=1) # cross-entropy with logits
d_out = (_sigmoid(out) - X) / n
else:
recon = 0.5 * np.sum((out - X) ** 2, axis=1)
d_out = (out - X) / n
beta = self.config.beta
loss = np.mean(recon + beta * kl_divergence(mu, logvar))
grads = {"W4": g.T @ d_out, "b4": d_out.sum(axis=0)}
dg = (d_out @ p["W4"].T) * (1.0 - g**2)
grads["W3"] = z.T @ dg
grads["b3"] = dg.sum(axis=0)
dz = dg @ p["W3"].T
# z = mu + sigma * eps feeds the decoder; the KL term adds its own direct gradients.
d_mu = dz + beta * mu / n
d_logvar = dz * eps * 0.5 * sigma + beta * 0.5 * (np.exp(logvar) - 1.0) / n
grads["Wmu"] = h.T @ d_mu
grads["bmu"] = d_mu.sum(axis=0)
grads["Wlv"] = h.T @ d_logvar
grads["blv"] = d_logvar.sum(axis=0)
dh = (d_mu @ p["Wmu"].T + d_logvar @ p["Wlv"].T) * (1.0 - h**2)
grads["W1"] = X.T @ dh
grads["b1"] = dh.sum(axis=0)
return float(loss), grads
def fit(self, X: np.ndarray) -> "VAE":
"""Train with mini-batch Adam. X: data, shape (n, d); values in [0, 1] for the `bernoulli` likelihood."""
cfg = self.config
X = np.asarray(X, dtype=float)
if X.ndim != 2:
raise ValueError("X must have shape (n, d)")
if cfg.likelihood == "bernoulli" and (X.min() < 0 or X.max() > 1):
raise ValueError("the bernoulli likelihood needs data in [0, 1]")
self.initialize(X.shape[1])
optimizer = _Adam(self.params, cfg.lr)
rng = np.random.default_rng(cfg.seed + 1)
self.loss_history_ = []
n = len(X)
for _ in range(cfg.epochs):
order = rng.permutation(n)
total = 0.0
for start in range(0, n, cfg.batch_size):
rows = order[start : start + cfg.batch_size]
eps = rng.normal(size=(len(rows), cfg.latent_dim))
loss, grads = self.loss_and_grads(X[rows], eps)
optimizer.step(grads)
total += loss * len(rows)
self.loss_history_.append(total / n)
return self
def elbo(self, X: np.ndarray, seed: int = 0) -> float:
"""Mean evidence lower bound per row, with one latent sample per row (up to the Gaussian constant)."""
self._check_ready()
X = np.asarray(X, dtype=float)
eps = np.random.default_rng(seed).normal(size=(len(X), self.config.latent_dim))
return -self.loss_and_grads(X, eps)[0]
def reconstruct(self, X: np.ndarray) -> np.ndarray:
"""Encode to the mean of q(z | x) and decode it. X: (n, d). Returns (n, d)."""
return self.decode(self.encode(X)[0])
def sample(self, n: int, seed: int = 0) -> np.ndarray:
"""Generate n new rows by decoding z ~ N(0, I). Returns (n, d)."""
return self.decode(np.random.default_rng(seed).normal(size=(n, self.config.latent_dim)))- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Create rows of ten features generated from two hidden factors plus noise. Fit VAE with VAEConfig latent_dim 2 and beta 1.0. Call encode and plot the means, then call sample for 200 rows and compare their feature averages with the data. Train again with beta 0 and beta 10, and for each compare reconstruct against the inputs and use kl_divergence on the encoder outputs to see how far the codes sit from the prior.
Check on learning
- Why can a plain autoencoder not be used to generate new data by decoding random codes, while a VAE can?
A way to think about it
Ask where the training codes of each model lie and what the decoder was ever trained on. One of them has seen every region that a standard normal draw is likely to hit.
- Without the reparameterisation, the code would be a random draw inside the network. Why does that stop backpropagation, and how does the rewrite fix it?
A way to think about it
A gradient needs a formula linking output to parameter. Compare a draw from a distribution that depends on with the expression where is fixed.
- With beta set to 0, what does the model reduce to, and what would you expect the encoder's variances to do?
A way to think about it
Remove the KL term and ask what the reconstruction loss alone prefers: a noisy code or an exact one.
- After training, the KL term is nearly zero for every input and all reconstructions look like the data average. What happened and what would you try?
A way to think about it
If the encoder outputs the prior for every input, the code tells the decoder nothing. Think about which term won, and about beta and the capacity of each half.
- Why does the encoder predict the log of the variance rather than the variance itself?
A way to think about it
A linear layer can output any real number. Check which of the two quantities is allowed to be negative.