🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Diffusion Models — State-of-the-Art Generative AI

Expert TopicsGenerative AI🟢 Free Lesson

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

Diffusion Model: Forward and Reverse ProcessForward Process (fixed): q(x_t | x_{t-1}) — Gradually add Gaussian noisex₀CleanImagex₁Slightnoisex₂Morenoisex₃Evenmore···x_TPureNoiseReverse Process (learned): p_θ(x_{t-1} | x_t) — Gradually remove noisex_TPureNoisex_{T-1}Denoisestepx_{T-2}Denoisestep···x₁Denoisestepx₀GeneratedImage!

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:

  1. Take clean image
  2. Sample random timestep
  3. Add noise:
  4. Model predicts noise:
  5. Loss:

Generation:

  1. Start with random noise
  2. For :
  3. Return

DDPM Noise Schedule

DDPM Noise Schedule and Training ObjectiveForward Processq(x_t | x_0) = N(x_t; √ε_t·x_0, (1-ε_t)I)ε_t = ∏_{s=1}^{t} (1 - β_s)β_t: noise schedule (linear, cosine, etc.)T = 1000 timesteps typicallyReverse Processp_θ(x_{t-1} | x_t) = N(x_{t-1}; μ_θ(x_t,t), σ_t²I)μ_θ = 1/√α_t (x_t - β_t/√(1-ε_t)·ε_θ)ε_θ: U-Net predicts noise at each steptimestep embedding guides the networkTraining Loss (Simplified)L_simple = E_{t,x_0,ε} [ ||ε - ε_θ(x_t, t)||² ]Predict the noise that was added, not the denoised image directly

Classifier-Free Guidance

Where = guidance scale:

  • : No guidance (standard)
  • : Good balance
  • : Very high quality, low diversity

Classifier-Free Guidance Visualization

Classifier-Free Guidance: Quality vs Diversity Trade-offw = 1.0Standard samplingHigh diversityLower qualityw = 7.5BalancedGood qualityGood diversityw = 15+High guidanceVery high qualityLow diversityGuideScaleLowHighHigher w pushes generations toward the conditioning signal (text prompt)

Latent Diffusion (Stable Diffusion)

Latent Diffusion Architecture

Latent Diffusion Model (Stable Diffusion)Image512×512×3EncoderVAE EncLatent z64×64×448× smaller!U-Net DiffusionDenoise in latent spaceCross-attention with textDenoised latent z₀DecoderVAE DecOutput512×512×3Text Encoder (CLIP)"a photo of a cat"

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.

python
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.

python
@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.

SamplerSteps neededStochastic?When to use it
Ancestral DDPM1000Yes, noise added each stepFinal images when compute is free
DDIM20 to 50No, when eta is zeroPreviews, iteration, prompt search
DPM-Solver++10 to 25Mostly deterministicProduction throughput with quality held
Euler ancestral20 to 50YesLatent 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.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-17

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Machine Learning Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement