Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbooks  /  The Diffusion Models Handbook
Handbook~14 min readIntermediate
Deep Dive

Diffusion, and the
art of removing noise.

Every AI image you've seen started as pure static. Diffusion models generate by doing something almost absurdly simple, thousands of times: take something noisy and make it slightly less noisy. Learn that one move and the whole thing — training, sampling, guidance, latent space — clicks into place.

01

Generation as denoising

How do you turn random noise into a photorealistic image? Trying to produce it in one shot is impossibly hard. Diffusion's insight is to make the problem gradual and reversible: if you can learn to remove a little noise, you can start from pure noise and remove a little, then a little more, over many steps — and arrive at a clean image.

The training trick is to learn from the easy direction. Destroying an image by adding noise is trivial and well-defined; reversing that destruction is what's hard and useful. So diffusion models learn to undo a noising process they can generate perfect training examples for. Generation is just running that learned undo, step by step, starting from noise.

→ The one-sentence version

Diffusion turns "generate an image" (hard) into "remove a little noise" (learnable), repeated many times from pure static to a coherent picture.

02

The forward process

The forward (diffusion) process is the easy, hand-designed direction: take a real image and add a small amount of Gaussian noise repeatedly, over many timesteps, until after enough steps the image is indistinguishable from pure random noise. This process is fixed — no learning involved — and it's how you manufacture training data.

Forward: add noise until nothing remains
t=0
clean image
→
t=…
+ a little noise
→
t=…
noisier
→
t=T
pure noise

A crucial property makes this practical: you can jump to any noise level in one step (the math lets you add the equivalent of t steps of noise directly). So during training you can instantly produce "a clean image with exactly this much noise added," which is exactly the training example the network needs.

That shortcut is a single closed form. With βt the per-step noise, αt = 1−βt, and ᾱt = ∏s≤t αs the running product, one draw of Gaussian noise ε lands you at step t directly:

xt = √ᾱt · x0  +  √(1−ᾱt) · ε  ,  ε ~ 𝒩(0, I)

The signal keeps a fraction √ᾱt of the image and the rest is noise, and because ᾱt + (1−ᾱt) = 1 the total variance stays fixed as t climbs (a variance-preserving schedule). It also makes the training target trivial: since you added ε, the network's job is just to predict it back — and subtracting a perfect ε prediction recovers x0 exactly. The runnable model below checks that composing t single noising steps equals this one-shot jump, and that the recovery is exact.

03

The reverse process

The reverse process is the hard, learned direction: go from noisier to less noisy. A neural network (typically a U-Net, or increasingly a transformer) is trained to take a noisy image and a timestep, and estimate how to remove a small increment of noise. Apply it repeatedly — noise → slightly cleaner → cleaner → … → image — and you've generated a sample.

Why step by step rather than one big jump? Because each small denoising step is a much easier, more accurate thing to learn than mapping pure noise directly to a photo. The gradualness is the whole point: many small, learnable corrections compose into an astonishingly hard generation task. The network never "draws" an image — it just keeps answering "what would this look like with a bit less noise?"

04

The training objective: predict the noise

Here's the elegant part interviewers love. Training is a simple regression. Take a clean image, pick a random timestep t, add the corresponding known amount of Gaussian noise, and feed the noisy image (and t) to the network. Train it to predict the noise that was added, with a plain mean-squared-error loss between predicted and actual noise.

loss = ‖ ε − εθ(noisy image, t) ‖²

That's it — no adversarial game, no complex objective. Because you added the noise yourself, you have the exact ground-truth target for free. And knowing the noise lets you subtract it to denoise. This simplicity and stability — a straightforward supervised loss with unlimited self-generated training pairs — is a big reason diffusion overtook trickier generative approaches.

→ Why it's so stable

The model just does supervised regression against noise it can generate perfectly. No two networks fighting (as in GANs), no delicate balance — just "guess the noise," which trains reliably and scales.

05

Sampling: steps vs speed

To sample (generate), start from pure random noise and run the reverse process: predict the noise, remove a bit, repeat for many steps until a clean image emerges. The number of steps is the central quality-vs-speed dial. The original formulation used many steps (hundreds or a thousand), which is slow; faster samplers (DDIM and successors) get high quality in far fewer steps (tens), and active research pushes toward single-digit or even one-step generation via distillation.

The tradeoff is intuitive: more steps mean smaller, more accurate corrections and usually better quality, but more compute and latency; fewer steps are faster but can lose fidelity. Sampling is where the per-image cost lives — which is why it's the knob every text-to-image service tunes for its latency and cost budget.

Many stepsHigher quality, slower — small accurate denoising increments, more compute.
Few stepsFaster, cheaper — fast samplers/distillation; some fidelity risk.
06

Conditioning & guidance

So far this generates a plausible image, not the one you asked for. Conditioning steers it: to make text-to-image, the model's denoising network is conditioned on a text embedding (from a text encoder), injected via cross-attention so that at every step the denoising is pulled toward matching the prompt. The same mechanism conditions on class labels, images (img2img), or masks (inpainting).

