rumblr Work in progressWIP

● The AI Primer · Lesson 34 · Part 5: other kinds of model, and generating media

Autoencoders and VAEs

This lesson covers Squeezing data into a code and back, and sampling new data from it

Members · open during launch 47 min14 figures and diagrams

What this is

What is an autoencoder?

An autoencoder is a neural network, the kind of program behind modern AI, that learns to squeeze a picture into a few numbers and rebuild the picture from them. It is never told what the numbers should mean; it works that out from the pictures. A variational autoencoder (VAE) is trained so that numbers made up at random also decode to a sensible picture, which lets it make new ones. Today VAEs do the squeezing inside image generators such as Stable Diffusion.

Why it matters: If you build or run an image, audio or video generator, there is almost certainly an autoencoder at both ends of it, and its settings shape the output. A plain autoencoder is also a way to get a compact fingerprint of unlabelled items, or to flag the ones that do not fit.

At a glance

Key takeaways

  1. Autoencoder: an encoder squeezes data through a narrow code (the bottleneck) and a decoder rebuilds it; training minimises the rebuild error. With no bends it learns what PCA (principal component analysis) learns; with bends it can follow curved data far better.
  2. No generation from a plain autoencoder: its codes land wherever training put them, with holes in between, so random codes decode to junk.
  3. VAE: the encoder outputs a region (μ, σ); the reparameterization trick z = μ + σ·ε samples from it in a way gradients can pass through; a KL penalty pulls every region towards the standard normal, so drawing z ~ N(0, I) and decoding generates new data.
  4. The trade-off: β weighs the KL. Too small brings back holes, too large blurs and finally collapses; squared error averages over overlapping possibilities, which is why VAE output is blurry.
  5. Today: VAEs compress images for latent diffusion, and VQ-VAEs turn images and audio into tokens for transformers.

How it works, from scratch

Suppose you have to describe a picture of a single line to a friend over the phone, and you may say only two numbers. You would agree on a system first: the first number says which way the line runs, the second says how far it sits from the middle. You squeeze the picture into two numbers, send them, and your friend draws it again.

An autoencoder is a neural network that invents such a system by itself. It has two halves. The encoder squeezes a picture into a few numbers, called the code. The decoder rebuilds the picture from the code. The network is never told what the numbers should mean, only that the rebuild must match the original. With so few numbers to pass through, it can meet that demand only by finding what really varies from picture to picture.

A second question follows. If your friend can draw from any two numbers, can you get a new picture by making two up? From a plain autoencoder, mostly not: most made-up codes are ones it never used, and they decode to smudges. A variational autoencoder (VAE) is trained so that a code drawn at random from a known range decodes to something sensible, which makes it a generator.

Chapter 1

The toy data: pictures of pen strokes

Both kinds of network are trained here on tiny pictures of one line each. Every picture is 8 × 8 = 64 pixels holding one soft pen stroke. The stroke runs in one of four directions (horizontal, vertical, diagonal down, diagonal up) and is shifted up to 2.5 pixels from the centre. The ink fades like a bell curve either side of the line: a pixel on the line has brightness 1.0, a pixel one pixel away about 0.25, a pixel two away almost nothing.

So each picture is 64 numbers, but only two facts change from picture to picture: the direction (one of four) and the offset (any amount). These are the two numbers of the phone call, and a good 2-number code has to find both from the pixels alone. The training set is 200 such pictures; eight of them are the top row of the second figure below.

In code: make_strokes draws the pictures and returns their hidden directions and offsets. View source

Chapter 2

Squeeze and rebuild: the autoencoder

Before the pictures, here is a code small enough to check by hand. Take points that lie on the line y = 2x, such as (1, 2) and (2, 4). Each takes two numbers to write down, but one number is enough: how far along the line the point is.

  • Encoder: code = u · x, where u = (1, 2)/√5 = (0.447, 0.894) is the line's direction scaled to length 1, and "·" is the dot product (multiply matching entries and add; see Math notation, from zero).
  • Decoder: rebuild = code × u.

For (1, 2): code = 0.447 + 1.789 = 2.236 (which is √5, its distance from the origin), and rebuild = 2.236 × (0.447, 0.894) = (1, 2). Nothing lost.

For (2, 3), which is off the line: code = (2 + 6)/√5 = 3.578, and rebuild = 3.578 × (0.447, 0.894) = (1.6, 3.2), the closest point on the line. The part that pointed away from the line, (0.4, −0.2), is gone. Training measures that loss, averaged over the examples, and shrinks it:

The formula and its symbols

Symbols

