← notes Generative & world models

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.

21 min read 7 interactive

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 μ\mu and a standard deviation σ\sigma 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 N(0,I)\mathcal N(0, I). The loss is the negative ELBO (evidence lower bound, a lower bound on log⁡p(x)\log p(x)):

LVAE(x)=−Eqϕ(z∣x)[log⁡pθ(x∣z)]+KL(qϕ(z∣x) ∥ N(0,I))\mathcal L_\text{VAE}(x) = -\mathbb E_{q_\phi(z\mid x)}\big[\log p_\theta(x\mid z)\big] + \mathrm{KL}\big(q_\phi(z\mid x)\,\|\,\mathcal N(0,I)\big)

The reparameterisation z=μ+σ⊙εz = \mu + \sigma \odot \varepsilon with ε∼N(0,I)\varepsilon \sim \mathcal N(0, I) moves the randomness outside the network, so gradients reach μ\mu and σ\sigma. The gap between the ELBO and log⁡p(x)\log p(x) 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 10−610^{-6}, 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.

autoencoderfchannelscompressionreconstruction
SD 1.x8448×PSNR 24.2
SD381612×PSNR 28.6, FID 1.06
FLUX.181612×ImageNet-256 PSNR 32.7 (as reported by HunyuanVideo)

More channels reconstruct better, but SD3 notes that “predicting latents with higher dd 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 1+T1+T frames become 1+T/41+T/4 latent frames. An image is a 1-frame video, and one VAE serves both. This is why video models generate 4k+14k+1 frames: 49, 121, 129.

calculator

From pixels to tokens

Pick a frame size, the number of frames, the autoencoder and the patch size.

Patch
latent T′ × h × w × c
compression
tokens N
attention vs 1024² image

The default is the walkthrough's example: 121 frames of 720p become a 31 × 90 × 160 × 16 latent and 111,600 tokens, about 742× the attention cost of a 1024² image. Set 1 frame, 512 × 512 and SD 1.x for the 48× image case.

Bury the data in noise

The forward process is fixed and has no parameters. DDPM uses T=1000T = 1000 steps and a schedule βt\beta_t that rises linearly from 10−410^{-4} 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:

xt=αˉt x0+1−αˉt ε,αˉt=∏s≤t(1−βs),ε∼N(0,I)x_t = \sqrt{\bar\alpha_t}\,x_0 + \sqrt{1-\bar\alpha_t}\,\varepsilon, \qquad \bar\alpha_t = \prod_{s\le t}(1-\beta_s), \quad \varepsilon \sim \mathcal N(0, I)

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 tt and jumps. The noise schedule is the sequence αˉt\bar\alpha_t, and SNRt=αˉt/(1−αˉt)\text{SNR}_t = \bar\alpha_t/(1-\bar\alpha_t) is the signal-to-noise ratio.

The schedule decides where the signal disappears. With the linear schedule αˉ600=0.026\bar\alpha_{600} = 0.026: 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 αˉ600=0.341\bar\alpha_{600} = 0.341 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.

Schedule
data points xₜ signal √ᾱₜ noise √(1−ᾱₜ) other schedule
ᾱₜ
SNR = ᾱ/(1−ᾱ)
points still near their mode
Toy data, real DDPM schedules. At t = 600 only 16% of points are still nearest their own cluster with the linear schedule (chance is 12.5%), against 31% with the cosine schedule.

Learn to remove it, step by step

A diffusion model is a VAE with a fixed encoder. The noisy samples x1,…,xTx_1, \dots, x_T are the latent variables, the “encoder” is the noising process, and the “decoder” is a learned reverse chain of Gaussian steps pθ(xt−1∣xt)p_\theta(x_{t-1}\mid x_t). The ELBO splits into one KL term per step, and each target step q(xt−1∣xt,x0)q(x_{t-1}\mid x_t, x_0) is a Gaussian in closed form. Write x0x_0 in terms of the noise, and every term becomes a noise regression. DDPM then drops the per-step weights:

Lsimple=Et, x0, ε[∥ε−εθ(αˉt x0+1−αˉt ε, t)∥2]L_\text{simple} = \mathbb E_{t,\,x_0,\,\varepsilon}\Big[\big\|\varepsilon - \varepsilon_\theta\big(\sqrt{\bar\alpha_t}\,x_0 + \sqrt{1-\bar\alpha_t}\,\varepsilon,\ t\big)\big\|^2\Big]

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 ∇xlog⁡p(x)\nabla_x \log p(x), an arrow towards higher probability. The noise predictor is a scaled score, ∇xtlog⁡pt(xt)≈−εθ(xt,t)/1−αˉt\nabla_{x_t}\log p_t(x_t) \approx -\varepsilon_\theta(x_t,t)/\sqrt{1-\bar\alpha_t}: 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: E[x0∣xt]=tanh⁡(αˉt xt/(1−αˉt))\mathbb E[x_0\mid x_t] = \tanh\big(\sqrt{\bar\alpha_t}\,x_t/(1-\bar\alpha_t)\big). 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 t′<tt' < t along the predicted noise, and may skip many steps:

