rumblr Work in progressWIP

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

Diffusion and flow matching

turning noise into data one small step at a time

This lesson covers Turning noise into images one small step at a time

Members · open during launch 48 min14 figures and diagrams

What this is

What is diffusion?

Diffusion is the method behind today's AI image, video and audio generators: a neural network learns to remove a little noise from a noisy picture. Run that skill many times, starting from pure static, and a new picture appears. Flow matching is the same idea along straighter paths, so it needs fewer steps. A tiny generator trained on dots in a plane shows every step, and the same steps explain an image generator's settings: steps, guidance, resolution and seed.

Why it matters: When you generate or edit images, video or audio, you choose the kind of generator, the number of steps, the guidance scale, the size and the sampler. Those choices set the bill and the artefacts you get.

At a glance

Key takeaways

  1. Forward process: mix data with a little random noise per step until only noise is left; the shortcut jumps to any step in one go.
  2. Training: show the network a noised example and its step; it guesses the noise and is graded by squared error. This is plain, stable regression, and the noise guess is the score (the direction toward the data), flipped and rescaled.
  3. Sampling: start from pure noise and repeatedly remove a little guessed noise (DDPM, with a fresh wobble each step), or take a few big deterministic jumps (DDIM).
  4. Flow matching: learn the velocity along straight lines from noise to data and follow it with Euler steps; straighter paths need fewer steps.
  5. Guidance: ask the same network with and without the label and push past the labelled guess; more on-prompt, less varied.
  6. At scale: denoise an autoencoder's small latent with a transformer that reads a text encoder's tokens; video and audio are the same idea with more tokens.

How it works, from scratch

Imagine a sculptor who cannot carve a statue in one go. Hand them a shapeless block and ask for a horse, and they freeze. Hand them a slightly rough horse, though, and they can always make it a little less rough: smooth this bump, deepen that line. Start from the shapeless block, repeat that one modest skill a hundred times, and a horse comes out.

A diffusion model works like that sculptor. It never learns to draw a picture from nothing, which is hard. It learns to take a picture with a little too much noise in it and remove some of that noise, which is much easier. Its practice material costs nothing: take any real picture, add the noise yourself, and you know the answer.

Figure 1 · Diagram

Reading it: the top arrow is the forward process: it destroys data by adding noise a little at a time, and it involves no learning. The bottom arrow runs the same road backwards, and that direction is what the network learns. To generate, only the bottom arrow runs, starting from fresh noise, so every run ends at a new sample.

A world small enough to see. A real image is a long list of numbers, one per pixel colour. The "images" here have just two numbers, so each one is a dot on a flat plane. The real data is four round blobs of dots, one in each corner (north-east, north-west, south-west, south-east), 600 dots in all. The task is to make new dots that land in the blobs, starting from random noise. Every idea below works unchanged on a 512 × 512 colour image, which has 786,432 numbers per "dot" instead of 2.

One fact about the blobs matters later: their average is the empty middle. A generator that plays safe and outputs the average answer puts its dots where no real data lives. The same failure blurs images, because the average of many sharp faces is a blur.

Chapter 1

Step 1: the forward process, adding noise a little at a time

The forward process is the half that needs no learning, so it comes first. Follow one pixel whose clean value is . Each step keeps most of the signal and mixes in a little fresh random noise. The noise is a random number drawn from a standard normal distribution: the bell curve centred on 0 whose typical size is 1 (values like 0.5, −1.2 and 0.1 are common, 3 is rare). Say step 1 mixes in a share of noise, and the random draw is .

The formula and its symbols

Symbols

Symbol Meaning here In the example
the step number, from 1 to (the last step) 1
the value before this step ( is the clean data) 2.0
the value after this step 2.06
"beta": how much noise this step mixes in, a number between 0 and 1 0.1
how much of the old value survives: it shrinks a little
"epsilon": fresh noise drawn from the standard normal bell curve 0.5
how much noise is mixed in

In words: "shrink the old value a little, then add a little random noise."

With the numbers: .

In Python
import math
x_prev, beta, eps = 2.0, 0.1, 0.5
# √(1 − β) x_{t−1}: shrink the old value
round(math.sqrt(1 - beta) * x_prev, 3)  # → 1.897
# √β ε: the noise mixed in
round(math.sqrt(beta) * eps, 3)  # → 0.158
round(math.sqrt(1 - beta) * x_prev + math.sqrt(beta) * eps, 2)  # → 2.06

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

