CodeRigor

LESSON

Autoencoders and the variational autoencoder

From a bottleneck that reconstructs its input to a model you can sample: the reparameterization trick, the closed-form KL term and the negative ELBO.

An autoencoder is a network trained to rebuild its own input through a narrow middle layer. A variational autoencoder changes one thing about that middle layer, and the change turns a compressor into a model you can sample from. This lesson pairs with Lectures 21 and 22 of CMU's 11-785 (Fall 2026), linked under Watch & read. You build the three pieces that make the idea trainable: the reparameterized sample, the closed-form KL term and the negative ELBO.

An encoder maps x to a code z with far fewer numbers than x, and a decoder maps z back to a reconstruction. Training minimizes the reconstruction error, so the code has to keep whatever the decoder needs. The simplest case is linear: with squared error, a linear encoder and decoder reach the same reconstruction error as PCA, on the same subspace. The snippet trains one by gradient descent and compares it with PCA from an SVD.

Python
import numpy as np

rng = np.random.default_rng(0)
basis = rng.normal(size=(2, 5)) * np.array([[3.0], [1.5]])
X = rng.normal(size=(200, 2)) @ basis + 0.3 * rng.normal(size=(200, 5))
X = X - X.mean(axis=0)                                   # 200 points in 5 dimensions

_, _, Vt = np.linalg.svd(X, full_matrices=False)
P = Vt[:2]                                               # the top two principal directions
pca_error = ((X - X @ P.T @ P) ** 2).sum(axis=1).mean()

E = rng.normal(size=(2, 5)) * 0.1                        # encoder: 5 numbers -> code of 2
D = rng.normal(size=(5, 2)) * 0.1                        # decoder: code of 2 -> 5 numbers
for _ in range(3000):
    Z = X @ E.T
    R = Z @ D.T - X
    D -= 0.01 * 2 * R.T @ Z / 200
    E -= 0.01 * 2 * (R @ D).T @ X / 200
ae_error = ((X @ E.T @ D.T - X) ** 2).sum(axis=1).mean()
print(round(pca_error, 3), round(ae_error, 3))

A plain autoencoder is still not a generator. Training only ever decodes codes that the encoder produced. Nothing says which other codes are valid, so a code picked at random can land in a region the decoder never saw, and its output has no reason to look like data.

The variational autoencoder fixes the gap by changing what the encoder returns. For each input it outputs a Gaussian over codes, N(μ, σ²) with one μ and one σ per latent dimension, and a penalty pulls every one of those Gaussians toward N(0, I). If the penalty works, the region the decoder is trained on is the region where N(0, I) puts its mass, and a z drawn from N(0, I) at test time decodes to something plausible. The objective for one example is the negative ELBO (the evidence lower bound, negated):

  • reconstruction: the cross-entropy between x and the decoder output, summed over the F features
  • plus KL(N(μ, σ²) || N(0, I)), summed over the Z latent dimensions
One forward pass of a VAE
start / 5
The encoder returns a mean and a log-variance. The noise ε comes from outside the network, so z stays a differentiable function of μ and log σ². The loss adds two terms.
One forward pass of a VAE
The encoder returns a mean and a log-variance. The noise ε comes from outside the network, so z stays a differentiable function of μ and log σ². The loss adds two terms.

For diagonal Gaussians the KL has a closed form, so it is computed exactly and needs no sampling. Per latent dimension it is 0.5 · (σ² + μ² - 1 - log σ²), and the dimensions add. Read the terms: μ² charges for a mean away from 0, σ² - 1 - log σ² charges for a spread away from 1, and at μ = 0, σ = 1 the whole expression is 0. Both charges are never negative, so the KL is 0 only at the prior.

The KL of one dimension
Solid: μ moves with σ = 1, KL = μ²/2. Dashed: σ moves with μ = 0, KL = 0.5 · (σ² - 1 - 2 ln σ). Both are 0 at the prior. The dashed curve rises on either side of σ = 1; the solid one is symmetric in μ, so only μ ≥ 0 is drawn.
The KL of one dimension
Solid: μ moves with σ = 1, KL = μ²/2. Dashed: σ moves with μ = 0, KL = 0.5 · (σ² - 1 - 2 ln σ). Both are 0 at the prior. The dashed curve rises on either side of σ = 1; the solid one is symmetric in μ, so only μ ≥ 0 is drawn.

