KnowML

Generative Models

Follow a folder of cat photos through three ways of teaching a network to make new ones, the VAE, the GAN and diffusion, and learn why diffusion's small denoising steps turn out to be so much easier to train.

⏱ 23 min readAssumes: neural network fundamentals & backprop (04), probability basics & KL divergence (01)
Start reading

Suppose you have a folder of a few thousand cat photos and you'd like one more, a photo that isn't in the folder but looks like it belongs there. A classifier that tells cats from dogs can't give you that. It only has to find where the boundary between the two classes lies, and for that it needs a handful of useful features. It never has to know what makes a photo look like a photo at all. A model that can produce the new picture has to know a lot more: out of every possible grid of pixel values, which ones look like cats and which are static.

In the language of probability, the classifier learns , the probability of a label given a photo. Our target model learns , how likely each possible photo is to turn up in a folder like ours. Once we have that, we can draw samples from it, and every sample is a new photo. A generative model is exactly that: a model of the data itself, good enough to sample from. It's a big ask, because a single 512×512 colour photo is 786,432 numbers, so we're modelling a distribution over a space with that many dimensions.

This chapter follows three ways of getting there. We start with the next-token idea you met in chapter 10, applied to pixels. Two more dominated the 2010s: the variational autoencoder (VAE, 2013), which trained stably but gave blurry samples, and the generative adversarial network (GAN, 2014), which gave sharp samples but needed an unstable game between two networks. Both work, and both have well-documented failure modes. Then came diffusion. DDPM (2020) learned to reverse a fixed noising process by regressing the noise, with no adversary at all, and latent diffusion (2022, Stable Diffusion) made it practical by working in a compressed space. Diffusion has since become the default for image, video and audio generation, and by 2023 to 2024 Diffusion Transformers (DiT) were increasingly replacing the U-Net as the denoiser.

We'll keep the cat photos in mind the whole way through and keep asking one question of each method: what does it ask a network to do with a single photo? Diffusion's answer, making a slightly noisy photo slightly cleaner, turns out to be far easier to learn than "draw a cat", and most of the chapter is about why. You'll need neural networks and backpropagation from chapter 04, and probability and KL divergence (a number that says how different two distributions are) from chapter 01. We'll define the rest as we go.

01Two older ways to make a cat

Telling classes apart versus making new examples

Let's pin down the difference first, since it's easy to blur the two. A classifier that separates cats from dogs is a discriminative model. It learns a function from inputs to outputs, , and nothing more, so it can get by without ever representing what a plausible photo looks like.

A generative model has to represent exactly that. It learns , the full distribution of "things that look like real cat photos", well enough that a fresh sample from it is something that was never in the training folder and still looks like it belongs. A discriminative model needs a boundary. A generative model needs to understand the shape of the whole space well enough to invent a new point inside it. Our job from here is to find a way to do that which a network can learn.

The first attempt: one piece at a time

Start with the approach you already know from language models. Any joint distribution can be split into a product of conditionals, each one predicting a piece given everything before it: . For text, that's next-token prediction. For our photos the same idea applies pixel by pixel, or, more practically, over discrete tokens produced by compressing the image first. We'd generate the top-left pixel, then the next one conditioned on it, and so on until the grid is full.

This works, and it gives an exact likelihood for any photo. But it has two costs. It's slow, since a single image takes thousands of sequential steps. And it can't revise: once a pixel or token is generated it's fixed, so there's no way to go back and improve an earlier guess. That second limit is a big part of why researchers went looking for other ways to break up the job of generating an image. One of the first was to squeeze each photo into a short code and learn to rebuild it from there.

VAEs: compress the photo, then tidy the compression