The square roots hold the value's size steady. What matters is its variance (its typical squared size), and the variances of independent things add. If the old value has variance 1, the new one has variance again. So after many steps the value is noise of size 1, not a number that has blown up or faded to zero.

The shortcut to any step

Training needs noisy examples at every step, and running steps one by one to make each of them is slow. Adding noise twice is the same as adding it once in a bigger dose, so one formula jumps straight to step . First multiply together the share of signal that each step keeps:

The formula and its symbols

Symbols

Symbol Meaning here In the example
the share of variance step keeps (often written ) 0.9, then 0.8
"multiply together, for = 1, 2, …, " (see Math notation, from zero)
"alpha bar": the share of the original signal's variance left after steps; 1 means clean, 0 means pure noise 0.72; or 0.64 in the jump below
the clean data 2.0
one fresh standard-normal draw, standing in for all the noise added so far 0.5
the signal share: how much of is still in
the noise share

In words: "multiply together the survival share of every step so far; then the noisy value is that much of the clean value plus the rest in noise."

With the numbers: two steps with then leave . In the schedule used here, step 30 leaves , so the pixel at 2.0 with noise 0.5 lands at .

In Python
import math
betas = [0.1, 0.2]
alpha_bar = 1.0
# ∏ (1 − β_s): multiply up what each step keeps
for beta in betas:
    alpha_bar *= 1 - beta
round(alpha_bar, 2)  # → 0.72
# the jump to step 30, where ᾱ = 0.64
x0, eps, alpha_bar_30 = 2.0, 0.5, 0.64
round(math.sqrt(alpha_bar_30) * x0 + math.sqrt(1 - alpha_bar_30) * eps, 2)  # → 1.9

Figure 2 · Diagram

Reading it: the solid chain is the slow way: one small dose of noise per arrow. The dotted arrow is the shortcut: pick any step , look up , draw one noise sample, and land where the chain would have taken you (in distribution: with the same spread of possible values). Training uses only the shortcut.

The noise schedule is the list of . The one used here has steps with rising in a straight line from 0.0001 to 0.1: tiny doses first, while there is fine detail to lose, bigger ones once little is left.

Figure 3 · Chart

t = 0 signal √ᾱ = 1.00 t = 10 signal √ᾱ = 0.98 t = 30 signal √ᾱ = 0.80 t = 50 signal √ᾱ = 0.53 t = 100 signal √ᾱ = 0.07 The forward process: four blobs dissolve into plain noise

Five panels: the four coloured blobs at step 0 blur at step 30, merge at step 50, and are a single shapeless cloud by step 100

Reading it: each panel is the whole dataset, noised to the step in its title, with every dot keeping its blob's colour. Step 10 barely differs from the clean data (its signal share is still 0.98). By step 30 the blobs have swollen into each other, though each colour still keeps to its own corner. By step 50 the colours overlap. At step 100 only 7% of the signal is left and the colours are mixed into a round cloud of plain noise. That cloud is the same whatever data you start from, and it is easy to draw from, so generation can start there.

Figure 4 · Chart

0 20 40 60 80 100 step t 0.0 0.2 0.4 0.6 0.8 1.0 share The noise schedule (T = 100, β from 0.0001 to 0.1) t = 37: half and half t = 30: 0.8 and 0.6 signal kept √ᾱ_t noise mixed in √(1 − ᾱ_t)

Two curves over 100 steps: the signal share falls from 1 to 0.07 while the noise share rises from 0 to nearly 1, crossing at step 37

Reading it: the x-axis is the step. The blue curve is the signal share and the red curve is the noise share . The two dots at step 30 are the worked example's 0.8 and 0.6. The dashed line at step 37 is where signal and noise are equal. Early steps change little (the curves are flat at the left), so the network gets plenty of practice on nearly clean data, where the fine detail lives.

In code: linear_schedule builds the schedule, noise_step takes one step and add_noise is the shortcut. View source

Chapter 2

Step 2: learning to denoise

The shortcut turns any clean example into a practice question at any noise level. Take the pixel from before: , noise , step 30, so . The network is shown only and the step number 30, and asked what noise was added. The right answer is 0.5. If it guesses 0.4, it is off by 0.1 and scores , where lower is better.

The network could be asked for the clean value instead, since the two answers carry the same information: given , and the noise, the clean value follows by undoing the shortcut, . Guessing the noise trains better, because its target has the same size (a standard-normal draw) whatever the step.

Figure 5 · Diagram

Reading it: three random choices feed in from the left: which example, which step, which noise. The shortcut mixes them into a noisy point. The network sees only the noisy point and the step (not the noise, and not the clean point). The noise takes the lower path straight to the loss, where the guess is graded against it. Everything after the loss is ordinary training, as in Neural networks.
The formula and its symbols