x^0=xt−1−αˉt ε^αˉt,xt′=αˉt′ x^0+1−αˉt′−σ2 ε^+σz\hat x_0 = \frac{x_t - \sqrt{1-\bar\alpha_t}\,\hat\varepsilon}{\sqrt{\bar\alpha_t}}, \qquad x_{t'} = \sqrt{\bar\alpha_{t'}}\,\hat x_0 + \sqrt{1-\bar\alpha_{t'}-\sigma^2}\,\hat\varepsilon + \sigma z

With σ=0\sigma = 0 the sampler is deterministic; with η=1\eta = 1 it is DDPM. CIFAR-10 FID with the same network:

steps1020501001000
DDIM13.366.844.674.164.04
DDPM41.0718.368.015.784.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.

Sampler
Schedule
samples xₜ paths of 10 samples clean guess x̂₀ = E[x₀ | xₜ] step times on the ᾱ curve
step
t → ᾱₜ
samples on a mode
network calls
The denoiser is exact for this toy mixture, so all error comes from the steps. With 5 DDIM steps the cosine schedule puts 72% of samples on a mode and the linear one 30%: most linear steps fall where ᾱ is near 0. With an exact denoiser, DDPM and DDIM land about equally well; the toy cannot show the FID gap in the table.

The network can predict the noise ε\varepsilon, the clean sample x0x_0, or the velocity v=αˉ ε−1−αˉ x0v = \sqrt{\bar\alpha}\,\varepsilon - \sqrt{1-\bar\alpha}\,x_0. The three are equivalent given xtx_t. They differ in stability: vv-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, εθ(xt,t,c)\varepsilon_\theta(x_t, t, c): 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:

ε~=εu+s (εc−εu),s=1+w\tilde\varepsilon = \varepsilon_u + s\,(\varepsilon_c - \varepsilon_u), \qquad s = 1 + w

The paper writes the scale as ww; most code writes ss, and Stable Diffusion’s default 7.5 is ss. By Bayes, ∇log⁡p(c∣xt)=−(εc−εu)/σt\nabla\log p(c\mid x_t) = -(\varepsilon_c - \varepsilon_u)/\sigma_t: 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 p(x∣c)1+w p(x)−wp(x\mid c)^{1+w}\,p(x)^{-w}: its mean moves away from the unconditional mean and its variance shrinks. In the walkthrough’s 1-D example, N(1,0.25)\mathcal N(1, 0.25) becomes N(1.14,0.14)\mathcal N(1.14, 0.14) at w=1w=1 and N(1.23,0.08)\mathcal N(1.23, 0.08) at w=3w=3.

guidance ww00.31.04.0
FID ↓7.272.437.8621.53
Inception Score ↑≈82158≈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 ww; its own tables show the opposite after w≈0.1w \approx 0.1–0.3.

playground

Guidance sharpens, then breaks

Move the guidance scale from 0 to 10. Hover the chart to read the shares.

middle cat mode (next to the dogs) outer cat modes dog modes off the data
w = s − 1
middle cat share
off the data
spread / mode std
Toy two-class data, exact denoisers, 30 DDIM steps. At s = 1 the samples cover all three cat modes. By s = 2 the cat mode next to the dogs is almost empty (5%), and at s = 10 samples overshoot past the data (12% off).

A Transformer in the latent

Latent diffusion trains the autoencoder once, freezes it, and runs the whole diffusion process on z=E(x)z = E(x). Text enters through cross-attention: image positions are queries, text tokens are keys and values. After 2M steps on ImageNet, f=8f = 8 beat pixel space by 38 FID points at the same compute, and f=32f = 32 lost too much information. Stable Diffusion v1 was an 860M-parameter U-Net with a frozen CLIP ViT-L/14 text encoder and the f=8f = 8 autoencoder.

The Diffusion Transformer (DiT) replaces the U-Net with a plain Transformer on patches of the latent. A latent of I×I×CI \times I \times C cut into p×pp \times p patches gives (I/p)2(I/p)^2 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.

imagetokensmultiply–adds per callattention share
256²256118 G4%
512²1024524 G13%
1024²4096≈2.9 T37%

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 (t=0t = 0 data, t=1t = 1 noise):

xt=(1−t) x0+t ε,dxtdt=ε−x0,LCFM=E∥vθ(xt,t)−(ε−x0)∥2x_t = (1-t)\,x_0 + t\,\varepsilon, \qquad \frac{dx_t}{dt} = \varepsilon - x_0, \qquad L_\text{CFM} = \mathbb E\big\|v_\theta(x_t, t) - (\varepsilon - x_0)\big\|^2

This is flow matching; with straight lines it is called rectified flow. To sample, start at noise and follow the predicted velocity back to t=0t = 0 with an ODE solver. The optimum is the average direction of all pairs whose lines pass through a point, v∗(x,t)=E[ε−x0∣xt=x]v^\ast(x,t) = \mathbb E[\varepsilon - x_0 \mid x_t = x].

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 t=1t = 1 points to the data mean, and one Euler step from ε=−1\varepsilon = -1 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.

Path
diffusion (VP) rectified flow after reflow Euler steps straight line, start to end
start x₁ (drag it)
exact end
Euler end
mean error, 80 starts
Toy 1-D data at −1 and +1, exact velocities, Euler steps in x for all three paths. One flow step lands every start on 0, the data mean. Diffusion and flow both need about 5 steps here; after one reflow the paths are straight and one step is exact.

Stable Diffusion 3 scaled rectified flow to 8B parameters. It samples tt from a logit-normal distribution, so training concentrates on the hard middle noise levels; “rf/lognorm(0.00, 1.00)” beat classic ε\varepsilon-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.

Attention

patches that hold the ball other patches / tokens attention from the chosen token
tokens attended (of 24)
reaches ball in latent frame 3
pairs / layer, 5 s 720p (my arithmetic)
Toy sizes: 9 frames, 3 latent frames, 24 tokens. With factorised attention the token that holds the ball in latent frame 1 cannot see the ball in latent frame 3 in one layer. Full 3-D attention can, at quadratic cost.

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.

TheoryImagesVideoSpeed & latents
2013
2020
2021
2022
2023
2024
2025
2026
Theory
Images
Video
Speed & latents
2013
2020
2021
2022
2023
2024
2025
2026

The lanes meet in 2024: SD3, FLUX and Sora are latent Transformers trained by denoising. Most later work targets speed, causal video and the latent itself.

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.