Advanced Topics
Diffusion Models — How DALL-E and Stable Diffusion Create Images
Understand the revolutionary diffusion models behind modern image generation. Learn how these models gradually denoise random noise into coherent images.
- Forward Diffusion — The process of adding noise to data
- Reverse Diffusion — Learning to denoise and generate new samples
- Conditional Generation — Guiding generation with text or other inputs
"Creation is just destruction in reverse."
Diffusion Models — Complete Guide
Diffusion models are the state-of-the-art for image generation (DALL-E, Stable Diffusion, Midjourney).
How Diffusion Works
Forward Process (fixed): Image -> Add noise -> Add noise -> ... -> Pure noise
Reverse Process (learned): Pure noise -> Remove noise -> ... -> Image
The model LEARNS to reverse the noise!
Forward and Reverse Diffusion Process
How diffusion models generate images: This diagram shows the two core processes of diffusion models. The forward process (top, flowing right) gradually adds Gaussian noise to a clean image x₀ over T timesteps, progressively destroying information until it becomes pure noise x_T ~ N(0,I). This process is fixed and non-learned — the noise schedule β_t controls how quickly noise is added. The reverse process (bottom, flowing left) is learned by a neural network: starting from random noise x_T, it iteratively denoises one step at a time, progressively recovering the clean image. At each step, the model predicts the noise ε_θ(x_t, t) that was added, and subtracts it to get a slightly cleaner version. After T denoising steps, the result is a generated image x₀. The key insight: by learning to reverse a simple, known corruption process, we get a powerful generative model that can create realistic images from pure noise.
DDPM (Denoising Diffusion Probabilistic Models)
Training:
- Take clean image
- Sample random timestep
- Add noise:
- Model predicts noise:
- Loss:
Generation:
- Start with random noise
- For :
- Return
DDPM Noise Schedule
Classifier-Free Guidance
Where = guidance scale:
- : No guidance (standard)
- : Good balance
- : Very high quality, low diversity
Classifier-Free Guidance Visualization
Latent Diffusion (Stable Diffusion)
Latent Diffusion Architecture
Training and Sampling in Code
The training loop is smaller than the theory suggests: sample a timestep, noise the image once, ask the network for the noise, take a mean squared error. Everything about schedules and samplers lives in how the coefficients below are computed.
import torch
import torch.nn.functional as F
def cosine_beta_schedule(timesteps, s=0.008):
steps = timesteps + 1
x = torch.linspace(0, timesteps, steps)
a_bar = torch.cos(((x / timesteps) + s) / (1 + s) * torch.pi * 0.5) ** 2
a_bar = a_bar / a_bar[0]
betas = 1 - (a_bar[1:] / a_bar[:-1])
return betas.clamp(0, 0.999)
T = 1000
betas = cosine_beta_schedule(T)
alpha_bar = torch.cumprod(1.0 - betas, dim=0)
def q_sample(x0, t, noise):
# jump straight to x_t without stepping through t - 1 earlier states
a = alpha_bar[t].sqrt()
s = (1 - alpha_bar[t]).sqrt()
return a * x0 + s * noise
def training_step(model, x0, t):
noise = torch.randn_like(x0)
xt = q_sample(x0, t, noise)
return F.mse_loss(model(xt, t), noise)
Sampling runs the learned reverse process from pure noise. With a deterministic sampler you may evaluate only a subset of timesteps, which is the single largest speed lever in the whole method: fifty steps of a deterministic sampler replace a thousand stochastic ones, and each skipped step is one full U-Net forward pass you do not pay for.
@torch.no_grad()
def ddim_sample(model, shape, steps=50, eta=0.0):
x = torch.randn(shape)
times = torch.linspace(T - 1, 0, steps).long()
for i, t in enumerate(times):
eps = model(x, t.expand(shape[0]))
a_t = alpha_bar[t]
a_prev = alpha_bar[times[i + 1]] if i + 1 < len(times) else torch.tensor(1.0)
x0_pred = (x - (1 - a_t).sqrt() * eps) / a_t.sqrt()
sigma = eta * ((1 - a_prev) / (1 - a_t)).sqrt() * (1 - a_t / a_prev).sqrt()
dir_xt = (1 - a_prev - sigma ** 2).clamp(min=0).sqrt() * eps
x = a_prev.sqrt() * x0_pred + dir_xt
if eta > 0:
x = x + sigma * torch.randn_like(x)
return x
Set eta to zero for a deterministic sampler that produces sharp results with less stochastic variation, or above zero to inject noise and recover the diversity of ancestral sampling at the cost of detail.
Noise Schedules and Sampler Trade-offs
The original linear schedule ramps beta from 0.0001 to 0.02 across a thousand steps. It spends most of the schedule at low noise levels and crushes the signal late, so small textures and thin structures are the first thing to go. The cosine schedule reshapes the accumulated alpha bar with a shifted cosine curve, offset by 0.008 to avoid a sharp boundary at either end, and decays the signal-to-noise ratio more evenly across timesteps.
Guidance adds a second axis of cost. Classifier-free guidance combines a text-conditioned prediction with an unconditional one, which means two U-Net passes per timestep unless both are batched together — doubling per-step compute for the quality gain. The guidance scale is a dial between coverage and fidelity rather than a quality setting: values around 7 to 12 give the balance most checkpoints were tuned for, and pushing past 15 trades diversity for saturation.
| Sampler | Steps needed | Stochastic? | When to use it |
|---|---|---|---|
| Ancestral DDPM | 1000 | Yes, noise added each step | Final images when compute is free |
| DDIM | 20 to 50 | No, when eta is zero | Previews, iteration, prompt search |
| DPM-Solver++ | 10 to 25 | Mostly deterministic | Production throughput with quality held |
| Euler ancestral | 20 to 50 | Yes | Latent diffusion checkpoints tuned for it |
Latent diffusion is why these loops are affordable. A 512 by 512 by 3 pixel image holds 786,432 values, while the equivalent latent at 64 by 64 by 4 holds 16,384 — exactly 48 times fewer — and attention cost grows with the square of the spatial resolution, so the ratio at 64 by 64 versus 512 by 512 is a factor of 64 fewer positions to attend over. The U-Net then runs entirely on the small grid, and the decoder is invoked once at the very end.
Common Mistakes
Keeping the original per-step variance term while switching to noise prediction
Fix: Modern implementations predict epsilon with the simplified objective and derive the mean; if you predict the clean image instead, clip it back to the data range before recomputing the mean.
Passing raw VAE latents to a Stable Diffusion U-Net
Fix: Scale latents by the checkpoint's factor, 0.18215 for Stable Diffusion 1.5, before the U-Net and divide it out afterwards, or generations come back washed out and low contrast.
Raising the guidance scale past 15 to rescue a vague prompt
Fix: Saturation and composition collapse follow quickly; rewrite the prompt, add a negative prompt, and keep the scale between 7 and 12.
Key Takeaways
What to Learn Next
-> GANs — Generative Adversarial Networks Complete Guide Learn about gans — generative adversarial networks complete guide.
-> Autoencoders — Encoding, Decoding and Representation Learning Learn about autoencoders — encoding, decoding and representation learning.
-> Autoencoders Learn about autoencoders.
-> Neural Networks Fundamentals — Perceptrons to Deep Learning Learn about neural networks fundamentals — perceptrons to deep learning.
-> Transformers — Attention Is All You Need Complete Guide Learn about transformers — attention is all you need complete guide.
-> Self-Supervised Learning — Pre-training Revolution Learn about self-supervised learning — pre-training revolution.