Skip to main content
LearnMLAcademy
Advanced10 min read

Diffusion Models

Derive diffusion models from scratch using forward noise and reverse denoising, with diffusion diagrams, prompt experiments, and output-quality checks.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Learning to generate by learning to remove noise

A diffusion model turns a difficult generation problem into many smaller denoising problems. During training, we deliberately corrupt real samples with known Gaussian noise. A neural network learns to predict that noise at different corruption levels. During generation, we begin with random noise and repeatedly use those predictions to move toward a structured sample.

Text prompts are optional conditioning, not a defining property of every diffusion model. An unconditional model can learn to generate without text. Lesson 7 explains how latent diffusion and Stable Diffusion add text encoders, latent representations, and other architecture choices.

Diffusion Models in Simple Words

Imagine taking a high-definition photograph of a cat and gradually sprinkling fine sand (Gaussian noise) over it across 1000 tiny steps until it is nothing but chaotic static. During training, a neural network learns how to sweep away a tiny pinch of sand for any given step. To generate a brand-new image, you simply start with pure random static and sweep away the sand step-by-step—and a breathtaking, unique image materializes out of the void!

1

Forward Process

Adds Gaussian noise step-by-step (q)

2

Noise Prediction

Neural network predicts noise vector ε

3

Reverse Process

Scheduler subtracts noise step-by-step (p)

4

Emergence

Structured, photorealistic sample emerges

Symbols and where they come from

SymbolMeaningSourceRole
x₀Clean sampleTraining datasetSignal we deliberately corrupt
tNoise timestep from 1 to TSampled during training; iterated backward during generationTells the model how noisy xₜ is
βₜSmall noise amount assigned to step tDeveloper-chosen or configured scheduleControls how quickly signal is destroyed
αₜ1 - βₜCalculatedFraction of signal retained at one step
ᾱₜProduct α₁ × ... × αₜCalculated from the scheduleTotal signal retained by timestep t
εGaussian noiseRandomly sampled from N(0, I)Known training target added to x₀
ε̂θ(xₜ, t)Predicted noiseCalculated by the learned neural networkUsed in the loss and reverse step

Figure 1 — Forward diffusion adds noise; reverse diffusion removes predicted noise

The upper path is a fixed training process. The lower path is the learned generation path: it begins at random xT and constructs a candidate x₀ rather than recovering a hidden original.

Four visual tiles show a clean circle x zero becoming progressively noisier at x one, x t, and x T along right-pointing forward arrows. A second row begins with noise x T and follows left-pointing reverse arrows through less noisy stages to an x zero candidate. Forward arrows say add scheduled noise; reverse arrows say predict and remove noise.

Noise schedule definitions
αₜ = 1 - βₜ and ᾱₜ = ∏ from s=1 to t of αₛ

A small βₜ adds a small amount of uncertainty at one step. Multiplying the α values gives ᾱₜ, the cumulative signal fraction after t steps. Early timesteps retain more signal; later timesteps retain less.

Jump directly from x₀ to any timestep t
xₜ = √ᾱₜ × x₀ + √(1 - ᾱₜ) × ε

√ᾱₜ scales the clean signal. √(1 - ᾱₜ) scales newly sampled Gaussian noise. This direct equation lets training create a noisy example at a randomly chosen timestep without simulating every earlier noising step.

Worked noising example with one value

ValueNumberStatusMeaning
x₀0.80Data-suppliedOne normalized clean data value
tA step whose ᾱₜ = 0.64Timestep sampled; ᾱₜ calculated64% cumulative signal coefficient before square root
ε-0.50Randomly sampled, then fixed for this exampleKnown noise target
√ᾱₜ0.80Calculated as √0.64Signal scale
√(1 - ᾱₜ)0.60Calculated as √0.36Noise scale

xₜ = 0.80 × 0.80 + 0.60 × (-0.50)

xₜ = 0.64 - 0.30 = 0.34