Symbol Meaning here In the example
the -th example: a point, or a picture's 64 pixels
the encoder: squeezes an example into a code
the code for example , often written 3.578
the decoder: rebuilds an example from a code
the rebuild, often written ("x hat") (1.6, 3.2)
what the rebuild got wrong, entry by entry (0.4, −0.2)
squared length of : square every entry and add
add up over every example
how many examples 2: (1, 2) and (2, 3)
the reconstruction loss: average squared error of the rebuilds 0.1

In words: "squeeze each example, rebuild it, measure the squared distance between the rebuild and the original, and average over all the examples."

With the numbers: (1, 2) rebuilds perfectly, error 0. (2, 3) rebuilds as (1.6, 3.2), error 0.4² + (−0.2)² = 0.16 + 0.04 = 0.2. Averaged over the two points, = (0 + 0.2)/2 = 0.1.

In Python
import math
# u: the line's direction, scaled to length 1
u = [1 / math.sqrt(5), 2 / math.sqrt(5)]
def f(x):
    return sum(u_m * x_m for u_m, x_m in zip(u, x))
def g(z):
    return [z * u_m for u_m in u]
def error(x):
    return sum((a - b) ** 2 for a, b in zip(x, g(f(x))))
# f(x): the encoder squeezes (2, 3) to one number
round(f([2, 3]), 3)  # → 3.578
# g(f(x)): the decoder rebuilds two numbers from it
[round(v, 2) for v in g(f([2, 3]))]  # → [1.6, 3.2]
# ‖x − x̂‖² for each point: (1, 2) is on the line, (2, 3) is not
[round(error(x), 2) for x in ([1, 2], [2, 3])]  # → [0.0, 0.2]
# L_rec: the average over n = 2 points
round((error([1, 2]) + error([2, 3])) / 2, 2)  # → 0.1

New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.

The real network has the same two halves, only bent. The encoder is a two-layer network like the one built in Neural networks: 64 pixels into 32 hidden numbers (through tanh, which lets it bend), then out to a code of 2 numbers. The decoder mirrors it: 2 numbers into 32 hidden, then out to 64 pixels squashed between 0 and 1 by a sigmoid so they are valid brightnesses. Training is the loop from Neural networks with the Adam optimizer from Optimizers: rebuild every picture, measure , send the gradient back through both halves, adjust, 1,500 times.

Figure 1 · Diagram

Reading it: follow the picture left to right. It is 64 numbers wide at both ends and only 2 numbers wide in the middle. That narrow middle is the bottleneck: without it the network could copy the pixels straight through and learn nothing. The loss box compares the two ends, and the dotted arrow is backpropagation carrying the blame back through the decoder and on into the encoder, so both halves learn together. The encoder is never shown a target code; it learns whatever code the decoder finds most useful.

Figure 2 · Chart

the original pictures (64 pixels each) autoencoder rebuild from 2 numbers (error 0.07) PCA rebuild from 2 numbers (error 4.42)

Eight strokes, their autoencoder rebuilds from 2 numbers (error 0.07) and their PCA rebuilds from 2 numbers (error 4.42): the autoencoder's are near perfect, PCA's are grey smudges

Reading it: the top row is eight real strokes, two of each direction. The middle row is what the autoencoder rebuilds from just 2 numbers per picture: nearly identical. The average error is about 0.07, against about 8.8 units of squared ink in a whole stroke, so it keeps over 99% of the picture. The bottom row squeezes the same pictures to 2 numbers with PCA and rebuilds them: grey smudges, keeping only about half of the picture.

In code: Autoencoder holds both halves and their backward pass; train runs Adam. View source

PCA is the straight-line special case

PCA (principal component analysis, built in Clustering and matching) had the same budget of two numbers and failed. It fits a flat sheet through the data and records where each point lands on the sheet. That is an autoencoder with no bends: the encoder is one matrix multiply, and so is the decoder.

The hand example above was such an autoencoder, with the direction written in by hand. Scatter 100 points near the line y = 2x and train a no-bend autoencoder with a 1-number code by plain gradient descent, and it finds that direction for itself: (0.447, 0.894), with the same rebuild error as PCA with one component. Baldi and Hornik proved in 1989 that this always happens: a linear autoencoder trained on squared error lands on the same flat sheet as PCA.

PCA smudged the strokes because a stroke sliding across the image does not travel in a straight line through pixel space. Take a horizontal stroke at the top and another at the bottom. Their average, the point halfway along the straight line between them, is two faint lines, not one stroke in the middle. The real strokes lie on a curved surface in the 64-dimensional space of pictures, and a flat sheet can only cut through it. The autoencoder's tanh layers let its "sheet" bend to follow the curve.

In code: train_linear_autoencoder is the no-bend autoencoder; pca_reconstruction rebuilds from the top principal components. View source

The code the network found

The autoencoder was never told about direction or offset. To see what its two numbers mean, place every picture at its code.

Figure 3 · Chart

