AI from scratch · Elective · How image generators work

How image generators work

Type "a yellow cab in the rain at night, Times Square" and a few seconds later there's a picture nobody ever took. Stable Diffusion, Midjourney, DALL·E and Flux all rest on one surprisingly simple idea, diffusion: it's easy to destroy an image by adding noise a little at a time, so train a network to undo one small step of that, and then run it backward from pure noise. This lesson shows the noise going in, the network that learns to take it out, how text steers it, and how the same machinery can quietly memorize.

1. Destroying an image, one small step at a time

Take an image \(x_0\) (pixels scaled to −1…1) and mix in Gaussian noise \(\varepsilon\) (Probability 3's bell curve, one draw per pixel). After \(t\) of \(T = 1000\) steps the image is

\[ x_t = \sqrt{\bar\alpha_t}\; x_0 + \sqrt{1 - \bar\alpha_t}\; \varepsilon \]

where \(\bar\alpha_t\) falls from 1 (all image) to about 0 (all noise) along a fixed schedule. The two weights' squares add to 1, so the overall spread stays the same while the image fades out of it.

Diffusion's forward process blends an image with noise in a fixed schedule until only noise is left: easy, with nothing to learn.

2. Learn to predict the noise

Training picks a real image, a random step \(t\) and random noise \(\varepsilon\), makes \(x_t\), and asks a network \(\varepsilon_\theta(x_t, t)\) to guess which noise was added. The loss is plain mean squared error (chapter 2):

\[ L = \big\lVert \varepsilon - \varepsilon_\theta(x_t, t) \big\rVert^2 \]

Knowing the noise is knowing the image: \(\hat x_0 = (x_t - \sqrt{1 - \bar\alpha_t}\,\varepsilon_\theta)/\sqrt{\bar\alpha_t}\). The network for images is a U-Net (the detector lesson's segmentation network, now outputting noise per pixel), told the step \(t\) through sine-wave features (chapter 7's positional encoding idea).

At step \(t = 990\) the image is almost pure noise. What's the best the network can do there?

With squared error the best guess is the mean of all images consistent with \(x_t\) (P2's mean as the best guess under squared penalty). Early in sampling that's a blurry average; each later step commits to more detail. That's why sampling is many small steps, not one jump.

The network is trained, at every noise level, to predict the noise that was added; predicting the noise is the same as predicting the clean image.

Why the noisy image is a blend you can sample in one shot
  1. One forward step: \(x_t = \sqrt{\alpha_t}\, x_{t-1} + \sqrt{1 - \alpha_t}\, \varepsilon_t\), shrinking the image a little and adding a little fresh noise.
  2. Substitute the previous step into this one: the image part gets \(\sqrt{\alpha_t \alpha_{t-1}}\), and the two noises are independent bells, so their variances add: \(\alpha_t (1 - \alpha_{t-1}) + (1 - \alpha_t) = 1 - \alpha_t \alpha_{t-1}\).
  3. Continuing down to \(x_0\): \(x_t = \sqrt{\bar\alpha_t}\, x_0 + \sqrt{1 - \bar\alpha_t}\, \varepsilon\) with \(\bar\alpha_t = \alpha_1 \alpha_2 \cdots \alpha_t\) and one combined noise \(\varepsilon\).
  4. So training never walks the chain: any step's noisy image is one formula away, which makes each training example cheap.
  5. The variances adding (not the standard deviations) is Probability 4's rule again; it's why the coefficients are square roots.

3. Sampling: from noise back to data

To generate, start from pure noise and repeat: estimate the clean image from the network's noise guess, then step a little toward it, back to a slightly less noisy \(x_{t-1}\). Below, every dot is a 2-D "image" (two numbers instead of a million pixels), the training data is the dots in the shape of a word, and the denoiser is the exact best one for this data. Press play: 600 points start as noise and flow onto the data.

Ten steps already give the shape; more steps refine it. Real samplers (DDIM, DPM-Solver) make 20–50 steps as good as the original 1,000. And notice where the points land: on the training dots, every one. That's the next section's lesson.

Sampling runs the denoiser backward from pure noise in small steps, each committing to a little more detail.

4. Autoencoders and VAEs: learning a smooth latent space

Before running diffusion on high-resolution images, models first compress pixels into a low-dimensional space. An autoencoder uses an encoder network \(f(x)\) to compress an image into a compact vector \(z\) (the latent, or bottleneck), and a decoder network \(g(z)\) to reconstruct the image \(\hat x\). The loss is reconstruction error \(\lVert x - \hat x \rVert^2\).

A plain autoencoder compresses well, but its latent space is full of holes: distinct clusters with vast empty chasms in between. If you pick a point in the empty space between training clusters, the decoder produces garbled nonsense. You cannot sample from it.

A Variational Autoencoder (VAE) fixes this by turning each image into a probability distribution: the encoder outputs a mean \(\mu(x)\) and a spread \(\sigma(x)\). To sample a latent vector \(z\) while allowing backpropagation, the reparameterization trick moves the randomness into an independent noise draw \(\varepsilon \sim \mathcal{N}(0, I)\):

\[ z = \mu + \sigma \odot \varepsilon \]

The VAE loss balances reconstruction against a Kullback–Leibler (KL) divergence penalty that pulls every encoding toward a standard normal bell curve \(\mathcal{N}(0, I)\):

\[ \mathcal{L}_{\text{VAE}} = \text{reconstruction error} + \mathbb{D}_{\text{KL}}\big(\mathcal{N}(\mu, \sigma^2) \parallel \mathcal{N}(0, I)\big) \]

The KL penalty prevents the encoder from scattering clusters across empty space. It forces the representations to overlap into a continuous, dense landscape. Below, an actual VAE trained on 8 × 8 handwritten digits maps every digit into a 2-D latent space. Drag the crosshair across the plane (or click it and use the arrow keys): the decoded digit changes gradually from one shape to the next. Its decoder is tiny, 2 → 24 → 64 numbers (1,672 weights), so expect blurry in-between shapes rather than crisp new digits.

2-D latent space \(z = (z_1, z_2)\)
decoded digit \(\hat x = g(z)\)

Drag in the latent plane: position decodes continuously into a handwritten digit.

Why is the reparameterization trick \(z = \mu + \sigma \odot \varepsilon\) necessary in a VAE?

You cannot backpropagate gradients through a stochastic sampling node \(z \sim \mathcal{N}(\mu, \sigma^2)\). Writing \(z = \mu + \sigma \varepsilon\) makes \(z\) a deterministic, differentiable function of the network's outputs.

A VAE maps images to a continuous distribution with no holes; the reparameterization trick lets backpropagation flow through the sampling step.

Why plain autoencoders leave holes in latent space
  1. An ordinary autoencoder only minimizes reconstruction error \(\lVert x - g(f(x)) \rVert^2\).
  2. To minimize reconstruction, the encoder can map each training class to a tiny, isolated point very far from others, where they never interfere.
  3. Because no training example ever falls into the spaces between these isolated points, the decoder never learns what those latent coordinates mean.
  4. Sampling a random vector from the empty space yields strange, unrecognizable artifacts.
  5. The VAE's KL divergence penalty acts like a spring pulling all latent distributions toward \(\mathcal{N}(0, I)\), forcing them to fill the space without leaving unmapped gaps.

5. Text, guidance and latents

A 1024 × 1024 × 3 image is encoded to a 128 × 128 × 4 latent. How many times fewer numbers does diffusion work on?

\(1024 \cdot 1024 \cdot 3 / (128 \cdot 128 \cdot 4) = 3{,}145{,}728 / 65{,}536 = 48\). Every one of the 20–50 denoising steps is that much cheaper.

Text steers generation through cross-attention, guidance amplifies the text's pull, and working in a compressed latent space makes it affordable.

Where it breaks: memorizing, and what the data carried

6. What to carry forward

All lessons: AI from scratch. Papers: Kingma & Welling, "Auto-Encoding Variational Bayes" (2013); Ho, Jain and Abbeel, "Denoising Diffusion Probabilistic Models" (2020); Rombach et al., "High-Resolution Image Synthesis with Latent Diffusion Models" (2022).

Last updated