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!
Forward Process
Adds Gaussian noise step-by-step (q)
Noise Prediction
Neural network predicts noise vector ε
Reverse Process
Scheduler subtracts noise step-by-step (p)
Emergence
Structured, photorealistic sample emerges
Symbols and where they come from
| Symbol | Meaning | Source | Role |
|---|---|---|---|
| x₀ | Clean sample | Training dataset | Signal we deliberately corrupt |
| t | Noise timestep from 1 to T | Sampled during training; iterated backward during generation | Tells the model how noisy xₜ is |
| βₜ | Small noise amount assigned to step t | Developer-chosen or configured schedule | Controls how quickly signal is destroyed |
| αₜ | 1 - βₜ | Calculated | Fraction of signal retained at one step |
| ᾱₜ | Product α₁ × ... × αₜ | Calculated from the schedule | Total signal retained by timestep t |
| ε | Gaussian noise | Randomly sampled from N(0, I) | Known training target added to x₀ |
| ε̂θ(xₜ, t) | Predicted noise | Calculated by the learned neural network | Used 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.
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.
√ᾱₜ 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
| Value | Number | Status | Meaning |
|---|---|---|---|
| x₀ | 0.80 | Data-supplied | One normalized clean data value |
| t | A step whose ᾱₜ = 0.64 | Timestep sampled; ᾱₜ calculated | 64% cumulative signal coefficient before square root |
| ε | -0.50 | Randomly sampled, then fixed for this example | Known noise target |
| √ᾱₜ | 0.80 | Calculated as √0.64 | Signal scale |
| √(1 - ᾱₜ) | 0.60 | Calculated as √0.36 | Noise 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.
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.34Forward 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
ε 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 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 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 = xtUnconditional 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
| Point | Why it matters | Practical check |
|---|---|---|
| Strong sample quality and coverage | No adversarial discriminator is required | Evaluate fidelity and diversity separately |
| Many inference steps | Quality can cost latency and compute | Benchmark scheduler and step count on the real device |
| Mistaking text conditioning for diffusion itself | Diffusion can be unconditional or use non-text conditions | Name the exact condition supplied to the denoiser |
| Confusing ε with ε̂ | ε is sampled truth during training; ε̂ is the model output | Log both shapes and confirm the loss compares matching tensors |
| Treating the reverse path as exact undo | Generation constructs a plausible sample, not the hidden original | Repeat 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.