Classifier-free guidance controls how strongly the output obeys the prompt. The trick: run the model both with and without the conditioning, and amplify the difference by a guidance scale. A higher scale forces tighter prompt adherence (more literal, more saturated) at some cost to diversity and naturalness; a lower scale is more varied and natural but looser. That guidance slider is the knob behind "make it follow my prompt more."

→ The guidance tradeoff

Classifier-free guidance pushes images to match the prompt more closely, but crank it too high and outputs get over-saturated and less realistic. It's a dial between prompt fidelity and image quality/diversity.

07

Latent diffusion

Running diffusion directly on full-resolution pixels is enormously expensive — every one of many steps processes a huge image. Latent diffusion (the approach behind Stable Diffusion) fixes this: an autoencoder first compresses images into a much smaller latent representation, the diffusion process runs entirely in that compact latent space, and a decoder turns the final latent back into a full-resolution image.

Because the latent is far smaller than the pixel image, training and sampling become dramatically cheaper — which is precisely what made high-quality text-to-image runnable on consumer hardware. The diffusion math is identical; it just operates on compressed latents instead of raw pixels. Latent diffusion is the practical breakthrough that took diffusion from research to everywhere.

08

Diffusion vs GANs & VAEs

Diffusion didn't arrive first, but it won the image-generation crown. GANs (a generator fooling a discriminator) can be fast but are notoriously unstable to train and suffer mode collapse (limited diversity). VAEs are stable and give a nice latent space but tend to produce blurrier samples. Diffusion offers the best of both: stable, simple training (just predict noise) with state-of-the-art quality and diversity.

The price is speed — generation takes many network passes, not one — which is exactly what fast samplers, distillation, and latent diffusion attack. The trend is clear: diffusion's training stability and sample quality made it the dominant approach for images (and increasingly video and audio), with the ecosystem steadily closing the speed gap.

ApproachStrengthWeakness
GANFast (one pass)Unstable training, mode collapse
VAEStable, useful latent spaceBlurrier samples
DiffusionStable training, top quality & diversitySlow (many steps) — being fixed
RUN IT YOURSELF

The forward process, in one equation

This is the DDPM schedule as runnable code: a linear β, its α = 1−β, and the running product ᾱ. Two facts that make diffusion trainable fall straight out. First, the one-shot jump x_t = √ᾱ·x₀ + √(1−ᾱ)·ε gives exactly the same signal coefficient as multiplying 300 single noising steps together — so training can teleport to any noise level for free. Second, because you added ε yourself, subtracting a perfect ε-prediction recovers x₀ exactly — the whole training objective in one line. SNR falls monotonically from ~455 to near zero as t climbs. Change the schedule or the timestep and watch the numbers move.

CPython · WebAssembly
By the numbers

Worked example: one training value traced through the schedule

Take the page’s runnable: a pixel value x₀ = 0.7, a noise draw ε = 1.3, the linear schedule with T = 1000. Jump straight to several timesteps with xₜ = √ᾱ·x₀ + √(1−ᾱ)·ε. The last column asks what happens if the network’s noise guess is off by just 0.1 and you subtract it to recover x₀.

tᾱsignal √ᾱnoise √(1−ᾱ)xₜSNRx₀ error from a 0.1 miss
00.99991.0000.0100.7139,999≈ 0.001
500.97000.9850.1730.91532.30.018
1000.89510.9460.3241.0838.540.034
3000.39400.6280.7781.4510.650.124
5000.07780.2790.9601.4440.0840.344
9990.000040.0061.0001.3040.0000415.7

Three things fall out. First, by t = 300 noise already outweighs signal (SNR 0.65), so most of the schedule is spent in heavy noise. Second, at t = 999 xₜ is 1.304, almost exactly ε: the image is gone, which is why sampling can start from a fresh random draw. Third, the error column is the reason for many small steps. The x₀ error is the noise miss times √(1−ᾱ)/√ᾱ, so a 0.1 miss costs 0.018 near the clean end but 15.7 at pure noise. Jumping from noise to an image in one prediction amplifies every mistake about 157-fold; taking small steps keeps each correction in the region where errors stay small.

Trade-offs

Cost and trade-offs: where the compute goes

For diffusion the honest unit is network evaluations. Time is evaluations per image, Space is how many values each evaluation processes. Step counts are typical orders of magnitude, not benchmarks.

CaseTimeSpaceWhy
Training, one example1 evaluation at a random tOne noisy image or latentNo sampling loop: the closed-form jump makes each example one regression.
DDPM samplingOne evaluation per step, on the order of 1,000Same per stepFaithful to the training process, and slow.
DDIM-style samplerTens of steps, e.g. 50Same per stepBigger, deterministic jumps reuse the same trained network.
+ classifier-free guidance2 evaluations per step: 50 steps = 100Conditional and unconditional, often batched togetherPrompt adherence costs a second pass at every step.
Distilled few-step model1 to 4 evaluationsSame per stepNeeds an extra training stage; some loss of diversity or fidelity.
Pixel space, 512×512 RGBPer step786,432 valuesEvery evaluation touches every pixel.
Latent space, 64×64×4Per step, plus one decoder pass at the end16,384 values: 48× fewerWhy latent diffusion made consumer-GPU generation practical.