Symbols

Symbol Meaning here In the example
"theta": all of the network's weights, the knobs training turns about 5,000 numbers here
the network's guess of the noise, given the noisy point and the step; written ("epsilon hat") (0.4, −0.8)
the noise that was really added (a 2-number vector in our world) (0.5, −1.0)
the error: how far off the guess is, per number (0.1, −0.2)
squared length: square every entry and add them up
expectation: the average over many random choices of example, step and noise; in code, the average over a batch the batch average
the loss: one number saying how bad the guesses are with these weights about 0.6 after training

In words: "over many random examples, steps and noises, average how far the network's noise guess is from the real noise, measured as squared distance."

With the numbers: true noise (0.5, −1.0), guess (0.4, −0.8): error (0.1, −0.2), squared length . A network that always guesses zero scores the average of , which is 1 + 1 = 2 (each standard-normal number has variance 1). That is the score to beat.

In Python
import random
eps = [0.5, -1.0]
guess = [0.4, -0.8]
# ‖ε − ε̂‖²: square each error and add
round(sum((e - g) ** 2 for e, g in zip(eps, guess)), 2)  # → 0.05
# the baseline: always guessing 0, averaged over many draws of 2-D noise
random.seed(0)
draws = [random.gauss(0, 1) ** 2 + random.gauss(0, 1) ** 2 for _ in range(100_000)]
round(sum(draws) / len(draws), 1)  # → 2.0

This is plain regression: predicting numbers, graded by squared error. Unlike a GAN, it has no opponent to keep in balance, and that stability is a large part of why diffusion displaced GANs. The original DDPM paper and the first Stable Diffusion models trained with this same loss, on far bigger networks and on images.

The network. The denoiser here is a small multi-layer network. Its input is the noisy point (2 numbers) plus the step, turned into 8 numbers of sines and cosines. A single number such as 30 is hard for a small network to use, while a spread of waves at different speeds is easy: the same trick as the sinusoidal positions in Positional information. Two hidden layers of 64 ReLU units turn that input into 2 numbers, the noise guess. It trains for 1,500 steps of Adam (Optimizers) on batches of 256, in about half a second.

Figure 6 · Chart

0 200 400 600 800 1000 1200 1400 training step 0.0 0.5 1.0 1.5 2.0 2.5 ‖ε − ε̂‖², batch average Learning to guess the noise guessing ε = 0 scores 2 each batch average of 25 batches

A training curve that starts at 2, the score of guessing zero, drops below 0.7 within a hundred steps and settles near 0.6

Reading it: the x-axis is training steps and the y-axis is the batch's average squared error. The dashed red line at 2 is the "always guess zero" baseline, and the untrained network starts right on it (its last layer starts near zero). The loss plunges within a hundred steps, then creeps down. It cannot reach 0: at low noise levels the noise is hidden inside the blob's own natural spread, so even a perfect network can only guess its average. The floor near 0.6 is that uncertainty, not a failure of training.

The noise guess is the score

Flip the noise guess around and it becomes an arrow pointing toward the data: if the noise pushed the point up and to the right, the way back is down and to the left. That arrow is the score: at any point, the direction in which the data gets more crowded fastest. A network that has learned to guess noise has learned the score at every noise level. That is why diffusion models are also called score-based models, and why this way of training is called denoising score matching.

The formula and its symbols

Symbols

Symbol Meaning here In the example
how crowded the noisy data is at point at step (its probability density) the standard bell curve
the logarithm of that density; crowdedness on a scale where multiplying becomes adding + a constant
"grad": the slope, in every direction, as moves; for one number, just the slope slope of is
the score: which way is uphill in crowdedness at
the network's noise guess 0.9
the noise share, which converts "noise" units into "distance" units 0.6
"approximately equal": exact for a perfect guesser

In words: "the direction toward the data is the noise guess, flipped and divided by the noise share."

With the numbers: take data that is already standard-normal, so every noisy version is the plain bell curve, whose score at is (the slope of ). At with , the best possible noise guess is , and the formula gives , the score itself, pointing back toward the crowd at 0.

In Python
import math
x_t, alpha_bar = 1.5, 0.64
# the best noise guess for standard-normal data: √(1 − ᾱ) · x_t
eps_hat = math.sqrt(1 - alpha_bar) * x_t
round(eps_hat, 2)  # → 0.9
# −ε̂ / √(1 − ᾱ): the score, which for the bell curve is −x
round(-eps_hat / math.sqrt(1 - alpha_bar), 2)  # → -1.5