A plain autoencoder has two halves. An encoder compresses an input into a short list of numbers called a latent code (latent because it's hidden inside the model, never seen in the data), and a decoder rebuilds the input from that code. Train it well and the reconstruction error goes to nearly zero. So can we throw away the encoder, pick a random latent code, and let the decoder draw a cat?

Not with a plain autoencoder. Its latent space is whatever shape happens to minimise reconstruction loss, and nothing says that two nearby codes should decode to anything sensible. A random code lands where the decoder has seen nothing like it, and what comes out is roughly noise.

A Variational Autoencoder fixes exactly this with two changes. First, the encoder stops outputting a single code. It outputs the parameters of a distribution over codes, a mean and a variance, and a sample is drawn from that distribution before it goes to the decoder. Second, the loss gets a KL-divergence term that pulls every photo's distribution toward a fixed, simple prior, usually a standard Gaussian (a bell curve centred at zero with spread one). That term forces the latent space to be smooth and densely packed around the origin, with no gaps. So any point you sample from the prior decodes into something plausible, and not only the points that came from encoding a real training photo. That's the difference between an autoencoder that can only reconstruct what it memorised and a VAE that can generate.

That first change hides a catch. Training sends gradients backward from the loss through every operation, back to the encoder's weights (chapter 04). A random draw from the encoder's distribution sits in the way, and a plain draw isn't an operation a gradient can pass through. A fix exists, the reparameterization trick. Draw a number eps from a standard Gaussian first, then compute the latent code as mu + sd * eps, where mu and sd are the encoder's mean and spread. Now the randomness enters as an input, and the path from the encoder's outputs to the code is ordinary arithmetic. In PyTorch sample() makes the plain draw and rsample() makes the reparameterized one.

In the code, both draws get the same seed so they return identical numbers, and we then try to backpropagate through each. Normal(mu, sd) stands in for what the encoder emits for one photo, and requires_grad=True marks the numbers we want gradients for. At the end we compute mu + sd * eps by hand, to show what rsample() does internally.

Try it Same seed, same sample, and only one of them has a gradient
import torch
from torch.distributions import Normal
r = lambda t: [round(v, 3) for v in t.tolist()]

mu = torch.tensor([0.5, -1.0], requires_grad=True)
sd = torch.tensor([0.8, 0.3], requires_grad=True)
q = Normal(mu, sd)            # what the encoder emits for one input

torch.manual_seed(0)
z_bad = q.sample()            # the draw happens inside the graph
print("sample() ", r(z_bad), "grad_fn", z_bad.grad_fn)
try:
    z_bad.sum().backward()
except RuntimeError as e:
    print("backward:", str(e).split(" and")[0])

torch.manual_seed(0)
z_ok = q.rsample()            # the randomness is pushed out to eps
print("rsample()", r(z_ok), "grad_fn", type(z_ok.grad_fn).__name__)
z_ok.sum().backward()
print("dL/dmu   ", r(mu.grad), " dL/dsd", r(sd.grad))

torch.manual_seed(0)
eps = torch.randn(2)          # the same draw, written out by hand
print("by hand  ", r(mu + sd * eps), " eps   ", r(eps))
Both draws are the same two numbers. sample() and rsample() both return [1.733, -1.088], because the seed is the same and so is eps. The first arrives with grad_fn None, which means PyTorch recorded no operation that produced it, and backward() refuses it. The second carries an AddBackward0, because it was built as mu + sd * eps, which the last line reproduces by hand. Then look at dL/dsd, which is [1.541, -0.293], exactly the eps that was drawn. With the randomness moved outside, it's a constant that the gradient flows past, where before it was an operation the gradient had to flow through. Without this trick the encoder half of a VAE couldn't be trained at all.

Now we have a generator that trains reliably and a loss with a clear meaning. Its weakness is sharpness, and section 04 shows with numbers where the blur comes from. For now, a second idea from a year later took a different route to sharper pictures.

GANs: two networks playing a game

A GAN skips the compression and trains two networks against each other. A generator maps random noise to a fake photo and tries to fool the other network. A discriminator looks at real photos from our folder and fakes from the generator, and tries to tell them apart. Train both at once and, in the ideal case, the generator is pushed until its photos can't be told from real ones. Notice that no density is ever written down. Instead the generator learns to sample well without ever saying how likely a photo is.

That objective can look like an arbitrary game somebody invented. Below, a derivation shows what it's secretly minimising when the discriminator is as good as it can be, and where the theory and the practice part company.

Derivation What the GAN loss is secretly minimising

The minimax objective looks like an arbitrary game somebody invented. It is not. Hold the discriminator at its optimum and the whole thing collapses into a recognisable distance between two distributions.

  1. The setup. The discriminator wants to output 1 on real data and 0 on fakes, so it maximises. The generator wants the opposite, so it minimises. Notice what is absent: no density is ever written down. only produces samples.
  2. Why this is legal: pushing through induces some distribution over samples, even though we cannot write it down. Re-expressing the second expectation over rather than puts both terms under a single integral in . We never need a formula for . We only need it to exist.
  3. Why we may optimise pointwise: is free to return whatever value it likes at each , independently of every other . An integral of independent terms is maximised by maximising each term separately. This step needs to range over all functions, and that is precisely where the theory quietly parts company with a finite network.
  4. Why: solve for the stationary point, then check , so it is a maximum rather than a minimum. Read the answer aloud. The best possible discriminator reports the fraction of the density at that is real.
  5. Why: substitute back in. The second term works because , which makes it a mirror image of the first. The generator now faces a fixed objective with no discriminator left in it.
  6. Why: Jensen-Shannon divergence is with . Each expectation above is one of those KL terms missing a factor of 2 inside its logarithm. Insert the 2 and compensate, and each term sheds a . Two of them give .
  7. Why: JSD is non-negative, and zero only when the two distributions match exactly. So the game has one global optimum, and at it the discriminator is reduced to a coin flip. It is not being fooled. It genuinely cannot tell.
Now the honest part. That result is elegant, and it describes a procedure you are not running. It assumes sits at its optimum for every . In practice you train for a handful of steps between generator updates, so you descend a rough estimate of JSD rather than JSD itself. The theory also works against you at the start. When is confidently correct, saturates and the generator's gradient nearly vanishes. That is why almost nobody implements the loss as written. The standard fix is to have the generator maximise instead: same fixed point, far stronger gradients early on. Knowing exactly where the derivation and the code diverge is the part worth carrying into an interview.

That gap between theory and practice shows up as two well-documented failure modes, and neither was ever fully solved in general. One is mode collapse. Here the generator finds a handful of outputs that reliably fool the current discriminator and stops producing anything else, so the diversity collapses even while each individual sample looks fine. Our generator might learn one convincing tabby and never draw anything else. Another is training instability. Two networks chase a moving target with no natural stopping point, so the pair tends to oscillate. It's also vulnerable to a discriminator that gets too good too fast, leaving the generator with almost no gradient signal to learn from. Careful architectures and loss variants (Wasserstein GANs, spectral normalization and others) made these failures less frequent, but "will this GAN converge nicely" was never something you could assume.

So here's where we stand. VAEs train stably and blur. GANs sharpen and wobble. Is there a way to get a stable training signal and sharp results? Next we take a different view of the whole problem, one that probably looks odd at first.

02Diffusion: un-shred the photo one step at a time

Destroy a photo, then learn to undo a little of it

The idea behind diffusion is to never ask a network to go straight from noise to a perfect image in one shot. Instead, take a real cat photo and destroy it. Add a small amount of Gaussian noise (random numbers from a bell curve, added to every pixel), then a bit more, then a bit more, hundreds of times, until what's left is indistinguishable from pure static. This is the forward process, and nothing in it is learned. It's a fixed, known recipe.

Now train a network to do the single easiest version of the reverse job. Show it a photo that's a little too noisy, ask it to predict what noise was added, and remove a little of that. It isn't asked to generate the whole image, only to make this one step less noisy. Chain that easy step backward, starting from pure noise and going all the way to , and you've generated a new image, one small, well-defined denoising decision at a time.

Why is that easier to learn than drawing the whole cat?

It helps on both of the problems we just met. For GANs, the trouble was a moving target. Here, at every step there's a well-defined right answer, the noise that was added, so the network is doing ordinary supervised regression and has no adversary to chase. For VAEs, the trouble was blur. A VAE asks one decoder to get the entire reconstruction right in a single forward pass, and when that's uncertain it hedges toward a blurry average. Diffusion spreads the work across hundreds of small, low-stakes corrections, each of which the network can learn to do well.

That's the whole idea, and it seems almost too simple. To make it concrete we need to say what the two processes look like together, and what network does the denoising. That's next.

03How the data flows

Two processes run in opposite directions over the same sequence of increasingly noisy images, , where is the clean cat photo and is pure noise. On one side, the forward process is fixed and needs no learning: it adds a bit of Gaussian noise at each step, according to a known schedule. On the other, the reverse process is the one neural network in this whole picture, trained to undo one forward step at a time. Below, the diagram shows both over the same trajectory, and the network at the bottom is a single set of weights reused at every timestep.

Forward noising (fixed) vs. reverse denoising (learned) over the same trajectory
forward noising q(xₜ | xₜ₋₁) — fixed, adds a little Gaussian noise each step → x₀ (clean) x_T/4 x_T/2 x_3T/4 x_T (noise) ← reverse denoising p_θ(xₜ₋₁ | xₜ) — learned, predicts & removes noise each step ε_θ(xₜ, t) the one trained network — same weights reused at every timestep
Top row, left to right: the fixed forward process, in which a real image (x₀) is gradually buried under Gaussian noise until it's indistinguishable from static (x_T). Bottom row, right to left: the learned reverse process, in which a single network ε_θ, reused at every timestep, predicts the noise at each step so it can be subtracted off. Start the reverse process from pure random noise and you've generated a new image.
The Markov chain of forward and reverse diffusion process
Reference figureThe forward (reverse) diffusion Markov chain, as drawn in the DDPM paper. Source: Ho et al. 2020, via Lilian Weng, What are Diffusion Models?

What the denoising network looks like

So what does look like as a network? There have been two answers, a few years apart. First came the U-Net, a convolutional encoder-decoder with skip connections between matching resolutions, the same backbone family used in image segmentation. It's a natural fit, because the input and output are both full images: a noisy image goes in and a predicted noise map comes out.

More recent large-scale systems use a Diffusion Transformer (DiT). Chop the image into patches (usually of a latent-space image, which section 05 explains), treat the patches like tokens, and run ordinary transformer blocks. It's the same architecture from chapter 08, applied to image patches instead of text tokens, with cross-attention or embedded conditioning bringing in the prompt at every block. DiT tends to scale more predictably with more compute and data, the same lesson the field had already learned from the original NLP transformers, so it seems to be where large systems are heading.

Steering it with a prompt or a pose

Either network has to be told what to draw, and that conditioning gets folded in at every denoising step. It might be text, a pose skeleton, a depth map or an edge map. Two common mechanisms are cross-attention, where the query comes from the image and the key and value come from the conditioning, and directly adding a conditioning embedding into the network.

ControlNet-style approaches take this further. Freeze a pretrained diffusion model entirely, then train a small parallel branch that reads an extra conditioning signal (edges, pose, depth) and injects its influence into the frozen network's intermediate activations. That gives precise structural control, exact pose and exact layout, without retraining or damaging what the original model already learned.

We've been saying "add noise according to a schedule" without the formula. It's short, and it turns out to hold the key to why training is cheap.

04The equations

Jumping straight to any noise level

The forward process is designed so you can jump to any noise level in one step, without simulating the steps before it: . Here is fresh Gaussian noise (one random number per pixel, drawn from a bell curve of spread one), and is a known, fixed schedule value that falls from near 1 (almost no noise) to near 0 (almost pure noise) as grows. That's the whole forward process, with no network involved and only algebra.

Is the shortcut the same as taking all the steps? Let's check. For this check we use a four-pixel "image" instead of a cat photo, so the numbers fit on a line. betas holds the small amount of noise added at each of 1000 steps, and abar is the running product of 1 - beta, written . A loop does 400 real noising steps on 20,000 copies of the image at once, so we can measure the average and spread of the result. After it, one line gets the same quantities from the closed form at abar[399], the value after 400 steps, with no loop. A last loop prints a noisy version of the image at four noise levels.

Try it Jump 400 noising steps in one multiply, and watch the signal go
import numpy as np
rng = np.random.default_rng(0)

T = 1000
betas = np.linspace(1e-4, 0.02, T)      # the DDPM linear schedule
abar = np.cumprod(1.0 - betas)          # alpha-bar_t, one per step
x0 = np.array([0.9, -0.7, 0.5, -0.3])   # a 4-pixel "image"

# The slow way: 400 real noising steps, on 20k copies at once.
x = np.repeat(x0[None], 20000, axis=0)
for t in range(400):
    z = rng.normal(size=x.shape)
    x = np.sqrt(1 - betas[t]) * x + np.sqrt(betas[t]) * z
print("x", tuple(x.shape))
print("400 steps:", np.round(x.mean(0), 3),
      "+/-", round(float(x.std(0).mean()), 3))

a = abar[399]                           # the same law, no loop at all
print("1 step:   ", np.round(np.sqrt(a) * x0, 3),
      "+/-", round(float(np.sqrt(1 - a)), 3))

for t in (0, 250, 500, 999):
    xt = np.sqrt(abar[t]) * x0 + np.sqrt(1 - abar[t]) * rng.normal(size=4)
    print(f"t={t:4d} sqrt(abar)={np.sqrt(abar[t]):.3f}",
          "x_t=", np.round(xt, 2))
The two middle lines agree. Four hundred chained noising steps land on mean [0.392 -0.307 0.223 -0.126] with spread 0.895, and the closed form gets [0.398 -0.309 0.221 -0.133] and 0.897 from a single multiply and no loop. That agreement is roughly why training is affordable: each image gets one random , never a whole trajectory. Now read the sqrt(abar) column. By t=500, the halfway point, only 0.279 of the original signal is left, and by t=999 it's 0.006 and x_t has no visible relation to x0. A linear schedule does most of its damage early, which is the complaint that later cosine schedules were built to fix.

The VAE loss, which diffusion inherits

Before the diffusion loss comes the VAE's. Diffusion inherits its whole argument, so we need this one straight before moving on. Below, a derivation shows where the VAE loss comes from, starting from , the quantity we'd like to maximise but can't compute, and ending with two terms that we can.

Derivation Where the VAE loss comes from, line by line

We want to maximise . We cannot: it requires , an integral over every possible latent. The way out is to stop computing it and start bounding it.

  1. Why this is legal: there is no anywhere in . Taking an expectation over of something that does not depend on changes nothing. This looks like it does no work, but it is the move that lets us introduce at all.
  2. Why: Bayes' rule, rearranged. Since , we can write .
  3. Why: multiply and divide by . This is the entire trick. It manufactures one term we can actually compute and one term we can bound.
  4. Why: the log of a product splits into a sum, and expectation is linear. The second term is exactly the definition of KL divergence between your encoder and the true posterior.
  5. Why: KL divergence is never negative. Drop a non-negative term from a sum and what remains is a lower bound. That inequality is the "LB" in ELBO.
  6. Why: expand inside the ELBO, then group the two terms that depend only on . Both pieces are now computable: the first by decoding a sample, the second in closed form for Gaussians.
The gap between the true log-likelihood and the ELBO is exactly . So maximising the ELBO does two jobs at once: it pushes the likelihood up, and it drags your encoder toward the true posterior. And it does the second one without ever computing that posterior, which was the intractable thing you started out trying to avoid.

So the loss has two competing parts: a reconstruction term that wants the code to carry everything about the photo, and the KL term that wants the code to look like the prior. Can we see them compete? In the code below, a single data point x = 2.0 goes through a decoder that is the identity (it hands the code back unchanged), so the reconstruction error has a closed form, (mu - x)**2 + sd**2, and so does the KL. Each run trains the encoder's mean and log-spread to minimise recon + beta * kl, and beta is the dial. At beta=1 that's the true VAE loss, and the other values turn the KL term down or up.

Try it Turn the KL dial and watch the other half of the ELBO pay for it
import torch

x = torch.tensor(2.0)      # one data point; the decoder is the identity

def terms(mu, logsd):
    sd = logsd.exp()
    recon = (mu - x) ** 2 + sd ** 2          # E_q[(x - z)^2], exactly
    kl = 0.5 * (mu ** 2 + sd ** 2 - 1) - logsd
    return recon, kl

print(f"{'beta':>5}{'mu':>8}{'sigma':>8}{'recon':>8}{'KL':>8}")
for beta in [0.01, 0.1, 1.0, 4.0, 50.0]:
    p = torch.zeros(2, requires_grad=True)   # [mu, log sigma]
    opt = torch.optim.Adam([p], lr=0.02)
    for _ in range(4000):                    # this is all training does
        recon, kl = terms(p[0], p[1])
        opt.zero_grad()
        (recon + beta * kl).backward()       # the only knob is beta
        opt.step()
    recon, kl = terms(p[0], p[1])
    print(f"{beta:5.2f}{p[0]:8.3f}{p[1].exp():8.3f}"
          f"{recon:8.3f}{kl:8.3f}")
Read the last two columns against each other. At beta=0.01 the reconstruction term is 0.005 and the KL is 4.134. At beta=50 they've swapped places, 4.660 and 0.003, and no setting buys both. The beta=50 row is posterior collapse in two numbers: mu=0.077 and sigma=0.981. The encoder has stopped encoding and emits the prior whatever the input, which costs nothing on the KL term and is worth nothing to the decoder. Notice too that the honest VAE, beta=1, already drags to 1.333 for a point sitting at 2.0. That gap is where the blur comes from.

The diffusion loss

With the VAE straight, the diffusion objective is short. Training the reverse process reduces, once the derivation settles, to one line:

  • x_0 a real training image, sampled from the dataset.
  • t a timestep sampled uniformly at random from to , so every training step picks a different noise level to work on.
  • ε the Gaussian noise you drew and added to to build with the formula above. It's the ground-truth label.
  • x_t the resulting noisy image at that timestep. This is what the network sees as input, along with itself.
  • ε_θ(x_t, t) the network's prediction: "given this noisy image and this timestep, what noise do I think was added?"
  • ‖·‖² plain L2 distance between the true noise and the predicted noise, an ordinary regression loss with nothing adversarial in it.

Below, a derivation treats diffusion as a VAE whose latents are the whole noising trajectory, and shows how the variational bound we just met turns into that single squared error.

Derivation How a variational bound collapses into that one MSE line

Diffusion is a VAE whose latents are the whole noising trajectory , and whose encoder is fixed by hand rather than learned. So it inherits the bound above, and the work is in simplifying it.

  1. Why: identical to the ELBO step above. The only change is that the latent is now a sequence, not a single .
  2. Why: both the forward and reverse joints factor into per-step terms, so the bound regroups into one KL per timestep. The first term contains no learnable parameters at all: both sides are fixed. It is a constant you can ignore.
  3. Why this step matters most: the reverse of a noising step is intractable on its own. Conditioned also on it becomes an ordinary Gaussian with a closed-form mean. That is the entire reason is carried through the derivation.
  4. Why: fix the reverse process to have the same variance as the forward posterior, and the KL between two Gaussians collapses to a scaled squared distance between their means. Every KL in the sum is now a regression target.
  5. Why: is an invertible function of . Substituting that relation into rewrites the mean-matching problem as a noise-matching problem. Same objective, different coordinates, and the noise coordinates turn out to be much easier to learn in.
  6. Why — and this is the honest part: the weights are simply dropped. That is not a mathematical simplification. Ho et al. found the unweighted version trains better, so the objective everyone uses is deliberately not the tight variational bound.
The MSE is not a heuristic somebody guessed. It is a variational bound on log-likelihood, made tractable by conditioning on , reparameterised into noise coordinates, and then knowingly un-weighted because that trains better. Only the last step is unprincipled, and knowing precisely which step that is separates reciting the loss from understanding it.

Look at what's missing from this loss: no discriminator, no generator fighting anything, no minimax. For our cat photos, one training step is to pick a random photo, pick a random timestep, add the matching amount of noise, ask the network to predict that noise, compute the mean squared error and backpropagate. It's supervised regression with an unusually clever choice of label.

Sampling: walking back from static

At sampling time you start from , pure noise. Then you use again and again to estimate and subtract off a bit of noise, stepping from to , then , and so on down to . Original DDPM sampling does this stochastically, adding a little fresh noise back at each step to match the forward process exactly, and needs on the order of hundreds to a thousand steps.

That's a lot of steps to wait for. DDIM reformulates the reverse process as non-Markovian (a step no longer depends only on the one before it) and deterministic. It uses the same trained network but a sampling procedure that can skip steps and still land close to a good sample. That cuts generation from hundreds of steps to a few dozen with the same weights. That's the difference between diffusion being usable in a real product and not.

05Why this architecture

Two design choices carry most of the weight in a modern diffusion system: the regression objective we just derived, and running the whole process in a compressed latent space. Each one answers a specific cost.

Why does diffusion train more stably than a GAN?

A GAN's loss is defined by two networks trying to outmanoeuvre each other, so there's no fixed target. Every time the discriminator updates, the correct gradient for the generator changes, and nothing guarantees the pair converges instead of oscillating. Diffusion training has none of that, because at every step there's a single, fixed, correct answer, the noise that was added. There's no adversary, so there's no oscillation and no mode collapse in the GAN sense. It also means the loss curve corresponds to the model getting better. That makes debugging and hyperparameter tuning tractable in a way GAN training famously isn't.

Why run diffusion in a compressed space?

There's still the cost of all those steps. Running the forward and reverse process directly on pixels means every one of the hundreds of denoising steps is a full forward pass of a large network over a full-resolution image. At 512×512×3 or larger, that's expensive to the point of being impractical on consumer hardware.

Latent diffusion gets around this by first training a VAE-style encoder and decoder pair that compresses images into a much smaller latent grid. A common choice is 8× spatial downsampling, so a 512×512 image becomes something like a 64×64 latent. Then the entire diffusion process runs inside that compressed space, forward noising and reverse denoising alike, and the final denoised latent is decoded back to pixels with the VAE decoder once, at the very end. This is the single change that took diffusion from a research curiosity needing serious compute to something that runs on a single consumer GPU. That's why it's called Stable Diffusion. And it explains the VAE's lasting role: even in a diffusion system, it's what makes generating affordable.

06Complexity, failure modes, and what breaks

We now have three families, and each has traded something away. Here's a table that puts them side by side on four things you'd care about when choosing one: how good the samples look, how stable training is, how fast sampling is, and whether you can measure the likelihood of a photo.

GANVAEDiffusion
Sample qualitySharp, high-fidelity when it worksOften visibly blurrierSharp, currently state of the art
Training stabilityNotoriously unstable — adversarial balanceStable — single well-behaved lossStable — plain regression loss
Sampling speedFast — one forward passFast — one forward passSlow — many iterative steps (DDIM/distillation narrow this)
Likelihood estimationNo explicit likelihood at allApproximate — optimizes a lower bound (ELBO)Approximate — also a (reweighted) variational bound

What breaks

Each cell where a family looks bad has a mechanism behind it, and it helps to know the mechanisms. For GANs we've met mode collapse already: the generator finds a small set of outputs that reliably fool the current discriminator and stops exploring the rest of the data distribution, so you get samples that are individually convincing and collectively fail to cover the real diversity of the folder. Wasserstein loss, minibatch discrimination and spectral normalization reduce how often it happens, and none of them eliminates it.

For VAEs, the blur comes from the loss. A pixel-wise reconstruction loss, averaged over every plausible way an ambiguous region could look, is minimised by outputting something close to the average of those possibilities, and that average looks blurry. Stronger decoders, and adversarial or perceptual losses added on top of the VAE objective, help. Even so, the core tension never fully goes away: KL regularization is needed for a latent space you can sample from, and it pulls against sharp reconstruction. That's the pull you watched in the beta table.

For diffusion, the cost is slow multi-step sampling. Plain DDPM needs hundreds to a thousand sequential network evaluations per sample. Each one is a full forward pass, and they can't be parallelised, because each step depends on the output of the last. DDIM is the direct first response: deterministic, skip steps, same weights. Further speedups come from distillation, where a student model is trained to match what the multi-step teacher would have produced in far fewer steps, sometimes down to single digits.

Two other families

Two more model families deserve a mention, even though they see less production use today. Normalizing flows build a generative model out of a sequence of invertible transformations (steps that can be run backwards). That gives an exact log-likelihood through the change-of-variables formula, a real advantage over the approximate bounds every other family here relies on. In return, every layer has to be restricted to invertible operations whose Jacobian determinant (a number measuring how much the transformation stretches or squeezes space) is easy to compute. That constrains the architecture, and has kept flows from matching GAN or diffusion sample quality at scale.

Energy-based models don't define how to sample directly. Instead they define a scalar "energy" function that should be low for realistic data and high for everything else, and generation means searching for low-energy points, typically with iterative gradient-based sampling such as Langevin dynamics. It's a conceptually elegant idea, and closely related to score-based views of diffusion. But training them (typically via contrastive divergence) and sampling from them efficiently are both hard. That has limited their production use relative to diffusion.

How do you know the samples are good?

One last problem affects all of these. Unlike a classifier, a generative model has no single clean accuracy number. There are two imperfect options. FID (Fréchet Inception Distance) compares the statistics of real and generated image features under a pretrained classifier network. It's the most commonly reported number in papers, and it's also a proxy: it's sensitive to the reference dataset and the feature extractor used, and it's known not to always track what humans prefer. Human preference evaluation, with pairwise comparisons such as "which image do you prefer", is closer to what matters for a product, but it's expensive, slow, and still noisy across raters.

Use both as proxies to triangulate with. Neither is ground truth, and a model can win on FID and still look worse to people, or the reverse. Next comes the practical side: steering diffusion with guidance and building a small one yourself.

07Summary

  1. A generative model learns P(data), not a boundary. A classifier learns and can ignore what a plausible photo looks like. A generative model has to capture it well enough that you can sample a new example.
  2. Autoregressive generation is exact but slow and can't revise. It predicts one pixel or token at a time, so one image takes thousands of sequential steps and an early guess is fixed once made.
  3. A VAE makes the latent space samplable. Its encoder outputs a distribution over codes and a KL term pulls it toward a standard Gaussian, so any point drawn from the prior decodes into something plausible.
  4. Reparameterization makes the encoder trainable. Writing the code as mu + sd * eps moves the randomness into an input, so gradients can flow through the draw.
  5. VAEs blur because of the loss. A reconstruction loss averaged over plausible versions is minimised by their average, and the KL term pulls against sharpness. With the KL weight turned far up, the encoder collapses to the prior.
  6. GANs trade a stable loss for sharp samples. Generator and discriminator play a game with no fixed target, and that leads to mode collapse and unstable training, even though the ideal optimum matches the data distribution.
  7. Diffusion destroys images with a fixed forward process and learns to undo it. Its network only ever predicts the noise added at one step, and that step has a well-defined right answer.
  8. One equation reaches any noise level. means training picks one random per image instead of simulating a trajectory.
  9. Training uses a plain squared error on the noise. It comes from a variational bound, with the weights dropped because the unweighted version trains better, and it has no adversary in it.
  10. Samplers decide how many steps you pay for. DDPM needs hundreds to a thousand, DDIM a few dozen with the same weights, and distillation can go lower.
  11. Latent diffusion runs the whole process on a compressed grid. An 8× downsampling turns 512×512 into about 64×64. That's why Stable Diffusion runs on a consumer GPU. Evaluation is still weak, since FID and human preference are both imperfect proxies.

08Build this

Classifier-free guidance

This is the single most practically important diffusion concept if you are using these models, and it is simpler than it sounds.

During training, the conditioning signal (a text prompt's embedding, say) is randomly dropped and replaced with a fixed "empty" token some fraction of the time. A common choice is around 10%. So the exact same network learns to predict noise two ways:

  • : the conditional prediction, given the prompt.
  • : the unconditional prediction, ignoring the prompt entirely.

At sampling time, compute both predictions and extrapolate away from the unconditional one, toward the conditional one, by more than the conditional prediction alone would give you:

where is the guidance scale. Illustrative: at you get the plain conditional prediction, with no extrapolation.

Push higher and you exaggerate the direction the prompt is already pulling the prediction, which produces images that adhere to the prompt much more strongly. Values in roughly the 7–15 range are commonly used defaults in practice; Stable Diffusion's original default sat around 7.5.

Push it too far and you trade away diversity, and start seeing oversaturated colors and artifacts. Guidance scale is a real dial with a real quality/adherence tradeoff, and there is no free lunch.

Guidance is the dial. The reverse process is the thing being steered, and it is small enough to build from scratch in an afternoon.

Project Denoise a Gaussian blob back into two moons ~2 hours · PyTorch + scikit-learn

Train a diffusion model on 2D points instead of images. The data is make_moons: two interleaved crescents. With two dimensions you can plot the entire distribution at every timestep, so the reverse process stops being a diagram and becomes something you watch happen, with no U-Net, no latent space and no GPU.

  1. Sample a few thousand points from make_moons with a little noise. Scatter-plot them. That plot is your ground truth for the rest of the project.
  2. Write the forward process straight from section 04: a linear schedule over a few hundred timesteps, precomputed , then . Plot the cloud at several values of and watch the crescents dissolve.
  3. Make a small MLP. Input is the 2D point plus a sinusoidal embedding of ; output is a 2-vector, the predicted noise. Train with the plain L2 loss from section 04.
  4. Sample. Draw from , run the reverse loop down to , and scatter-plot the whole cloud every twenty steps. Stack the frames into an animation or a grid.
  5. Now break it twice. Keep the trained weights and cut the reverse loop to a handful of steps. Then retrain with the timestep input removed from the network entirely.
You'll know it worked when the frames show a round blob stretching, then splitting, with the gap between the two crescents opening late in the run. Nothing in your code describes a crescent. The network only ever saw noisy points and was only ever asked to predict noise.
What the two breakages teach. With only a handful of reverse steps the cloud lands in a smeared version of the moons, and the gap tends to fill in. Each step assumes the correction it makes is small, and that assumption fails when the steps get large. That is the sampling cost from section 06, and what DDIM attacks. Dropping the timestep input fails harder. The network can no longer tell the start of the trajectory from the end, so it applies one average correction everywhere and the shape never resolves.

Where this runs in production

Three distinct pretrained components, chained together, each doing one well-scoped job:

  1. Text encoder. A pretrained language model or CLIP-style text tower turns the prompt string into a conditioning embedding.
  2. Latent diffusion U-Net or DiT. Starts from random noise in latent space and runs the reverse denoising loop, typically a few dozen steps under DDIM-style sampling, with classifier-free guidance applied at every step to sharpen prompt adherence.
  3. VAE decoder. The final denoised latent passes through once, producing the actual pixel-space image.

Guidance is not a fourth model. It carries no weights of its own: it runs the same denoising network twice per step, once conditioned and once not, then extrapolates between the two predictions.

Video generation runs the same core machinery, but adds a new problem: temporal consistency. It is not enough for every individual frame to look right. Consecutive frames need to agree on where objects are, how they are moving, and what they look like. Otherwise you get flicker, and objects that subtly warp between frames.

There are two approaches. One extends the denoising network with temporal attention or convolution layers that let it look across nearby frames. The other diffuses over a whole short clip's latent representation jointly, instead of generating each frame's noise independently. Both treat time as another axis the network has to get right and not as an afterthought bolted onto single-image diffusion.

09Where you meet this in the wild

Generative modelling stopped being about pretty pictures somewhere around 2022. The interesting uses now are the ones where the thing being sampled is not an image at all.

The pattern to notice: diffusion works wherever you can define a sensible way to add noise and a network that can undo it. Pixels were just the first domain where that was easy. Atoms, weather states, and robot trajectories turned out to work too.

Text-to-image
Turning a prompt into an image nobody has drawn
The canonical use, and the one that made latent diffusion famous. Stable Diffusion, Midjourney and DALL·E all sample from a learned image distribution conditioned on text. The VAE is what makes it affordable: diffusion runs in a compressed latent space, not on raw pixels.
Structural biology
Designing a protein that does not exist yet
Baker Lab's RFdiffusion denoises protein backbones instead of pixels: add Gaussian noise to atom coordinates, train a network to reverse it, then sample entirely new structures. It produced experimentally validated binders and symmetric assemblies, not just plausible-looking output.
Weather
Forecasting a distribution, not a single future
DeepMind's GenCast is a diffusion transformer that samples whole 15-day weather trajectories. Because it samples rather than predicts a point estimate, running it repeatedly gives a genuine ensemble — which is exactly what you need to talk about the risk of an extreme event.
Audio
Getting from a spectrogram to a waveform
This is where GANs are still the pragmatic answer rather than a historical footnote. HiFi-GAN generates a full waveform in one forward pass, which matters when a voice agent has a latency budget measured in milliseconds. See 13.
Quietly, everywhere
The VAE as a compressor, not a generator
Most production VAEs are not being used to generate anything. They are used for the latent space itself: a compact, smooth representation that something else operates in. That is precisely the job the VAE does inside Stable Diffusion.
Reach for a generative model when
  • You need plausible new samples and no label: data augmentation, simulation, design search.
  • The answer is one-to-many: many valid images fit a prompt, and many valid weather trajectories fit today's readings. A regressor forced to pick one will average them into mush.
  • You need calibrated uncertainty and can get it by sampling repeatedly, rather than from a single confidence score.
  • You want a learned latent space to work in, and generation is a side effect you may never use.
Look elsewhere when
  • You only need a decision boundary. A discriminative classifier will be smaller, faster and easier to evaluate.
  • You need exact likelihoods. Diffusion and GANs do not give them cleanly, while normalizing flows do at a cost in expressiveness.
  • Latency is tight and quality is negotiable. Iterative denoising is many forward passes; a one-shot model may be the better trade.
  • You cannot define what "realistic" means for your data well enough to evaluate it. If you cannot tell a good sample from a bad one, you cannot train or ship this.

10Going deeper: the decisions that change your output

Everything above explains why diffusion works. This section is about the handful of choices that decide what you get out of it.

Inside Stable Diffusion, at inference

The pipeline above listed three components, but it did not say what each one costs you at generation time, and the distribution is lopsided.

  • The text encoder runs once and is cheap enough to ignore.
  • The denoising network runs once per step, and twice per step when guidance is on, so it is the entire compute budget.
  • The VAE decoder runs once, at the end. Also cheap next to the loop.

So a 30-step generation with classifier-free guidance is 60 forward passes of a large network. Everything else rounds to zero.

Why the latent space matters more than it sounds

The compression is 8× in each spatial dimension: a 512×512 image becomes a 64×64 latent.

Eight times in each direction means 64× fewer spatial positions to process. Every one of those 60 forward passes gets 64× cheaper.

That multiplier is the difference between a model that runs on a consumer GPU and one that does not.

The knobs, roughly in order of how much they move the result:

  • Step count. Cost is linear in it. How low you can go depends entirely on the sampler.
  • Guidance scale. Prompt adherence traded against diversity, covered above.
  • Sampler. Changes the step floor by an order of magnitude, and costs nothing to swap.
  • Resolution. Cost is quadratic in it, and quality also tends to degrade well away from the resolution the model was trained at.

Samplers: same weights, different arithmetic

A sampler is the rule for stepping from to , and it is not part of the trained model at all. Swap it whenever you like.

SamplerTypical stepsDeterministicNeeds training
DDPM (ancestral)Hundreds to ~1000No, injects fresh noise each stepNo
DDIMA few dozenYesNo
DPM-Solver10 to 20YesNo
Distilled (e.g. LCM)1 to 4YesYes, a distillation run

DPM-Solver treats the reverse process as an ODE and applies a higher-order numerical solver to it. Same network, same weights, better integration. Its authors report high-quality samples in 10 to 20 network evaluations, a 4 to 16× speedup over previous training-free samplers.

The first three rows are the same model

DDPM, DDIM and DPM-Solver are not different models. They are different ways of numerically integrating the same learned reverse process.

You can download one checkpoint and get any of them, which is why sampler choice is the cheapest large speedup available to you.

The fourth row is different in kind. Getting below roughly ten steps means changing the weights.

Adaptation without retraining

Almost nobody trains one of these from scratch, so practical work is nearly all adaptation of a checkpoint someone else paid for. Five techniques cover most of what people do, and they differ mainly in how much of the model they are willing to disturb.

  • LoRA. Freeze the base weights and learn a small low-rank update beside them. Proposed for language models, it transfers directly to diffusion. The files are small enough to swap and stack freely.
  • DreamBooth. Fine-tune the model on a handful of images of one subject, bound to a rare identifier token. Strong subject fidelity. Also the heaviest option, and the most prone to overfitting a small reference set.
  • Textual inversion. Keep the model entirely frozen and learn one new embedding vector for one new token. The smallest possible intervention, and correspondingly limited in what it can express.
  • ControlNet. Clone the encoder and train the copy on a spatial conditioning signal: edges, depth, pose, segmentation. It controls composition, with content left to the prompt.
  • IP-Adapter. Add a separate cross-attention path for image features, so an image can act as a prompt alongside the text. Roughly 22M parameters, and it composes with the others.

ControlNet has a detail worth stealing for your own work. The trained copy reconnects to the frozen base through zero-initialised convolutions. At the start of training those layers output nothing, so the branch is a no-op and cannot damage a working model. It grows its influence from zero as training proceeds.

Where GANs still win

Not many places, but the ones that remain are real and worth being precise about.

A GAN generator produces its output in one forward pass. Diffusion needs several at absolute minimum, usually dozens. When the latency budget is small and fixed, that gap decides the architecture on its own.

  • Neural vocoding. HiFi-GAN emits a waveform in a single pass. A voice agent replying in real time cannot afford a denoising loop. See 13.
  • Super-resolution and restoration. Real-ESRGAN-style models are still widely deployed for upscaling, where one pass is enough.

Notice what those share: the output is tightly constrained by the input, so the one-to-many problem that drives mode collapse is much smaller to begin with. Add a hard latency budget and the trade tips toward the GAN.

Few-step generation

Better samplers took diffusion from a thousand steps down to roughly ten, which is where training-free cleverness runs out. Going lower means changing the weights as well as integrating them more carefully.

Consistency models are trained so that every point along a trajectory maps directly to that trajectory's endpoint. If that property holds, you can jump straight to the answer instead of walking to it.

Latent consistency models apply the idea to an existing latent diffusion model by distilling it. The authors report 2 to 4 step generation at 768×768, distilled in roughly 32 A100-hours.

The trade is consistent across the whole family. You give up some quality and some diversity, you gain a large cut in latency, and you pay a distillation run up front.

Evaluation is the bottleneck

The failure-modes section introduced FID and human preference. Both are weaker than their ubiquity suggests.

The Rethinking FID analysis lays out the specific problems:

  • Inception features were trained for classification. They represent the content of modern text-to-image output poorly.
  • FID compares only the first two moments, which assumes the feature distributions are Gaussian, and typically they are not.
  • Sample complexity is poor, so the number you get shifts with how many samples you scored.
  • It can contradict human raters, and does not reliably track gradual improvement in a model.

That paper proposes CMMD instead, pairing CLIP embeddings with a maximum mean discrepancy distance.

Generative quality is easy to see and hard to measure, and no automated metric settles the question today.

11Interview questions

BeginnerWhat's the difference between a generative and a discriminative model?

A discriminative model learns — it only needs a boundary that separates classes, and never has to represent what makes data plausible in the first place. A generative model learns itself, well enough to sample brand-new, never-seen examples from that distribution.

BeginnerWhy isn't a plain autoencoder a generative model, but a VAE is?

A plain autoencoder's latent space is shaped only by reconstruction loss. Nothing guarantees that a random point in it decodes to anything sensible, so you cannot sample from it. A VAE adds a KL-divergence term that pulls every input's latent distribution toward a fixed prior, usually a standard Gaussian. That forces the space to be smooth and densely packed, with no gaps, so any point drawn from the prior decodes to a plausible output rather than a memorized reconstruction.

IntermediateWhy do diffusion models train more stably than GANs?

GAN training is an adversarial minimax game between two networks with no fixed target. The "correct" gradient for the generator keeps changing as the discriminator updates, and nothing guarantees convergence rather than oscillation or collapse. Diffusion training has one fixed correct answer at every step, the noise actually added, so it reduces to ordinary supervised regression with an L2 loss. There is no adversary to oscillate against, and the loss curve tracks improvement.

IntermediateWhat does classifier-free guidance actually do at sampling time?

The model was trained to predict noise both with the conditioning (e.g. a prompt) and without it (conditioning replaced by an empty token). At sampling time you compute both predictions and extrapolate away from the unconditional prediction toward the conditional one, scaled by a guidance weight . This exaggerates the direction the prompt is already pulling the model, producing much stronger prompt adherence at the cost of some sample diversity, and can introduce artifacts if pushed too high.

IntermediateWhy does Stable Diffusion run in latent space instead of pixel space?

Diffusion needs many sequential network evaluations per sample. Running that directly on full-resolution pixels makes every one of those steps a full forward pass over a large image, which is expensive enough to be impractical on consumer hardware. Latent diffusion compresses images into a much smaller latent grid with a pretrained VAE encoder first, runs the entire noising/denoising process there, and decodes back to pixels only once at the end — the compute savings are what make diffusion tractable outside a datacenter.

DeepWalk me through the DDPM training objective — what is the network actually predicting, and why does that make it easy to train?

Sample a real image , a random timestep , and random Gaussian noise . Construct the noisy image directly via — no simulation needed. Feed and into the network and have it predict ; train with L2 loss between the true and predicted noise. It's easy to train because it's plain supervised regression with a well-defined, always-available label — you never need an adversary, a search procedure, or an intractable likelihood; you just need to be able to add noise and subtract it back off.

DeepWhat's mode collapse, and why is it still a genuinely hard, unsolved problem for GANs?

Mode collapse is when the generator converges on a small set of outputs that reliably fool the current discriminator and stops exploring the rest of the real data distribution — high-quality individual samples, low overall diversity. It's hard because the generator's objective only ever asks "can I fool the discriminator right now," with no explicit term rewarding coverage of the full data distribution — so a narrow, reliable strategy is a perfectly valid local optimum of the adversarial game. Architectural and loss-level mitigations reduce how often it happens in practice, but none of them change the underlying game-theoretic incentive that makes it possible in the first place.

12Go deeper

●Now write it yourself

Reading the derivation and being able to produce it are different skills. These are Deep-ML problems that exercise what this page covers — each one is checked against real test cases, not multiple choice.

Matched to this page from Deep-ML's catalogue of 1,380 problems. More at deep-ml.com, and Where to practise covers the other platforms and what each one trains.