Diffusion Models
A diffusion model creates an image by starting from pure random noise and removing a little noise at a time, over many steps, until a clear picture appears. It learns how by doing the opposite in training: taking real images, adding noise, and learning to predict the noise that was added. Most modern image generators, such as Stable Diffusion, Midjourney, DALL-E and Imagen, are built on this idea, and so are many video and audio generators.
The Two Directions
| Process | Description |
|---|---|
| Forward process (adding noise) | It is used in training: add a known amount of random noise to a real image |
| Reverse process (removing noise) | It is used in generation: start from noise and remove predicted noise, step by step |
| Denoiser | A neural network that looks at a noisy image and predicts the noise in it, usually a U-Net |
| Steps | How many times noise is removed; more steps usually means a cleaner image, but takes longer |
| Conditioning | It is used to steer the result, with a class label or, in text-to-image, the prompt |
| Seed | The number that sets the starting noise; the same seed and settings give the same image |
Example: Adding Noise
This program takes one handwritten digit from scikit-learn and adds noise to it, as the forward process does. The numbers become characters, darkest to brightest: .:-=+*#@.
import numpy as np
from sklearn.datasets import load_digits
digits = load_digits()
x0 = digits.images[0] / 8 - 1 # one handwritten 0, pixels scaled to -1 ... 1
T = 100 # number of noise steps
betas = np.linspace(0.0001, 0.1, T) # how much noise each step adds
alpha_bar = np.cumprod(1 - betas) # how much of the image survives after t steps
def show(img):
chars = " .:-=+*#%@"
for row in img:
print(" " + "".join(chars[int(np.clip((v + 1) / 2, 0, 0.999) * 10)] * 2 for v in row))
rng = np.random.default_rng(0)
noise = rng.normal(size=x0.shape)
for t in [0, 10, 30, 99]:
xt = np.sqrt(alpha_bar[t]) * x0 + np.sqrt(1 - alpha_bar[t]) * noise # jump straight to step t
print(f"step {t + 1}: {np.sqrt(alpha_bar[t]):.0%} image, {np.sqrt(1 - alpha_bar[t]):.0%} noise")
show(xt)step 1: 100% image, 1% noise
--%%++
%%@@**@@--
..@@.. **==
::## ++==
--++ ++++
::** ##==
..%%--**##
--%%**
step 11: 97% image, 23% noise
--%%==......
##@@--%%..
..@@:: %%==
..::** ++--
--++ ++++..
==%%....##**::
::::@@..**%%
::##++ ::
step 31: 79% image, 62% noise
.. ++##--::++--
++%% ##
..@@++ @@::::
----== ++..
++++:: ++##++
##@@--::**%%##
****@@ ++%% ::
::-- ++== **
step 100: 7% image, 100% noise
++--%%++::**@@@@
.. ::++ ==
..--##@@--@@..**
@@++.. ::** --
--##****..==%%@@
@@@@%%++--@@@@
@@@@## ++%% **
**%% ..:: @@::Explanation:
betasset how much noise each of the 100 steps adds, a little at first and more later.alpha_barmultiplies them together, so the program can jump straight to any step.- At step 11 the 0 is still clear (97% image). By step 31 it is fading into noise, and at step 100 it is 7% image and 100% noise: just static.
- Training uses exactly this formula: pick a real image, a random step and random noise, mix them, and ask the denoiser to predict the noise.
Example: A Diffusion Model from Scratch
This program trains a tiny denoiser on the 1,797 digits, then generates new digits from pure noise. The digit you ask for (2, 7 or 4) is the conditioning, a very small version of a text prompt.
import torch
from sklearn.datasets import load_digits
from torch import nn
digits = load_digits()
X = torch.tensor(digits.data / 8 - 1, dtype=torch.float32) # 1,797 digits, 64 pixels from -1 to 1
labels = torch.tensor(digits.target)
T = 100
betas = torch.linspace(0.0001, 0.1, T)
alphas = 1 - betas
alpha_bar = torch.cumprod(alphas, dim=0)
# The denoiser: given a noisy image, the step number and the digit wanted, predict the noise
class Denoiser(nn.Module):
def __init__(self):
super().__init__()
self.step = nn.Embedding(T, 64)
self.digit = nn.Embedding(10, 64) # the "prompt": which digit to draw
self.net = nn.Sequential(nn.Linear(64 + 64, 256), nn.SiLU(), nn.Linear(256, 256), nn.SiLU(), nn.Linear(256, 64))
def forward(self, x, t, d):
return self.net(torch.cat([x, self.step(t) + self.digit(d)], dim=1))
torch.manual_seed(0)
model = Denoiser()
optimizer = torch.optim.Adam(model.parameters(), lr=0.002)
print(f"Denoiser: {sum(p.numel() for p in model.parameters()):,} parameters")
# Training: add a random amount of noise to real digits, and learn to predict that noise
for step in range(1, 6001):
i = torch.randint(0, len(X), (128,))
t = torch.randint(0, T, (128,))
noise = torch.randn(128, 64)
a = alpha_bar[t].sqrt()[:, None]
noisy = a * X[i] + (1 - alpha_bar[t]).sqrt()[:, None] * noise
loss = nn.functional.mse_loss(model(noisy, t, labels[i]), noise)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if step in (1, 1000, 6000):
print(f"training step {step}: loss {loss.item():.3f}")
# Generation: start from pure noise and remove a little predicted noise, 100 times
@torch.no_grad()
def generate(digit, seed):
g = torch.Generator().manual_seed(seed)
x = torch.randn(1, 64, generator=g)
for t in reversed(range(T)):
tt = torch.tensor([t])
predicted = model(x, tt, torch.tensor([digit]))
x = (x - betas[t] / (1 - alpha_bar[t]).sqrt() * predicted) / alphas[t].sqrt()
if t > 0:
x = x + betas[t].sqrt() * torch.randn(1, 64, generator=g)
return x.reshape(8, 8)
chars = " .:-=+*#@"
images = [generate(d, seed=d).clamp(-1, 1) for d in [2, 7, 4]]
print("\nGenerated from pure noise: a 2, a 7 and a 4")
for r in range(8):
print(" ".join("".join(chars[int((v + 1) / 2 * 8.999)] * 2 for v in img[r].tolist()) for img in images))Denoiser: 122,304 parameters
training step 1: loss 1.009
training step 1000: loss 0.200
training step 6000: loss 0.141
Generated from pure noise: a 2, a 7 and a 4
==##@@==.. ::###### .. **--
..==--==@@:: --##@@@@ ==@@ ..
.. ..--@@-- ..**-- @@-- ::==
##** **@@** ++@@::**++++
::##:: --##@@@@@@== ==@@@@@@@@::
==**==-- ..--**##== ::++**..
..==@@**##++ ....**-- **==::
++**++**-- ..@@==.. ++@@==..Explanation:
- The denoiser is a small network (122,304 parameters) that gets a noisy image, the step number and the wanted digit, and predicts the noise. Its loss falls from 1.009 to 0.141.
- Generation runs the steps backward: start with 64 random numbers, and 100 times subtract the predicted noise (plus a little fresh noise, which keeps results varied).
- The results are new digits, not copies: a 2, a 7 and a 4 drawn from noise in about 6 seconds of training. Real image models do the same thing with far larger networks and millions of images.
How Image Generators Work
| Part | What it does in Stable Diffusion |
|---|---|
| Text encoder | Turns the prompt into embeddings (a CLIP text model); see "Multimodal Models" |
| U-Net denoiser | Removes noise step by step, guided by the prompt embeddings through attention |
| Latent space | Diffusion runs on a compressed 64 × 64 × 4 version of the image instead of 512 × 512 pixels, which is much faster |
| VAE decoder | Turns the final latent into a full 512 × 512 picture |
| Guidance scale | It is used to set how strongly the image follows the prompt; 7.5 is a common default |
Example: The Checkpoint
This program completes the chapter's checkpoint: generate images with a diffusion model locally, varying steps and prompts, and describe the effect of each. It uses BK-SDM-Tiny, a Stable Diffusion model made smaller by removing parts of the U-Net and distilling it from the full model (see "Distillation and Smaller Models"). It is about a 2 GB download and runs on a laptop CPU.
The programs in this chapter need pip install torch transformers diffusers scikit-learn scipy pillow. The first run of each pretrained model downloads it from Hugging Face; download and loading messages are left out of the output shown.
import torch
from diffusers import StableDiffusionPipeline
# BK-SDM-Tiny: a compressed Stable Diffusion model (CreativeML OpenRAIL-M license), about 2 GB
pipe = StableDiffusionPipeline.from_pretrained("nota-ai/bk-sdm-tiny", use_safetensors=True, safety_checker=None)
print(f"U-Net (the denoiser): {sum(p.numel() for p in pipe.unet.parameters()):,} parameters")
print(f"Text encoder (reads the prompt): {sum(p.numel() for p in pipe.text_encoder.parameters()):,} parameters")
def make(prompt, steps, seed, filename):
generator = torch.Generator().manual_seed(seed) # the starting noise; same seed, same picture
image = pipe(prompt, num_inference_steps=steps, generator=generator).images[0]
image.save(filename)
print(f"{filename:22} steps {steps:2} seed {seed} {image.size[0]}x{image.size[1]} \"{prompt}\"")
apple = "a red apple on a wooden table, photo"
print("\n1. Same prompt and seed, more denoising steps")
for steps in [5, 10, 25]:
make(apple, steps, 0, f"apple_steps{steps}.png")
print("\n2. Same seed and steps, different prompts")
make("a red apple on a wooden table, watercolor painting", 25, 0, "apple_watercolor.png")
make("a school bus parked in front of a library, photo", 25, 0, "bus.png")
print("\n3. Same prompt and steps, a different seed")
make(apple, 25, 1, "apple_seed1.png")U-Net (the denoiser): 323,384,964 parameters
Text encoder (reads the prompt): 123,060,480 parameters
1. Same prompt and seed, more denoising steps
apple_steps5.png steps 5 seed 0 512x512 "a red apple on a wooden table, photo"
apple_steps10.png steps 10 seed 0 512x512 "a red apple on a wooden table, photo"
apple_steps25.png steps 25 seed 0 512x512 "a red apple on a wooden table, photo"
2. Same seed and steps, different prompts
apple_watercolor.png steps 25 seed 0 512x512 "a red apple on a wooden table, watercolor painting"
bus.png steps 25 seed 0 512x512 "a school bus parked in front of a library, photo"
3. Same prompt and steps, a different seed
apple_seed1.png steps 25 seed 1 512x512 "a red apple on a wooden table, photo"Explanation:
| What changed | Effect, in the images in the diagram above |
|---|---|
| 5 steps | Not enough denoising: a mostly empty wooden table with a small, smeared fruit in a corner |
| 10 steps | Still unfinished: a jumble of colored shapes |
| 25 steps | A clean, detailed red apple on the table, matching the prompt |
| Prompt: "watercolor painting" | Same seed and steps, but painted apples on paper: the prompt controls style as well as content |
| Prompt: school bus and library | A completely different scene from the same starting noise |
| Seed 1 | Same prompt and steps, a different apple in a different place: the seed sets the starting noise |
- The U-Net has 323 million parameters and the text encoder 123 million. The full Stable Diffusion 1.x U-Net has about 860 million.
- Time grows with steps: on this laptop's CPU, one run took about 11 seconds at 5 steps and 30 seconds at 25. A GPU is many times faster.
safety_checker=Noneis needed because this model's files don't include Stable Diffusion's content filter. For anything public, add a filter and follow the model's license (CreativeML OpenRAIL-M), which forbids harmful uses.
With the same seed, settings and library versions, the same image comes out on the same machine.
Common Mistakes
Too few steps. Fast, but unfinished; 20 to 50 steps is typical for this kind of model, though some newer models are designed for 1 to 4.
Expecting the same image from a different seed. The seed is the starting noise; keep it fixed while you adjust the prompt.
Thinking the model searches for a stored picture. It generates a new image from noise, though it can sometimes reproduce images that were common in its training data.
Ignoring licenses and rights. Model licenses limit uses, and generated images can raise copyright and likeness questions; see "Audio and Video Generation".
Interview Corner
How does a diffusion model generate an image?
It starts from random noise and repeatedly uses a trained denoiser to predict and remove noise, guided by conditioning such as a text prompt, until an image remains. In training, it learned to predict the noise added to real images.
What is latent diffusion?
Running the diffusion process on a compressed representation of the image, from a VAE encoder, instead of on the pixels. It is much cheaper; a decoder turns the final latent back into a full-size image.
Practice
Exercise: guidance scale. Add guidance_scale=2.0 and then guidance_scale=12.0 to the pipe(...) call for the apple at 25 steps. How closely does each image follow the prompt, and how natural does it look?
Check your understanding:
- What does the denoiser learn to predict in training?
- Why did the 5-step apple look unfinished?
- What stays the same and what changes when only the seed changes?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| Load a pipeline | StableDiffusionPipeline.from_pretrained("nota-ai/bk-sdm-tiny", use_safetensors=True) |
| Generate | pipe(prompt, num_inference_steps=25, generator=torch.Generator().manual_seed(0)).images[0] |
| Follow the prompt more | guidance_scale=7.5 (higher is stricter) |
| Steer away from faults | negative_prompt="blurry" |
| Noisy image at step t | sqrt(alpha_bar[t]) * x0 + sqrt(1 - alpha_bar[t]) * noise |
Was this tutorial helpful?