The noisy value 0.34 is calculated from a scaled clean signal and scaled sampled noise. Training gives xₜ = 0.34 and timestep t to the model; the target it must predict is ε = -0.50.

Reproduce the forward-noising calculation

This runnable PyTorch function implements the direct noising equation and reproduces xₜ ≈ 0.34 from the worked example.

Python · requires PyTorch
import torch

def add_noise(x0, alpha_bar_t, epsilon):
    signal_scale = torch.sqrt(alpha_bar_t)
    noise_scale = torch.sqrt(1.0 - alpha_bar_t)
    xt = signal_scale * x0 + noise_scale * epsilon
    return xt

x0 = torch.tensor([0.8])                 # data-supplied clean value
alpha_bar_t = torch.tensor(0.64)         # calculated from chosen schedule
epsilon = torch.tensor([-0.5])           # fixed sampled noise for this demo
xt = add_noise(x0, alpha_bar_t, epsilon)
print(xt.item())                         # approximately 0.34

Forward Diffusion Signal Retention (ᾱₜ) Over 1000 Timesteps

Cosine schedule prevents signal from vanishing too abruptly in early timesteps compared to linear schedule.

At t=0, ᾱ₀ ≈ 1 (100% clean image). By t=1000, ᾱ₁₀₀₀ ≈ 0 (image is completely submerged in Gaussian noise N(0, I)).

The noise-prediction objective

A common DDPM training loss
L_noise = mean((ε - ε̂θ(xₜ, t))²)

ε is the sampled noise we know because training added it. ε̂ is the model’s learned prediction after seeing noisy xₜ and timestep t. θ names the model parameters updated by the optimizer.

Continue the example: if the model predicts ε̂ = -0.35, the one-value squared error is (-0.50 - (-0.35))² = (-0.15)² = 0.0225. Reducing this loss teaches the model to recognize the noise present at many different timesteps.

Timestep conditioning is essential because the same visible pattern means something different when a sample is slightly noisy versus almost pure noise. The model converts t into an embedding and uses it while predicting ε.

Figure 2 — Training creates a known noise target; generation repeatedly reuses the trained denoiser

During training, ε is known because we sampled it. During generation, the parameters stay fixed and an optional condition may guide—not define—the repeated reverse steps.

In the training lane, clean sample x zero, sampled timestep t, and sampled noise epsilon converge to calculate noisy x t. The denoiser predicts epsilon hat, the loss compares epsilon hat with the known epsilon, and a backward arrow updates model parameters. In the generation lane, sampled starting noise x T and an optional condition enter a repeated denoiser and scheduler loop with fixed parameters, producing a final x zero candidate.

What the scheduler does during generation

The neural network predicts noise; the scheduler performs the mathematical update from the current xₜ to a less noisy sample. It stores the timestep sequence, α and β values, and the specific reverse update rule. Different schedulers can trade generation speed, randomness, and quality while using the same trained denoiser.

More reverse steps give the sampler more opportunities to refine the output, but every step requires another model evaluation. That repeated evaluation is a major reason diffusion inference can be slower than one-pass generators.

Training phase

This is PyTorch-style pseudocode because the model architecture, data loader, timestep sampler, and schedule object depend on the application. Every line corresponds to the training half of Figure 2.

PyTorch-style pseudocode
# PyTorch-style training pseudocode: model and schedule are application-specific.
for x0 in training_loader:
    t = sample_timesteps(batch_size)             # developer-defined range
    epsilon = torch.randn_like(x0)                # sampled target noise
    xt = schedule.add_noise(x0, epsilon, t)       # calculated noisy sample
    epsilon_hat = model(xt, t, condition=None)    # learned prediction
    loss = mse(epsilon_hat, epsilon)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

Generation phase

This is scheduler-based pseudocode. The trained parameters stay fixed while the loop makes one reverse update per configured timestep.

