A diffusion model makes a new picture, or a new sound, from pure static. It learns which way is back toward real data, then walks there in small noisy steps.
Learn the score, the noisy walk that uses it, and why walking down a ladder of noise levels is what makes it work.
Pick a method, then press Run. Each dot is a walker that starts in static. Compare how many walkers end in the heavy blob with the share the data really has. Then we build, piece by piece, every part of it: the walk, the score, the noise ladder and the denoiser.
You need a feel for a gradient (the slope that points uphill) and the bell curve. We build the rest from zero.
Based on the Diffusion Models lecture of Stanford EE269: Signal Processing for Machine Learning, taught by Mert Pilanci. The slides. Every idea is re-taught here in our own words and devices.
Toy world, illustrative: three round blobs of real data (spread 0.35) with 60%, 25% and 15% of the data, and 400 walkers that start as a broad bell curve of static. The walkers use the exact score of the blob mixture, not a trained network, so you see the method and not a training error. Plain descent and Langevin use 300 steps of size 0.02 at the data’s own sharpness; Annealed uses 10 noise levels from 3 down to 0.1, 12 steps each. Chapters 2, 8 and 9 build each piece.
Chapter 0
See why a machine can start from pure noise, and the one thing it must learn to turn that noise into something real
Tune an old radio to the gap between two stations. You hear hiss. The hiss carries no music at all. It is just random numbers, millions per second, with no pattern.
Now picture a machine that listens to that hiss and nudges it, a tiny step at a time, until a new song comes out. Not a song from a record. A song that never existed, but sounds as if a band played it. That machine is a diffusion model, and this lesson builds it from the ground up.
A generative model is a program that makes new examples that look like a collection of real ones: new faces, new voices, new street scenes. To do this it must know what the real ones have in common.
Statisticians put it this way. Every kind of signal has a data distribution, written p(x). It is a rule that says how likely each possible signal x is. Making something new means drawing one sample from that rule, the way you draw one card from a deck.
Why is that hard? Take a small colour picture, 64 pixels wide and 64 tall with three colour values per pixel. That is 64 × 64 × 3 = 12,288 numbers. Pick 12,288 numbers at random and you get static, every time. Real photos live in a thin sliver of that huge space. The generator has to find the sliver.
Here is the first trick, and it is one you already know from audio. Adding noise to a signal is trivial: draw a random number for each sample and add it. The more noise, the less of the signal survives.
Below is a toy signal, a spiral of 600 points in the plane. Each point is a two number signal, so the picture is easy to see. Drag the noise up and watch the spiral dissolve. At zero noise you can see the arms. At high noise you see a round cloud with no memory of the spiral.
Faint blue is the clean spiral. Purple dots are the same 600 points after adding noise of the size you choose. Drag the noise from 0 to 1.5 and watch when the arms stop being visible.
Toy data: 600 points on a spiral that winds 1.75 turns, with a gap of about 1.4 units between neighbouring arms near the edge and less near the centre. Noise is a fresh bell curve draw (spread equal to the noise level) added to both coordinates of each point, fixed by a seed so it is the same on every visit. “Lost” means the nearest clean point is more than 60 places along the spiral from the point’s own home.
Look at the middle of the slider, around noise 0.5. Near the centre of the spiral the arms are close, so the noise has already mixed them. Near the rim the arms are far apart and still survive. Different parts of the signal die at different noise levels. Remember that. It returns in Chapter 7.
Now run the film backwards. A cloud of static is in front of you. Which way should each point move to look more like the spiral? Nobody told it. The answer depends on where all the real points lie.
Learning that direction is the whole job. The lecture reaches it in nine small steps, and each step is a chapter here. The steps are worth knowing in order, because each one fixes a problem the last one left behind.
The lecture is 44 slides by Mert Pilanci, given at Stanford on 23 March 2023. It ends with three readings: Stanford’s CS236 course on deep generative models, Sinho Chewi’s notes on log-concave sampling, and Kevin Murphy’s book Probabilistic Machine Learning: Advanced Topics. We link each one where it helps.
Go back to the walkers above. Plain descent is Chapter 1. Langevin is Chapter 2. The share bars, and why plain Langevin misses the 60%, come from the score in Chapter 3. Annealed noise is Chapters 7 and 8. In Chapter 9 the same walkers become pixels and sound.
Chapter 1
Learn the step rule that adaptive filters use, and see that every walk in this lesson starts from it
You call a friend on speakerphone. Your friend’s voice leaves the speaker, bounces around your room and comes back into the microphone as an echo. A phone has to cancel that echo, and every room is different.
The phone cannot know the room in advance. So it uses a filter that learns the room while you talk. That is an adaptive filter, and the lecture opens with it because its learning rule is the first step on our road. Our adaptive filters lesson covers filters in full. Here we need only the rule.
A filter makes each output sample from the last few input samples. It multiplies each recent sample by a number, a weight, and adds the results. The list of weights is the filter. Change the weights and you change what the filter does.
Write the last few input samples as one list, a_t = [at, at−1, …]. The lecture calls it the signal data frame. Write the filter’s weights as x. Then the filter’s output is the single number aᵀx, the sum of each sample times its weight. The weights of a perfect echo canceller would give an output equal to the echo, dt, the desired signal.
It will not be perfect at the start, so there is an error, aᵀx − dt. The learner wants this error to shrink. Squaring it makes every miss positive and punishes big misses most. The lecture calls this the instantaneous error:
Think of the cost as a landscape. Each possible set of weights is a place. Height is the cost there. The learner wants the lowest place. The gradient is the slope at your feet: a list of numbers that points straight uphill. Step against it and you go downhill, like a ball rolling.
Here is the gradient of ft. Call the error u = aᵀx − d. Then f = ½u², and its slope is u times the slope of u. The slope of u with respect to the weights is just a. So the gradient is (aᵀx − d)a. The error says how far to move. The frame a says in which direction.
This rule is called LMS, for Least Mean Square. Here is one update with real numbers. The weights start at x = [0, 0, 0]. The frame is a = [1, 0.5, −1] and the desired value is d = 0.9. The output is 0, so the error is 0 − 0.9 = −0.9. The gradient is −0.9 × [1, 0.5, −1] = [−0.9, −0.45, 0.9]. With α = 0.1 the new weights are [0, 0, 0] − 0.1 × [−0.9, −0.45, 0.9] = [0.09, 0.045, −0.09].
In the device below, the room is a secret three number filter, [0.8, −0.4, 0.2]. The learner never sees it. It sees only the input and the echo, and it runs the update at every sample.
Dashed blue lines are the secret weights. The three warm curves are the learner’s weights over 400 samples. Drag the step size and watch speed, jitter and blow up.
Toy room, illustrative: the input is white noise with spread 1, the echo is the secret filter applied to it plus a little measurement noise (spread 0.05), and each update uses one sample. The distance is the straight-line distance between the learner’s three weights and the secret three. Press New signal for a fresh random signal.
With a small step the weights glide in smoothly but slowly. With a larger step they arrive fast but jitter around the target. Past about 0.4 they can fly off to huge numbers. The red state shows that failure.
Why does the phone use a single sample at a time? Because the real goal is the average cost over all the samples, f(x) = (1/n) ∑ fi(x). Computing that average slope means looking at all n samples at every step, and for a live call they have not even arrived yet.
The trick is to use one sample’s slope as a stand-in. It is a noisy guess. Sometimes it points a little off, but on average it points the right way. That is stochastic gradient descent, SGD. LMS is SGD applied to filters. Neural network training is SGD applied to millions of weights.
The lecture states what SGD promises. If the average cost is convex, a single bowl with no other dips, then with well-chosen step sizes the weights end up near the global best. The slide adds a condition, for example that the gradients are Lipschitz continuous, meaning the slope never changes faster than a fixed rate. If the cost is not convex, the weights end up near a stationary point, a place where the gradient is zero and the ground is flat: a valley floor, a hilltop or a saddle.
Symptom: the learner’s weights swing wider with each update and the numbers explode. Measurement: in the device at α = 0.7 the distance to the secret filter passes one million before the 400 samples run out. Fix: shrink the step. Classical adaptive filter theory (not in the slides) says that for white Gaussian input with l weights, the average squared error is stable only for α below 2 / (l + 2) times the input power. With l = 3 and input power 1, that limit is 0.4, which is what the device shows.
Keep the picture of a walker that takes steps along a noisy downhill direction. The next chapter turns the noise from a nuisance into the whole point.
Chapter 2
Add a random kick to every downhill step and watch a walker that used to settle become a walker that samples
Put a marble in a bowl and it rolls to the bottom and stops. Now put the bowl on a table that hums and shakes. The marble no longer stops. It jitters around the bottom, and it sometimes climbs partway up the side.
Film the shaking marble for an hour and count where it spent its time. Mostly near the bottom, rarely high on the rim. That count is a distribution: a rule that says how often each place is visited. The shaken bowl turns a descent into a sampler. This chapter makes that precise.
Take the downhill step from Chapter 1 and add a random kick to it. The kick is Gaussian noise: a fresh draw from the bell curve, with the same spread in every direction. Statisticians write one draw as zt ∼ N(0, I), which reads “z is drawn from a bell curve centred at zero with unit spread”. The lecture calls the result noisy gradient descent, also the Langevin sampler:
Why a square root? Take many small steps and the random kicks add up like a drunken walk. Their total size grows with the square root of the number of steps. So each kick must shrink with the square root of ε. Then the shaking keeps the same strength however finely you slice time.
The slide states the promise. Run this long enough, with small enough steps, and under mild conditions (for example, f convex) the walker’s position follows a distribution proportional to e−f(x). This is called Langevin Monte Carlo. Low f means a big e−f, so the walker visits low places often and high places rarely, exactly like the marble.
Try one dimension and a bowl shaped like a bell curve, f(x) = (x − μ)² / (2σ²). Then e−f is a Gaussian density with centre μ and spread σ. The sampler should therefore hover around μ with a spread of σ. Take μ = 0 and σ = 1.
Check it by hand. The slope of f is x, so one step is x′ = x − (ε/2)x + √εz = a x + √ε z, with a = 1 − ε/2. Once the cloud settles, its variance V stops changing. The variance after a step is a²V + ε (the old cloud, shrunk by a, plus fresh noise). Setting that equal to V gives V = ε / (1 − a²).
Take ε = 0.5. Then a = 0.75, a² = 0.5625, and V = 0.5 / 0.4375 = 1.143, a spread of 1.069. Take ε = 0.1: a = 0.95, V = 0.1 / 0.0975 = 1.026, a spread of 1.013. As ε shrinks the spread tends to 1, the true value. That is the “ε → 0” in the slide, seen in numbers.
1,500 walkers start together at x = 3.5. Bars show where they are now. The blue curve is the target, e−f with σ = 1. Turn the shaking off and on, and change the step size.
Exact toy: f(x) = x²/2, so the target is a bell curve of spread 1. Each walker takes enough steps to settle (8 divided by the step size, between 60 and 400). The predicted spread comes from V = ε / (1 − a²) with a = 1 − ε/2, derived in the text; the measured spread is computed from the walkers on screen.
Without shaking, every walker slides to x = 0 and sits on the same spot: a descent finds the single best point. With shaking, the walkers fan out into the whole bell curve. Notice that it is the noise that gives the sampler its spread. Take it away and the sampler collapses to one answer.
The lecture next uses a multi-dimensional bowl: f(x) = ½(x − μ)T Σ−1(x − μ). Here μ is a vector, the centre, and Σ is the covariance matrix, a table that says how spread out the cloud is in each direction and how the directions move together. The slide notes that this is a least-squares problem, ½‖Ax − b‖² with A = Σ−1/2 and b = Σ−1/2μ, the same family Chapter 1 trained filters on.
Ordinary descent, x − εΣ−1(x − μ), glides to μ and stops. The noisy version keeps wandering, and its cloud takes the shape Σ: wide where Σ is wide, an ellipse tilted where the directions are linked. One detail: slides 8 to 12 write the drift without the one half. Then the matching noise is √(2ε) instead of √ε. We keep the matched pair from slide 5.
Look back at the hero. Plain descent sent each walker to the nearest blob and parked it there. Langevin kept every walker moving around, yet at that small shake the walkers still stayed in the blob they first reached. The sampler is right in the limit, but the limit can take forever when the bowl has several dips, because a small shake cannot climb the hill between two of them. Chapter 7 fixes this.
Symptom: the cloud comes out wider than the target. Measurement: at ε = 2 the device’s walkers have a spread near 1.41, not 1.00, because the discrete step is too coarse. Fix: a smaller ε, paid for with more steps. Smaller steps are accurate but slow. That trade follows us all the way to the sampling speed of image models.
Chapter 3
Name the one quantity the walker needs, see why it ignores the size of each blob, and meet it for a bell curve
You are hiking in thick fog on a hillside. You cannot see the summit, and you cannot see the whole map. All you can feel is the slope under your boots: which way is up, and how steeply.
That local feeling is enough to climb. It is also all the Langevin walker of Chapter 2 needed. It never looked at the whole landscape. It asked at each step only: which way is more likely, from here? This chapter gives that arrow its name.
In Chapter 2 the landscape was a bowl f(x), and the walker settled where e−f was large. Turn that around. Suppose you start with a probability density p(x): a curve whose height says how likely each signal x is. Which landscape makes e−f equal to p? Take f = −log p. High density becomes a deep valley.
The lecture sets f := log p on slide 13 and writes the step with a minus sign. With that sign, f would be the hill and the walker would run away from likely data. Read it as the lecture surely means it: the walker moves uphill in log p. In symbols, using f = −log p, the step becomes:
Why the logarithm? The log of a curve has the same hills and valleys, but the slope of log p equals p′/p, the relative change. That gives a gift. A density is usually known only up to a constant, p = e−f/Z, where Z makes the area equal to one and is nearly impossible to compute. The slope of log Z is zero, so Z vanishes: the score is just −∇f. A generator can use the score without ever computing Z.
One warning. This slope is taken with respect to the signal x, not with respect to a model’s weights, which is the slope you know from training. The lecture writes a model of the score as sθ(x), where θ holds the weights. Both slopes appear in this lesson, and they are different things.
Take the one-dimensional bell curve with centre μ and spread σ. Its log is −(x − μ)²/(2σ²) plus a constant. The slope of that is the score:
s(x) = −(x − μ) / σ² (the slide’s sign is lost in print; this is the sign that points toward μ)
It is a straight line through zero at μ. For μ = 0 and σ = 2 we get s(x) = −x/4. At x = 3 the score is −0.75: an arrow of length 0.75 pointing left, toward the centre. At x = −4 it is +1: an arrow pointing right. At x = 0 it is exactly zero. In many dimensions the same is s(x) = −Σ−1(x − μ).
The lecture reads this as a score card. Near the centre, the score is near zero: a signal there is already typical, so nothing needs fixing. Far from the centre the score is large: the signal is unusual and the arrow says exactly how to fix it. That is why the slide calls scores near zero good scores. Zero score also marks the stationary points of the density, which are its peaks, and also its valleys and saddle points.
Now give the data two blobs, as slide 16 does. Say 50% of the data sits in a left blob and 50% in a right blob, far enough apart that they barely touch. Inside the left blob the score is the left bell curve’s score. Inside the right blob it is the right one’s. The score is a patchwork of the two pieces.
The slide draws the consequence: the mixing weights are lost. Change the left blob to 90% of the data and, inside a blob, the score does not change at all. A slope only describes the neighbourhood where you stand, and in each blob the neighbourhood looks the same. Try it.
Top: the density of two blobs centred at −3 and +3, each with spread 1. Bottom: its score. Slide the probe to read the arrow at any point. Then slide the weight of the left blob and watch where the score moves.
Exact two-blob mixture: s(x) = r·(−(x + 3)) + (1 − r)·(−(x − 3)), where r is the share of the density at x that belongs to the left blob. “Baseline” in the read-out means the same probe with equal weights, 50% and 50%.
Set the probe at x = 2. The score is 1.00 whatever the weight: the right blob owns that spot. Now drag the probe to x = 0, the valley between the blobs. At equal weights the score is zero there, since the two pulls cancel. At 90% left, it is −2.4: the valley now leans toward the heavy blob. So the weights hide only in the thin valley between blobs, where the score is hardest to estimate.
This explains the hero. A walker at the data’s own sharpness follows the score of the blob it lands in. It never feels the weight. That is why plain Langevin sent one third of the walkers to each blob, and why Chapters 7 and 8 need a trick that makes the valleys visible.
Symptom: a sampler that visits every mode, but with the wrong shares. Measurement: the hero shows about 35% of walkers in a blob that holds 60% of the data. Fix: blur the data, so the blobs overlap and the valleys fill in. Blurring is nothing but adding noise, and the weights come back into view.
Chapter 4
Store the arrows as connect-the-dots lines, see how many dots a sampler needs, and learn what the guarantee does and does not cover
Suppose you want to hand a friend a map of slopes for a whole mountain range. You cannot write down the slope at every point, because there are infinitely many. So you plant a few signposts, each with a slope written on it, and tell your friend to draw straight lines between the signposts.
With a few signposts the map is crude. With many it is nearly perfect. A neural network does something very close to this, and the lecture says so directly. This chapter shows how many signposts a sampler needs.
Slide 17 plots the score of a mixture of Gaussian blobs that barely overlap. Look at its shape. Inside each blob the score is a straight slanted line, because a bell curve’s score is linear (Chapter 3). Between two blobs the line snaps from one slope to the next in a steep jump. The whole curve is a row of straight pieces with sharp joins.
Slide 18 shows the same curve for a different mixture of blobs, again with straight pieces and sharp joins. Both slides carry one message. The score of data made of blobs is piecewise linear: straight in pieces, with bends between.
A neural network is a function built from many small units called neurons. One neuron takes a number, multiplies it by a weight, adds a bias and then applies a bend. The bend we use is the ReLU, short for rectified linear unit. It passes positive numbers unchanged and turns every negative number into zero. Its graph is a flat line that bends upward at zero.
Add up several shifted and scaled ReLUs and you get a line with several bends, one for each ReLU. That is why the slide says one-dimensional ReLU networks work like piecewise linear interpolators: more neurons give more bends, and more bends can follow a more complicated curve. The lecture writes the whole network as one expression:
Look at the data flow, because it surprises people. For a 64 × 64 colour picture, x has shape 3 × 64 × 64 and the network’s output also has shape 3 × 64 × 64. The score is one arrow per pixel value, so a score network turns a picture into a picture-shaped field of arrows.
Before the real thing, here is the one-dimensional toy. The device stores the true score of two blobs (centres −3 and +3, spread 1, equal weights) at a few evenly spaced signposts and draws straight lines between them. That is a stand-in for what a trained ReLU network can do with the same number of bends. Then it runs the Langevin sampler of Chapter 3 using only the connect-the-dots score.
Top: the true score (blue) and the connect-the-dots version (warm). Bottom: where 1,200 walkers end up when they follow the warm line, against the true density (blue). Choose how many straight pieces the line has.
Illustrative: the signposts sit at equal spacing from −6 to 6 and carry the exact score there, a stand-in for a trained network, which would spend its bends where they matter. Walkers start as a bell curve of spread 2 and take 600 steps of size 0.05. “Mismatch” is the total variation distance between the sample histogram and the true density over 36 bins: 0 is a perfect match, 1 means no overlap.
With 2 pieces the line has one bend, a single straight slope through the middle. The walkers pile into one broad hump centred at zero, and the two blobs vanish. With 4 pieces the middle is flat, so the walkers spread evenly across the valley. At 8 pieces two humps appear. At 16 they match the true density closely. The sampler can be no better than the arrows it follows.
Slide 20 states what we can prove. If the score model equals the true score, then as the number of steps grows and the step size shrinks, the walkers’ distribution converges to p. The closeness is measured by the Wasserstein distance, also called the earth mover’s distance. Picture each distribution as a pile of soil. Ask for the cheapest way to reshape one pile into the other. The cost is the amount of soil moved times how far it moves.
A tiny example. Pile A has half a unit of soil at x = 0 and half at x = 2. Pile B has half at x = 1 and half at x = 3. Moving every bit by 1 turns A into B, so the distance is 0.5 × 1 + 0.5 × 1 = 1. For two single spikes at a and b, the slide notes the distance is just the gap between them.
The guarantee holds when log p is concave, meaning its graph is one cap with no dips. Such densities are called log-concave, and the multivariate bell curve is one. For densities with several peaks, like our blobs, we only get convergence near stationarity: the walkers end where the score almost vanishes, which can be any one of the peaks. This is precisely the weak spot Chapter 3 found.
Symptom: samples that miss a mode or invent one. Measurement: in the device the mismatch is about 0.7 with 2 pieces, 0.3 with 4, and under 0.1 with 8 or 16. Fix: give the network more capacity, and then train it with data it will actually meet. The next chapter turns to the training.
Chapter 5
Turn an impossible training target into an easy one by adding noise, and see why the easy target teaches the hard answer
A hiker stands on a trail. You know exactly where she is. Her phone shows a blurry GPS fix a few metres away. If I ask “which way from the fix to the true spot?”, you can answer at once: from the fix, straight back to the hiker.
Now imagine a million hikers on a thousand trails, and a million blurry fixes. For any one fix you cannot tell which hiker made it. But a program could still learn the average direction back to the trail. That is how a score network is trained, and this chapter shows why it works.
To train a network sθ to match the score, the obvious loss is the average squared gap to the true score: Ex∼p ‖sθ(x) − ∇log p(x)‖². The lecture lists the trouble on slide 21. We do not know ∇log p, since that is what we are trying to learn. Worse, for natural signals such as images and audio the density p is zero over almost all of the space. Real photos fill a thin sliver, and the log of zero is minus infinity, so the score does not even exist off the sliver.
The cure is on the same slide: smooth the signals by adding Gaussian noise, x̃ = x + n with n ∼ N(0, σ²I). Noise smears the thin sliver into a thick fog that covers the space. The noisy density, called qσ(x̃), is positive everywhere, so its score exists everywhere.
Slide 22 draws the chain p(x) → qσ(x̃|x) → qσ(x̃). The middle arrow is the corruption channel: given a clean x, it hands you a noisy copy drawn from N(x, σ²I). Because this one step is a bell curve, its score is known exactly. The log density is −‖x̃ − x‖²/(2σ²) plus a constant, and its slope with respect to x̃ is:
The sign matters. The arrow points back, against the noise. The lecture prints the final target without its minus sign in places, and slide 24 says “the score function predicts the noise from noisy samples”. Both are one idea. A score network predicts −n/σ, so the network’s output times −σ is the noise.
Take a worked number. The clean value is x = 1.0. Use σ = 0.5 and a noise draw n = 0.8. The noisy copy is x̃ = 1.0 + 0.5 × 0.8 = 1.4. The target is −(1.4 − 1.0)/0.25 = −1.6, and −n/σ = −0.8/0.5 = −1.6 as well. The network must output −1.6 at the point 1.4 for this training pair.
Here is the short derivation slide 23 promises. The score we truly want is the score of the blurred data, ∇ log qσ(x̃). Write qσ(x̃) = ∫ p(x) qσ(x̃|x) dx, take the slope inside the integral, and divide by qσ(x̃):
∇ log qσ(x̃) = ∫ [ p(x) qσ(x̃|x) / qσ(x̃) ] ∇ log qσ(x̃|x) dx = E[ ∇ log qσ(x̃|x) | x̃ ]
The bracket is the chance that a clean point x is the home of the noisy point x̃. So the hard score is the average of the easy targets over all homes the point could have come from. Now recall a fact about least squares: the single number that minimises squared error against a set of values is their average. So a network trained with squared error on the easy target learns exactly that average, the hard score. That is why the two losses on slide 23 are the same up to a constant:
Seeing is believing. The device draws noisy copies of a two-blob data set, shows each copy’s easy target, and averages the targets in small bins. That average is the learned score. The blue line is the true score of the blurred data.
Each purple dot is one noisy copy of clean data (two blobs at −2 and +2), plotted at height of its easy target. The warm line averages the dots in small bins. Drag the noise level and see where the average matches the blue true score, and where there is no data.
Toy data: half the clean points at −2 and half at +2, each with a little spread (0.2). 3,000 noisy copies per draw; the dots show 500 of them, and heights beyond ±8 are clipped. The warm line is the average of the targets in bins 0.2 wide; a bin with fewer than 5 copies counts as unseen and is shaded red. The blue line is the exact score of the blurred two-blob density.
At σ = 0.3 the dots huddle near the two blobs. The average is rough, and about 40% of the stretch from −3.5 to +3.5 has no samples at all, so the network would be guessing there. At σ = 0.8 the fog covers the whole stretch, and the learned average hugs the true score within 0.08. More noise gives the network more places to learn the arrows.
Slides 25 and 26 show the method on the classic swiss roll, a thin spiral sheet of points in the plane. A ReLU network, credited to Kevin Murphy, learns the score, and the slide draws it as a grid of little arrows pointing in toward the spiral. Then three Langevin walkers start in empty space and follow the arrows: each one slides in toward the roll and then wanders along it. That is the whole generator, working in two dimensions.
Symptom: the walkers make strange shapes in the empty parts of the space. Measurement: at σ = 0.3 about four in ten bins hold no training points. Fix: raise σ so the noise covers the space. The price is that the model now learns a blurrier distribution than the real one. Chapter 7 shows how to keep both benefits.
Chapter 6
Clean a noisy signal as well as any method can, and discover that the cleaning step is the score in disguise
A friend texts you a photo of a hand-written number, but the picture is grainy. The digit might be a 1 or a 7. You are asked to give the best single guess of the clean image. What do you do?
You do not just keep the grainy pixels. You also do not simply pick the neater-looking digit. The best guess weighs both candidates by how likely each one is, given what you see. That weighted guess has a name, and the lecture shows it is built from the score.
Slide 27 sets the stage. A clean signal x is drawn from p(x). We see only x̃ = x + n, where n is bell curve noise of spread σ. The question: how do we denoise x̃ optimally? “Optimal” here means the guess with the smallest average squared error.
Bayes’ rule gives the tool. The posterior, p(x|x̃), is the distribution of clean signals that could have produced what we saw. It is proportional to the prior p(x), how likely each clean signal is at all, times the channel qσ(x̃|x), how likely this noisy copy is from that clean one. (Slide 28 prints the channel twice. One factor is correct.) The best guess under squared error is the posterior mean, the average of all candidates weighted by posterior probability, written E[x|x̃].
Here comes the link. In Chapter 5 we found that the score of the blurred data is an average of easy targets: ∇ log qσ(x̃) = E[ −(x̃ − x)/σ² | x̃ ]. Pull the constants out of the average. The right side is (E[x|x̃] − x̃)/σ². Solve for the posterior mean and you have Tweedie’s formula, slide 28:
Read it in words. The best denoiser starts at the noisy point and takes one step along the score, of length σ² times the score. Noisier data means a longer step, because there is more to undo. Turn the formula around, as the slide does: the score is the denoising error divided by σ², that is, (E[x|x̃] − x̃)/σ². A good denoiser is therefore a good score estimator. Train a network to clean, and it holds the score. Train it on the score, and it cleans.
Test the formula on a case you already know. Let the clean signal be a bell curve with spread τ, so it has variance τ². Add noise of variance σ². The noisy signal is a bell curve with variance τ² + σ², and its score is −x̃/(τ² + σ²).
Tweedie then gives x̃ − σ²x̃/(τ² + σ²) = x̃ · τ²/(τ² + σ²). The best denoiser just shrinks the noisy value by a gain, τ²/(τ² + σ²). It is the signal power divided by signal plus noise power, the gain of the classical Wiener filter. With τ² = 1 and σ² = 0.25 the gain is 0.8, and a noisy reading of 1.0 is cleaned to 0.8.
For a bell curve prior the answer is a plain shrink. Every value is pulled toward zero by the same fraction, and a filter with one fixed gain can do that. For richer data, like pictures, the right correction depends on where you are, and a network has to learn it. The device uses a prior in between: a clean value that is either +1 or −1, with equal chance.
The clean signal is either −1 or +1. The blue curve is the density of the noisy value. Slide the noisy reading and the noise level. The warm dot is Tweedie’s answer, reached by one step along the score.
Exact toy: the clean value is −1 or +1 with probability one half each. The score of the noisy density is computed from the two bell curves at the reading; the denoised value is x̃ + σ² × score. The posterior mean computed directly, tanh(x̃/σ²), gives the same number, which the read-out checks.
Set the reading to 0.3 and σ = 0.5. The posterior says +1 is the source with 92% chance and −1 with 8%. The score of the noisy density is 2.13. The estimate is 0.3 + 0.25 × 2.13 = 0.83, and tanh(1.2) = 0.83 agrees. Now slide the reading to 0. The two sources are equally likely and the estimate is exactly 0, a value the clean data never takes.
Symptom: a denoised output that looks like a blur, an average of two possible images. Measurement: at a reading of 0 the best guess is 0 for every σ, a point between the two true values and not equal to either. Fix: do not trust one big denoising jump. Take a small step along the score, add a little noise, and repeat, so that the walker commits to one source. This is the reason the sampler of Chapter 3 takes many noisy steps instead of one clean one.
Chapter 7
See why one noise level cannot do the job, and train a single network to clean at ten levels at once
A sculptor does not start with the finest chisel. She starts with a big one that knocks off large chunks and fixes the overall shape. Then she swaps to a smaller chisel for the face, and last of all to a tiny one for the eyelashes. Each tool is right for one scale of detail.
Noise levels play the part of chisels. A large level fixes the broad layout of a signal. A tiny level fixes the finest detail. The lecture’s main idea on this page is to keep the whole set.
Slides 29 and 30 list what goes wrong when you pick a single noise level σ and train a score model on it.
The fix, from Song and Ermon (2019), is to use many levels at once. Each level covers for a weakness of the others.
Choose L noise spreads and perturb every training signal with each one. Slide 35 gives the example L = 10 with σ1 = 1 and σ10 = 0.01. At 0.01 the noise is almost invisible to a person looking at an image. (Slide 31 lists the levels in rising order and slide 35 in falling order. We use the falling order of slide 35.)
The slides sketch the ladder as 1, 0.5, …, 0.01. We space the ten levels evenly on a logarithmic scale instead, so that each is 0.6 times the one before. That gives 1.00, 0.60, 0.36, 0.22, 0.13, 0.077, 0.046, 0.028, 0.017 and 0.010. In decibels, with a signal of unit power, the signal-to-noise ratio is −20 log10σ: 0 dB at the top rung, 40 dB at the bottom.
Now the network needs to know which rung it is on, since cleaning heavy noise and cleaning light noise are different jobs. So the score model takes two inputs, the noisy signal and the level: sθ(x̃, σ). For a 64 × 64 colour picture, x̃ has shape B × 3 × 64 × 64 for a batch of B pictures. The level is one number per picture, turned into a vector by an embedding and fed into the layers. The output has the same shape as x̃.
Why do coarse and fine live on different rungs? Natural signals carry most of their power in slow, broad features, and less at fine scales. Noise like ours has a flat spectrum, the same power at every frequency. So big noise buries the fine detail first and leaves the broad shape. Small noise leaves almost everything and hides only the finest texture. This is the reason a big rung teaches layout and a small rung teaches detail.
Purple is a 220 Hz tone with two overtones plus noise at the chosen rung. Blue is the clean tone. The bars below show how big each rung’s loss is if you do not weight it (warm) and after weighting (green line). Press Hear it to listen.
Illustrative: the signal is a sum of three sine waves (220, 440 and 660 Hz, sampled at 8,000 per second) scaled to unit power; the first 256 samples are drawn. Noise has the stated spread, so the signal to noise ratio is −20 log10σ. Unweighted loss scale is 1/σ², the size of the squared target (n/σ)² for a typical draw. Playback is quiet, is clipped at full scale, and starts only when you press the button.
Slide the rung from 1 to 10. At rung 1 the tone is buried: 0 dB means noise as strong as the tone. By rung 4 you can see the waveform’s rhythm. At rung 10 the picture is almost clean. In the bars, notice the unweighted loss scale climbs from 1 at the top rung to 10,000 at the bottom rung.
Slides 33 and 34 combine the levels into one loss, a weighted sum of the Chapter 5 losses, one per level:
The slide picks λi = σi². Here is why. The target at rung i has size about 1/σi, so its squared error is about 1/σi². At σ = 0.01 that is 10,000 times the top rung’s. Unweighted, the tiny levels would drown the rest. Multiply by σ² and the sum becomes ‖σi sθ(x̃, σi) + n‖², the form on slide 34. The network now outputs something of unit size at every rung, namely the negative of the noise.
A number to hold on to: at σ = 0.1 with a draw n = 1.2, the target is −12 and its square is 144. With weight σ² = 0.01 the loss is 1.44, which is just n². The same draw at σ = 1 gives the same 1.44. The rungs now speak on one scale.
Slide 35 turns this into a loop. Each iteration, do five things:
Look at what the loop never does. It never samples a picture and it never runs a walk. It only practises cleaning. Generation comes from how we use the trained network, which is the next chapter.
Symptom: samples with crisp texture but a wrong overall shape. Measurement: without weights the loss at the bottom rung is 10,000 times the loss at the top rung, so training spends almost all its effort on fine detail. Fix: weight each rung by σ², or equivalently train the network to output the noise.
Chapter 8
Use the trained ladder to turn static into data, and see that the simplest version of the walk is a denoising diffusion model
A photographer pulls a blurry scene into focus by turning the lens ring. First a big turn, when everything is a smear. Then smaller and smaller turns as the shapes sharpen. She never jumps straight to the final focus, because from a smear she cannot tell where it is.
Sampling from a trained score ladder works the same way. Start at the blurriest rung, where the score is easy and the walker can travel far. Then step down one rung at a time. Each rung hands its result to the next, a little sharper.
The lecture calls this annealed Langevin dynamics. The word “annealing” comes from metalwork: heat the metal, then cool it slowly so that its atoms settle into a good arrangement. Here the “heat” is the noise level and we lower it slowly. Slide 37 gives the procedure:
Run T of these steps on each rung. Then take the final position of rung i as the starting position of rung i + 1, and move down. We begin at the noisiest rung and end at the quietest. The slide’s wording says “smallest first”, but its own loop and slide 35’s list only make sense in this order, with σL the quietest.
Why a step size that scales with σ²? On a rung of noise σ, the data looks smeared over a distance of about σ. A step has to be about that long to travel, and a shake of about that size to explore. Make the step proportional to σ² and every rung takes the same fraction of its own length scale per step.
A worked set of numbers (illustrative). Take the quietest rung σL = 0.05 and ε0 = 0.001. At the top rung σ = 2 the step is ε = 0.001 × 4 / 0.0025 = 1.6. At the bottom rung it is 0.001. The two differ by a factor of 1,600, yet the walker moves the same fraction of the local scale in both.
Here is the best part, and it uses Chapter 6. Tweedie said the denoiser’s answer is μ̂ = x + σ² s(x). So the score step (ε/2)s equals (ε/(2σ²)) (μ̂ − x). Call the fraction γ = ε/(2σ²). One Langevin step is then:
x ← x + γ (μ̂ − x) + σ√(2γ) z (move a fraction γ toward the denoiser’s guess, then add fresh noise)
The walker moves a fraction of the way toward the clean guess and re-adds some noise. Slide 38 states the consequence: each step of applying the score function can be viewed as denoising, that is, reversing the noise corruption process. And that slide makes one more change: set T = 1. One step per rung, and use many rungs. That simplified loop is a denoising diffusion model.
Slide 39 shows the best-known version, from Ho and colleagues (2020, the paper behind “DDPM”). It has the same two halves. For training: pick a clean signal and a random step index, noise it, and train the network to predict the noise that was added (this is Chapter 5, with the noise as target). For sampling: start from pure static and apply the network one step at a time, from the noisiest step down to the cleanest. Ho and colleagues used 1,000 steps, with the noise added at each step rising from 0.0001 to 0.02. Slide 40 draws the spiral at the start, the middle and the end of the noising film, with the learned reverse walk below it.
Now run it. The device uses the spiral of 120 training points from Chapter 0. The score is exact: it is the score of those 120 points blurred by the rung’s noise, so you see the method, not a training error. Compare four ways to walk from static to spiral.
Choose a schedule, then press Run. Blue dots are the 120 data points. Teal dots are 300 walkers starting as static. The budget is the number of score evaluations per walker.
Exact toy, illustrative: each step is x ← x + γ(μ̂ − x) + σ√(2γ)z with γ = 0.2, where μ̂ is the average of the data points weighted by how close they are, at the rung’s noise. Rungs run from σ = 2 down to 0.05 on a log scale; the one-level run keeps σ = 0.05. “On the spiral” means within 0.2 of a data point. The inner quarter is the first 30 of the 120 points. Because the score is exact for these 120 points, the walkers can only land on them; a trained network blurs between points and so makes new ones.
With one level the walkers mostly reach the spiral, but they pile up on the outer arms. Only about 10% land on the inner quarter, which holds 25% of the data. With annealed or diffusion schedules at the same budget of 100 evaluations, about 20% land there, much closer to its fair share. That is the ladder at work: the big rungs fix how the walkers split between arms, and the small rungs polish. With only 10 rungs of 1 there are too few steps, and about half the walkers are still off the spiral.
Symptom: the samples land in the wrong places, or smear between arms. Measurement: in the device, 10 rungs of 1 step leave about 45% of walkers off the spiral, and the one-level run puts only about 10% of them on the inner quarter of the data. Fix: more rungs with small steps, or more steps per rung. The honest cost is speed: a thousand-step sampler calls the network a thousand times per image, and speeding that up is a field of its own.
Chapter 9
Meet the network that holds the score for pictures, then see why audio is often turned into a picture first
Everything so far used points on a page. Real signals are bigger. One second of speech at 8,000 samples per second is 8,000 numbers. A small photo is 12,288. The walker is the same, but the score must now be held by a network that can read a whole picture or a whole stretch of sound.
The last three content slides of the lecture answer three questions. Which network? Which signals? And how do you steer it to make what you ask for? This chapter takes them in order.
Slide 41 says good denoising networks tend to be good score estimators, and gives the examples: deep convolutional networks and U-Nets. A convolutional network slides a small set of weights over the signal, so the same pattern detector works everywhere, the way a filter slides along a time signal in Chapter 1.
A U-Net is shaped like the letter. The left arm shrinks the picture step by step while adding feature channels, so that deep layers see a wide area. The right arm grows it back. A skip connection copies each shrinking stage straight across to the matching growing stage, so fine detail is not lost on the way down. The data flow, with illustrative shapes for a 64 × 64 colour picture:
The output must match the input shape, because it holds one arrow component per pixel value (Chapter 4). That is why a U-Net fits so well: it is built to turn a picture into a picture of the same size.
Slide 42 shows generated faces and generated scenes. The pictures are the same idea as the spiral, with 12,288 dimensions in place of two: start from static, walk down the ladder, and a face appears.
Slide 43 moves to sound. WaveGrad (Chen et al., 2020) generates an audio waveform directly: it starts from noise of the same length as the clip and denoises it, one rung at a time. The slide notes that the walk can be conditioned on an input, for example a text prompt in text-to-speech. Conditioning just adds an input c to the network, sθ(x̃, σ, c), and trains it with pairs of signal and condition. In WaveGrad the condition is a spectrogram. Text first becomes a spectrogram, and the spectrogram steers the waveform.
The slide also points to Riffusion, which does something cheeky. It treats a spectrogram, a picture of how a sound’s frequencies change over time, as an ordinary image and uses an image diffusion model to draw new ones. Our short-time Fourier transform lesson shows how that picture is made. A spectrogram keeps only magnitudes, so a separate step must estimate the phase to turn the picture back into sound. A classic method for that is Griffin and Lim’s.
Why use a picture at all? Test it. The device below hides a chirp, a tone that sweeps from 300 Hz to 3,000 Hz, in noise, and shows it both ways.
Top: the waveform, 4,096 samples (0.5 s at 8,000 per second). Bottom: its spectrogram, with time across and frequency up (0 to 4 kHz). Drag the signal to noise ratio down and compare which view still shows the sweep. Press the blue button to overlay the clean signal.
Illustrative: a linear chirp of unit power from 300 to 3,000 Hz plus white noise, 8,000 samples per second. The spectrogram uses a 128-sample Hann window, steps of 64 samples and 65 frequency bins, 62.5 Hz each. A frame counts as “found” if its loudest bin is within two bins of the true sweep. The blue lines, shown on request, are the clean tone and its true frequency.
At 14 dB both views show the chirp. At −6 dB the waveform is a fuzzy band and you cannot see the sweep, yet in the spectrogram the loudest cell sits on the sweep in about 92% of the frames. At −12 dB it falls to about 35%. The spectrogram packs a sound’s structure into a few bright cells, and noise spreads thinly over all of them. That is why a picture of sound is a friendly thing to denoise.
Conditioning follows from Chapter 3. The score of data given a condition c splits in two: ∇ log p(x|c) = ∇ log p(x) + ∇ log p(c|x). One part says “look like the data” and the other says “agree with c”. A model can learn the sum directly from pairs, as WaveGrad does, or add a separate steering term on top. Our score matching and guidance lesson develops the second route. For the full image story see the diffusion lesson and the flow and diffusion models series.
Symptom: at heavy noise the model cannot see any structure and guesses. Measurement: at −12 dB the sweep is the loudest thing in only about 35% of spectrogram frames. Fix: do not ask the network to find structure at that noise level from scratch on every step. The top rungs only need to settle the coarse layout, the sweep’s direction, and the rungs below see a far cleaner input, as you saw in Chapter 7.
Chapter 10
Carry away the numbers, the code and the habits, and find where to read next
The whole lecture fits in one line. Add noise to data in several amounts. Train a network to point back toward the clean data at each amount. Then start from static and walk down the noise levels, one small noisy step along the network’s arrows at a time.
Everything else is a reason this works. SGD gives the learning rule (Chapter 1). Noise in the step turns a descent into a sampler (Chapter 2). The score is the only arrow the sampler needs (Chapter 3), and a network can hold it (Chapter 4). Noise makes the score learnable (Chapter 5) and equals optimal denoising (Chapter 6). A ladder of levels fixes what one level cannot (Chapter 7). Walking the ladder is a diffusion model (Chapter 8), and U-Nets carry it to pictures and sound (Chapter 9).
| Idea | Formula or value | Source |
|---|---|---|
| LMS step | x ← x − α(aTx − d)a. Stable for white Gaussian input below α = 2/(l + 2) times the input power, so 0.4 for 3 weights. | Slide 2. The stability bound is classical, not in the slides. |
| Langevin step | x ← x + (ε/2)s(x) + √ε z, with z ∼ N(0, I). The walker follows e−f as ε → 0. | Slides 5, 13 |
| Spread of the sampler | V = ε/(1 − a²), a = 1 − ε/2. At ε = 0.5 the spread is 1.07 instead of 1. | Worked in Chapter 2 |
| Score | s(x) = ∇x log p(x). For a bell curve, −(x − μ)/σ². It needs no normalising constant. | Slides 13 to 15 |
| Mixture of blobs | The score is a patchwork of the blobs’ scores. The mixing weights are lost between blobs. | Slides 16, 17 |
| Guarantee | Convergence in Wasserstein distance when log p is concave. Otherwise only near stationarity. | Slide 20 |
| Easy target | ∇ log q(x̃|x) = −(x̃ − x)/σ² = −n/σ, where x̃ = x + σn. | Slides 22, 24 |
| Denoising score matching | min E ‖sθ(x + σn) + n/σ‖². The slides drop the sign. | Slides 23, 24 |
| Tweedie | E[x|x̃] = x̃ + σ²∇ log qσ(x̃). For a bell curve prior, the gain τ²/(τ² + σ²). | Slide 28 |
| Noise ladder | L = 10, σ from 1 down to 0.01, a range of 40 dB. Weight each level by σ². | Slides 33 to 35 |
| Annealed step | εi = ε0σi²/σL², with T steps per level. Take T = 1 for diffusion. | Slides 37, 38 |
| DDPM | 1,000 steps, noise per step from 0.0001 to 0.02 (Ho et al.). | Slide 39 and the paper |
Training is five lines. Sampling is a double loop. The shapes in the comments are the real ones for a batch of colour pictures. This is a sketch of the method in PyTorch style, not a tuned recipe.
pythonimport torch sigmas = torch.logspace(0, -2, 10) # 1.0 ... 0.01, ten rungs (slide 35) def train_step(net, opt, x): # x: (B, C, H, W) clean batch B = x.shape[0] i = torch.randint(0, len(sigmas), (B,)) # one rung per picture sigma = sigmas[i].view(B, 1, 1, 1) n = torch.randn_like(x) # unit noise, shape (B, C, H, W) x_noisy = x + sigma * n # the noisy copy, same shape s = net(x_noisy, sigmas[i]) # score estimate, (B, C, H, W) loss = ((sigma * s + n) ** 2).sum(dim=(1, 2, 3)).mean() # weight sigma^2 (Ch 7) opt.zero_grad(); loss.backward(); opt.step() # one SGD step (Ch 1) return loss.item() @torch.no_grad() def sample(net, shape, eps0=2e-5, T=100): # annealed Langevin (slide 37); eps0 illustrative x = torch.randn(shape) * sigmas[0] # static at the top rung for sigma in sigmas: # noisiest to quietest eps = eps0 * (sigma / sigmas[-1]) ** 2 # step scales with sigma^2 for _ in range(T): # T = 1 gives a diffusion model z = torch.randn_like(x) s = net(x, sigma.expand(shape[0])) x = x + 0.5 * eps * s + eps.sqrt() * z return x # 10 x 100 = 1,000 network calls
Count the cost. With 10 rungs and 100 steps each, one batch of pictures takes 1,000 passes through the network. That is why practical samplers work so hard to cut the number of steps.
Every chapter ended with a failure and a fix. Here they are as a game. Read each symptom, then choose the fix that the lecture’s idea gives.
Read the symptom, then press the fix that cures it. Use Next symptom to move on.
The five cases come from Chapters 2, 2, 3, 7 and 6. Each fix names the idea that cures the symptom; the measurements are in those chapters’ devices.
The previous lecture, Transformers for signals, built the attention networks that now sit inside many score models. This lecture used them as black boxes and asked what to train them on. The next, convex neural networks, returns to training itself. Earlier ones supply the signal tools: adaptive filters for LMS, the STFT for spectrograms, deep learning for the networks, and autoencoders, which learn to compress and rebuild.
This lesson is based on the Diffusion Models lecture of Stanford EE269, Signal Processing for Machine Learning, taught by Mert Pilanci. See the course site and the lecture slides. The swiss roll example on slides 25 and 26 is credited there to Kevin Murphy. We re-teach every idea in our own words and our own devices, and we copy none of the slide images.
Now press Present or Teach and explain the whole walk out loud, from memory: the step, the score, the noise ladder and the cleaning. Then go back to the walkers at the top, press Run on Plain descent, Langevin and Annealed in turn, and say why the shares come out as they do.