−25 −20 −15 −10 −5 0 code number 1 −15 −10 −5 0 5 10 15 code number 2 A plain autoencoder's codes: one strand per stroke direction where a standard normal draw usually lands horizontal vertical diagonal down diagonal up

The plain autoencoder's 200 codes form separate strands, one colour per stroke direction, spread from about -24 to 14, far from the small circle where a standard normal draw usually lands

Reading it: each dot is one picture, placed at its 2-number code and coloured by its stroke direction, with bigger dots for larger offsets. The codes form strands: pictures of one direction line up along a curve, now and then broken into pieces, and moving along a strand slides the stroke. So the network found both hidden facts. Now look at the axes: the codes run from about −24 to 14. Nothing asked for that range; it is an accident of training. The dashed circle near 0 is where a code drawn at random from a bell curve would usually land, and it catches almost none of the strands.

Chapter 3

Why a plain autoencoder cannot generate: holes

To make a new picture, make up a code and decode it. The simplest way to make up a code is to draw each number from the standard normal distribution, the bell curve centred on 0 with a spread (standard deviation) of 1: most draws fall between −1 and 1, almost all between −3 and 3. Written for several numbers at once, it means "draw each number from that bell curve, independently".

The decoder turns any code into some picture. But training only ever showed it the codes of real pictures, which lie on the strands. Off the strands it draws whatever its weights happen to produce. Call a decoded picture junk when its squared distance to the nearest real stroke is more than 1.0, about a ninth of a whole stroke's squared ink.

Draw the code z = (1.2, −0.9) and decode it with the plain autoencoder. The result is a bright smear with about three times the ink of any real stroke, at a squared distance of about 7.5 from the nearest one. Over 500 such draws the median distance is about 3, and three quarters of the draws are junk.

The standard normal is a hard test for this autoencoder, whose codes sit far from 0. Draw instead from the box that holds its own codes, from −24 to 1.6 across and −17 to 14 up, and about 44% of the codes still decode to junk. They fall in the holes between the strands.

Figure 4 · Chart

−20 −10 0 code number 1 −15 −10 −5 0 5 10 15 code number 2 44% of random codes in the box land in a hole codes of real strokes random code, decodes to a stroke random code, decodes to junk decoded: the 12 worst (top) and 12 best (bottom)

Left: the autoencoder's codes and 300 random codes from their bounding box, 44 percent marked as junk; right: the worst decoded ones are black blobs and the best are clean strokes

Reading it: on the left, black dots are the codes of real strokes and the dashed rectangle is the box around them. Every blue circle is a random code that decoded to something close to a real stroke; every red cross decoded to junk. The red crosses sit in the open spaces between strands, the blue circles near them. On the right are the decoded pictures themselves: the 12 worst (top two rows) are black blobs no pen would draw, and the 12 best (bottom) are clean strokes, because those random codes happened to land on a strand.

So a good compressor is not yet a generator. To sample new data you need a code space with a known shape that you can draw from, no holes inside that shape, and smoothness, so that nearby codes decode to similar pictures. A plain autoencoder gives none of these, because its loss only ever looks at the codes of real pictures.

In code: distance_to_data measures how far each picture is from the nearest real stroke, and JUNK_DISTANCE is the line for junk. View source

Chapter 4

The VAE: encode to a fuzzy region, not a point

A VAE changes what the encoder outputs. Instead of placing each picture at one point on the map of codes, the encoder gives it a small fuzzy region, "somewhere around here": a centre μ and a spread σ. During training the decoder is handed a random point from inside that region, so it must draw the right picture from anywhere nearby. A whole neighbourhood now decodes sensibly, not just one point.

On its own, that would not last. Rebuilding is easiest from a tiny region, so the encoder would shrink every region back to a point, anywhere on the map. A second term in the loss stops it. Every region pays a penalty, called rent here, which grows the further the region sits from the middle of the map and the smaller it shrinks. The regions crowd towards the centre and overlap, and the holes between the strands fill in.

Take one picture and one code number. The encoder says μ = 0.5 and σ = 0.5: "about 0.5, give or take 0.5". At one training step a draw from the standard bell curve gives ε = 1.2, so the decoder is handed z = 0.5 + 0.5 × 1.2 = 1.1. At the next step the draw is ε = −0.4 and the decoder gets z = 0.5 − 0.2 = 0.3. From both codes it must rebuild the same picture.

Figure 5 · Diagram

Reading it: compare it with the plain autoencoder's diagram. The encoder now has two outputs per code number: a centre μ and a size, given as log σ² (the logarithm of the variance, used because it can be any number while σ itself must stay positive). In the box z = μ + σ·ε the fuzzy region becomes one concrete code, with fresh random noise ε at every step. The loss has two parts. The rebuild error, as before, wants each region small and apart from the others, so the decoder can tell which picture it came from. The rent, labelled KL for a reason given below, is fed straight from μ and log σ² and wants every region to look like the standard bell curve. Training settles on a compromise between the two, and a weight β sets the exchange rate.