Scheduler-based pseudocode
# Scheduler-based generation pseudocode.
xt = torch.randn(output_shape)                    # sampled starting noise
for t in schedule.timesteps_from_T_to_0:
    epsilon_hat = model(xt, t, condition=None)    # or supply a condition
    xt = schedule.reverse_step(xt, epsilon_hat, t)
generated_sample = xt

Unconditional and conditional diffusion

Unconditional

The denoiser receives xₜ and t. Generation samples from the overall learned data distribution.

Conditional

The denoiser also receives a class, text embedding, image, mask, or other condition that guides which outputs are likely.

Strengths, limitations, and common mistakes

PointWhy it mattersPractical check
Strong sample quality and coverageNo adversarial discriminator is requiredEvaluate fidelity and diversity separately
Many inference stepsQuality can cost latency and computeBenchmark scheduler and step count on the real device
Mistaking text conditioning for diffusion itselfDiffusion can be unconditional or use non-text conditionsName the exact condition supplied to the denoiser
Confusing ε with ε̂ε is sampled truth during training; ε̂ is the model outputLog both shapes and confirm the loss compares matching tensors
Treating the reverse path as exact undoGeneration constructs a plausible sample, not the hidden originalRepeat with different seeds and inspect variation

Summary / Key Takeaways

  • A diffusion model learns generation as a sequence of smaller denoising problems rather than one direct output step.
  • Training samples a timestep t and known Gaussian noise ε, then calculates xₜ from the clean sample x₀ and the configured noise schedule.
  • The denoiser receives xₜ and t and learns to predict ε by minimizing mean squared noise-prediction error.
  • The true ε is sampled during training, whereas ε̂ is the model output; confusing them breaks the learning objective.
  • Generation starts from random xT and repeatedly combines denoiser predictions with scheduler updates until a structured sample appears.
  • More reverse steps can improve refinement but require more model evaluations, increasing latency and compute.
  • Text is optional conditioning rather than part of diffusion itself; the next lesson moves denoising into a compact latent space.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Diffusion Models"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
During diffusion training, what is the difference between ε and ε̂?
Question 2 of 5numerical/formula
For x₀ = 0.80, ᾱₜ = 0.64, and ε = -0.50, what noisy value xₜ is calculated?
Question 3 of 5interpretation
Which statement correctly contrasts diffusion training and generation?
Question 4 of 5debugging/diagnostic
A training loop compares the predicted noise ε̂ with the clean sample x₀ instead of the sampled noise ε. What is wrong?
Question 5 of 5application/scenario
During generation, which component converts a model noise prediction into the next, usually less noisy sample?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1During diffusion training, what is the difference between ε and ε̂?▼

Correct Answer: ε is sampled target noise; ε̂ is the model's prediction of that noise

Training knows ε because it deliberately added that sampled noise. The denoiser produces ε̂ after seeing xₜ and t, and the loss compares the two.

2For x₀ = 0.80, ᾱₜ = 0.64, and ε = -0.50, what noisy value xₜ is calculated?▼

Correct Answer: 0.34

The signal and noise scales are 0.80 and 0.60, so xₜ = 0.80×0.80 + 0.60×(-0.50) = 0.64 - 0.30 = 0.34.

3Which statement correctly contrasts diffusion training and generation?▼

Correct Answer: Training adds known noise to real samples and updates parameters; generation starts from random noise and keeps trained parameters fixed

Training creates noisy examples with known ε and learns from prediction error. Generation uses the trained denoiser and scheduler repeatedly from a random starting sample.

4A training loop compares the predicted noise ε̂ with the clean sample x₀ instead of the sampled noise ε. What is wrong?▼

Correct Answer: The loss uses the wrong target for the noise-prediction objective

For the lesson's common DDPM objective, ε is the supervised target. Comparing ε̂ with x₀ teaches a different and mismatched objective.

5During generation, which component converts a model noise prediction into the next, usually less noisy sample?▼

Correct Answer: The scheduler

The denoiser predicts noise, while the scheduler stores the timestep sequence and numerical reverse-update rule used to calculate the next sample.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next