In code: DenoiserMLP is the network, train_noise_predictor is the training loop in the diagram, and noise_to_score is the score formula. View source

Chapter 3

Step 3: sampling, running the process backwards

A trained noise guesser generates the way the sculptor works: look at the block, guess which parts are not horse, chip away a small share of them, and look again. The sculptor never chips away everything that looks wrong at once, because the guess is rough while the block is rough and improves as the shape emerges. In numbers, a point sits at at a step with and . The network guesses the noise in it is . One step back removes a scaled share of that guess, undoes the shrinking, and (except on the very last step) adds a little fresh noise.

The formula and its symbols

Symbols

Symbol Meaning here In the example
the current, noisier point 1.0
the network's noise guess, 0.5
this step's noise dose, from the schedule 0.19
how much of the guess belongs to this one step: only a sliver of all the noise was added here
undo this step's shrink
fresh standard-normal noise; 0 on the final step 0 or 0.5
a small random wobble
the slightly cleaner point 0.9, or 1.118 with the wobble

In words: "subtract this step's share of the guessed noise, scale back up, and add a small fresh wobble."

With the numbers: ; with the wobble : .

In Python
import math
x_t, eps_hat = 1.0, 0.5
beta, alpha_bar = 0.19, 0.75
# remove this step's share of the guessed noise, then undo the shrink
mean = (x_t - beta / math.sqrt(1 - alpha_bar) * eps_hat) / math.sqrt(1 - beta)
round(mean, 4)  # → 0.9
# add a small fresh wobble z
z = 0.5
round(mean + math.sqrt(beta) * z, 4)  # → 1.1179

Adding noise while removing it looks backwards, but the network's guess is an average over every clean point that could have produced . Stepping to that average every time would pull every sample toward the safe, blurry middle. The fresh wobble lets each sample commit to one possibility, so the samples spread over the whole data, as the real data does. This recipe is DDPM (denoising diffusion probabilistic models).

Figure 7 · Diagram

Reading it: the loop runs once per step, times here and 1,000 in the original paper. Each lap costs one full run of the network, so the number of laps sets the price of a sample.

Figure 8 · Chart

t = 100 t = 40 t = 20 t = 10 t = 0 Sampling: 100 small denoising steps turn noise (purple) into the blobs (grey)

Five panels of purple dots over grey blobs: a round noise cloud at step 100 is still shapeless at 40 and 20, splits into four clusters by 10, and matches the blobs at 0

Reading it: grey dots are the real data, purple dots are 600 samples being generated, shown at five moments of the backwards run. For the first half almost nothing seems to happen: the network makes coarse, whole-cloud decisions while the noise is still loud. Between steps 20 and 10 the cloud splits toward the four corners, and the last few steps tighten each group onto its blob. The network was never told there are four blobs; it learned that from guessing noise.

Fewer steps with DDIM

A hundred network calls per sample is slow. A sculptor in a hurry works differently: they picture the finished horse, rough the block out to a state only slightly less finished than that, and look again, making a few big moves instead of many small ones. DDIM samples the same way. Take the pixel from Step 1: at , and suppose the network guesses the noise perfectly, . First predict the finished value, then re-noise it to a much quieter level, , reusing the same noise guess instead of drawing new noise.

The formula and its symbols

Symbols

Symbol Meaning here In the example
the current point, at step 1.9
the network's noise guess 0.5
"x-zero hat": the predicted clean point, from undoing the shortcut 2.0
the earlier step to jump to; any step before , not just 96% signal
the signal left at steps and 0.64 and 0.96
the point after the jump: the predicted clean point, re-noised lightly 2.06

In words: "guess the finished point by undoing the shortcut, then walk back to a quieter noise level along the same noise direction, with no fresh randomness."

With the numbers: , then . Jump to and you land on itself.

In Python
import math
x_t, eps_hat = 1.9, 0.5
alpha_bar_t, alpha_bar_s = 0.64, 0.96
# x̂₀: undo the shortcut to predict the clean point
x0_hat = (x_t - math.sqrt(1 - alpha_bar_t) * eps_hat) / math.sqrt(alpha_bar_t)
round(x0_hat, 4)  # → 2.0
# x_s: re-noise it lightly, along the same noise direction
round(math.sqrt(alpha_bar_s) * x0_hat + math.sqrt(1 - alpha_bar_s) * eps_hat, 4)  # → 2.0596