In code: VAE is the Autoencoder with an encoder that has two outputs, μ and log σ². View source

The reparameterization trick: noise as an input

The random draw in the middle of the network is a problem for training. Backpropagation asks of every step: "if I nudge this number, how does the loss change?" That rate of change is the gradient, or derivative (see Math notation, from zero). A code drawn straight from the region gives no answer for how it would move if μ or σ moved, so the gradient stops at the draw and the encoder never learns.

Picking a random seat in a row shows the way round. You could close your eyes and point; if someone then moves the row one seat to the left, there is no saying where your finger would have landed. Or you could roll a die for how many seats from the middle, and count from wherever the middle is. Now if the row moves one seat left, your seat moves one seat left with it. Both give a random seat, but only the second says how the seat responds when the row moves. The reparameterization trick does the second: it draws the noise ε first, as an ordinary input, and builds the code from it with arithmetic:

The formula and its symbols

Symbols

Symbol Meaning here In the example
the centre of the picture's region, from the encoder 0.5
the natural logarithm of the region's variance, from the encoder; "log of y" is the power you raise to in order to get y
Euler's number, ≈ 2.718
the spread of the region (standard deviation); undoes the log and the square 0.5
"epsilon": random noise, one number per code number 1.2
"is drawn from"
the standard normal: centre 0, spread 1, each number independent (, the identity matrix, says "no links between numbers")
multiply matching entries (element by element)
the code the decoder receives this step 1.1

In words: "roll a standard bell-curve number, stretch it by the region's spread, and shift it to the region's centre."

With the numbers: , so . Now the gradients have a route: nudge μ by a little and z moves by the same amount (∂z/∂μ = 1); nudge σ by a little and z moves by ε times as much (∂z/∂σ = ε = 1.2). The symbol ∂ reads "how much this changes when that is nudged".

In Python
import math
mu, log_var, eps = 0.5, math.log(0.25), 1.2
round(log_var, 3)  # → -1.386
# σ = e^(½ log σ²)
sigma = math.exp(0.5 * log_var)
round(sigma, 3)  # → 0.5
# z = μ + σ ⊙ ε
z = mu + sigma * eps
round(z, 3)  # → 1.1
# nudge μ, then σ, by a tiny h and watch z: ∂z/∂μ = 1 and ∂z/∂σ = ε
h = 1e-6
round((mu + h + sigma * eps - z) / h, 3)  # → 1.0
round((mu + (sigma + h) * eps - z) / h, 3)  # → 1.2

Figure 6 · Diagram

Reading it: both rows produce the same kind of random code: a draw from a bell curve centred on μ with spread σ. In the top row the randomness sits between the encoder's outputs and the loss, and the dotted arrow of backpropagation has nowhere to go. In the bottom row the randomness comes in from the side as ε, an input like a pixel, and everything from μ and σ to the loss is ordinary arithmetic the chain rule can pass through.

The same trick lets gradients pass through random draws elsewhere, for example in the noisy steps of diffusion models (Diffusion and flow matching) and in reinforcement learning with continuous actions.

In code: reparameterize is the formula; a test checks the two gradients against small nudges. View source

The KL penalty: rent for every region

With gradients flowing through the draw, the encoder can learn μ and σ. What it learns depends on the rent. The rent has a formal name: the KL divergence (Kullback-Leibler divergence) from the region to the standard bell curve, a measure of how different two distributions are that is 0 only when they match (Training stages uses it for distillation). For a bell-curve region and the standard bell curve, it has a short closed form:

The formula and its symbols

Symbols

Symbol Meaning here In the example
how much distribution differs from distribution ; 0 when they match
the picture's region: a bell curve with centre μ and variance σ²
the standard bell curve every region is pulled towards
how many numbers in the code 1 (the stroke network uses 2)
a counter over the code numbers
rent for sitting away from the centre: 0 at μ = 0, growing on both sides 0.25
rent on size: smallest (exactly 1) when σ = 1, huge as σ shrinks to a pin, growing if it bloats
shifts the total so a perfect match costs exactly 0
a constant that falls out of the bell curve's formula

In words: "for each code number, add the squared distance of its centre from 0, plus its variance, minus the log of its variance, minus 1; add those up over the code numbers and halve."

With the numbers: for μ = 0.5 and σ = 0.5, ½ (0.25 + 0.25 − (−1.386) − 1) = ½ × 0.886 = 0.443. It splits into two rents: the centre alone costs ½ × 0.25 = 0.125, the shrunken size alone ½ (0.25 + 1.386 − 1) = 0.318, and 0.125 + 0.318 = 0.443. A second code number that already has μ = 0 and σ = 1 adds ½ (0 + 1 − 0 − 1) = 0, so the 2-number total is still 0.443. Shrink σ to a pin of 0.05 and the rent jumps to 2.62.