Cost multiplies down the table: steps × guidance passes × values per pass. A service tunes all three, and the cheapest image is a distilled model, in latent space, with guidance batched into one call.

Watch for

Common mistakes

  • Thinking the network outputs the image

    In the page’s formulation it outputs the noise, and the sampler turns that into a slightly cleaner image. Some models predict x₀ or a mix of the two (v-prediction) instead, so check what a checkpoint was trained to predict before writing a sampler for it.

  • Sampling with a different schedule than training

    The network only learned the noise levels its training ᾱ schedule produced. Swap in another schedule at sampling time and it is asked about noise levels it never saw. Samplers can skip steps, but they must use the same ᾱ values.

  • Assuming the last step is pure noise

    In this schedule ᾱ at t = 999 is 0.00004, so a sliver of signal (0.006 × x₀) survives. Training never sees truly pure noise, yet sampling starts from it. Lin et al. (2023) showed this mismatch skews outputs toward medium brightness, and fixed it by rescaling the schedule to reach zero.

  • Guidance without conditioning dropout

    Classifier-free guidance subtracts an unconditional prediction. A model that was always trained with a prompt never learned one. The conditioning has to be dropped for a share of training examples so a single network learns both.

  • Buying quality with more steps forever

    With a good sampler quality plateaus after some tens of steps, while cost keeps rising linearly. Measure your sampler’s curve and stop where it flattens; past that you are paying latency for nothing.

In the wild

Where this shows up in production and interviews

  • Text-to-image services

    Latency and GPU cost per image are steps × guidance passes × resolution, as in the cost table. Product knobs such as “fast” and “quality” modes are usually just different step counts and samplers on the same model.

  • Editing: img2img and inpainting

    img2img noises an existing image only part way, to some middle t, then denoises from there. The “strength” slider picks that t: low keeps the composition, high keeps little. Inpainting does the same while holding the unmasked pixels fixed.

  • Beyond images

    The same predict-the-noise loop runs over video frames and audio, and in a discrete form over text: masking tokens instead of adding Gaussian noise, as the Diffusion LLMs handbook explains.

  • The interview version

    Write the training step in four lines: pick x₀, pick t, add ε with the closed form, regress ε. Then explain why many small denoising steps beat one jump (the 157-fold error amplification above), and what classifier-free guidance and latent space each cost.

Self-check

Check yourself

In the page’s schedule, is the image at t = 300 mostly signal or mostly noise?

Mostly noise. √ᾱ = 0.628 against √(1−ᾱ) = 0.778, so SNR = 0.65. The signal coefficient is still large, but the noise variance (0.606) already exceeds the signal’s (0.394).

Your network’s noise estimate is off by 0.1. Why does that ruin a one-shot generation from t = 999 but barely matter at t = 50?

Recovering x₀ divides by √ᾱ: the error becomes 0.1 × √(1−ᾱ)/√ᾱ. At t = 50 that is 0.018; at t = 999, where √ᾱ = 0.006, it is 15.7. Small steps keep each correction where the multiplier is small.

A service runs 50 sampler steps with classifier-free guidance. How many network evaluations per image, and what is the cheapest way to halve them without retraining?

100: two per step. Without retraining, the lever is fewer steps (25 steps = 50 evaluations), accepting some quality risk. Dropping guidance also halves it, but loosens prompt adherence. Distillation cuts further, but that is a retraining stage.

Why does latent diffusion speed up training as well as sampling?

Every training example is one network evaluation on the noisy input. A 64×64×4 latent is 16,384 values against 786,432 for a 512×512 RGB image, so each evaluation does far less work. The autoencoder is trained once, separately, and its cost is shared by everything after.

Frequently asked

Quick answers

How do diffusion models work?

They learn to reverse a noising process: add known noise to real data and learn to predict it. To generate, start from pure noise and iteratively remove a little predicted noise over many steps until a coherent sample emerges.

What's the training objective?

Predict the noise. Add a known amount of Gaussian noise to a clean example at a random timestep and train the network to output that noise with a simple regression loss — no adversarial game.

What is classifier-free guidance?

A way to control prompt adherence: run the model with and without the conditioning and amplify their difference by a guidance scale. Higher = follows the prompt more closely, at some cost to diversity/realism.

What is latent diffusion?

Running diffusion in a compressed latent space (via an autoencoder) instead of on full-resolution pixels — far cheaper to train and run. It's the approach behind Stable Diffusion.

Finished this one? 0 / 209 Handbooks done
NextDiffusion LLMs Next on the “How models actually work” ladder · rung 8 of 11

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks