Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

How diffusion models work

After this lesson: I can add noise to data step by step and remove it again to generate new points.

70 min lesson5 commandsJupyterLab data science lab: pandas, Matplotlib and scikit-learn in the browser

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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

WordWhat it meansExample
Forward processadding a little noise to data at every step
Noise schedulehow much noise each step adds0.001 rising to 0.2
Signal lefthow much of the original survives the noise
Reverse processremoving the noise step by step
Denoiserthe 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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

The 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

StepNoise drawnNew valueSignal left
02.01.0
10.50.949 × 2.0 + 0.316 × 0.5 = 2.060.949
2-1.00.949 × 2.06 + 0.316 × -1.0 = 1.630.9
30.30.949 × 1.63 + 0.316 × 0.3 = 1.640.854

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Try it: how fast the signal fades

Code: python
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

Command
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

Command
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

Command
docker exec jupyter python3 steps/diff.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What diff.py printed

Forward stepMean radiusShare near the ring
11.991.0
101.860.33
251.520.16
501.230.1
Signal left at step 500.067

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

The 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

Command
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

Command
docker exec jupyter python3 steps/undiff.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What undiff.py printed

Reverse stepMean radiusShare near the ring
101.320.12
251.430.16
401.860.35
502.01.0
Within 0.05 of a training point0.98

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A 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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Assignment: 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.

Code: python
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

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.