In Python
import math
def kl(mu, var):
    return 0.5 * (mu ** 2 + var - math.log(var) - 1)
# one code number with μ = 0.5, σ = 0.5 (σ² = 0.25)
round(kl(0.5, 0.25), 3)  # → 0.443
# the rent for the centre alone, then for the size alone
round(0.5 * 0.5 ** 2, 3)  # → 0.125
round(kl(0.0, 0.25), 3)  # → 0.318
# a code number that already is the standard normal pays nothing
kl(0.0, 1.0)  # → 0.0
# Σ over j: two code numbers, their rents add
round(kl(0.5, 0.25) + kl(0.0, 1.0), 3)  # → 0.443
# shrink σ to a pin (σ = 0.05) and the rent jumps
round(kl(0.5, 0.05 ** 2), 2)  # → 2.62

Figure 7 · Chart

−3 −2 −1 0 1 2 3 mean μ (spread held at σ = 1) 0 1 2 3 4 KL penalty Rent for sitting far from the centre μ = 0.5 costs 0.125 0.0 0.5 1.0 1.5 2.0 2.5 3.0 spread σ (mean held at μ = 0) 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 Rent for shrinking to a pin (or bloating) σ = 0.5 costs 0.318

Left: the KL penalty is a parabola in the centre mu, with mu = 0.5 costing 0.125; right: in the spread sigma it is zero at sigma = 1, rises steeply towards a pin, with sigma = 0.5 costing 0.318

Reading it: the left curve holds the spread at σ = 1 and moves the centre: a bowl with its bottom at μ = 0, so sitting at 0.5 costs 0.125 and sitting at 3 costs 4.5. The right curve holds the centre at 0 and changes the spread. It is 0 at σ = 1 (the dashed line), rises gently if the region bloats, and shoots up as σ heads towards 0. That steep wall on the left stops the encoder from shrinking every region to a pin, which would turn it back into a plain autoencoder with holes. The two red dots add up to the worked example's 0.443.

In code: kl_to_standard_normal is the formula; a test checks it against a brute-force average over 400,000 samples. View source

The whole VAE loss

Add the rent, weighted by β, to the rebuild error, and you have the loss a VAE trains on:

The formula and its symbols

Symbols

Symbol Meaning here In the example
the picture (2, 3) from the line example
the decoder's rebuild from the sampled code (1.6, 3.2)
the rebuild error, as in the plain autoencoder 0.2
the region the encoder draws for picture : read "q of z given x"
"beta": how much one unit of KL rent costs, in units of rebuild error 0.3
KL(…) the rent, worked out above 0.443

In words: "rebuild well, but pay β for every unit by which your regions differ from the standard bell curve."

With the numbers: 0.2 + 0.3 × 0.443 = 0.2 + 0.133 = 0.333.

In Python
rebuild, kl_value, beta = 0.2, 0.443, 0.3
# L = ‖x − x̂‖² + β · KL
round(rebuild + beta * kl_value, 3)  # → 0.333

The VAE paper derives this loss, with β = 1, as the negative of the evidence lower bound (ELBO): a quantity that can never exceed the log-probability the model gives to the real pictures, so pushing the bound up pushes that probability up. Choosing squared error amounts to assuming each pixel is the decoder's output plus bell-curve noise of spread s, and working that through gives β = 2s². The stroke VAE uses β = 0.3, which assumes pixel noise of spread about 0.39. Trained with it, the VAE places the 200 pictures like this:

Figure 8 · Chart

−3 −2 −1 0 1 2 3 code number 1 (μ) −3 −2 −1 0 1 2 3 code number 2 (μ) A VAE's codes: fuzzy regions packed inside the bell curve horizontal vertical diagonal down diagonal up

The VAE's 200 codes packed within about two units of the origin, one strand per stroke direction, each with a small shaded fuzzy region

Reading it: the same 200 pictures as the plain autoencoder's map, now placed at their centres μ, each with its fuzzy region shaded around it (regions are drawn one σ wide). The dashed circles are radius 1 and 2 of the standard bell curve. Compare the axes with the plain autoencoder's: the codes now sit around 0 with a spread of about 1.1 in each direction, instead of wandering from −24 to 14. The strands are still there, so the code still holds direction and offset, but they are packed side by side, and the regions (σ about 0.14) overlap along each strand. Far less empty space is left between them.

In code: VAE.loss_and_gradients computes both terms and their gradients. View source

Chapter 5

Sampling new strokes