There is one obstacle to training. The decoder needs a sample z, and drawing a random number is not an operation with a derivative with respect to μ and σ. The reparameterization trick moves the randomness out of the way: draw ε from N(0, I) first, then compute z = μ + σ ⊙ ε. Now z is an ordinary function of μ and σ, with dz/dμ = 1 and dz/dσ = ε, and the gradient reaches the encoder. In PyTorch this is the difference between Normal.rsample(), which is reparameterized, and Normal.sample(), which returns a tensor with no gradient path.

Python
import numpy as np

eps = np.random.default_rng(1).standard_normal(200_000)
mu, sigma = 1.0, 0.5
z = mu + sigma * eps               # E[z^2] = mu^2 + sigma^2, so the exact slopes are 2 mu and 2 sigma
print((2 * z).mean().round(1), (2 * z * eps).mean().round(1))

The exact slopes of E[z²] are 2μ = 2 and 2σ = 1, and the estimates made through the trick land on them.

The network predicts the log-variance, because that number is unconstrained and one exp turns it into a valid variance. The standard deviation is σ = exp(0.5 · logvar). Dropping the 0.5 gives the variance where the standard deviation belongs, a slip that runs without any error while the noise has the wrong scale.

A worked example with two latent dimensions: μ = (1, 0), logvar = (0, ln 4), so σ = (1, 2), and ε = (0.5, -1).

Python
import numpy as np

mu = np.array([1.0, 0.0])
logvar = np.array([0.0, np.log(4.0)])               # sigma = [1, 2]
eps = np.array([0.5, -1.0])
z = mu + np.exp(0.5 * logvar) * eps
kl = 0.5 * (np.exp(logvar) + mu**2 - 1 - logvar)    # one value per latent dimension
print(z.tolist(), kl.round(4).tolist(), kl.sum().round(4))

The first dimension costs 0.5 (all of it from μ), the second costs 0.8069 (all of it from the spread). Now add the reconstruction: three features, x = (1, 0, 1), and decoder logits (2, -1, 0).

Python
import numpy as np

x = np.array([1.0, 0.0, 1.0])
logits = np.array([2.0, -1.0, 0.0])
per_feature = np.logaddexp(0.0, logits) - x * logits   # binary cross-entropy with logits
kl = 0.5 + 0.5 * (4.0 - 1.0 - np.log(4.0))             # the total from the example above
print(per_feature.round(4).tolist(), (per_feature.sum() + kl).round(4))
print((per_feature.mean() + kl).round(4), (kl / (per_feature.sum() + kl)).round(2), (kl / (per_feature.mean() + kl)).round(2))

The summed cross-entropy is 1.1333 and the example's negative ELBO is 2.4402. The second printed line averages the features instead of summing them, a mistake covered next.

Mistakes people make:

  • The 0.5 missing in σ = exp(0.5 · logvar), so σ is too large whenever logvar is positive and too small whenever it is negative.
  • A wrong sign or term in the KL. A test with logvar = 0 everywhere cannot see it: there σ² - 1 and log σ² are both 0, so + logvar and - logvar agree.
  • Averaging the reconstruction over the F features while the KL is summed over the Z dimensions. Up to one overall factor, that is the same as multiplying the KL by F. In the example, with three features, the KL's share of the loss jumps from 54% to 78%, which pushes the codes toward the prior at the expense of the reconstruction.

Sum over features, sum over latent dimensions, and average over the batch only at the end.

The tests check the result four ways. The KL is compared with torch.distributions.kl_divergence, the reconstruction with binary_cross_entropy_with_logits, the gradients of reparameterize and negative_elbo with values worked out by hand, and a repeated batch must not change the loss. That shows your functions compute the objective you wrote down. It does not show that a model trained on it generates good samples, or that its codes are used: a KL near zero for every input would mean the encoder ignores x, and no unit test sees that.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →