Act IV · Generation and Perception
Part 21 of 31Diffusion and Flow
How does a model turn pure noise into data, and how few steps can it take?
The part opens with a denoiser trained on the computer walking 300 points from noise into the letters 'AI'. The data are those letters made into a mixture of 400 small Gaussians, so the score, the best denoiser and the flow's velocity are known exactly and every learned thing is measured against the truth. The forward process destroys data slowly and has a closed form; the variational bound turns into weighted errors of a noise guess, Tweedie's formula says the best guess is the score, and Vincent's theorem says plain regression learns it. Time is then run backwards with Anderson's reverse SDE or the probability-flow ODE, and DDPM, DDIM, EDM's Heun steps and DPM-Solver are compared by evaluations spent. The part turns from following a curved path in many steps to straightening it: flow matching regresses on straight-line velocities, reflow straightens the pairs, and distillation, consistency models and MeanFlow reach one step. Guidance turns a request into a push on the score. It ends with noise replaced by blanks: masked diffusion's bound is a weighted cross-entropy, and a masked-diffusion language model of the series' own is put on the scoreboard beside an autoregressive model of the same size.
What you need. Multivariable calculus and Gaussian algebra; the Ornstein-Uhlenbeck process and Fokker-Planck equation of Part 5, and Langevin sampling from Part 20.
- Mathematics and history
- score matching, the reverse SDE, DDPM/DDIM, EDM, flow matching, reflow, distillation, guidance, discrete diffusion
- Models, data
- LLaDA
What you will be able to do
Undergraduate
- Describe the forward process and compute how much signal and noise are left after t steps.
- Explain in words why learning to guess the noise is enough to walk from noise back to data, and what the guidance weight w does to a sample.
Master's
- Derive the forward closed form, Tweedie's formula, and the equality of denoising and explicit score matching up to a constant.
- Derive DDIM's step and show it is Euler's method in (x/alpha, sigma/alpha).
- Derive flow matching's marginal velocity and classifier-free guidance's tilted density.
Research
- Prove the marginal-field theorem of flow matching and relate its straight paths to the Benamou-Brenier optimum.
- Derive masked diffusion's bound as a weighted cross-entropy and as an any-order autoregressive loss, and state what the bound does and does not say about likelihood.
Engineering
- Choose a sampler, a step spacing and a noise schedule for a budget of network evaluations, and measure the result against a many-step reference.
- Distil a many-step sampler to a few steps, and report what guidance costs in recall for what it gains in precision.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 13 min · Master's 46 min · Research 55 min · Engineering 26 min.
- 0From noiseUndergraduate2 min
- 1Destroying data slowlyUndergraduate3 min
- 2The bound, and guessing the noiseMaster's3 min
- 3Tweedie's formulaMaster's3 min
- 4Denoising score matchingMaster's3 min
- 5Running time backwardsMaster's3 min
- 6DDPM and DDIMMaster's2 min
- 7Noise schedulesEngineering2 min
- 8EDM: preconditioning and HeunMaster's3 min
- 9DPM-Solver: an exact linear partEngineering3 min
- 10Optimal transport and flow matchingResearch3 min
- 11Rectified flow and reflowMaster's2 min
- 12DistillationEngineering3 min
- 13One step from scratchResearch2 min
- 14GuidanceUndergraduate3 min
- 15From points to picturesUndergraduate2 min
- 16Diffusion for discrete dataResearch3 min
- 17Diffusion language modelsEngineering5 min
- Recap, problems, and what comes nextAll tracks2 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
From noiseUndergraduate2 min
Noise: three hundred random points. A network, trained on this computer, nudges each one a little, fifty times. Part 20 ended with Langevin dynamics: walk uphill on the score, the slope of the data's log-density, with noise turned down level by level. Here the network has learned that slope at every noise level, from examples alone.
How we got here. In 2015 Jascha Sohl-Dickstein and colleagues borrowed an idea from physics: destroy the structure in data slowly, with noise, and learn to run the destruction backwards. In 2019 Yang Song and Stefano Ermon learned the score at many noise levels; in 2020 Jonathan Ho, Ajay Jain and Pieter Abbeel made the recipe simple: just guess the noise. In 2021 one framework joined them, and diffusion overtook GANs. In 2022 latent diffusion became Stable Diffusion, released with open weights; then transformers became the denoisers, straight-line flows trained the image models of 2024, and video followed; by 2025 the same idea was writing text, and in 2026 Google released an open diffusion language model.
This is Part 21 of AI, Built: diffusion and flow. In this part: the forward process and the bound that trains the reverse; why guessing the noise is learning the score; running time backwards, with a stochastic equation or a deterministic one, and the samplers that solve them; the design choices, from noise schedules to EDM and DPM-Solver; flow matching and optimal transport; how to get from fifty steps to one; how to ask for something specific; and diffusion for text, with a language model of our own on the scoreboard. Our toy models in this part are trained on this computer.
1Destroying data slowlyUndergraduate3 min
Annealed Langevin, at the end of Part 20, needs the score at every level of noise. Where do the levels come from? From a process that destroys the data on purpose. Take every point, shrink it a little towards the origin, and add a little Gaussian noise. Do it a thousand times. The shrinking keeps the spread from growing; the noise erases the letters, a little at each step, until only a round bell of noise is left. That is the forward process. It has no parameters: nothing in it is learned.
You don't have to run the thousand steps to know where a point ends up. Write one step: the point shrunk, plus fresh noise. Substitute the step before it. The two noises are independent Gaussians, so their sum is one Gaussian whose variance is the sum of theirs. Keep going down to the clean point, and the whole chain collapses into a single jump: the data shrunk by the square root of alpha bar, plus noise of variance one minus alpha bar, where alpha bar is the product of all the shrink factors. So training can sample any noise level at once, without simulating the chain.
Check it on our letters. Run twenty thousand points through all thousand steps, and at moments regress where they are on where they started. The slope should be the square root of alpha bar: at step 500 it is , the formula says . The leftover variance should be one minus alpha bar: against . The largest gap anywhere is , After all thousand steps, alpha bar is times ten to the minus : what is left of a point is of it.
One more fact, and the model's job is defined. Run a step backwards, and suppose you knew the clean point. Bayes says the previous point's distribution is the forward step times the jump to step t minus one: both Gaussian in the previous point, so completing the square gives a Gaussian, whose mean blends the clean point and the noisy one. In continuous time, write alpha for the shrink and sigma for the noise: their squares add to one. Ours is a quarter circle, cosine and sine, the forward process of Part 5's Ornstein-Uhlenbeck chapter run on a clock. Every step back is a known Gaussian, if you know where you started. The model has to manage without.
2The bound, and guessing the noiseMaster's3 min
Part 20's variational autoencoder had a code and a bound. Here the codes are the noisy versions, x one to x T, and the encoder is the forward process, fixed. The decoder runs the chain backwards, each step a Gaussian whose mean a network chooses. Jensen's inequality gives the same bound on the log-likelihood as before. Both chains are products of their steps, so the bound is a sum over steps. Now use the last chapter's fact: rewrite each forward step by Bayes, given the clean point. The extra jumps cancel in pairs, and what is left is a sum of KL divergences, one per step: how far the network's step back is from the true step back, given the clean point.
Each KL term compares two Gaussians. With fixed variances, the part that depends on the network is the squared distance between their means; the remaining constant does not depend on theta. Write the true mean in terms of the noisy point and the noise that made it, by substituting for the clean point. That suggests the parameterization Ho, Jain and Abbeel chose in 2020: let the network output a guess of the noise, and build its mean the same way. Then the network-dependent part of each intermediate Gaussian KL is a weight lambda t times the squared error of the noise guess. Training a diffusion model is a regression: look at a noisy point, say what noise was added.
How big are the weights? For DDPM's schedule, with the step's variance set to beta, lambda falls from 0.50 at the first step to 0.010 at the last, a factor of 49: the bound cares most about the nearly clean steps. Ho and colleagues found that dropping the weights altogether, every step counted the same, gave better pictures: an FID of 3.17 on CIFAR-10, the best of its day. That is the simple loss, and almost every diffusion model since has trained on a loss like it. The exact weighting returns in chapter seven: it is a choice of which noise levels to practise most.
Here is our own denoiser learning on the letters, trained with the simple loss, a noise level drawn at random for each of its examples. At each checkpoint we stop, and draw points from the same noise. Untrained, it flings them to the edges. By step the letters can be read. The rest is refinement: the loss barely moves, but the strokes sharpen, the distance from the data going from to , . Every step of training only asked for the noise in one blurred point; the letters emerge from millions of those guesses.
3Tweedie's formulaMaster's3 min
A noisy point could have come from many clean ones. Here is a one-dimensional data distribution, two bumps. We see a noisy value, x t, at a moderate noise level. Bayes gives the distribution of the clean value it came from: wide, because the noise is wide, and pulled towards the bumps. The guess with the smallest expected squared error is the average of this distribution, the posterior mean. That is what a network trained by squared error learns to output, if it can. Move the noisy value, and the posterior mean slides between the bumps, never quite reaching either.
That average has a formula. Herbert Robbins published it in 1956, crediting Maurice Tweedie: the posterior mean is the noisy point plus sigma squared times the score, divided by alpha. The proof is three lines. The noised density is a blur of the clean one. Differentiate under the integral: only the Gaussian depends on x. Divide by the density, and Bayes turns the integral into the posterior mean. Now the noise. The best guess of the noise is the noisy point minus alpha times the best clean point, over sigma: minus sigma times the score. A network trained to guess the noise is learning the score. That is why diffusion works.
Check it. In one dimension, compute the posterior mean by brute force, integrating over a fine grid, and compare it with Tweedie's formula, using the exact score. They agree to decimal places: the formula is exact. In two dimensions, on our letters, estimate each posterior mean by Monte Carlo, weighting fifty thousand clean points by how likely each is to have produced the noisy one. The estimates land within of the formula, on average.
What does the best denoiser do with very noisy points? Here are its guesses for five hundred noisy points, at four noise levels. At high noise every guess is near the middle of the letters: the average letter, with a squared error of 1.57. As the noise falls, the guesses spread onto the strokes, and the error drops to 0.078. So you cannot use this posterior-mean denoiser alone to turn pure noise into a sample in one step: its best guess is a blur. Samplers take many small steps instead, re-guessing as the noise falls: chapters five and six.
4Denoising score matchingMaster's3 min
Tweedie says the network should learn the score. But nobody gives us the score of real images to fit. In 2005 Aapo Hyvarinen faced this for energy models: fit a function s to the score, by squared error, when the target is unknown. Integrating by parts removes the target: what is left is the trace of the Jacobian of s, plus its squared length, averaged over the data. But a naive exact trace costs one backward pass per dimension: for one colour image of 512 by 512 pixels, 786,432 of them, for every training example. Random-projection estimators can reduce that cost.
In 2011 Pascal Vincent found the way around. Add noise to each example, and fit the score of the noise itself, which we know exactly. The theorem: that loss equals the loss against the score of the whole noised data, plus a constant. Here is why. Expand the square on the left. The only term that could differ is the cross term. Write the noised data's score as its gradient over itself; the noised data is an average of noise around each example, so its gradient is an average of theirs; and that is the left side's cross term. Everything else is a constant. And the score of the added noise is minus the noise over sigma: fitting it is chapter two's noise guessing, exactly.
Our letters let us check the theorem directly, because there the exact score is known. Take our denoiser at each checkpoint of its training, at the lowest noise level, t equal to 0.1. The white curve is the loss on fresh noise. The grey line is the constant: the loss that even the exact score would have, because the noise in a noisy point can't be fully recovered. The orange curve is the network's error against the exact score, measured directly. The theorem equates expectations. Our finite-sample loss minus constant estimates the error: at the end, 29.1103 minus 28.1390 against 0.8630. The cross term has magnitude up to 0.1159 at the end of training across 3 seeds; it explains the measured gap. The loss never reaches zero, and doesn't have to: the gap above the constant is the part training can remove.
Where is the score hardest to learn? At the end of training, the error is largest at t equal to and smallest at : In 2019 Yang Song and Stefano Ermon trained one network for many noise levels this way, and sampled with Part 20's annealed Langevin. Denoising, at every noise level, by plain regression: that is what every diffusion model learns.
5Running time backwardsMaster's3 min
In 2021 Yang Song and colleagues let the number of steps go to infinity. The chain of small shrinks and small kicks becomes a stochastic differential equation: a drift towards the origin, and Brownian motion, Part 5's Ornstein-Uhlenbeck process with a rate that rises over time. Run it, and the letters dissolve into a bell of noise.
In 1982 Brian Anderson showed that such a diffusion has a reverse in time that is also a diffusion: the same shrink and kicks, plus a push up the score of the noised data at that moment. The score is the only thing in it we don't know, and the last three chapters showed how a network learns it. Here it is run with the exact score of our letters: noise flows back into the letters, each point jittering all the way.
There is a second way back, with no randomness at all. Start from Part 5's Fokker-Planck equation for the density: the drift moves it, the noise spreads it. The spreading term can be rewritten, because the gradient of p is p times the gradient of log p. Now both terms are a divergence of something times p: a continuity equation, the law of a fluid whose particles move with a velocity field. So particles that simply follow this velocity, with no noise at all, have exactly the same density at every moment as the noisy ones. Song and colleagues called it the probability-flow ODE: one more use for the same score.
Here are both, run with the exact score from the same forty starting points. The SDE's paths wander: joining fifty recorded segments, on average each is long. The ODE's glide, . They end at different places. But measure the whole clouds against fresh samples of the true density, at every time. And the ODE can be run both ways: from data to noise and back, with mean return error : an approximately inverted numerical map. The ideal ODE is Part 20's continuous normalizing flow; its likelihood requires a divergence integral. One learned score, two ways back; the next chapters are about solving them in as few steps as possible.
6DDPM and DDIMMaster's2 min
Two ways to discretize the walk back, with our trained denoiser. DDPM, the 2020 recipe, discretizes the reverse SDE: at each step it guesses the clean point, steps to the Gaussian of chapter one, and adds a little fresh noise. Its paths wander, like the Brownian motion they reverse. DDIM, a year later, adds no noise at all: each point glides to a fixed destination, and in far fewer steps.
DDIM's step is two lines. From the noisy point, the network's noise guess gives a guess of the clean point, by Tweedie. To step to a lower noise level, put the clean guess back with less noise, keeping the noise's direction: the same noise, smaller. Divide by alpha, and the step is exactly one Euler step of the probability-flow ODE, in the coordinates x over alpha and sigma over alpha. Song, Meng and Ermon derived it from a different forward process with the same marginals, and gave it a knob, eta: at zero, no noise, the ODE; at one, DDPM again. The network doesn't change, only the sampler.
How few steps will do? Measure how far the samples land from the data, with the sliced Wasserstein distance: drop both clouds onto many random lines, and compare where their points fall. With five DDIM steps the letters are blurred, at ; at a hundred, , against a sampling baseline of for a fresh sample of the data itself. Each step is one run of the network, so fewer steps is faster pictures. The paths are curved, and curved paths need many small steps: the next three chapters are about taking fewer.
7Noise schedulesEngineering2 min
A noise schedule says how much signal survives at each time. Its one number is the signal-to-noise ratio, alpha squared over sigma squared, best seen on a log scale. DDPM's linear betas, the cosine schedule of Alex Nichol and Prafulla Dhariwal, ours, and flow matching's straight line all run from plenty of signal to almost none, at different speeds. One detail matters: DDPM's last step still has a log signal-to-noise ratio of -10.1, not minus infinity. In 2024 Shanchuan Lin and colleagues identified a mismatch between nonzero terminal training SNR and pure-noise inference. In Stable Diffusion this restricted the brightness range; they proposed zero terminal SNR along with training and sampler fixes.
Does the schedule change what is being learned? In 2021 Diederik Kingma, Tim Salimans, Ben Poole and Jonathan Ho took the bound to continuous time: an integral over time of the clean-point error, weighted by how fast the signal-to-noise ratio falls. Change the variable to the ratio itself. With the denoiser expressed as a function of this ratio, monotone schedules with the same endpoints give the same continuous-time bound. This compares reparameterized denoisers, not unchanged weights under a new time input. What the schedule does change is practice: with time drawn uniformly, each schedule visits the noise levels with a different frequency, changing which levels supply the gradient updates. EDM, in the next chapter, skips the schedule and draws noise levels from a log-normal directly.
We trained the same noise-guessing network four ways, changing only which noise levels it practises: the same budget, seeds each. Because our letters' exact denoiser is known, we can compare each error across noise levels. At the highest noise, is the furthest off and the closest among these runs.
The schedule also decides where a sampler puts its steps. Here are three samplers, with the exact denoiser, at the same budget of about sixteen network evaluations, on four spacings of the noise levels.
8EDM: preconditioning and HeunMaster's3 min
By 2022 there were many diffusion models, each with its own schedule, parameterization and sampler. Tero Karras and colleagues at NVIDIA pulled them apart. Drop the shrinking: let x be the clean point plus noise of size sigma, with sigma running from eighty down to almost nothing. Tweedie, with alpha equal to one, says the score is the denoiser's correction over sigma squared. And the probability-flow ODE becomes very plain: the rate of change of x with sigma is x minus its denoised version, over sigma. Everything, every schedule and parameterization, is a way of computing the denoiser D.
Their first idea is preconditioning: wrap the network so that its job looks the same at every noise level. Write the denoiser as a skip connection plus a scaled network. Scale the input to unit variance, choose the skip so that the network's errors are magnified as little as possible, and then the output scale that makes the target have unit variance too. Why it matters: predict the noise, and an error in the output moves the clean guess by sigma times as much, eighty times at the top. Predict the clean point, and the network must output the whole answer even at almost no noise. EDM's output error-amplification factor is bounded by both sigma and the data spread. On our letters, with a data spread sigma d of 0.90, its target's spread stays between 0.97 and 1.00 at every noise level.
We tested it: the same network, the same noise levels from EDM's log-normal, the same budget, three ways of reading its output, seeds each. Against the exact denoiser, at the highest noise, is furthest off; at the lowest, . After sampling, lands closest to the data on average.
Their second idea is the solver. Euler's method follows the slope at the start of the step, and on a curved path it overshoots. Heun's method takes that Euler step, measures the slope where it lands, and redoes the step with the average of the two slopes: second order, so halving the step cuts the error by four, for two network evaluations a step. EDM's last step is plain Euler. On our letters, at evaluations the Euler-to-Heun error ratio is , and at , . With these two ideas and a careful spacing of the steps, Karras and colleagues reached an FID of 1.79 on CIFAR-10 with thirty-five evaluations.
9DPM-Solver: an exact linear partEngineering3 min
In 2022 Cheng Lu and colleagues at Tsinghua noticed that the ODE has a part that needs no network. The x over sigma term is linear in x, and can be solved exactly, the way you solve a linear equation with an integrating factor. What is left is an integral of the denoiser over the step, weighted by an exponential in lambda, minus the log of sigma. Only that integral needs approximating. Methods like this are called exponential integrators. Hold the denoiser fixed over the step, and out comes exactly DDIM's update. So DDIM was already the first-order exponential integrator; it is exact whenever the clean guess doesn't change during the step.
To do better, approximate how the denoiser changes over the step. DPM-Solver-2 uses a midpoint evaluation. Our data-prediction update is the DPM-Solver plus plus two S variant; it uses the denoiser halfway through the step in lambda. DPM-Solver plus plus, in its two-step multistep form, spends nothing extra: it reuses the denoiser from the previous step and extends the line through the two. One network evaluation per step, second order. On CIFAR-10 the first version reached an FID of 4.70 in ten evaluations, and 2.87 in twenty; the multistep form ships in the common diffusion libraries.
Here is the whole family on our letters, run with the exact denoiser so that the only error is the solver's, all on EDM's spacing, from the same noise. The error is measured against the high-resolution reference of the ODE. On log scales, a first-order method's line has slope minus one, a second-order method's minus two. With about eight evaluations the best is , at . With about thirty-two, is times more accurate than DDIM.
Here are three of them after about evaluations, beside the high-resolution reference. and a high-resolution solve of the network's ODE lands from the data, against for a fresh sample of the letters. Ten to thirty evaluations, then, with a solver that knows the equation. Fewer than that needs a different idea: chapter twelve.
10Optimal transport and flow matchingResearch3 min
Step back to an older question. In 1781 Gaspard Monge asked how to move a pile of earth into a hole with the least work. Pair every bit of noise with a bit of data so that the average squared distance moved is as small as possible: Leonid Kantorovich's 1942 version, and its minimum is the squared Wasserstein distance of Part 20. In 2000 Jean-David Benamou and Yann Brenier wrote the same problem as a flow: of every velocity field that carries one density into the other, find the one with the least kinetic energy. The answer moves every particle in a straight line at constant speed, and the lines never cross.
Flow matching borrows the straight lines without solving the transport problem. Three groups proposed it at once, in 2023: Yaron Lipman and colleagues at Meta, Xingchao Liu and colleagues in Texas, and Michael Albergo and Eric Vanden-Eijnden in New York. Pair noise and data at random, join each pair with a straight line, and the pair's velocity is simply data minus noise. But these lines cross, and a flow can't: at a crossing a particle would need two velocities. The theorem that saves it: the density at time tau is an average over pairs, each moving at its own velocity, so it obeys the continuity equation with the average velocity at each point: the expected data-minus-noise, given that a line passes through x. And regressing on the pairs' velocities learns exactly that average, the same trick as denoising score matching.
On our letters this average velocity is known exactly. Here it is at four moments: early on, everything heads for the middle; late, each point heads for its nearest stroke. Follow it from noise, and compare the particles with the straight-line interpolation of random pairs at the same time. But look at the paths: they bend, with a straightness of . And the cost: Its kinetic energy, , is far above its cost: the paths are curved and the speed uneven. Flow matching is not optimal transport; it is a good start.
Albergo and Vanden-Eijnden's framing makes the family clear: a stochastic interpolant mixes noise and data with any two coefficient curves, plus optional noise. Flow matching's straight line is one choice; a diffusion model's quarter circle, cosine and sine, is another, and the same average-velocity argument turns either into a flow. Straight lines between pairs do not make straight flows. The bends come from averaging over random pairings; to straighten the flow, change the pairing. That is the next chapter.
11Rectified flow and reflowMaster's2 min
Here is a flow-matching network learning our letters, from the same noise at each checkpoint. The loss falls fast and then stalls, well above zero. It can't reach zero: random pairs give every point many velocities, and the network can only learn their average. And its paths bend: straightness 0.52, in 3 seeds from 0.51 to 0.52.
Xingchao Liu, Chengyue Gong and Qiang Liu called the fix reflow. Run the trained flow, and pair each noise point with where the flow actually takes it. The ODE gives a deterministic pairing. Train a second flow on the straight lines between those endpoints; these chords can still cross. For ideal exact rectification they proved that convex transport costs never increase, and that repeating it straightens the paths. On our letters, once, and twice.
Measured, with the same update budget per trained network, three seeds each: the distance from the data after a given number of Euler steps. Plain flow matching needs many steps: in one step its samples land from the data, against for the noise itself. the best single step is 's, at , Straightness measures geometry. One Euler step is exact on a path with constant velocity; straight geometry alone is insufficient. Teachers and reflow pairing add compute.
Here is what one step looks like on our letters, from each of the four. In practice: InstaFlow, in 2023, combined reflow with distillation to make Stable Diffusion draw in one step. Stable Diffusion 3 and FLUX one, in 2024, were trained as rectified flows, straight lines between noise and data, with the architecture that is Part 22's story.
12DistillationEngineering3 min
Solvers can only do so much: a curved path needs steps. Distillation changes the network instead. A slow teacher's results become the targets that a fast student learns to hit. Tim Salimans and Jonathan Ho's progressive distillation, in 2022: a student learns to do two of the teacher's steps in one; then it becomes the teacher, and the steps halve again. They went from thousands of steps to four, with an FID of 3.0 on CIFAR-10. Ours starts from our flow-matching teacher at steps and halves times, training steps a round.
Consistency models, from Yang Song, Prafulla Dhariwal, Mark Chen and Ilya Sutskever in 2023, skip the rounds. Teach a network to send every point on an ODE path straight to the path's end. Then any point, including pure noise, is one jump from a sample. Build in the boundary: at the data end, the jump is nothing. And train self-consistency: a point's jump must match the jump from one teacher step further along, with that target held fixed. Ours, distilled from the same teacher, one jump from the same noise during training: it ends 0.040 from the data, on average over 3 seeds. In 2024 Cheng Lu and Yang Song made the continuous-time version stable at scale: two steps, an FID of 1.88 on ImageNet at 512 pixels.
A third way matches distributions rather than paths. Tianwei Yin and colleagues' distribution matching distillation trains a one-step generator so that, blurred to every noise level, its samples look like the teacher's. At each noise level, differentiate through the noised sample, including its noise-map Jacobian. The gradient is the difference of two scores: the generator's own distribution's, minus the real one's. The real score is the teacher. The fake score comes from a second diffusion model, trained all along on the generator's latest samples. Ours: the generator starts as the teacher's single blurry step and is pushed, sample by sample, onto the letters: 0.053 from the data at the end, over 3 seeds. Our demonstration uses a normalized score-difference adaptation. Published DMD also used teacher-output regression and reached an FID of 2.62 on 64-pixel ImageNet. DMD2 revised the training, including a GAN loss, and reached 1.28 with a longer budget.
Side by side, one step from the same noise. The teacher's own single step is a blur, from the data. The budgets differ, as they do in practice, and on images the ranking depends on scale and care. Many of today's fastest image models are distilled; FLUX one's quickest version, for one, by an adversarial form of distillation, in one to four steps. All of them need a teacher. Can a model be one-step from scratch?
13One step from scratchResearch2 min
In 2025 Zhengyang Geng, Kaiming He and colleagues trained a one-step model with no teacher at all. Here is one point's path under our flow model: it bends. Flow matching learns v, the velocity at each moment, so it has to take many small steps. MeanFlow learns u instead: the average velocity between two times s and t, like the average speed over a trip rather than the speedometer's reading. With it, a single jump from s to t lands on the path, however much it bends. To get u exactly you would integrate the velocity along the path: the slow work we wanted to avoid. The trick: write t minus s times u as z t minus z s, and differentiate in s. Out comes an identity: the average velocity is the velocity now, plus t minus s times how fast the average changes as the start moves along the path. That derivative costs one Jacobian-vector product, about one extra run of the network. So the network is trained to match the right-hand side, held fixed: no integral, and no teacher. On ImageNet at 256 pixels it reached an FID of 3.43 in one step.
Here is ours learning: one jump from the same noise, at checkpoints during training. A year earlier, Kevin Frans and colleagues' shortcut models got there another way: the network is told the size of the jump, and trained so that one jump of size two d equals two jumps of size d, starting from plain flow matching at size zero. Watch both learn to land on the letters.
Here is every one-step model of this part, from the same noise. Training budgets differ, and teachers and auxiliary models add cost. Each method has seeds. The best single step is 's, at , Among the models with no teacher, the best is , at . Plain flow matching's single step, at , is the comparison's one-step flow-matching baseline.
14GuidanceUndergraduate3 min
So far the model draws whatever it likes. To ask for something, tell it what you want: a caption, or here, which letter. We trained a flow model on two letters, A and I, telling it which letter each example came from, except one time in five, when it is told nothing. One network learns both: the letter it is asked for, and letters in general. Here it is learning, asked for an A at each checkpoint.
The first way to ask came from Bayes' rule. Take logs and gradients, and the score of the images that fit a label is the ordinary score plus the gradient of a classifier's log probability: the evidence, p of y, doesn't depend on x, so it disappears. Multiply the classifier's push by a weight w above one, and at each noise level this score points along a sharpened density, reweighted towards what the classifier is surest of. Prafulla Dhariwal and Alex Nichol did this in 2021, with a classifier trained on noisy images, and beat GANs on ImageNet.
Classifier guidance needs a second network. In 2022 Jonathan Ho and Tim Salimans noticed that the model told the label and the model told nothing already contain a classifier: the gradient of log p of y given x is their difference. So start from the unconditional direction and push along the difference, towards the conditional one and past it, by a weight w. One network, two evaluations per step, no classifier. This is classifier-free guidance, and it became the standard way for text-to-image models to follow their prompts.
Ask for an A, from the same starting noise, at three weights. We track the share with x below zero, a left-region proxy, and those points' mean radius. At w equal to zero the request is ignored: percent have x below zero. At one, the plain conditional model: percent. At four you extrapolate beyond the conditional velocity: percent; the mean radius in the negative-x region changes from to . Across the whole sweep, with seeds: precision, the share of samples that look like real A's, peaks at w equal to .
Guidance trades variety for fidelity. Plot every weight on a plane: recall across, precision up. In 2024 Tero Karras and colleagues asked why push away from the unconditional model at all. Its fault is that it is worse: so guide instead with a smaller, less-trained version of the same conditional model. Their aim is to correct errors in the conditional model using a weaker version of that same conditional model. They set records on ImageNet: an FID of 1.01 at 64 pixels and 1.25 at 512. Our weak model is narrower and trained an eighth as long.
15From points to picturesUndergraduate2 min
Points in a plane were a warm-up. A picture is also a point: here, capital letters from many fonts, 20 by 20 pixels. Each picture is a list of 400 numbers, one point in a space of 400 dimensions. The model is the flow matching we trained on the letters A and I, with more numbers in and out.
Here it is learning: sixteen pictures from the same noise at each checkpoint. At first, static. Then grey blobs where letters tend to be, then strokes and capital-like shapes, still noisy and sometimes ambiguous. And here is one sample's path from static toward a letter-like image.
A batch of samples: noisy capitals mixed with ambiguous shapes, in a range of styles. Are they copies? Each sample is, on average, from its nearest training picture; the training pictures average to the nearest different image, excluding zero distances. So the samples are
Real images have millions of numbers, and denoising every one of them is expensive. In 2022 Robin Rombach, Patrick Esser, Bjorn Ommer and colleagues ran diffusion in a compressed space instead: an autoencoder turns a picture into a small grid of latents, the diffusion model works there, and a decoder turns the result back into pixels, 48 times fewer numbers, with text steering through cross-attention. Released with open weights that August, it became Stable Diffusion, the same year as OpenAI's DALL-E 2 and Google's Imagen. Then William Peebles and Saining Xie replaced the denoiser's convolutions with a transformer, and by 2024 diffusion and flow transformers were drawing video, OpenAI's Sora, and pictures at twelve billion parameters. By 2025 Google's Veo 3 generated video and its sound together, by latent diffusion. The encoders, the transformers and the video models are the next part.
16Diffusion for discrete dataResearch3 min
Text is made of symbols, not numbers, so Gaussian noise doesn't fit. In 2021 Jacob Austin and colleagues at Google generalized diffusion to symbols: each step replaces a symbol at random, according to a matrix of probabilities, and the matrices multiply into a closed form, just as the Gaussians did. Two choices matter. Swap a letter for a random one, or blank it out with a special mask symbol, which then stays blank: absorbing noise. The blanks won. At the end, everything is blank, and the reverse process fills the blanks in.
With blanks, the bound becomes remarkably simple. Each letter is blank with probability t. Going back from time t to an earlier time s, a blank either stays blank, with probability s over t, or reveals its letter. The model's step back can differ only in which letter it reveals, so each KL term is the reveal probability times the cross-entropy of guessing the letter. Add up the steps, and the bound is an integral: one over t times the cross-entropy of guessing every blank from the letters still showing. Three groups derived this in 2024. Regroup by the number of blanks k and integrate out time: each mask count contributes its expected mean loss per blank. Sum over k for the whole-sequence bound; divide by sequence length for loss per character. The sequence bound is an autoregressive model's loss, averaged over every order in which the letters could be revealed.
Check it where everything can be enumerated: strings of letters from a, b and c, drawn from a Markov chain, every probability known. Three models predict the blanks: the exact conditionals, the same blurred towards uniform, and one that ignores the context. The bound of a chain with T steps, computed exactly: with one step, the exact model's bound is bits per letter; with steps, , settling onto the integral, the dashed lines. The integral, the weighted cross-entropy, and the average over every order of revealing agree to decimal places, for every model.
The idea has a lineage. In 2014 Benigno Uria, Iain Murray and Hugo Larochelle trained one network for every order of an autoregressive model; in 2022 Emiel Hoogeboom and colleagues connected such any-order models to diffusion. In 2024 Aaron Lou, Chenlin Meng and Stefano Ermon defined a score for discrete data, ratios of probabilities, and won a best-paper award at ICML; the same year, two groups, Subham Sahoo's and Jiaxin Shi's, showed separately that plain masked diffusion, the weighted cross-entropy, does as well, and Jingyang Ou and colleagues that the model doesn't even need to be told the time. Which is what made the next step possible: language models trained this way, at scale.
17Diffusion language modelsEngineering5 min
In February 2025 Shen Nie, Chongxuan Li and colleagues trained LLaDA, an eight-billion-parameter language model, entirely by masked diffusion: two point three trillion tokens, every training example a passage with a random fraction of it blanked. It was competitive with LLaMA 3 of the same size, and beat GPT-4o at completing a poem backwards, line before line, a task left-to-right models find hard. We built a pair to compare: a masked-diffusion model and an autoregressive model of exactly the same size, trained on the novels with the same initial weights, the same batches and the same number of steps. The only differences are the attention mask and the task.
Here they are learning. On held-out text, the autoregressive model's exact bits per character, and the diffusion model's bound, both falling. Above, the diffusion model fills in a line of the passage with half its characters blanked, at each checkpoint; below, the other model writes on its own. By the end the diffusion model gets percent of the blanks right.
And here is ours writing 64 characters, from all blanks, in 16 rounds. Each round it guesses every blank, keeps the guesses it is surest of, and leaves the rest blank, LLaDA's rule. Characters appear at the most confident positions first. Each round fills several blanks while earlier choices stay fixed; positions need not proceed left to right.
At equal size, data and steps, on held-out blocks of characters, : the bound is bits per character against . Three different estimates of the bound, which the derivation says are equal in expectation, . The gap is not the end of the story: in 2025 Mihir Prabhudesai and colleagues found that when data is scarce and must be repeated for many epochs, diffusion models keep improving after autoregressive ones overfit.
On the scoreboard's passage, in blocks of 64 characters: the masked-diffusion model's bound, 2.94 bits per character, give or take 0.02, and the autoregressive twin, 2.23. Part 13's transformer, with 4 times the context, is at 2.00. Historical rows retain their original scoring protocols, so this is not a matched-target ranking. A bound is an upper limit on negative log likelihood; our Monte Carlo number estimates that bound.
Writing characters one round per character costs network evaluations, like an autoregressive model. Diffusion can use fewer rounds with several characters each. We score the samples with an autoregressive model from the other seed. This is that judge's likelihood score; coherence and diversity need separate checks. Real text scores . With rounds, ; with eight, ; all at once, : guessing many characters independently, in one go, leaves their dependencies unmodeled.
Fixed-length writing has a cost: nothing can be cached, and the length is set in advance. Marianne Arriola and colleagues' block diffusion splits the difference: blocks left to right, like an autoregressive model, diffusion inside each block. In 2025 Inception Labs launched Mercury, billed as the first commercial diffusion language models, at over a thousand tokens a second on H100 hardware; Google's Gemini Diffusion reported nearly fifteen hundred tokens per second excluding overhead, at about the coding quality of a small Gemini; Fast-dLLM added caching and confident parallel decoding to open models, up to twenty-seven times faster; LLaDA two point oh reached a hundred billion parameters by converting an autoregressive model. And in June 2026 Google released DiffusionGemma with open weights: 256 tokens a block, over a thousand tokens a second on one GPU, and, in Google's own words, lower in quality than the standard Gemma 4. Speed and task quality must be measured together; a likelihood bound alone does not settle that trade.
Recap, problems, and what comes nextAll tracks2 min
Let's take stock. A diffusion model destroys data slowly with noise, and learns to undo it. The training bound's intermediate Gaussian KL terms train the network through weighted noise-guessing errors, and the best noise guess is minus the noise scale times the score, by Tweedie's formula; denoising score matching learns it by plain regression. Time can be run back with a stochastic equation or a deterministic one; DDPM and DDIM discretize them, and EDM and DPM-Solver solve them in ten to thirty steps. Flow matching learns straight-line velocities, reflow straightens the paths, and distillation or MeanFlow reaches a single step. Guidance turns a request into a push. The same machinery draws pictures, and, with blanks for noise, writes text.
This machinery comes back. Next time it meets real images and video, in compressed latent spaces with transformers as the denoisers. Speech and sound generators use it, in Part 23; denoising as a way to learn features returns in Part 24; diffusion builds molecules and protein structures in Part 25; world models imagine the next frame with it in Part 29; and making it fast is part of Part 19's story.
Here are six problems, from the forward process's closed form to the masked bound. Pause here and work through them; full solutions are in this part's notes.
Next time: images, video and 3D. A picture is cut into patches, and the patches become tokens, so the transformers of Part 13 can look at pictures, and denoise them.
To go deeper, Simon Prince's Understanding Deep Learning covers diffusion clearly and for free, and Sander Dieleman's blog posts on diffusion are a wonderful companion. Thanks for watching, and see you in Part 22.
Where it goes next. The machinery meets real images and video in Part 22, in compressed latent spaces with transformers as the denoisers. Speech and sound generators use it in Part 23, denoising as a way to learn features returns in Part 24, diffusion builds molecules and protein structures in Part 25, and world models imagine the next frame with it in Part 29.
Key results
The part's results in one place, for revision.
Try it
Lab 21 · Guessing the noise is learning the score
On a three-bump mixture in one dimension, where the score at every noise level is known, check the forward process's closed form, check Tweedie's formula by quadrature, and train a small network to guess the noise: its loss must stay a fixed constant above its squared error against the exact score.
python -m videos.ai.labs 21
needs numpy, scipy, matplotlib · download lab21.py ·
source on GitHubafter 300 steps: slope of x_t on x_0 0.6285 (sqrt(abar) = 0.6296)
after 300 steps: leftover variance 0.6047 (1 - abar = 0.6036)
Tweedie: largest gap to the brute-force posterior mean 6.7e-16
noise-guessing loss, start to end 1.575 to 0.454
error against the exact score's noise guess 1.138 to 0.0050
their difference at every checkpoint 0.437 to 0.450 (constant C = 0.448)
The network never sees a score, only noisy points and the noise that was added; its loss is the error against the exact score plus a constant, so driving the loss down drives the network to the score.
The code (125 lines; it asserts its own result)
"""Lab 21: run the forward process, check Tweedie's formula, and train a noise-guesser that learns the score."""
import numpy as np
from videos.coursekit import labs
from explainer.ai.autodiff import Tensor
TITLE = "Guessing the noise is learning the score"
GOAL = ("On a three-bump mixture in one dimension, where the score at every noise level is known, check the forward "
"process's closed form, check Tweedie's formula by quadrature, and train a small network to guess the noise: "
"its loss must stay a fixed constant above its squared error against the exact score.")
TASKS = [
"Change the noise level from step 300 to step 50 and to step 800. Where is the constant C largest, and why is the score hardest to learn at low noise?",
"Train the network to guess the clean point x0 instead of the noise, and convert its output to a score with Tweedie's formula.",
"Use the exact score in 50 DDIM steps from noise (the widget's update) and compare the samples' histogram with the mixture.",
]
W = np.array([0.3, 0.4, 0.3]) # the data: a mixture of three narrow Gaussians
MU = np.array([-1.5, 0.2, 1.4])
S = np.array([0.15, 0.25, 0.15])
def marginal(x, a, b):
"""The density of a x0 + b eps and its score, both exact."""
var = a * a * S ** 2 + b * b
comp = W * np.exp(-0.5 * (x[:, None] - a * MU) ** 2 / var) / np.sqrt(2 * np.pi * var)
p = comp.sum(1)
return p, (comp * (a * MU - x[:, None]) / var).sum(1) / p
def sample_data(rng, n):
k = rng.choice(3, n, p=W)
return MU[k] + S[k] * rng.standard_normal(n)
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. the forward chain, step by step, against one jump
betas = np.linspace(1e-4, 0.02, 1000)
abar = np.cumprod(1 - betas)
t = 300
a, b = np.sqrt(abar[t - 1]), np.sqrt(1 - abar[t - 1])
x0 = sample_data(rng, 20000)
x = x0.copy()
for beta in betas[:t]:
x = np.sqrt(1 - beta) * x + np.sqrt(beta) * rng.standard_normal(len(x))
slope = (x @ x0) / (x0 @ x0)
left = np.var(x - slope * x0)
lab.row(f"after {t} steps: slope of x_t on x_0", f"{slope:.4f} (sqrt(abar) = {a:.4f})")
lab.row(f"after {t} steps: leftover variance", f"{left:.4f} (1 - abar = {b * b:.4f})")
assert abs(slope - a) < 0.02 and abs(left - b * b) < 0.02, "the forward chain has the closed form"
# 2. Tweedie: the posterior mean by brute-force quadrature against (x + sigma^2 score) / alpha
xs = np.linspace(-2.2, 2.2, 221)
g = np.linspace(-4, 4, 8001)
prior = (W * np.exp(-0.5 * (g[:, None] - MU) ** 2 / S ** 2) / np.sqrt(2 * np.pi * S ** 2)).sum(1)
like = np.exp(-0.5 * (xs[:, None] - a * g[None]) ** 2 / (b * b))
brute = (like * prior * g).sum(1) / (like * prior).sum(1)
_, score = marginal(xs, a, b)
tweedie = (xs + b * b * score) / a
gap = np.abs(brute - tweedie).max()
lab.row("Tweedie: largest gap to the brute-force posterior mean", f"{gap:.1e}")
assert gap < 1e-6, "Tweedie's formula"
# 3. a network that guesses the noise: 1 -> 24 -> 24 -> 1, tanh, trained with Adam on the series' autodiff
h = 24
params = [Tensor(v, requires_grad=True) for v in (
rng.standard_normal((1, h)), np.zeros(h), rng.standard_normal((h, h)) / np.sqrt(h), np.zeros(h),
rng.standard_normal((h, 1)) / np.sqrt(h), np.zeros(1))]
def net(v):
w1, b1, w2, b2, w3, b3 = params
return ((((Tensor(v[:, None]) @ w1 + b1).tanh() @ w2 + b2).tanh()) @ w3 + b3)
ev_x0, ev_eps = sample_data(rng, 40000), rng.standard_normal(40000)
ev_x = a * ev_x0 + b * ev_eps
best = -b * marginal(ev_x, a, b)[1] # E[eps | x] = -sigma * score
const = float(np.mean((ev_eps - best) ** 2)) # what no network can remove
def losses():
out = net(ev_x).data[:, 0]
return float(np.mean((out - ev_eps) ** 2)), float(np.mean((out - best) ** 2))
m = [np.zeros_like(p.data) for p in params]
v2 = [np.zeros_like(p.data) for p in params]
steps, lr, curve = 1200, 0.01, []
for k in range(steps + 1):
if k % 100 == 0:
curve.append((k, *losses()))
bx0, be = sample_data(rng, 256), rng.standard_normal(256)
for p in params:
p.grad[:] = 0
loss = ((net(a * bx0 + b * be) - be[:, None]) ** 2).mean()
loss.backward()
for i, p in enumerate(params):
m[i] = 0.9 * m[i] + 0.1 * p.grad
v2[i] = 0.999 * v2[i] + 0.001 * p.grad ** 2
p.data -= lr * (m[i] / (1 - 0.9 ** (k + 1))) / (np.sqrt(v2[i] / (1 - 0.999 ** (k + 1))) + 1e-8)
curve = np.array(curve)
gaps = curve[:, 1] - curve[:, 2]
lab.row("noise-guessing loss, start to end", f"{curve[0, 1]:.3f} to {curve[-1, 1]:.3f}")
lab.row("error against the exact score's noise guess", f"{curve[0, 2]:.3f} to {curve[-1, 2]:.4f}")
lab.row("their difference at every checkpoint", f"{gaps.min():.3f} to {gaps.max():.3f} (constant C = {const:.3f})")
lab.note = ("The network never sees a score, only noisy points and the noise that was added; its loss is the error "
"against the exact score plus a constant, so driving the loss down drives the network to the score.")
assert curve[-1, 2] < 0.1 * curve[0, 2] and curve[-1, 2] < 0.02, "the noise-guesser has learned the score"
assert np.abs(gaps - const).max() < 0.04 * max(1.0, curve[0, 2]), "Vincent: the two losses differ by a constant"
assert curve[-1, 1] > const - 0.01, "no network beats the posterior mean"
fig, ax = labs.figure(2, size=(11, 4.2))
p, sc = marginal(xs, a, b)
ax[0].fill_between(xs, 0, p / p.max(), color=labs.MUTED, alpha=0.25, label="density of x_t (scaled)")
ax[0].plot(xs, -b * sc, color=labs.GOLD, lw=3, alpha=0.7, label="exact: -sigma x score")
ax[0].plot(xs, net(xs).data[:, 0], color=labs.BLUE, label="network's noise guess")
ax[0].set(title=f"The best noise guess at step {t}", xlabel="noisy point x_t", ylabel="guess of the noise")
ax[0].legend(loc="upper left")
ax[1].plot(curve[:, 0], curve[:, 1], "o-", color=labs.BLUE, ms=3, label="noise-guessing loss (trainable from data)")
ax[1].plot(curve[:, 0], curve[:, 2], "o-", color=labs.GREEN, ms=3, label="error against the exact score")
ax[1].axhline(const, color=labs.GOLD, ls="--", label=f"the constant C = {const:.3f}")
ax[1].set(title="Two losses, one constant apart", xlabel="training step", ylabel="mean squared error", yscale="log")
ax[1].legend(loc="center right")
lab.fig = fig
return lab
Now change it
- Change the noise level from step 300 to step 50 and to step 800. Where is the constant C largest, and why is the score hardest to learn at low noise?
- Train the network to guess the clean point x0 instead of the noise, and convert its output to a score with Tweedie's formula.
- Use the exact score in 50 DDIM steps from noise (the widget's update) and compare the samples' histogram with the mixture.
Problems, with solutions
Try each problem before opening its solution.
-
For q(x_t | x_{t-1}) = N(√(1−β_t) x_{t-1}, β_t I), show q(x_t | x_0) = N(√ᾱ_t x_0, (1−ᾱ_t) I) with ᾱ_t = ∏_{s≤t}(1−β_s).
Solution
By induction. Suppose x_{t−1} = √ᾱ_{t−1} x_0 + √(1−ᾱ_{t−1}) ε̄ with ε̄ standard normal. Then x_t = √(1−β_t) x_{t−1} + √β_t ε_t = √ᾱ_t x_0 + [√((1−β_t)(1−ᾱ_{t−1})) ε̄ + √β_t ε_t]. The bracket is a sum of independent Gaussians, so it is Gaussian with variance (1−β_t)(1−ᾱ_{t−1}) + β_t = 1 − (1−β_t)ᾱ_{t−1} = 1 − ᾱ_t. The base case t = 1 is the step itself.
-
For x = α x_0 + σ ε, prove Tweedie's formula E[x_0 | x] = (x + σ² ∇log p(x))/α, and deduce that the best noise guess is −σ ∇log p(x).
Solution
p(x) = ∫ N(x; α x_0, σ² I) p(x_0) dx_0. Differentiating under the integral, ∇p(x) = ∫ (α x_0 − x)/σ² N(x; α x_0, σ²I) p(x_0) dx_0. Dividing by p(x), N p(x_0)/p(x) = p(x_0 | x), so ∇log p(x) = (α E[x_0 | x] − x)/σ², which rearranges to Tweedie's formula. Since ε = (x − α x_0)/σ, E[ε | x] = (x − α E[x_0 | x])/σ = −σ ∇log p(x), and the conditional mean minimizes the expected squared error.
-
Prove that denoising score matching and explicit score matching differ by a constant independent of θ.
Solution
Write J_D = ½E‖s(x̃) − ∇log q(x̃|x)‖² and J_E = ½E‖s(x̃) − ∇log q_σ(x̃)‖². Expanding, each is ½E‖s‖² minus a cross term plus a term without θ. The cross terms are equal: E_{q_σ}[s·∇log q_σ] = ∫ s·∇q_σ dx̃ = ∫∫ s·∇x̃ q(x̃|x) p(x) dx dx̃ = E{x,x̃}[s·∇log q(x̃|x)], using ∇log q = ∇q/q twice and q_σ = ∫ q(x̃|x) p(x) dx. So J_D − J_E does not depend on θ.
-
Show that DDIM's step x_s = α_s x̂_0 + σ_s ε̂ solves dx/dσ = (x − D)/σ exactly, in x/α and σ/α, when D = x̂_0 is constant over the step.
Solution
In x̃ = x/α and σ̃ = σ/α the state is x̃ = x_0 + σ̃ ε and the probability-flow ODE is dx̃/dσ̃ = (x̃ − D)/σ̃. With D constant, d(x̃ − D)/dσ̃ = (x̃ − D)/σ̃, so x̃ − D is proportional to σ̃: x̃_s = D + (σ̃_s/σ̃_t)(x̃_t − D). With ε̂ = (x̃_t − D)/σ̃_t this is x̃_s = D + σ̃_s ε̂; multiplying by α_s gives x_s = α_s D + σ_s ε̂, DDIM's step.
-
At a fixed noise level and with ideal conditional and unconditional scores, show that classifier-free guidance with weight w gives the score of the normalized density proportional to p_t(x) p_t(c | x)^w, and w = 1 gives the conditional score. This local identity does not establish the endpoint distribution of an entire guided trajectory.
Solution
At fixed t, with exact scores and densities evaluated at that noise level, the guided score is ∇log p(x) + w(∇log p(x|c) − ∇log p(x)). By Bayes, ∇log p(x|c) − ∇log p(x) = ∇log p(c|x) (p(c) does not depend on x), so the guided score is ∇log p(x) + w ∇log p(c|x) = ∇log[p(x) p(c|x)^w]. At w = 1 it is ∇log p(x|c). (In ε or velocity form the same holds, since each is an affine function of the score at fixed t.)
-
For masked diffusion on n symbols, show C(n, k) ∫₀¹ t^{k−1}(1−t)^{n−k} dt = 1/k, and deduce that the bound is the any-order autoregressive loss.
Solution
∫₀¹ t^{k−1}(1−t)^{n−k} dt = B(k, n−k+1) = (k−1)!(n−k)!/n!, and multiplying by C(n, k) = n!/(k!(n−k)!) leaves 1/k. The bound ∫₀¹ (1/t) E[Σ_{blanks} CE] dt sums over blank sets M of t^{|M|}(1−t)^{n−|M|}/t, so a set of size k gets weight 1/(k C(n, k)): the bound is Σ_k E_{|M|=k}[(1/k) Σ_{i∈M} −log p(x_i | x_{∖M})]. In a uniformly random order, the step that reveals the j-th symbol has a uniformly random hidden set of size k = n − j + 1 and predicts a uniformly random member of it, so its expected loss is the same k-th term; summing over j gives the any-order autoregressive loss.
Notes and sources
Glossary
| English | 中文 |
|---|---|
| diffusion model | 扩散模型 |
| forward process, reverse process | 前向过程,反向过程 |
| noise schedule; β_t; ᾱ_t (alpha bar) | 噪声调度;β_t;ᾱ_t(阿尔法拔) |
| variance preserving (VP) | 方差保持 |
| evidence lower bound (ELBO); negative ELBO (loss upper bound) | 证据下界(ELBO);负ELBO(损失上界) |
| noise prediction (ε-prediction), the simple loss | 噪声预测(ε预测),简化损失 |
| denoiser D(x; σ) | 去噪器D(x; σ) |
| Tweedie's formula, posterior mean | 特威迪公式,后验均值 |
| score matching, denoising score matching | 分数匹配,去噪分数匹配 |
| stochastic differential equation (SDE), reverse-time SDE | 随机微分方程(SDE),反向时间SDE |
| probability-flow ODE | 概率流常微分方程(概率流ODE) |
| Fokker–Planck equation, continuity equation | 福克-普朗克方程,连续性方程 |
| DDPM, DDIM, ancestral sampling, η | DDPM,DDIM,祖先采样,η |
| signal-to-noise ratio (SNR), log-SNR, terminal SNR | 信噪比,对数信噪比,终端信噪比 |
| step spacing | (采样)步长间隔 |
| preconditioning (c_in, c_skip, c_out) | 预条件化(c_in,c_skip,c_out) |
| error amplification | 误差放大 |
| Euler's method, Heun's method, second order | 欧拉法,休恩法,二阶 |
| exponential integrator, integrating factor | 指数积分器,积分因子 |
| DPM-Solver, DPM-Solver++ (multistep) | DPM-Solver,DPM-Solver++(多步法) |
| network evaluations (NFE) | 网络调用次数(NFE) |
| sliced Wasserstein distance | 切片瓦瑟斯坦距离 |
| optimal transport, coupling, transport cost | 最优传输,耦合(配对),运输代价 |
| Benamou–Brenier formula, kinetic energy | 贝纳穆-布雷尼耶公式,动能 |
| flow matching; conditional and marginal velocity | 流匹配;条件速度与边缘速度 |
| marginal-field theorem | 边缘速度场定理 |
| stochastic interpolant | 随机插值 |
| rectified flow, reflow, straightness | 整流流,重流,直度 |
| minibatch optimal transport (OT-CFM) | 小批量最优传输 |
| distillation, teacher, student | 蒸馏,老师,学生 |
| progressive distillation | 渐进蒸馏 |
| consistency model, self-consistency, consistency distillation | 一致性模型,自洽性,一致性蒸馏 |
| distribution matching distillation (DMD) | 分布匹配蒸馏(DMD) |
| MeanFlow, average velocity | MeanFlow,平均速度 |
| shortcut model | 捷径模型 |
| Jacobian-vector product, stop-gradient | 雅可比-向量积,停止梯度 |
| classifier guidance, classifier-free guidance (CFG), guidance weight w | 分类器引导,无分类器引导(CFG),引导权重w |
| autoguidance | 自引导 |
| precision and recall (k-NN) | 精确率与召回率(k近邻) |
| latent diffusion, latents | 潜空间扩散,潜变量 |
| diffusion transformer (DiT) | 扩散Transformer(DiT) |
| discrete diffusion (D3PM), transition matrix | 离散扩散(D3PM),转移矩阵 |
| uniform noise, absorbing (mask) noise, mask token [M] | 均匀噪声,吸收态(掩码)噪声,掩码词元[M] |
| masked diffusion, weighted cross-entropy | 掩码扩散,加权交叉熵 |
| any-order autoregressive model | 任意顺序自回归模型 |
| a tight bound | 紧的界 |
| block diffusion | 块扩散 |
| surest-first unmasking (low-confidence remasking) | 最有把握优先的揭开(低置信度重掩码) |
| AR-judge bits per character; generative perplexity = 2^bpc | 自回归评判模型的每字符比特数;生成困惑度 = 2^每字符比特数 |
| diffusion language model (dLLM) | 扩散语言模型 |
QA metric conventions: cached dpm2 denotes midpoint data-prediction DPM-Solver++(2S). Cached floor values are finite-sample reference baselines, not mathematical lower bounds. DSM scene consumers convert historical noise-error terms by 1/(2 sigma_t^2) to the displayed half-squared-score loss without rewriting the training caches. The Euler VP initialization now represents the same physical start as the other solvers; the reviewed-input guard rejects legacy solver acceptance records. A new independent review must identify all affected rows and picture arrays while preserving original outcomes separately.
Guidance metric conventions: legacy onA is the fraction with x < 0, a left-region proxy rather than A membership; spread is mean radius about that subset's centroid. Metrics use 1,000 generated points per seed and a seeded 1,000-point real-A reference subset; panels show the first 500 points of seed 0. Reflow's loss plot is per-coordinate squared velocity error, with loss markers hidden until the first recorded update.
Sources
Books: S. J. D. Prince, Understanding Deep Learning (2023), ch. 18; K. P. Murphy, Probabilistic Machine Learning: Advanced Topics (2023), ch. 25; C. Villani, Optimal Transport: Old and New (2009). S. Dieleman's blog posts on diffusion (sander.ai).
Papers: Sohl-Dickstein, Weiss, Maheswaranathan & Ganguli (2015); Ho, Jain & Abbeel, DDPM (2020); Song & Ermon (2019); Song et al., Score-Based Generative Modeling through SDEs (2021); Anderson, Reverse-time diffusion equation models (1982); Robbins (1956); Efron, Tweedie's formula and selection bias (2011); Hyvärinen (2005); Vincent (2011); Song, Meng & Ermon, DDIM (2021); Nichol & Dhariwal (2021); Kingma, Salimans, Poole & Ho, VDM (2021); Lin, Liu, Li & Yang, Common diffusion noise schedules and sample steps are flawed (2024); Karras, Aittala, Aila & Laine, EDM (2022); Karras et al., Guiding a diffusion model with a bad version of itself (2024); Lu et al., DPM-Solver (2022) and DPM-Solver++ (2022); Benamou & Brenier (2000); Lipman et al., Flow Matching (2023); Liu, Gong & Liu, Rectified Flow (2023); Albergo & Vanden-Eijnden (2023); Albergo, Boffi & Vanden-Eijnden, Stochastic Interpolants (2023); Tong et al. (2024); Pooladian et al. (2023); Liu et al., InstaFlow (2023); Salimans & Ho, Progressive Distillation (2022); Song, Dhariwal, Chen & Sutskever, Consistency Models (2023); Lu & Song, sCM (2025); Yin et al., DMD (2024) and DMD2 (2024); Geng, Deng, Bai, Kolter & He, MeanFlow (2025); Frans, Hafner, Levine & Abbeel, Shortcut Models (2024); Dhariwal & Nichol, Diffusion Models Beat GANs (2021); Ho & Salimans, Classifier-Free Guidance (2022); Rombach et al., Latent Diffusion (2022); Peebles & Xie, DiT (2023); Esser et al., SD3 (2024); Black Forest Labs, FLUX.1 model cards (2024); Google DeepMind, Veo 3 model card; Austin et al., D3PM (2021); Uria, Murray & Larochelle (2014); Hoogeboom et al., Autoregressive Diffusion Models (2022); Lou, Meng & Ermon, SEDD (2024); Sahoo et al., MDLM (2024); Shi et al., MD4 (2024); Ou et al., RADD (2024); Nie et al., LLaDA (2025); Arriola et al., Block Diffusion (2025); Inception Labs, Mercury (2025); Google DeepMind, Gemini Diffusion (2025); Wu et al., Fast-dLLM (2025); Ant Group et al., LLaDA2.0 (2025); Google, DiffusionGemma (10 June 2026); Prabhudesai et al., Diffusion Beats Autoregressive in Data-Constrained Settings (2025).
The text-model replay curves evaluate 64 held-out blocks (4,096 characters) at each checkpoint. The final comparison uses 512 held-out blocks (32,768 characters) starting at validation offset 200,000. These are distinct evaluation cohorts, so a replay curve endpoint need not equal the final comparison value. Diffusion entries estimate a loss upper bound; autoregressive entries evaluate exact per-character loss.
Three-seed whiskers on the point-model comparison bars show the observed minimum and maximum; text-model uncertainty bars explicitly show ±one standard error. The DPM solver picture row compares three candidate solvers at about 12 evaluations with a separately labeled high-resolution reference that uses a larger budget. SDE/ODE path-length statistics average each path’s total length after adding its 50 recorded segments.
Schedule invariance compares reparameterized denoisers expressed in signal-to-noise ratio under monotone schedules with the same endpoints. It does not guarantee identical fixed-weight behavior or finite-training results.
About this partfrom its README
Part 21 of a thirty-one-part series on how modern AI works and how it came to be (see the series plan and the syllabus). How models make things from noise, from the 2015 idea of destroying data slowly to the diffusion language models of 2026. Part 20 ended with Langevin dynamics and the score; this part learns the score at every noise level and follows it back. The Part 21 toy models are trained on a CPU: points in the plane, letter pictures, and text. Earlier scoreboard rows use restored original results with their own target and context protocols; published large-model results are attributed to their sources.
The data are Part 5's letters "AI" made into a smooth density, a mixture of 400 small Gaussians (exact.py), so that
the score, the best denoiser, the probability-flow ODE and flow matching's velocity field are all known exactly; the
experiments then measure every learned or discretized thing against the truth. Pictures are 20 x 20 capital letters
drawn from the system's fonts; text is Part 1's thirty novels, through Part 13's characters.
The picture-neighbor baseline uses at most 300 references from every seventh training picture, comparing each with all training pictures and excluding exact zero distances. Counts depend on the reviewed font inputs. A mean nearest-neighbor distance does not rule out individual copies.
Chapter notes
- From noise. Our denoiser walks 300 points from noise into the letters; how we got here, 2015–2026; the plan.
- 1. Destroying data slowly. The forward process (Sohl-Dickstein et al. 2015; DDPM's schedule); its closed form q(x_t | x_0) derived; checked on 20,000 points run through 1,000 steps (slope, leftover variance, whole clouds); the posterior q(x_{t-1} | x_t, x_0); the variance-preserving continuous form (Part 5's Ornstein–Uhlenbeck).
- 2. The bound, and guessing the noise. The variational bound as a sum of KL terms; Gaussian KLs become weighted squared errors of a noise guess (Ho, Jain & Abbeel 2020); DDPM's weights λ_t, computed; the simple loss; our denoiser's training replayed (samples from the same noise at checkpoints, the loss).
- 3. Tweedie's formula. The best squared-error guess is the posterior mean (1D picture); Tweedie's formula proved (Robbins 1956; Efron 2011); checked against brute-force quadrature (1D), Monte Carlo over 50,000 points (2D) and our network; the best denoiser's one-jump guesses blur at high noise.
- 4. Denoising score matching. Explicit score matching and its trace (Hyvärinen 2005); Vincent's theorem (2011), proved; checked through training: loss = constant + error against the exact score, at four noise levels, three seeds; where the score is hardest; Song & Ermon (2019).
- 5. Running time backwards. The VP SDE (Song et al. 2021); Anderson's reverse-time SDE (1982); the probability-flow ODE derived from Fokker–Planck; reverse SDE and ODE run with the exact score: paths, marginals against fresh samples at every time, the ODE run there and back.
- 6. DDPM and DDIM. Both samplers with our network; DDIM's step derived, and shown to be Euler in (x/α, σ/α); η; distance from the data against the number of steps.
- 7. Noise schedules. SNR and log-SNR of DDPM, cosine (Nichol & Dhariwal 2021), ours and flow matching; DDPM's terminal SNR (Lin et al. 2024); the continuous bound's invariance (Kingma et al. 2021); where training spends its noise levels; four schedules trained at equal budgets (three seeds), error against the exact denoiser by noise level and distance after sampling; four step spacings for three solvers.
- 8. EDM: preconditioning and Heun. Karras et al. (2022): the σ-parameterization, dx/dσ = (x − D)/σ; preconditioning derived (c_in, c_skip, c_out) and measured on our data (target spread, error amplification); noise, clean-point and EDM targets trained at equal budgets (three seeds); Heun's method, and when it beats Euler.
- 9. DPM-Solver: an exact linear part. Lu et al. (2022a, b): the exponential integrator derived; first order is DDIM; DPM-Solver++(2S) and DPM-Solver++(2M); Euler, DDIM, Heun, DPM-Solver++(2S), DPM-Solver++(2M) and DDPM compared with the exact denoiser (error against a high-resolution ODE reference by number of evaluations), then with our network.
- 10. Optimal transport and flow matching. Monge (1781), Kantorovich (1942), Benamou–Brenier (2000); the optimal pairing of 1,500 points (Hungarian algorithm); flow matching (Lipman et al.; Liu et al.; Albergo & Vanden-Eijnden; 2023) and the marginal-field theorem, proved and checked with the exact velocity at four times; straightness, kinetic energy and transport cost against the optimum; stochastic interpolants (Albergo, Boffi & Vanden-Eijnden 2023): the diffusion path as an interpolant.
- 11. Rectified flow and reflow. Flow matching's training replayed; reflow (Liu, Gong & Liu 2023) once and twice; minibatch OT pairs (Tong et al. 2024; Pooladian et al. 2023); straightness and distance by number of Euler steps, three seeds; InstaFlow, SD3, FLUX.1.
- 12. Distillation. Progressive distillation (Salimans & Ho 2022), 64 → 1 steps, replayed round by round; consistency models (Song et al. 2023; sCM, Lu & Song 2025), consistency distillation replayed; distribution matching distillation (Yin et al. 2024a, b): the KL gradient as a difference of scores, derived and trained; all three at one step, three seeds. The small DMD demonstration isolates score-difference updates; the published DMD benchmark also used teacher-output regression.
- 13. One step from scratch. MeanFlow (Geng et al. 2025): the average velocity and its identity, derived; shortcut
models (Frans et al. 2024); both replayed; every one-step model of the part on one board, three seeds. Our MeanFlow
uses a plain squared error, an adaptation of the paper's adaptively weighted loss; this comparison does not
reproduce the paper's full training recipe. Both one-step networks use slower time features than the part's
other networks, because MeanFlow differentiates the network along time (see
fewstep.py). - 14. Guidance. Conditioning with label dropout (replayed); classifier guidance via Bayes (Dhariwal & Nichol 2021); classifier-free guidance (Ho & Salimans 2022); negative-x fraction (a proxy for the A class), precision and recall swept over w for classifier-free guidance, classifier guidance (a noisy classifier we train) and autoguidance (Karras et al. 2024, with a weaker model of our own); three seeds.
- 15. From points to pictures. A picture as a point in 400 dimensions; flow matching on letter pictures, replayed; one sample's journey; nearest-training-picture distances; latent diffusion (Rombach et al. 2022) and the image and video systems of 2022–2025 (architectures: Part 22).
- 16. Diffusion for discrete data. D3PM (Austin et al. 2021): uniform and absorbing noise; masked diffusion's bound derived as a weighted cross-entropy and as an any-order autoregressive loss (Sahoo et al. 2024; Shi et al. 2024; Ou et al. 2024); checked exactly on a 4-letter language: the T-step bound, the weighted cross-entropy and the any-order average, for three models; the lineage (Uria et al. 2014; Hoogeboom et al. 2022; SEDD, Lou et al. 2024).
- 17. Diffusion language models. LLaDA (Nie et al. 2025); our masked-diffusion model and an autoregressive model of exactly the same size, data, initial weights, batches and steps, two seeds each, training replayed (bits, fill-in, writing); three estimates of the bound; the model read left to right; the scoreboard row (a bound, in 64-character blocks); writing with fewer rounds (surest first, at random, in blocks), judged by the other seed's autoregressive model; block diffusion (Arriola et al. 2025), Mercury, Gemini Diffusion, Fast-dLLM, LLaDA2.0, DiffusionGemma (June 2026).
- Outro. Eight pictures from the part's results, where the ideas come back, six problems, Part 22's teaser, references.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Forward process in closed form; ELBO → ε-prediction; Tweedie.
- Denoising score matching, proved.
- Reverse SDE and the probability-flow ODE; DDIM; SNR schedules.
- EDM: preconditioning, Heun; DPM-Solver as an exponential integrator.
- Optimal transport and Benamou–Brenier; flow matching (marginal-field theorem); stochastic interpolants.
- Rectified flow and reflow.
- Distillation: progressive, consistency models (sCM), DMD; MeanFlow, shortcut models.
- Guidance: classifier via Bayes, CFG, autoguidance.
- Discrete diffusion: D3PM; masked diffusion's ELBO as weighted cross-entropy (derived).
- LLaDA, block diffusion, fast diffusion LMs.
- A masked-diffusion LM on the novels (scoreboard row, as a bound).
中文讲义
本讲的中文部分(与英文版对应)。
习题(中文)
- 对 q(x_t | x_{t−1}) = N(√(1−β_t) x_{t−1}, β_t I),证明 q(x_t | x_0) = N(√ᾱ_t x_0, (1−ᾱ_t) I),其中 ᾱ_t = ∏_{s≤t}(1−β_s)。
- 对 x = α x_0 + σ ε,证明特威迪公式 E[x_0 | x] = (x + σ² ∇log p(x))/α,并推出最佳的噪声猜测是 −σ ∇log p(x)。
- 证明去噪分数匹配与显式分数匹配只相差一个与 θ 无关的常数。
- 证明当 D = x̂_0 在一步之内不变时,DDIM 的一步 x_s = α_s x̂_0 + σ_s ε̂ 在坐标 x/α、σ/α 下精确地解出 dx/dσ = (x − D)/σ。
- 在固定噪声时刻 t、条件与无条件分数均精确时,证明权重 w 的无分类器引导给出正比于 p_t(x) p_t(c | x)^w 的归一化密度的分数, 且 w = 1 时等于条件分数。这个局部恒等式不保证整条引导轨迹的终点分布。
- 对 n 个符号上的掩码扩散,证明 C(n, k) ∫₀¹ t^{k−1}(1−t)^{n−k} dt = 1/k,并推出这个损失上界等于对均匀随机揭示顺序取平均的自回归损失。
解答
Solutions
- 归纳法。设 x_{t−1} = √ᾱ_{t−1} x_0 + √(1−ᾱ_{t−1}) ε̄,ε̄ 为标准正态。则 x_t = √ᾱ_t x_0 + [√((1−β_t)(1−ᾱ_{t−1})) ε̄ + √β_t ε_t]。 方括号里是两个独立高斯变量之和,仍是高斯变量,方差为 (1−β_t)(1−ᾱ_{t−1}) + β_t = 1 − ᾱ_t。t = 1 时就是那一步本身。
- p(x) = ∫ N(x; α x_0, σ² I) p(x_0) dx_0。在积分号下求导得 ∇p(x) = ∫ (α x_0 − x)/σ² · N · p(x_0) dx_0;除以 p(x), N p(x_0)/p(x) 就是后验 p(x_0 | x),所以 ∇log p(x) = (α E[x_0 | x] − x)/σ²,移项即得特威迪公式。由 ε = (x − α x_0)/σ, E[ε | x] = (x − α E[x_0 | x])/σ = −σ ∇log p(x),而条件均值使期望平方误差最小。
- 记 J_D = ½E‖s(x̃) − ∇log q(x̃|x)‖²,J_E = ½E‖s(x̃) − ∇log q_σ(x̃)‖²。展开后,两者都是 ½E‖s‖² 减去一个交叉项,再加一个 与 θ 无关的项。两个交叉项相等:E_{q_σ}[s·∇log q_σ] = ∫ s·∇q_σ dx̃ = ∫∫ s·∇x̃ q(x̃|x) p(x) dx dx̃ = E{x,x̃}[s·∇log q(x̃|x)], 用了两次 ∇log q = ∇q/q,以及 q_σ = ∫ q(x̃|x) p(x) dx。所以 J_D − J_E 与 θ 无关。
- 在 x̃ = x/α、σ̃ = σ/α 下,状态为 x̃ = x_0 + σ̃ ε,概率流 ODE 为 dx̃/dσ̃ = (x̃ − D)/σ̃。D 不变时 d(x̃ − D)/dσ̃ = (x̃ − D)/σ̃, 所以 x̃ − D 与 σ̃ 成正比:x̃_s = D + (σ̃_s/σ̃_t)(x̃_t − D)。记 ε̂ = (x̃_t − D)/σ̃_t,即 x̃_s = D + σ̃_s ε̂;乘以 α_s 得 x_s = α_s D + σ_s ε̂,正是 DDIM 的一步。
- 固定 t,使用该噪声时刻的精确分数与密度,引导后的分数函数是 ∇log p(x) + w(∇log p(x|c) − ∇log p(x))。由贝叶斯公式,∇log p(x|c) − ∇log p(x) = ∇log p(c|x)(p(c) 与 x 无关),所以它等于 ∇log p(x) + w ∇log p(c|x) = ∇log[p(x) p(c|x)^w]。w = 1 时就是 ∇log p(x|c)。(在固定的 t 下, ε 或速度都是分数函数的仿射函数,所以结论同样成立。)
- ∫₀¹ t^{k−1}(1−t)^{n−k} dt = B(k, n−k+1) = (k−1)!(n−k)!/n!,乘以 C(n, k) = n!/(k!(n−k)!) 就剩下 1/k。损失上界 ∫₀¹ (1/t) E[Σ_空白 CE] dt 对每个空白集合 M 的权重是 t^{|M|}(1−t)^{n−|M|}/t 的积分,大小为 k 的集合得到权重 1/(k C(n, k)), 所以损失上界等于 Σ_k E_{|M|=k}[(1/k) Σ_{i∈M} −log p(x_i | x_{∖M})]。在均匀随机的顺序里,揭开第 j 个符号的那一步,面对的是一个 大小为 k = n − j + 1 的均匀随机隐藏集合,并预测其中均匀随机的一个,所以它的期望损失正是第 k 项;对 j 求和,就得到任意顺序 自回归的损失。
Build the film
python -m videos.ai.ai21.compute # the part's numbers, into .cache/ai21
python tools/build.py ai21 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py ai21 Hook # one chapter, silent, with a contact sheet
Scenes: videos/ai/ai21. Setup: see the course page. Source of these notes: the README and the scenes' narration.