With the codes packed around 0, generating no longer needs the encoder: draw a code from the standard bell curve and decode it. Take the same code as before, z = (1.2, −0.9). The VAE decodes it to a horizontal stroke through the centre of the picture, at a squared distance of about 0.06 from a real stroke in the training set, where the plain autoencoder made a smear 7.5 away. Over 500 draws the VAE's median distance is about 0.56, against the plain autoencoder's 3.

Figure 9 · Diagram

Reading it: generating uses only the right half of the network. The encoder did its job during training: through the rent, it taught the decoder that codes live where the standard normal puts them. That is why the first box can draw from . The dotted arrow marks that nothing flows from the encoder here.

Figure 10 · Chart

plain autoencoder: 24 codes from N(0, I) (median distance to a real stroke 2.93) VAE: 24 codes from N(0, I) (median distance to a real stroke 0.56)

Left: 24 codes from N(0, I) decoded by the plain autoencoder, many black blobs; right: the same codes decoded by the VAE, clean strokes and a few soft blends

Reading it: both panels decode the same 24 random codes. The plain autoencoder (left) gives blobs, broken lines and a few strokes by luck. The VAE (right) gives strokes in all four directions at many offsets, plus a few soft blends of two directions. The blends are where the VAE still falls short. With only 2 numbers to hold four directions, some codes sit on the border between two strands, and the decoder hedges between them. About a third of the VAE's samples are still junk, most of them blends like these.

The third need was smoothness: nearby codes should decode to similar pictures. To check it, decode an even grid of codes over the middle of the map. A space of codes where position means something in this way is called a latent space.

Figure 11 · Chart

code number 1 → code number 2 → Decoding every point of a grid from -2.2 to 2.2

An 11 by 11 grid of codes from -2.2 to 2.2, each decoded by the VAE: neighbouring tiles are similar strokes, and regions of the map hold each direction

Reading it: every tile is the VAE's decoding of one point on the grid. Read along any row or column: the stroke changes a little at a time, sliding or turning, with no sudden jumps to junk. Whole regions of the map belong to one direction, and the blends sit on the borders between them. Because of this smoothness, moving a picture's code edits the picture.

Interpolation: walking between two codes

Smoothness can also be checked along a line. Encode two pictures to codes and , step along the straight line between them, and decode every stop:

The formula and its symbols

Symbols

Symbol Meaning here In the example
the codes of the two pictures at the ends of the walk and
how far along the walk: 0 at , 1 at 0.25
the code at that point of the walk

In words: "take a share of the first code and a share of the second, and add them."

With the numbers: at , . The walk in the figure uses nine stops, .

In Python
z_a, z_b = [-1.0, 0.5], [1.0, 1.5]
# z_t = (1 − t) z_a + t z_b, a quarter of the way along
t = 0.25
[(1 - t) * a + t * b for a, b in zip(z_a, z_b)]  # → [-0.5, 0.75]
# the nine stops of a walk
[i / 8 for i in range(9)]  # → [0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0]

Figure 12 · Chart

plain autoencoder: the worst stop is 3.88 from any real stroke VAE: the worst stop is 0.70 from any real stroke Walking in a straight line between two vertical strokes (offsets -1.15 and 1.95)

Two walks between the same two vertical strokes: the plain autoencoder's passes through a smeared cross 3.88 from any real stroke; the VAE's passes through diagonal strokes, never more than 0.70 from a real one

Reading it: both rows walk between the same two vertical strokes, one left of centre and one right of it. The plain autoencoder's walk (top) leaves its strand and crosses a hole: the middle frames are a smeared cross, 3.88 away from any real stroke. The VAE's walk (bottom) takes a surprising route, through diagonal strokes, because in its 2-number map the diagonal strand sits between those two points. But every stop is a believable stroke, never more than 0.70 from a real one. Averaged over 60 random pairs, the VAE's biggest jump from one frame to the next is also smaller (about 1.6 against 2.4).

A walk like this is a common check on any learned code: if the walk passes through junk, the space has holes.

In code: generate draws codes and decodes them; interpolate decodes the walk between two pictures. View source

Chapter 6

The trade-off: β, blur and collapse

The stroke VAE was trained with β = 0.3, and the choice matters, because β sets the price of the rent. Set it too low and every region shrinks to a pin far from the centre: rebuilds are sharp, but the holes come back. Set it too high and every region moves to the centre and swells to the full bell curve. Then every picture's region is the same region, the code carries no information, and the decoder can do no better than draw the average of all the strokes, a grey smudge. That failure is called posterior collapse.

VAEs trained at β from 0.01 to 3 show both failures:

β rebuild error KL (information in the code) median sample distance to a real stroke
0.01 0.16 10.3 2.40
0.1 0.23 5.7 0.87
0.3 0.31 4.4 0.56
1 0.92 2.9 0.81
3 6.08 0.0 4.73

