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?
- Recover the exact original image
- Guess an average-looking image: the posterior is wide, so its best guess is blurry
- Nothing: it isn't trained there
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
- 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.
- 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}\).
- 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\).
- So training never walks the chain: any step's noisy image is one formula away, which makes each training example cheap.
- 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.
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?
- Drawing random numbers directly has no derivative; moving the noise into an external input \(\varepsilon\) lets backpropagation compute \(\frac{\partial L}{\partial \mu}\) and \(\frac{\partial L}{\partial \sigma}\)
- It turns Gaussian noise into uniform noise
- It removes the need for an encoder
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
- An ordinary autoencoder only minimizes reconstruction error \(\lVert x - g(f(x)) \rVert^2\).
- To minimize reconstruction, the encoder can map each training class to a tiny, isolated point very far from others, where they never interfere.
- Because no training example ever falls into the spaces between these isolated points, the decoder never learns what those latent coordinates mean.
- Sampling a random vector from the empty space yields strange, unrecognizable artifacts.
- 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
- Conditioning. To follow a prompt, the denoiser also gets the text, embedded by a text encoder (CLIP or a T5, the embeddings lesson's kind of model), mixed in through cross-attention (chapter 7): every image patch can attend to every word.
- Classifier-free guidance. During training the text is dropped 10% of the time, so the same network learns both \(\varepsilon(x_t, t, \text{text})\) and \(\varepsilon(x_t, t)\). At sampling, push past the conditional prediction, away from the unconditional one: \(\hat\varepsilon = \varepsilon_{\text{uncond}} + w(\varepsilon_{\text{cond}} - \varepsilon_{\text{uncond}})\). The "guidance scale" \(w\), often 5–8, trades variety for following the prompt.
- Latent diffusion. A 1024 × 1024 color image is 3 million numbers. Stable Diffusion first compresses images with a VAE to a 128 × 128 × 4 latent (65,536 numbers, 48 times fewer), runs diffusion there, and decodes with the VAE at the end. That's what made it run on one consumer GPU.
A 1024 × 1024 × 3 image is encoded to a 128 × 128 × 4 latent. How many times fewer numbers does diffusion work on?
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
- Memorization. The demo's denoiser is the exact best one for its training points, and it reproduces training points: nothing new at all. Real networks can't represent that exact function, which is what makes them generalize, but not always: studies have extracted near-copies of training images (repeated ones especially) from Stable Diffusion. The practice notebook measures how close its generated digits come to the nearest training digit.
- Training data and rights. Generators trained on scraped images reproduce styles, watermarks and sometimes specific works, which is the subject of lawsuits by artists and photo agencies. Know your model's data and license before using its images commercially.
- Bias and failures. "A doctor" defaults to whatever the training images mostly showed (the word vectors lesson's biases, in pictures); hands, text inside images and counting objects are classic weak spots.
6. What to carry forward
- Forward: \(x_t = \sqrt{\bar\alpha_t} x_0 + \sqrt{1 - \bar\alpha_t} \varepsilon\), a fixed schedule from image to noise.
- Train a U-Net to predict \(\varepsilon\) with MSE at every noise level.
- Sample from noise in 20–1,000 small denoising steps.
- VAEs compress images into continuous latent spaces via reparameterization and KL divergence.
- Text via cross-attention, classifier-free guidance scale \(w\), latent diffusion for speed.
- Check for memorization and know the data's rights.
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