From static to a picture
A diffusion model generates data by starting from pure noise and removing a little at a time. What is left looks like the training data. It learns this by watching data being turned into noise.
Most image and video generators today are diffusion models. This lesson builds one on 2-D points, with every step visible.
By the end of this lesson
Note
I can add noise to data step by step and remove it again to generate new points.
Key words
| Word | What it means | Example |
|---|---|---|
| Forward process | adding a little noise to data at every step | |
| Noise schedule | how much noise each step adds | 0.001 rising to 0.2 |
| Signal left | how much of the original survives the noise | |
| Reverse process | removing the noise step by step | |
| Denoiser | the model that guesses the noise in a noisy input |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
4 questionsThe forward process adds noise
At each step of the forward process the point shrinks a little and gets a little random noise. With a share β of noise, the new value is √(1 - β) × old + √β × noise.
The noise schedule says β for each step. The signal left, the share of the original still there, falls at every step. After enough steps only noise is left, and no step needs training.
Worked example: one number, β = 0.1
| Step | Noise drawn | New value | Signal left |
|---|---|---|---|
| 0 | 2.0 | 1.0 | |
| 1 | 0.5 | 0.949 × 2.0 + 0.316 × 0.5 = 2.06 | 0.949 |
| 2 | -1.0 | 0.949 × 2.06 + 0.316 × -1.0 = 1.63 | 0.9 |
| 3 | 0.3 | 0.949 × 1.63 + 0.316 × 0.3 = 1.64 | 0.854 |
The cells students fill in are left blank in this preview.
Check
Have a go
Check
3 questionsTry it: how fast the signal fades
import math
# How much of the original is left after each step of noise.
beta = 0.1 # the share of noise added at every step
left = 1.0
for step in range(1, 21):
left = left * (1 - beta)
if step in [1, 2, 3, 10, 20]:
print("step", step, "signal left", round(math.sqrt(left), 3))
# Change beta to 0.2 and press Run. How much is left after 20 steps?
Make a free account to save your work and track your progress.
Noise a ring of points in the lab
The lab's data are 200 made-up points on a ring of radius 2. The schedule has 50 steps, from β = 0.001 to β = 0.2. One script holds the ring and the schedule. The next adds the noise and prints two things: the mean distance from the centre and the share near the ring.
Pure noise in two numbers has a mean radius of about 1.25, so watch the radius fall towards that.
Write the ring and the schedule
docker exec jupyter sh -c "printf '%s\n' 'import numpy as np' 'r = np.random.default_rng(0)' 'angle = r.uniform(0, 2 * np.pi, 200)' 'ring = 2 * np.stack([np.cos(angle), np.sin(angle)], axis=1)' 'betas = np.linspace(0.001, 0.2, 50)' 'abar = np.cumprod(1 - betas)' 'def report(name, x):' ' radius = np.linalg.norm(x, axis=1)' ' print(name, \"mean radius\", round(radius.mean(), 2), \"near the ring\", round((abs(radius - 2) < 0.2).mean(), 2))' > steps/ring.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the forward script
docker exec jupyter sh -c "printf '%s\n' 'from ring import np, r, ring, betas, abar, report' 'x = ring.copy()' 'for t in range(50):' ' x = np.sqrt(1 - betas[t]) * x + np.sqrt(betas[t]) * r.normal(0, 1, x.shape)' ' if t + 1 in (1, 10, 25, 50):' ' report(\"forward step \" + str(t + 1), x)' 'print(\"signal left at step 50:\", round(np.sqrt(abar[-1]), 3))' > steps/diff.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Noise the ring for 50 steps
docker exec jupyter python3 steps/diff.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
What diff.py printed
| Forward step | Mean radius | Share near the ring |
|---|---|---|
| 1 | 1.99 | 1.0 |
| 10 | 1.86 | 0.33 |
| 25 | 1.52 | 0.16 |
| 50 | 1.23 | 0.1 |
| Signal left at step 50 | 0.067 |
The cells students fill in are left blank in this preview.
Check
Have a go
Check
3 questionsThe reverse process removes noise
To generate, start from fresh noise and run the steps backwards. At each step a denoiser guesses the noise in the current points, and the reverse process takes a little of it away.
A real denoiser is a neural network trained on noisy copies of the data. Its loss is the squared gap between the noise added and the noise guessed. The lab uses the exact best guess for its 200 points instead, so nothing is trained.
One reverse step, fifty times
flowchart LR
N["Points of pure noise"] --> G["Denoiser guesses the noise"]
G --> S["Take a little noise away"]
S --> A["Add a little fresh noise, except at the end"]
A --> G
S --> P["After 50 steps: new points"]Write the reverse script
docker exec jupyter sh -c "printf '%s\n' 'from ring import np, r, ring, betas, abar, report' 'def guess_x0(x, t):' ' gap = ((x[:, None, :] - np.sqrt(abar[t]) * ring[None]) ** 2).sum(axis=2)' ' weight = np.exp(-(gap - gap.min(axis=1, keepdims=True)) / (2 * (1 - abar[t])))' ' return weight @ ring / weight.sum(axis=1, keepdims=True)' 'x = r.normal(0, 1, (500, 2))' 'for t in range(49, -1, -1):' ' noise = (x - np.sqrt(abar[t]) * guess_x0(x, t)) / np.sqrt(1 - abar[t])' ' x = (x - betas[t] / np.sqrt(1 - abar[t]) * noise) / np.sqrt(1 - betas[t])' ' if t > 0:' ' x = x + np.sqrt(betas[t]) * r.normal(0, 1, x.shape)' ' if t in (40, 25, 10, 0):' ' report(\"reverse step \" + str(50 - t), x)' 'copy = np.sqrt(((x[:, None, :] - ring[None]) ** 2).sum(axis=2)).min(axis=1)' 'print(\"within 0.05 of a training point:\", round((copy < 0.05).mean(), 2))' > steps/undiff.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Generate 500 points from noise
docker exec jupyter python3 steps/undiff.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
What undiff.py printed
| Reverse step | Mean radius | Share near the ring |
|---|---|---|
| 10 | 1.32 | 0.12 |
| 25 | 1.43 | 0.16 |
| 40 | 1.86 | 0.35 |
| 50 | 2.0 | 1.0 |
| Within 0.05 of a training point | 0.98 |
The cells students fill in are left blank in this preview.
Check
Have a go
Check
3 questionsA common mistake
Warning
Many people think a diffusion model removes the noise in one go. One guess from pure noise is poor, as the radius of 1.32 after ten steps shows. Each step trusts the guess a little, and only many small steps give a clean sample.
A perfect denoiser copies its data
Of the 500 new points, 0.98 sat within 0.05 of a training point. The exact best guess knows only those 200 points, so it steers every sample onto one of them.
A neural network cannot fit its data perfectly, and that is why it makes new points between them. A large model trained on few copies of one picture can still reproduce it, which lesson 6 returns to.
Check
Have a go
Check
3 questionsAssignment: noise and denoise by hand
Write four functions for a diffusion model on 2-D points.
alpha_bars(betas) gives a list: after each step, the product of 1 - beta over every step so far, each rounded to 4 places. add_noise(x0, noise, alpha_bar) jumps straight to a noisy point: for each of the two numbers, math.sqrt(alpha_bar) * x0[i] + math.sqrt(1 - alpha_bar) * noise[i], rounded to 4 places. guess_clean(xt, noise_guess, alpha_bar) undoes that with a guess of the noise: (xt[i] - math.sqrt(1 - alpha_bar) * noise_guess[i]) / math.sqrt(alpha_bar), rounded to 4 places. mean_radius(points) gives the mean distance of the points from (0, 0), rounded to 2 places.
import math
def alpha_bars(betas):
return []
def add_noise(x0, noise, alpha_bar):
return x0
def guess_clean(xt, noise_guess, alpha_bar):
return xt
def mean_radius(points):
return 0.0
Make a free account to save your work and track your progress.
Exit quiz
Have a go