The samples are best in the middle. At β = 3 the KL is zero: the regions are the standard bell curve itself, and the rebuild error of 6.08 is what you get by drawing the average stroke every time.

Why VAE pictures are blurry

Even at a good β the regions overlap, so one code can stand for several different pictures. What should the decoder draw for it? Take a single pixel that is black (1) in one of those pictures and white (0) in the other, equally likely. Squared error has a clear answer:

The formula and its symbols

Symbols

Symbol Meaning here In the example
the pixel's true value, which could be either picture's 0 or 1, equally likely
the decoder's guess for that pixel 0, 0.5 or 1
the squared error of the guess
expected value: the average over the possibilities, each weighted by its chance
"the that makes what follows as small as possible"

In words: "the guess with the smallest average squared error is the average of the possibilities."

With the numbers: guess black (1): error 1 half the time, 0 otherwise, average 0.5. Guess white (0): also 0.5. Guess grey (0.5): error 0.25 either way, average 0.25. Grey wins, and grey is the average of 0 and 1.

In Python
outcomes = [0.0, 1.0]
def expected_error(c):
    return sum((x - c) ** 2 for x in outcomes) / len(outcomes)
# E[(x − c)²] for three guesses: white, grey, black
[expected_error(c) for c in (0.0, 0.5, 1.0)]  # → [0.5, 0.25, 0.5]
# E[x]: the average outcome, which is the winning guess
sum(outcomes) / len(outcomes)  # → 0.5

Across a whole picture, "average the pictures this code might mean" is a blur. The more the regions overlap, the more pictures each code must stand for, and the blurrier the output.

Figure 13 · Chart

1 0 − 2 1 0 − 1 1 0 0 β (weight on the KL penalty) 0 2 4 6 8 10 Too little β: holes. Too much: blur, then collapse rebuild error KL (information in the code) samples' distance to a real stroke β = 0.01 β = 0.03 β = 0.1 β = 0.3 β = 1 β = 3 8 samples at each β (rows, top to bottom)

Left: as beta grows from 0.01 to 3, rebuild error rises, KL falls to zero, and sample distance is lowest near beta 0.3; right: 8 samples per beta, sharp but broken at 0.01, clean at 0.3, softer at 1 and uniform grey smudges at 3

Reading it: on the left, β grows along a logarithmic axis. The blue rebuild error stays low, then climbs steeply past β = 1. The green KL, the information the code carries, falls steadily and hits zero at β = 3. The red line, how far random samples are from real strokes, is a U: high at small β (holes), lowest near β = 0.3, high again at large β (blur and collapse). On the right are eight samples at each β. The top rows have sharp ink in junk shapes. The middle rows are clean strokes. The β = 1 row is softer. The bottom row is eight copies of the same grey smudge: the collapse.

Some uses turn β up on purpose. The β-VAE (Higgins and colleagues, 2017) does, to get codes whose numbers line up with separate factors, like direction and offset here, and pays for it in blur. Systems built on VAEs deal with blur in one of two ways. They add a second judge of realism to the loss (an adversarial loss, the idea behind GANs, as in VQGAN), or they let a stronger generator do the generating while the autoencoder only compresses.

In code: beta_sweep trains and measures one VAE per β, including β = 0.03, which the table leaves out. View source

Chapter 7

What autoencoders are used for

Compressing was the autoencoder's job before it was ever a generator, and it still is. A plain autoencoder compresses, it denoises (train on noisy inputs, ask for clean outputs), and it detects anomalies: an input the network rebuilds badly is unlike anything it trained on, which is one way to flag fraud or a failing machine.

Inside today's image generators, the autoencoder does the compressing for a stronger generator. Stable Diffusion's autoencoder turns a 512 × 512 colour image (512 × 512 × 3 = 786,432 numbers) into a 64 × 64 × 4 grid of codes (16,384 numbers): 48 times fewer. The diffusion model does all its work on that small grid, and the decoder paints full-size pixels only at the very end. Its KL weight is tiny, so it is mostly a compressor, with just enough rent to keep the codes well-behaved.

A VQ-VAE (vector-quantized VAE) goes one step further: it snaps each code vector to the nearest entry of a learned codebook, so an image becomes a grid of whole numbers, the entries' positions in the codebook. Those numbers are tokens, and a transformer can read and write them the way it reads and writes words. Neural audio codecs do the same for sound.

Figure 14 · Diagram

Reading it: in the top row the autoencoder is the outer shell: its encoder shrinks the image 48-fold on the way in, its decoder restores it on the way out, and the expensive generator in the middle never touches a pixel. Training and sampling run far faster on 16,384 numbers than on 786,432, which is what made high-resolution diffusion affordable (see Diffusion and flow matching). In the bottom row the snapping step turns continuous codes into token ids, which is how images and audio can enter and leave a language-model-style transformer (see Multimodal models).