This is DDIM (denoising diffusion implicit models). It uses the same trained network and changes only the sampling loop. It adds no fresh noise, so the same starting noise always gives the same sample, and it can take 20 jumps instead of 100 small steps. On the blobs, 20 DDIM jumps land about as close to the data as 100 DDPM steps. Closeness here is the two-way distance: the average of two distances, from each sample to its nearest real point and from each real point to its nearest sample, so piling every sample onto one blob cannot score well.

In code: ddpm_sample is the small-step sampler, ddim_sample the jumping one, and two_way_distance the measure of closeness. View source

The price of a sample is its number of network calls. The original DDPM used 1,000, and samplers like DDIM brought that down to about 20 to 50.

Chapter 4

Step 4: flow matching, straight paths from noise to data

Going below 20 to 50 calls needs a straighter road. A diffusion sample's path from noise to data curves, in a shape set by the noise schedule, and a sampler taking big steps cuts its corners. Flow matching draws a straight line from each noise point to a data point instead, and trains the network to report the motion along it. The network becomes a map of arrows, like a weather map of wind: at every place and time it says which way to move, and how fast. To generate, drop a noise point on the map and let it drift.

A warning about labels. From here on, as in flow-matching papers, is the noise and is the data, and time runs from 0 (noise) to 1 (data). In the diffusion chapters before, was the clean data.

Take the noise point and the data point . The straight line between them passes, a quarter of the way along, through . The speed along the line is constant: it covers the distance in one unit of time, so the velocity is 3 everywhere on it. The network is trained to output 3 when shown the point at time 0.25.

The formula and its symbols

Symbols

Symbol Meaning here In the example
a noise point (standard normal) −1
a real data point, paired with the noise at random 2
time along the line, from 0 (noise) to 1 (data), drawn at random in training 0.25
the point on the straight line at time −0.25
the velocity of that line: where to go, and how fast; the same at every 3
the network's guessed velocity at that place and time say 2.5
, squared length and average over many random draws, as in Step 2

In words: "pick a noise point, a data point and a time; find the point that far along the straight line between them; train the network to output the line's direction and speed there."

With the numbers: ; target velocity ; a guess of 2.5 scores .

In Python
x0, x1, t = -1.0, 2.0, 0.25
# (1 − t) x₀ + t x₁: the point on the straight line
x_t = (1 - t) * x0 + t * x1
x_t  # → -0.25
# x₁ − x₀: the velocity to learn
x1 - x0  # → 3.0
# a guess of 2.5 is graded by squared error
(2.5 - (x1 - x0)) ** 2  # → 0.25

To generate, start from noise at and follow the arrows in a few Euler steps (the simplest way to follow a velocity: move in a straight line for a short time, then look again):

The formula and its symbols

Symbols

Symbol Meaning here In the example
the step size in time; equal steps means 0.75
the velocity the network reports here and now 3
where you are after moving for time 2.0

In words: "move for a short time in the direction, and at the speed, the network says."

With the numbers: from , one step of at velocity 3 gives , the data point. On a straight line, one step of any size is exact, because there is no bend to cut.

In Python
x_t, v, h = -0.25, 3.0, 0.75
# x + h v: one Euler step
x_t + h * v  # → 2.0

Figure 9 · Diagram

Reading it: training (top) is the same shape as diffusion's: random choices in, a point in between, a squared-error guess. The difference is the target: a velocity along a straight line rather than hidden noise. Sampling (bottom) is a plain loop of Euler steps from to , with no schedule, no shrink factors and no fresh noise.

Training on random pairs has a catch. Many different straight lines pass through the same point (from different noise to different data), so the network cannot know which one it is on, and it learns the average of their velocities. The learned paths are therefore only roughly straight. They bend, because two paths can never cross: at any point the network gives one velocity, so two paths that met would continue together.

Figure 10 · Chart

Training: random pairs, straight lines (they cross) noise x₀ data x₁ Sampling: the learned flow (paths never cross, so they bend)

Left: 16 straight lines from noise to data that cross each other. Right: the learned flow's 16 paths from the same noise, which never cross and curve to reach the blobs

Reading it: hollow circles are noise, filled circles are where each path ends. On the left are training pairs: every line is straight, but they criss-cross because noise and data were paired at random. On the right, the learned flow starts from the same noise. Its paths never cross, so they bend to share out the blobs, mostly near the end. The straighter the paths, the fewer Euler steps you need. Rectified flow uses this: it retrains on the model's own (noise, sample) pairs, which no longer cross, and each round makes the paths straighter, until one or two steps are enough.

