Phase 1: Diffusion Model Fundamentals · 50 min · Python · PyTorch · Hugging Face Diffusers
The Problem
Before 2020, image generation was dominated by GANs (Generative Adversarial Networks). GANs were fast but unstable — training collapses, mode dropping, and limited diversity were constant problems. Then in 2020, a paper called DDPM (Denoising Diffusion Probabilistic Models) changed everything. Diffusion models were slower, but they were stable, diverse, and produced higher quality images. By 2022, Stable Diffusion brought latent diffusion to consumer GPUs, and by 2024, FLUX and Sora pushed diffusion to production quality.
If you're building generative media systems, you need to understand how diffusion works — not at a PhD level, but at an engineering level. You need to know what the model is doing when you set num_inference_steps=4 and what guidance_scale=7.5 actually controls.
What you'll build
A visualization of forward diffusion (adding noise to an image step by step) and reverse diffusion (denoising from pure noise to a coherent image). You'll implement forward diffusion from scratch and use a pre-trained model for reverse diffusion.
The Concept
Forward diffusion: adding noise
Forward diffusion is simple: take an image and progressively add Gaussian noise over T steps. At step 0, you have the original image. At step T, you have pure noise.
import torch
def forward_diffusion(image, num_steps=1000, beta_start=0.0001, beta_end=0.02):
"""
Forward diffusion: progressively add noise to an image.
Args:
image: tensor of shape (C, H, W) with values in [0, 1]
num_steps: total diffusion steps (T)
beta_start, beta_end: noise schedule parameters
Returns:
List of noisy images at each step
"""
betas = torch.linspace(beta_start, beta_end, num_steps)
alphas = 1.0 - betas
alpha_bars = torch.cumprod(alphas, dim=0)
noisy_images = []
for t in range(num_steps):
noise = torch.randn_like(image)
# x_t = sqrt(alpha_bar_t) * x_0 + sqrt(1 - alpha_bar_t) * noise
noisy = torch.sqrt(alpha_bars[t]) * image + torch.sqrt(1 - alpha_bars[t]) * noise
noisy_images.append(noisy)
return noisy_images
The key formula at each step t:
x_t = √(ᾱ_t) · x_0 + √(1 - ᾱ_t) · ε
where:
x_0 = original image
ε = Gaussian noise (sampled from N(0, I))
ᾱ_t = cumulative product of (1 - β_t)
β_t = variance schedule (small → large)
At early steps (t near 0), the image is mostly intact. At later steps (t near T), the image is dominated by noise. At step T, the image is pure Gaussian noise — the original structure is completely destroyed.
Forward diffusion is not learned
Forward diffusion is a fixed mathematical process — no neural network is involved. It's just adding noise according to a schedule. The learning happens in reverse diffusion.
Reverse diffusion: denoising
Reverse diffusion is where the neural network comes in. The model learns to predict the noise that was added at each step, then subtracts it to denoise.
Forward: x_0 → x_1 → x_2 → ... → x_T (adding noise)
Reverse: x_T → x_{T-1} → ... → x_1 → x_0 (removing noise)
The neural network ε_θ(x_t, t) takes the noisy image x_t and the timestep t, and predicts the noise ε that was added. Then we subtract the predicted noise:
def reverse_diffusion_step(model, x_t, t, alpha_bar_t, beta_t):
"""One step of reverse diffusion: predict noise and remove it."""
# Model predicts the noise
predicted_noise = model(x_t, t)
# Remove predicted noise
mean = (1 / torch.sqrt(1 - beta_t)) * (x_t - (beta_t / torch.sqrt(1 - alpha_bar_t)) * predicted_noise)
# Add small amount of noise for diversity (except at t=0)
if t > 0:
noise = torch.randn_like(x_t)
x_t_minus_1 = mean + torch.sqrt(beta_t) * noise
else:
x_t_minus_1 = mean
return x_t_minus_1
Starting from pure noise x_T, we run T reverse steps to get x_0 — the generated image.
What does the neural network in a diffusion model actually predict?
The neural network predicts the noise ε that was added at each diffusion step. By subtracting the predicted noise from the noisy image, we get a slightly less noisy image. Repeating this T times transforms pure noise into a coherent image. This is fundamentally different from GANs, which generate the image directly.
Why diffusion replaced GANs
| Property | GANs | Diffusion |
|---|
| Training stability | Unstable (mode collapse) | Stable |
| Diversity | Limited (few modes) | High (covers full distribution) |
| Quality | Good | Better (especially at scale) |
| Speed | Fast (single forward pass) | Slow (T denoising steps) |
| Controllability | Limited | High (text, image, ControlNet) |
| Scaling | Difficult | Excellent (DiTs scale with compute) |
The trade-off: diffusion models are slower (multiple steps vs single pass), but they're more stable, diverse, and controllable. For production systems, the quality and control advantages far outweigh the speed cost — especially with techniques like FLUX Schnell (4 steps) and distillation.
Noise schedules
The noise schedule (β_t values) controls how quickly noise is added:
| Schedule | β_t Shape | Characteristics |
|---|
| Linear | Constant increase | Simple, works well |
| Cosine | Slow start, fast middle, slow end | Smoother, better for large T |
| Scaled | Adjusted for resolution | Used in SDXL, FLUX |
# Linear schedule (DDPM original)
betas = torch.linspace(0.0001, 0.02, 1000)
# Cosine schedule (Improved DDPM)
def cosine_beta_schedule(timesteps, s=0.008):
steps = timesteps + 1
x = torch.linspace(0, timesteps, steps)
alphas_cumprod = torch.cos(((x / timesteps) + s) / (1 + s) * torch.pi * 0.5) ** 2
alphas_cumprod = alphas_cumprod / alphas_cumprod[0]
betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1])
return betas
Using pre-trained diffusion models
In production, you don't implement diffusion from scratch — you use pre-trained models via Hugging Face Diffusers or fal.ai APIs:
from diffusers import FluxPipeline
import torch
# Load FLUX.1 Schnell (4-step diffusion model)
pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.float16)
pipe.to("cuda")
# Generate: this runs reverse diffusion internally
image = pipe(
prompt="a cat sitting on a windowsill",
num_inference_steps=4, # Only 4 steps (Schnell is distilled)
guidance_scale=0.0, # Schnell doesn't need guidance
height=1024, width=1024,
).images[0]
When you call pipe(prompt, num_inference_steps=4), the pipeline:
- Encodes the text prompt into embeddings (CLIP/T5)
- Generates random noise in latent space
- Runs 4 reverse diffusion steps (predicting and removing noise)
- Decodes the latent to pixel space (VAE)
- Returns the final image