Module 8

Autoencoders

Ask a network to copy its input to its output through a bottleneck too narrow to hold it, and it has to work out what matters. No labels required.

Why it matters

Every model so far learned from labelled examples. An autoencoder learns from the data alone, by compressing each input to a short code and reconstructing it. The code is a learned representation, and the variational version turns the decoder into a generator: pick a code, get a new image. The idea returns in module 10 in a different role, where a sparse autoencoder is trained not on images but on the internal activity of another network, to find out what that network represents.

The idea

Compress, then reconstruct

An autoencoder is two networks trained together. The encoder maps an input $x$ to a low-dimensional code $z$, and the decoder maps $z$ back to a reconstruction $\hat x$:

$$z = f(x), \qquad \hat x = g(z), \qquad \text{minimise } \; \ell(x, \hat x) .$$

The code is the latent representation, and its small size is the whole point: with only two numbers to describe a 64-pixel image, the network must spend them on whatever distinguishes one image from another. For pixel brightnesses between 0 and 1, a natural reconstruction loss is the cross-entropy of module 1, added up over the pixels:

$$\ell(x, \hat x) = - \sum_{j} \Big[ x_j \log \hat x_j + (1 - x_j) \log (1 - \hat x_j) \Big] .$$

If the encoder and decoder are both linear and the loss is squared error, the best solution spans the same subspace as principal component analysis. Non-linear layers let the code follow curved structure that PCA cannot.

What a plain autoencoder leaves undefined

Nothing in that objective says how the codes should be arranged. Training is free to scatter them over any region of the latent space, at any scale, with gaps in between, and the decoder is only ever asked about points that are codes of training images. Decode a point in a gap and you get whatever the decoder happens to do there. A plain autoencoder compresses; it does not give you a way to generate.

The variational autoencoder

A variational autoencoder (VAE) fixes this by making the model probabilistic. Declare in advance how codes are distributed, the prior $p(z) = \mathcal{N}(0, I)$, and let the decoder define $p(x \mid z)$. The encoder no longer outputs a point but a small Gaussian cloud for each input,

$$q(z \mid x) = \mathcal{N}\big(\mu(x),\; \operatorname{diag} \sigma^2(x)\big),$$

and training maximises a lower bound on the log-probability the model gives the data, the evidence lower bound or ELBO:

$$\log p(x) \;\ge\; \underbrace{\mathbb{E}_{z \sim q(z \mid x)}\big[ \log p(x \mid z) \big]}_{\text{reconstruct } x \text{ from its code}} \;-\; \underbrace{\operatorname{KL}\big( q(z \mid x) \,\Vert\, p(z) \big)}_{\text{stay close to the prior}} .$$

The first term is the reconstruction loss with its sign flipped. The second is new: it penalises every input's cloud for straying from the standard normal. For Gaussians it has a closed form,

$$\operatorname{KL} = \tfrac{1}{2} \sum_{k} \big( \mu_k^2 + \sigma_k^2 - \log \sigma_k^2 - 1 \big),$$

which is zero only when $\mu = 0$ and $\sigma = 1$. Together the two terms pull against each other. Reconstruction wants each input's cloud small and far from the others; the KL term wants them all wide and on top of each other. The compromise is a latent space packed around the origin with overlapping clouds and no gaps, so that any point drawn from the prior decodes to something sensible.

The reparameterisation trick

There is one obstacle. The loss involves a random sample $z \sim \mathcal{N}(\mu, \sigma^2)$, and “draw a random number” is not an operation gradients can pass through: how would $\mu$ and $\sigma$ learn? The answer is to move the randomness outside:

$$z = \mu + \sigma \odot \varepsilon, \qquad \varepsilon \sim \mathcal{N}(0, I) .$$

Now $\varepsilon$ is just another input, and $z$ is an ordinary differentiable function of $\mu$ and $\sigma$ with $\partial z / \partial \mu = 1$ and $\partial z / \partial \sigma = \varepsilon$. Backpropagation proceeds as usual. In practice the encoder outputs $\log \sigma^2$, which can be any real number, and $\sigma$ is recovered as $\exp(\tfrac{1}{2} \log \sigma^2)$.

Live demo: a two-dimensional latent space of digits

Sixty-four pixels through two numbers

Where 250 unseen digits land. Click or drag to choose a point.

What the decoder draws across the same square

Top: ten unseen digits. Bottom: the same digits after being squeezed through two numbers.

Both models are 64 → 32 → 2 → 32 → 64 with tanh hidden layers, trained with Adam for 1,200 steps on 600 digits. The orange ring marks the point being decoded. For the variational model the dashed circles are one and two standard deviations of the prior, and each digit is plotted at the mean of its cloud.

Try this

  1. Train the Autoencoder. Digits of the same kind gather together, although nobody told the network which digit is which. Note how far the codes spread: the corner of the plot gives the range of the axes.
  2. Drag the ring across the plot and watch the decoded image. Go between two clusters, then out to an empty corner. What does the decoder produce where no digit landed?
  3. Switch to Variational and train. The codes now sit inside the dashed circles. Drag the ring again: the decoded image changes smoothly, one digit turning into another, with no dead regions near the origin.
  4. Compare the two reconstruction rows and the reconstruction losses. The variational model is blurrier. That is the price of the KL term, which forbids it from giving each digit a tight, private patch of the plane.

Exercise

The reparameterisation trick and the ELBO

Write the three functions at the heart of a VAE: the reparameterised sample, the KL divergence from the prior, and the ELBO for images with pixel values between 0 and 1. The tests check each against its definition, including a Monte Carlo estimate of the KL divergence and the gradients that the trick makes possible.

Check yourself

Why can gradients not pass through “sample $z$ from $\mathcal{N}(\mu, \sigma^2)$”, and what does the trick change?

A sampling step has no derivative with respect to its parameters as an operation in the graph. Writing $z = \mu + \sigma \varepsilon$ makes the random part, $\varepsilon$, an input that does not depend on any parameter, and leaves $z$ as plain arithmetic on $\mu$ and $\sigma$, which autodiff handles like any other sum and product.

The KL term is zero when every input gets $\mu = 0$ and $\sigma = 1$. Why is that not what training converges to?

Because then the code would say nothing about the input, and the decoder could do no better than output the average image. The reconstruction term penalises that heavily. Training settles where the gain in reconstruction from making codes informative balances the KL cost of moving them away from the prior.

A linear autoencoder trained with squared error finds the same subspace as which classical method?

Principal component analysis: its codes span the directions of greatest variance in the data.

Where this leads

Autoencoders learn representations by compressing. Module 9 builds the architecture whose internal representations the rest of the course sets out to read: the transformer.

Sources: D. P. Kingma and M. Welling, “Auto-encoding variational Bayes”, ICLR (2014); D. J. Rezende, S. Mohamed and D. Wierstra, “Stochastic backpropagation and approximate inference in deep generative models”, ICML (2014); P. Baldi and K. Hornik, “Neural networks and principal component analysis: learning from examples without local minima”, Neural Networks 2 (1989); G. E. Hinton and R. R. Salakhutdinov, “Reducing the dimensionality of data with neural networks”, Science 313 (2006); I. Goodfellow, Y. Bengio and A. Courville, Deep Learning, MIT Press (2016), ch. 14 and 20. Digit images: E. Alpaydin and C. Kaynak, “Optical Recognition of Handwritten Digits”, UCI Machine Learning Repository (1998), doi:10.24432/C50P49, CC BY 4.0.