The same averaging explains what a single step does. With one Euler step from , every noise point moves by the average velocity toward the data in general, and lands on the data's average: the empty middle of the four blobs. Training on straight lines does not make one step enough; only straight learned paths do.

Figure 11 · Chart

1 2 3 5 10 20 50 network calls per sample 1 0 − 1 two-way distance to the data Straighter paths need fewer steps a fresh draw of the real blobs plain noise diffusion (DDIM jumps) flow matching (Euler steps)

Sample quality against the number of network calls, on log axes: at one or two calls both are about as far off as plain noise; flow matching nears the fresh-data floor by about 5 calls, diffusion by about 10

Reading it: the x-axis is network calls per sample and the y-axis is the two-way distance between samples and data (lower is better). The green floor is a fresh draw of the real blobs, as good as samples can get; the grey line is plain noise. At one or two calls neither method does much better than noise. Flow matching (teal) gets close to the floor within about 5 calls, while diffusion's DDIM jumps (purple) need about 10 to get as close. Both had the same network size and training time, so the straighter paths alone account for needing roughly half the steps.

In code: train_velocity_predictor trains the velocity network, euler_sample follows it, and step_sweep measures both methods at each step count. View source

Flow matching also has no noise schedule to tune. Stable Diffusion 3 is trained as a rectified flow. Underneath, flow matching belongs to the same family as diffusion: a network trained by squared error to point from noise toward data, followed step by step.

Chapter 5

Step 5: conditioning and guidance, generating what you asked for

So far the generator makes a dot in whichever blob its noise leads to. To ask for a particular corner, it needs conditioning: the label goes into the network as an extra input. Our labels are four corners, given as a one-hot vector (all zeros except a 1 in the chosen slot), plus a fifth slot that means "no label". A text-to-image model does the same with a sentence in place of a corner name.

Classifier-free guidance goes further by comparing two guesses: the network's noise guess when told the label, and its guess without it. One network learns both. In training, the label is hidden (replaced by "no label") on a random 20% of examples. At sampling time the network is asked twice per step, once with the label and once without, and the sampler pushes past the labelled guess, further in the direction the label moved it.

Say that at some point during sampling the guess without the label is and the guess with the label "south-west" is . The label moves the guess by . With guidance weight , move three times as far.

The formula and its symbols

Symbols

Symbol Meaning here In the example
the noise guess with the label hidden (, "empty set", stands for "no label") 0.2
the noise guess given the label 0.5
what the label changes: the direction "more like " 0.3
the guidance weight (or guidance scale): 0 ignores the label, 1 is the plain labelled guess, above 1 exaggerates 3
"epsilon tilde": the guided guess, used in place of by the sampler 1.1

In words: "start from the unlabelled guess and move times as far as the label would move it."

With the numbers: . With it is 0.2 (the label is ignored); with it is 0.5 (exactly the labelled guess).

In Python
eps_uncond, eps_cond = 0.2, 0.5
# ε̃ = ε̂_∅ + w (ε̂_c − ε̂_∅), for w = 0, 1 and 3
[round(eps_uncond + w * (eps_cond - eps_uncond), 2) for w in (0, 1, 3)]  # → [0.2, 0.5, 1.1]

Figure 12 · Diagram

Reading it: each step runs the same network twice, once with the label hidden and once with it shown, which doubles the cost of a step. The two guesses meet in the mixing box, and only the mixed guess reaches the sampler, which is otherwise unchanged. No second network is trained: the weight is a choice made at sampling time.

Figure 13 · Chart

w = 0: 27% south-west spread 0.72 w = 1: 100% south-west spread 0.27 w = 3: 100% south-west spread 0.14 Classifier-free guidance, asking for "south-west"

Three panels of 400 green samples asked to be south-west: at w = 0 they spread over all four blobs (27% south-west); at w = 1 all land on the south-west blob with spread 0.27; at w = 3 they bunch into a tight knot at its outer edge

Reading it: grey dots are the data, green dots are samples asked for "south-west" at three guidance weights. At the label is ignored, so samples land in all four corners, only about a quarter in the south-west. At nearly all land in the right blob with roughly the real blob's spread. At they are all on target but bunched into a tight knot, pushed to the side of the blob farthest from the other blobs: the most unmistakably south-west spot. Raising the weight trades variety for being on target, and past a point it exaggerates.

In code: guided_noise is the formula, and guidance_sweep measures the share on target and the spread at each weight. View source

The "guidance scale" setting in image tools is this . Text-to-image systems run it well above 1, because unguided samples follow the prompt only loosely. Set too high, it makes images oversaturated and alike, the image version of the tight knot.