So in a generator that works on codes, an autoencoder sits at both ends of the pipeline, and its quality sets a ceiling: whatever detail the decoder cannot rebuild, no generator working in its latent space can produce.

Test yourself

8 questions

Answer each one out loud or on paper before you open it.

Question 1What is the bottleneck for? What goes wrong if the code is as wide as the input?Think it through, then reveal

It forces the network to keep only what matters: with 2 numbers for 64 pixels, it must find the few facts that actually vary. If the code is as wide as the input, the network can learn to copy the pixels straight through, rebuild perfectly and learn nothing useful, unless something else (noise on the input, a penalty on the code) stops it.

Question 2Why can't you generate new pictures by decoding random codes from a plain autoencoder?Think it through, then reveal

Its loss only ever sees the codes of real pictures, so it says nothing about where codes should live or what lies between them. The codes end up in an arbitrary range with holes between clusters, and a random code usually lands in a hole, where the decoder's output is junk.

Question 3What problem does the reparameterization trick solve?Think it through, then reveal

Backpropagation needs every step between the weights and the loss to be something you can differentiate, and a random draw is not. Writing the draw as z = μ + σ·ε with the noise ε as a separate input turns sampling into arithmetic, so gradients reach μ and σ, and through them the encoder.

Question 4What do the two terms of the VAE loss each want, and why do you need both?Think it through, then reveal

The rebuild term wants regions small and far apart so every picture is decoded precisely. The KL term wants every region to be the standard bell curve. Without KL you get a plain autoencoder with holes; without the rebuild term every region collapses onto the bell curve and the code carries nothing. The balance gives a packed, smooth code space that still tells pictures apart.

Question 5Work out the KL penalty for one code number with μ = 0 and σ = 2.Think it through, then reveal

½ (0 + 4 − log 4 − 1) = ½ (3 − 1.386) = 0.807. A region that is too big pays rent too, though less steeply than one that is too small.

Question 6Why are VAE samples blurry?Think it through, then reveal

Regions overlap, so one code can stand for several pictures, and under squared error the best single answer is their average. Averaged pictures are blurred pictures. Raising β increases the overlap and the blur.

Question 7What is posterior collapse?Think it through, then reveal

When the KL rent outweighs what the code saves in rebuild error, the encoder makes every region the standard bell curve, the code carries no information, and the decoder outputs the same average picture for every code. In this lesson that happens at β = 3.

Question 8Why does latent diffusion run inside an autoencoder's code space instead of on pixels?Think it through, then reveal

The code is many times smaller (48 times for Stable Diffusion's 512 × 512 images) and keeps what matters to the eye, so the expensive, many-step generator is far cheaper to train and run. The decoder turns the result back into full-size pixels once, at the end.

Primary sources

The papers behind this lesson

Hinton & Salakhutdinov, Reducing the Dimensionality of Data with Neural Networks (Science, 2006)

Showed that deep autoencoders, once they could be trained, compress data far better than PCA.

The paper
Kingma & Welling, Auto-Encoding Variational Bayes (2013)

Introduced the variational autoencoder, the reparameterization trick and the ELBO loss with its closed-form Gaussian KL.

Read on rumblr →The paper
Rezende, Mohamed & Wierstra, Stochastic Backpropagation and Approximate Inference in Deep Generative Models (2014)

Developed the same idea independently at the same time, showing how to backpropagate through random sampling.

The paper
Burgess et al., Understanding disentangling in β-VAE (2018)

Explains why turning up β pushes the code's numbers to line up with separate factors of the data, and what it costs in rebuild quality.

The paper
van den Oord, Vinyals & Kavukcuoglu, Neural Discrete Representation Learning (2017)

Introduced the VQ-VAE, which snaps codes to a learned codebook and so turns images and audio into tokens.

Read on rumblr →The paper
Rombach et al., High-Resolution Image Synthesis with Latent Diffusion Models (2021)

Ran diffusion inside a lightly regularized autoencoder's code space, the design behind Stable Diffusion.

The paper

Researcher's shelf

Further reading

  • Kingma & Welling, An Introduction to Variational Autoencoders (2019): https://arxiv.org/abs/1906.02691
  • Carl Doersch, Tutorial on Variational Autoencoders (2016): https://arxiv.org/abs/1606.05908
  • Goodfellow, Bengio & Courville, Deep Learning, chapter 14, Autoencoders: https://www.deeplearningbook.org/contents/autoencoders.html
  • Esser, Rombach & Ommer, Taming Transformers for High-Resolution Image Synthesis (VQGAN, 2020): https://arxiv.org/abs/2012.09841
  • PyTorch's VAE example: https://github.com/pytorch/examples/tree/main/vae

About this lesson. This lesson is built from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it. Its hand-built interactive figures are still to come: the status page shows which lessons have them.