Diffusion: compress, add noise, learn to remove it
Image and video generators compress pixels into a VAE latent, train a Transformer to remove noise from it, and sample along nearly straight paths. This note follows that spine from DDPM to video DiTs.
A diffusion model learns to run noise backwards. During training you take a real image, bury it in Gaussian noise of a known amount, and ask a network which noise you added. You made the noise, so you know the answer: this is ordinary supervised regression. To generate, you start from pure noise and remove the predicted noise a little at a time.
A GAN must learn the whole map from noise to image in one jump, with an adversarial signal that can be unstable. A VAE learns a stable map but averages away detail. Diffusion cuts the hard problem into many easy ones: “remove a little noise” is a regression with a stable loss, and the global structure comes out of many small steps. The price is speed at sampling time.
Compress first: the VAE as a zip file
A 512 × 512 RGB image has 786,432 numbers. The Stable Diffusion encoder maps it to a 64 × 64 × 4 latent, 16,384 numbers, 48× fewer. Self-attention cost grows with the square of the number of positions, so 64² instead of 512² positions is up to 4096× less attention compute.
The compressor is a variational autoencoder (VAE). For each image the encoder outputs a mean and a standard deviation per latent dimension: a small cloud of codes instead of one point. The decoder must rebuild the image from any point of the cloud, and a KL term pulls every cloud towards . The loss is the negative ELBO (evidence lower bound, a lower bound on ):
The reparameterisation with moves the randomness outside the network, so gradients reach and . The gap between the ELBO and is exactly the KL from the encoder to the true posterior, so raising the ELBO also makes the encoder a better guess of which codes produced the image.
A VAE alone gives blurry samples. Its decoder is trained with a squared error, and the squared-error optimum is the average of all images that fit a code. Modern generators therefore use the VAE only to compress and never sample from its prior. The latent diffusion autoencoder makes three changes: a KL weight of about , a loss of L1 + LPIPS + a patch GAN to restore sharp texture, and a rescaling of the latent to unit variance (0.18215 for SD 1.x), because diffusion schedules assume unit-variance data.
| autoencoder | f | channels | compression | reconstruction |
|---|---|---|---|---|
| SD 1.x | 8 | 4 | 48× | PSNR 24.2 |
| SD3 | 8 | 16 | 12× | PSNR 28.6, FID 1.06 |
| FLUX.1 | 8 | 16 | 12× | ImageNet-256 PSNR 32.7 (as reported by HunyuanVideo) |
More channels reconstruct better, but SD3 notes that “predicting latents with higher is a more difficult task”: its 16-channel latent paid off only for large models. Easy to reconstruct and easy to generate pull in opposite directions.
Video VAEs also compress time, usually by 4, and they are causal: a 3-D convolution is padded only on the past side. The first frame is encoded alone and each later group of 4 frames gives one latent frame, so frames become latent frames. An image is a 1-frame video, and one VAE serves both. This is why video models generate frames: 49, 121, 129.
calculator
From pixels to tokens
Pick a frame size, the number of frames, the autoencoder and the patch size.
Bury the data in noise
The forward process is fixed and has no parameters. DDPM uses steps and a schedule that rises linearly from to 0.02. Each step shrinks the sample a little and adds a little Gaussian noise. Because a sum of independent Gaussians is Gaussian, any step can be reached in one jump:
The two coefficients have squares that sum to 1, so unit-variance data keeps unit variance (“variance preserving”). Training never runs the chain; it draws a random and jumps. The noise schedule is the sequence , and is the signal-to-noise ratio.
The schedule decides where the signal disappears. With the linear schedule : the signal is almost gone, and the last 40% of the steps are spent on near-pure noise. The cosine schedule of improved DDPM gives and destroys the signal more evenly.
playground
Noise buries a ring of eight clusters
Drag t on the slider or directly on the chart. Switch the schedule.
Learn to remove it, step by step
A diffusion model is a VAE with a fixed encoder. The noisy samples are the latent variables, the “encoder” is the noising process, and the “decoder” is a learned reverse chain of Gaussian steps . The ELBO splits into one KL term per step, and each target step is a Gaussian in closed form. Write in terms of the noise, and every term becomes a noise regression. DDPM then drops the per-step weights:
On CIFAR-10 this simple loss gave FID 3.17, against 13.51 for the full ELBO; predicting the mean of the step directly gave 13.22.
The score of a density is , an arrow towards higher probability. The noise predictor is a scaled score, : the predicted noise points away from the data. In continuous time the forward process is an SDE, and it has a reverse-time SDE and a deterministic probability-flow ODE with the same marginals. The ODE maps each noise sample to one image, and ODE solvers can take large steps.
The best denoiser can be written down for a world with two “images”, the numbers −1 and +1: . At high noise it is about 0, the average of the data; at low noise it is the nearest data point. Real models behave the same way: early steps fix the layout, late steps commit to details.
DDIM samples a trained DDPM without retraining. Each step predicts the clean sample, then moves to an earlier noise level along the predicted noise, and may skip many steps:
With the sampler is deterministic; with it is DDPM. CIFAR-10 FID with the same network:
| steps | 10 | 20 | 50 | 100 | 1000 |
|---|---|---|---|---|---|
| DDIM | 13.36 | 6.84 | 4.67 | 4.16 | 4.04 |
| DDPM | 41.07 | 18.36 | 8.01 | 5.78 | 4.73 |
At 50 steps DDIM is close to its 1000-step quality, a 20× speed-up for free. A fixed noise also gives a fixed image, which makes interpolation and editing possible.
animation
Sampling with the exact denoiser
Press Play. Then choose Linear with 5 steps, and turn on the clean guesses.
The network can predict the noise , the clean sample , or the velocity . The three are equivalent given . They differ in stability: -prediction is “the most stable option” and Imagen Video and CogVideoX use it.
Guide it towards the prompt
The denoiser takes the condition as an extra input, : a class embedding, or text from a frozen encoder (CLIP, T5 or an LLM) read through attention. That alone makes images that follow the prompt only loosely. Classifier guidance pushed each step along the gradient of a classifier trained on noisy images and took ImageNet 256 FID from 10.94 to 4.59, at the cost of an extra classifier.
Classifier-free guidance (CFG) removes the classifier. Train one network, and replace the condition by an empty token with probability 0.1 or 0.2. At sampling, run it twice and extrapolate:
The paper writes the scale as ; most code writes , and Stable Diffusion’s default 7.5 is . By Bayes, : the difference of the two predictions is an implicit classifier gradient, learned for free. The price is two network passes per step. The guided target behaves like : its mean moves away from the unconditional mean and its variance shrinks. In the walkthrough’s 1-D example, becomes at and at .
| guidance | 0 | 0.3 | 1.0 | 4.0 |
|---|---|---|---|---|
| FID ↓ | 7.27 | 2.43 | 7.86 | 21.53 |
| Inception Score ↑ | ≈82 | 158 | ≈295 | ≈420 |
On ImageNet 128 a little guidance improves both numbers; strong guidance keeps raising clarity (IS) but hurts FID because diversity collapses. Text-to-image systems still use strong guidance, because users value prompt-following over variety. The CFG paper’s text calls FID “monotonically decreasing” in ; its own tables show the opposite after –0.3.
playground
Guidance sharpens, then breaks
Move the guidance scale from 0 to 10. Hover the chart to read the shares.
A Transformer in the latent
Latent diffusion trains the autoencoder once, freezes it, and runs the whole diffusion process on . Text enters through cross-attention: image positions are queries, text tokens are keys and values. After 2M steps on ImageNet, beat pixel space by 38 FID points at the same compute, and lost too much information. Stable Diffusion v1 was an 860M-parameter U-Net with a frozen CLIP ViT-L/14 text encoder and the autoencoder.
The Diffusion Transformer (DiT) replaces the U-Net with a plain Transformer on patches of the latent. A latent of cut into patches gives tokens. The timestep and class enter through adaLN-Zero: an MLP predicts the scale, shift and a residual gate of each block from their embedding, and it starts at zero, so every block starts as the identity. Across 12 model sizes and patch sizes, FID correlated with forward compute at −0.93, and DiT-XL/2 reached FID 2.27 on ImageNet 256.
| image | tokens | multiply–adds per call | attention share |
|---|---|---|---|
| 256² | 256 | 118 G | 4% |
| 512² | 1024 | 524 G | 13% |
| 1024² | 4096 | ≈2.9 T | 37% |
Each doubling of the side gives 4× the tokens and 16× the attention cost. Video multiplies this again.
Straight paths: flow matching
Pair each training sample with a noise draw and join them with a straight line. With the SD3 convention ( data, noise):
This is flow matching; with straight lines it is called rectified flow. To sample, start at noise and follow the predicted velocity back to with an ODE solver. The optimum is the average direction of all pairs whose lines pass through a point, .
Each training pair is a straight line, but the learned field is an average over pairs, so the sampling paths curve. With data at +2 and −2, the best velocity at points to the data mean, and one Euler step from lands on 0, which is not a data point. Rectified flow’s fix is reflow: generate (noise, image) pairs with the trained model and retrain on them. The new paths cross less, are straighter, and work with very few steps.
playground
Straight in training, curved in sampling
Drag the start point on the left edge. Change the path and the number of Euler steps.
Stable Diffusion 3 scaled rectified flow to 8B parameters. It samples from a logit-normal distribution, so training concentrates on the hard middle noise levels; “rf/lognorm(0.00, 1.00)” beat classic -prediction with a linear schedule. Its MM-DiT concatenates text and image tokens for attention but keeps separate weights for each modality, so text and image read each other in every layer. It uses three text encoders (CLIP-L, OpenCLIP bigG and the 4.7B T5-XXL), RMSNorm on queries and keys for stability, and a time shift towards more noise at high resolution. FLUX.1 [dev] is a 12B rectified-flow Transformer with double-stream and single-stream blocks. It is trained with guidance distillation: it produces the CFG result in one pass, with the guidance strength as an input.
Video as spacetime patches
A video model must make every frame good and make the frames agree: the same objects, moving plausibly, under consistent light. Video also costs more, and good captioned video is scarce, so models train on images as 1-frame videos and caption videos automatically.
The first phase (2022–2023) added time to image models. Factorised U-Nets put temporal attention after each spatial block. Imagen Video chained 7 diffusion models, and Stable Video Diffusion showed that data curation is a main lever: it cut 577M clips to 152M. The second phase started with Sora (February 2024). Its report gives no model details, but it states the recipe: compress video in space and time, cut the latent into spacetime patches that act as Transformer tokens, and train a diffusion Transformer on videos and images of native sizes. Most open models now share it: a causal 3-D VAE, 1 × 2 × 2 patches, a DiT with full 3-D attention, flow matching, and strong recaptioning.
animation
A clip becomes a sequence of spacetime tokens
Press Play to go from frames to tokens. Then click a token and switch the attention pattern.
Factorised attention (space within a frame, then time at each position) is cheap. But when things move fast, the same position in two frames shows different objects, and CogVideoX found that separated attention fails on large motion. Full attention lets every patch see every other patch. Strong VAE compression and patchify are what make it affordable.
Tokens are the bottleneck. Five seconds of 720p at 24 fps is 121 frames, 31 latent frames, and 31 × 45 × 80 = 111,600 tokens with a 4 × 8 × 8 VAE and 2 × 2 patches: 27× the tokens of a 1024² image and about 742× the attention cost per layer. A 4 × 16 × 16 VAE without patchify gives the same grid; only extra compression helps, and Wan 2.2’s 4 × 16 × 16 VAE plus 2 × 2 patches gives 28,520 tokens. The walkthrough reads this as the reason why VAE compression keeps rising (4 × 8 × 8, then 4 × 16 × 16, then LTX-Video’s 8 × 32 × 32).
Since 2025, models also generate sound. Veo 3 applies latent diffusion jointly to audio and video latents; Sora 2 adds synchronised dialogue and sound effects; LTX-2 runs a 14B video stream and a 5B audio stream with cross-attention between them. “World simulator” is a claim about emergent physics: the Sora report itself says that the model does not accurately model glass shattering. Treat it as a research direction.
2023–2026: faster, longer, new latents
A 50-step sampler with CFG needs 100 network calls per image. Distillation trains a student that needs 1–4. Consistency models learn the map from any point of an ODE path to its end (one-step CIFAR-10 FID 3.55, distilled). DMD2 matches the teacher’s distribution with a difference of two scores plus a GAN loss and reaches one-step FID 1.28 on ImageNet 64. MeanFlow learns the average velocity over an interval and needs no teacher: FID 3.43 on ImageNet 256 with one call.
Video moves towards causal, streaming generation, frame by frame like an LLM. The obstacle is exposure bias: a model trained on real past frames is tested on its own, and its small errors grow. CausVid distils a bidirectional teacher into a causal student with a KV cache; Self Forcing trains on the model’s own roll-outs and reaches 17 fps with 0.69 s latency on one H100.
The latent itself is being redesigned. REPA aligns early DiT features with DINOv2 and speeds up training by over 17.5×. RAE replaces the VAE with a frozen representation encoder and a trained decoder (FID 1.13 with guidance). JiT returns to raw pixels and shows that the target matters: predicting the clean image gives FID 8.6–10.5, predicting the noise 372–395.
playground
2013–2026 in four lanes
Click any chip to read what the work did and its key number.
The walkthrough’s own reading: speed is largely solved for images, and long video is the open problem, where causal generation and KV caches matter more than step counts. Diffusion and autoregression are merging, so the useful question is what a model generates in parallel and what in sequence.