Chapter 6

Step 6: scaling up to real images, video and audio

Everything so far ran on dots of two numbers. A 512 × 512 colour image is numbers, and the denoiser would run on all of them at every step. Latent diffusion works on a much smaller code of the image, its latent, instead. An autoencoder (a network that squeezes an image into a small code and rebuilds it; see Autoencoders and VAEs) shrinks each side by 8 and keeps 4 numbers per position: numbers. The denoiser now works on 48 times fewer numbers, and every one of its many steps is that much cheaper.

The formula and its symbols

Symbols

Symbol Meaning here In the example
image height and width in pixels 512, 512
3 colour channels: red, green, blue 3
how much the autoencoder shrinks each side 8
numbers kept per latent position (latent channels) 4
shrink factor how many times fewer numbers the denoiser handles 48

In words: "count the numbers in the image, count the numbers in its latent code, and divide."

With the numbers: . The latent is then cut into 2 × 2 patches, each patch becoming one token for a transformer: tokens. A 16-frame video clip in the same latent space is 16 times that, 16,384 tokens, and since attention compares every token with every other (Attention), it costs times as much.

In Python
H, W, f, c = 512, 512, 8, 4
pixels = H * W * 3
latents = (H // f) * (W // f) * c
pixels, latents  # → (786432, 16384)
# shrink factor
pixels / latents  # → 48.0
# 2 × 2 patches of the 64 × 64 latent: the transformer's tokens
tokens = (64 // 2) * (64 // 2)
tokens  # → 1024
# 16 video frames: 16× the tokens, 256× the attention pairs
(16 * tokens) ** 2 // tokens ** 2  # → 256

Figure 14 · Diagram

Reading it: follow the noise from the left. It is not an image but a small latent, and all the sampling steps (the loop on the denoiser box) happen in that cheap space. The prompt takes the upper path: a text encoder, such as CLIP's text half (Training embedding models), turns it into token vectors that the denoiser reads through cross-attention (attention whose queries come from the image patches and whose keys and values come from the text tokens). Guidance's "no label" answer is an empty prompt. Only at the very end does the decoder turn the latent into pixels, once.

The same recipe has grown in three directions:

  • The denoiser became a transformer. Early systems used a U-Net (a convolutional network, CNNs and RNNs); the diffusion transformer (DiT) cuts the latent into patches and treats them as tokens, so the scaling lessons of language models carry over.
  • Video adds a time axis: the latent is a stack of frames, and patches span space and time. It is the same denoising, with far more tokens.
  • Audio is denoised as a spectrogram (a picture of sound: time across, pitch up, loudness as brightness) or as an audio autoencoder's latent.

Compared with the other generators in this part:

GAN (GANs) VAE (Autoencoders and VAEs) Diffusion and flow matching
Training a generator against a critic: unstable reconstruct plus stay near a simple code: stable squared error on noise or velocity: stable
Samples sharp often blurry sharp
Covers all of the data? can mode collapse (ignore whole regions) yes yes
Cost of one sample one network call one network call 5 to 50 network calls

In code: latent_shrink and patch_tokens do the counting above. View source

What stays expensive is the number of network calls per sample. DDIM, flow matching and distillation (training a second network to reach in a few steps what the first reaches in many) all aim to cut it.

Test yourself

7 questions

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

Question 1Why does the network learn to guess the noise, rather than the clean picture?Think it through, then reveal

The two carry the same information: given the noisy point, the step and the noise, the clean point follows by undoing the shortcut. Guessing the noise works better in practice because the target is always the same size (a standard-normal draw) at every step, which makes one network easy to train across all noise levels. The noise guess, flipped and rescaled, is also the score: the direction toward the data.

Question 2Training only ever takes one jump from clean to noisy. Why does generation need many steps back?Think it through, then reveal

The noise guess is an average over every clean point that could have produced the noisy one. From heavy noise that average is vague, pointing at the middle of the data, so one big step lands on a blur (or, in our blobs, the empty middle). Small steps let the guess sharpen as the sample commits to one specific region, and the network is asked again at every stage.

Question 3Why does DDPM add fresh noise at each step, when the goal is to remove noise?Think it through, then reveal

Without it, every step moves toward the network's averaged guess and samples drift toward safe, typical, blurry results. The small fresh wobble keeps each sample exploring one specific possibility, so the samples cover all of the data. DDIM drops the wobble on purpose, trading that randomness for determinism and big jumps.

Question 4What does flow matching change, and why can it get away with fewer steps?Think it through, then reveal

It replaces the noise schedule with straight lines from noise to data and trains the network to output the velocity along them. Following a velocity with Euler steps is only exact on straight paths; the learned paths are straighter than diffusion's, so fewer steps cut fewer corners. They are not perfectly straight, because paths can't cross, which is what rectified flow's retraining fixes.

Question 5What does the guidance weight do, and what goes wrong if it is too large?Think it through, then reveal

It sets how far past the labelled guess to go, along the direction from the unlabelled guess to the labelled one. 0 ignores the prompt, 1 follows it plainly, above 1 exaggerates it, so samples match the prompt more reliably. Too large and samples become samey, over-saturated caricatures of the prompt, bunched into the most extreme examples.

Question 6Why do real image generators denoise in a latent space instead of on pixels?Think it through, then reveal

Most of an image's pixel values are fine texture that a decoder can fill in. An autoencoder shrinks a 512 × 512 image 48-fold into a latent that keeps the meaningful structure, and since sampling runs the denoiser dozens of times, every step becomes that much cheaper. The decoder runs just once, at the end.

Question 7When would you choose a GAN over a diffusion model?Think it through, then reveal

When one-shot speed matters most: a GAN makes a sample in a single network call, where diffusion needs several to dozens. Diffusion wins on training stability and on covering all of the data (GANs can mode-collapse), which is why it took over image generation; distillation is now closing its speed gap.

Primary sources

The papers behind this lesson

Sohl-Dickstein et al., Deep Unsupervised Learning using Nonequilibrium Thermodynamics (2015)

The original idea: destroy data slowly with noise, and learn to reverse the destruction.

The paper
Song and Ermon, Generative Modeling by Estimating Gradients of the Data Distribution (2019)

Generated samples by learning the score at many noise levels and following it.

The paper
Ho, Jain and Abbeel, Denoising Diffusion Probabilistic Models (2020)

The simple "guess the noise" loss and the sampler of Step 3, with the first high-quality image results.

Read on rumblr →The paper
Song, Meng and Ermon, Denoising Diffusion Implicit Models (2020)

Deterministic sampling with big jumps, using the same trained network.

Read on rumblr →The paper
Song et al., Score-Based Generative Modeling through Stochastic Differential Equations (2020)

Showed diffusion and score-based models are one family, described as continuous time processes.

Read on rumblr →The paper
Ho and Salimans, Classifier-Free Diffusion Guidance (2022)

Guidance from one network trained with and without the label, no separate classifier needed.

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

Denoising in an autoencoder's latent space, with text via cross-attention: the basis of Stable Diffusion.

Read on rumblr →The paper
Peebles and Xie, Scalable Diffusion Models with Transformers (2022)

Replaced the U-Net with a transformer over latent patches, and showed it improves with scale.

Read on rumblr →The paper
Lipman et al., Flow Matching for Generative Modeling (2022)

Trained continuous flows by regressing velocities along simple paths from noise to data.

Read on rumblr →The paper
Liu, Gong and Liu, Flow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow (2022)

Straight-line paths, and retraining on the model's own pairs to straighten the learned flow for few-step sampling.

Read on rumblr →The paper
Esser et al., Scaling Rectified Flow Transformers for High-Resolution Image Synthesis (2024)

Rectified flow with a transformer denoiser at scale: Stable Diffusion 3.

The paper

Researcher's shelf

Further reading

  • Ho, Jain and Abbeel, Denoising Diffusion Probabilistic Models (2020): https://arxiv.org/abs/2006.11239
  • Song, Meng and Ermon, Denoising Diffusion Implicit Models (2020): https://arxiv.org/abs/2010.02502
  • Ho and Salimans, Classifier-Free Diffusion Guidance (2022): https://arxiv.org/abs/2207.12598
  • Lipman et al., Flow Matching for Generative Modeling (2022): https://arxiv.org/abs/2210.02747
  • Liu, Gong and Liu, Rectified Flow (2022): https://arxiv.org/abs/2209.03003
  • Rombach et al., Latent Diffusion Models (2021): https://arxiv.org/abs/2112.10752
  • Peebles and Xie, Diffusion Transformers (2022): https://arxiv.org/abs/2212.09748
  • Lilian Weng, What are Diffusion Models?: https://lilianweng.github.io/posts/2021-07-11-diffusion-models/
  • Hugging Face, The Annotated Diffusion Model (DDPM, line by line in code): https://huggingface.co/blog/annotated-diffusion
  • Hugging Face Diffusers documentation: https://huggingface.co/docs/diffusers/index

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.