The transformer backbone behind today's image and video generators (Stable Diffusion 3, FLUX, Sora-style video models). The same flow-matching recipe drives the action expert of VLAs like π0. GPU inference study guide with sampling math, architecture, and edge deployment notes.
Module 2 (ViT): patchify with a strided Conv2d, tokens as image patches
Gaussian noise and mean-squared error. No probability theory beyond "add noise, then predict it" is needed.
Time: about 75 minutes to read and try the widgets, 10 minutes to run diffusion.py on a CPU, and 1–3 hours for the exercises in §11.
What you'll learn
Noise any sample to any timestep in one line, and read a noise schedule (ᾱ, SNR)
Trace a DiT forward pass: patchify → blocks with adaLN-Zero → unpatchify
Why DDIM, flow matching and distillation cut 1000 steps to 50, 28 or 1–4, and what classifier-free guidance costs
Estimate FLOPs, arithmetic intensity and a latency lower bound on Jetson Orin, including the VAE decoder
🎬 Learn it visually
But how do AI images and videos actually work?, guest video by Welch Labs on 3Blue1Brown (video, 37 min). Watch this first: a beautifully animated explanation of how a diffusion model turns noise into an image step by step, and how a text prompt steers it.
What are Diffusion Models?, Lilian Weng (Lil'Log). The standard written reference: the forward process, the ε-prediction loss, DDIM and guidance, with every derivation in one place. Read it next to §1–§4.
Perspectives on diffusion, Sander Dieleman. The same model seen from many angles (denoiser, score function, ODE/flow, autoencoder); good once the basics click and you want intuition for why it works.
Coding Stable Diffusion from scratch in PyTorch, Umar Jamil (video, 5 h). Code-along: the theory first, then the VAE, the text encoder, the U-Net, the sampler and classifier-free guidance, all written by hand.
The Annotated Diffusion Model, Niels Rogge and Kashif Rasul (Hugging Face). A DDPM implementation in PyTorch with the paper's equations next to the code that implements them.
Notation on this page
T
number of DDPM noise levels (T = 1000), not tokens
t
DDPM timestep, an integer 0 … T−1, large t = more noise (§1–§3.1); flow time in [0, 1], t = 0 noise and t = 1 data (§3.2, §9)
K
sampling steps = network calls per sample (num_steps in code)
N
tokens per latent = (H/P)², as in Module 1; N(μ, σ²) is a Gaussian
x₀, x_data
clean sample: x₀ in DDPM sections, x_data in flow-matching sections
ε, ε̂, v
noise, predicted noise, velocity
H
latent height = width; in §9 the action horizon (VLA notation), with d_a = action dimension
B, d, L, h, P
batch, width, layers, heads, patch size, as in Modules 1–2
The Core Idea: Iterative Denoising
In plain words: learn to undo a little noise, then repeat. Training shows the network noisy versions of real images and asks "which noise was added?". Generation starts from pure static and removes a little of the predicted noise at each step until a picture is left.
A diffusion model generates samples by slowly removing noise from a random starting point. Training teaches a neural network to predict the noise that was added to real data at some timestep; sampling runs that network in reverse, step by step.
What to notice: training never walks the chain step by step; it jumps straight to a random noise level. Only sampling is iterative.
① Training: pick a random t, add noise ε in one step (§1), and train the network to predict it (ε̂). Loss = MSE(ε̂, ε): plain regression, stable training (§1.2).
② Sampling: start from Gaussian noise and run the network K times, subtracting a little predicted noise each step. K = 1000 (DDPM) → ~50 (DDIM) → 28–50 (flow matching, FLUX [dev]) → 1–4 (distilled).
③ The whole model is ONE function, ε̂ = model(x_t, t, condition): it predicts the noise from the noisy input and the timestep. Training and sampling share the same forward pass; only the wrapping loop differs.
The key insight: if the model can predict noise accurately, subtracting a little at each step walks us from pure Gaussian noise back to a real sample. Training is MSE regression — stable and well-understood — which is a big part of why diffusion beat GANs.
1. Forward Process: Adding Noise Analytically
In plain words: to make a training example at noise level t, blend the clean image with fresh random noise in one go. A single number ᾱ_t says how much of the original is left.
The forward process is fixed (not learned) and has a closed form, so we can jump directly to any timestep without simulating the intermediate steps: one multiplication, one addition, one noise sample.
Forward noising: q(x_t | x₀)
Intuition
x_t is a weighted mix of the clean sample and pure noise; as t grows, the weight moves from the image to the noise.
The noisy sample x_t is Gaussian, centred on the clean sample x₀ shrunk by root-alpha-bar-t, with variance one minus alpha-bar-t. Equivalently: root-alpha-bar-t parts image plus root-of-one-minus-alpha-bar-t parts standard noise. x₀, ε and x_t all have the image's shape (e.g. [4, 32, 32] for a DiT latent); ᾱ_t is one number per timestep, precomputed once from the β schedule. Small t: x_t ≈ x₀ (almost clean). t = T − 1: x_t ≈ ε (almost pure noise).
Why it exists
It lets training jump straight to any timestep. Adding Gaussian noise t times in a row is the same as adding one Gaussian with the combined variance, and ᾱ_t keeps track of how much signal is left. Without the closed form, every training example would need t sequential noising steps. The squares of the two coefficients sum to 1, so x_t keeps unit variance when x₀ does.
Tiny example
One pixel, DiT's linear schedule. Clean value x₀ = 0.8, noise draw ε = −1.2.
At t = 500 only ᾱ = 7.8% of the variance is signal (SNR = −10.7 dB). The network's job: given x_t = −0.9292 and t = 500, guess ε = −1.2.
Code
eps = torch.randn_like(x0) # ε ~ N(0, I)
x_t = sqrt_ab[t].view(-1, 1, 1, 1) * x0 \
+ sqrt_1m_ab[t].view(-1, 1, 1, 1) * eps # one jump to level t
Try it: what x_t looks like at each noise level
x_t for a 24×24 toy image (values in [−1, 1])
ᾱ_t
–
signal √ᾱ_t
–
noise √(1−ᾱ_t)
–
SNR
–
ε̂-error gain in x̂₀
–
What to notice: with DiT's linear schedule the noise coefficient overtakes the signal (SNR below 0 dB) from t = 259 on; with the cosine schedule only from t = 496, so cosine spends more of its steps at medium noise. Now drag t to 999: the cosine schedule leaves ᾱ ≈ 2×10⁻⁹, and the last stat shows how much an ε̂ error gets magnified when you solve for x₀ there (the box below explains why that matters).
1.1 The noise schedule
The sequence ᾱ_1, ..., ᾱ_T controls how fast noise is added. Common choices:
Schedule
Shape
Used by
Linear
β_t linear from 0.0001 → 0.02 (T = 1000)
DDPM, ADM, DiT (and diffusion.py's default)
Cosine
ᾱ_t = f(t)/f(0), f(t) = cos²((t/T + s)/(1+s) · π/2), each β capped at 0.999
Improved DDPM (Nichol & Dhariwal, 2021); schedule="cosine" in diffusion.py
Scaled linear
√β_t linear from √0.00085 → √0.012
Stable Diffusion 1.x/2.x, SDXL
Rectified flow (no β)
x_t = (1−t)·x_data + t·ε (SD3/FLUX direction: t = 1 is noise; §3.2 and the VLA/robot modules use the opposite); SD3 samples t from a logit-normal and shifts it towards noise at high resolution
Stable Diffusion 3, FLUX (see §3.2)
Cosine changes ᾱ slowly near both ends, so fewer steps are spent on nearly-clean or nearly-pure-noise inputs than with the linear schedule (try the widget above). Nichol & Dhariwal introduced it for small pixel-space images; DiT kept ADM's linear schedule, and so does our reference implementation.
Pitfall: the end of the schedule. A sampler predicts the clean sample as x̂₀ = (x_t − √(1−ᾱ_t)·ε̂) / √ᾱ_t, so an error δ in ε̂ becomes an error of δ·√((1−ᾱ_t)/ᾱ_t) in x̂₀. At t = 999 that factor is 157 for the linear schedule but about 20,000 for cosine (ᾱ ≈ 2.4×10⁻⁹). In a 50-step DDIM test with an exact ε-predictor for Gaussian toy data (target std 0.5), adding noise of std 0.01 to ε̂ left the linear-schedule samples at std ≈ 0.47, while the cosine-schedule samples blew up to std ≈ 3.1 (exercise 3 reproduces this). That is why diffusion.py defaults to DiT's linear schedule.
1.2 The training loss: guess the noise
In plain words: show the network a noisy image and its noise level, ask "which noise was added?", and grade the answer with squared error. You made the noise yourself, so you always know the right answer.
The ε-prediction loss
Intuition
A plain regression problem: input = noisy sample and timestep, target = the noise that was mixed in.
Average, over training images x₀, random timesteps t and random noise draws ε, the squared distance between the true noise ε and the network's guess ε-theta of x_t and t. Both have the image's shape; the loss is one number.
Why it exists
It is mean-squared-error regression on a target you generate yourself, so training is stable, a big reason diffusion overtook GANs. DDPM (Ho et al., 2020) derived it as a simplified, unweighted form of the variational bound and found that it gave better samples than the full bound. Predicting ε keeps the target at unit variance at every t, and the same output can be turned into an estimate of x₀ (§3.1).
Tiny example
From §1: x₀ = 0.8, ε = −1.2, t = 500 gave x_t = −0.9292. If the network answers ε̂ = −1.15, the loss is (−1.2 − (−1.15))² = 0.0025. For a 2-pixel image with ε = [−1.2, 0.5] and ε̂ = [−1.0, 0.3]: ((−0.2)² + 0.2²) / 2 = 0.04.
Code
t = torch.randint(0, T, (B,)) # a random noise level per sample
x_t, eps = schedule.q_sample(x0, t) # one jump (§1)
loss = F.mse_loss(model(x_t, t, y), eps) # guess the noise
2. The DiT Architecture
In plain words: DiT is a ViT that outputs an image instead of a class. It cuts the noisy latent into patch tokens, runs Transformer blocks, and stitches the tokens back into a noise prediction of the same shape. The noise level and the class act like control knobs on every block, not like extra words in the sequence.
DiT replaces the classic U-Net denoiser with a pure transformer. Benefits: simpler code, cleaner scaling (more params consistently help), reuses all the transformer infrastructure. Downside: no inductive bias from conv downsampling.
At the top level, DiT is a pretty standard transformer pipeline with one twist: conditioning (timestep + class) is broadcast to every block through AdaLN parameters, not concatenated into the token sequence the way text prompts are in an LLM.
datalearned weights / conditioningmixing across tokens (attention)outputbookkeeping
What to notice: the output has exactly the input's shape, and the condition never enters the token sequence.
Main tensor path: patchify → tokens → L transformer blocks → final layer → unpatchify → ε̂. [B, 4, 32, 32] → [B, N, d] (unchanged through all blocks) → [B, 4, 32, 32]. Patchify is a Conv2d with k = s = P giving [B, (H/P)², d]; the position table is a fixed 2D sin-cos buffer. L = 28 for DiT-XL/2.
Conditioning vector c: a single [B, d] vector built once from (t, y): the timestep (an integer 0..T−1) goes through sinusoidal features + an MLP, the class id (or the null class) through an embedding lookup, and the two are added. c is broadcast to every DiT block AND the final layer (adaLN modulation). The blocks never see t or y directly, only c.
Zooming in on a single DiT block — this is where adaLN-Zero conditioning actually does its work:
What to notice: the condition c never touches the tokens directly. Per channel, it only sets how the LayerNorm output is scaled and shifted, and how much of each sub-layer is added back to the blue residual stream (the gates).
Six vectors: c → SiLU → Linear(d → 6d) gives (shift₁, scale₁, gate₁, shift₂, scale₂, gate₂), each [B, d]: one number per channel, shared by all N tokens of a sample (broadcast).
LayerNorms have no learnable γ, β of their own; the modulation x̂·(1 + scale) + shift replaces them. Attention is non-causal (every patch sees every patch); the MLP is d → 4d → d with GELU.
At initialization the Linear is all zeros, so both gates are 0, each ⊕ adds 0, and block(x) = x (identity). Training learns how much to add.
2.1 adaLN-Zero — the key contribution
The novel part of DiT is how it injects conditioning. DiT compared four options: appending t and y as extra tokens ("in-context"), cross-attention to them, adaptive LayerNorm (adaLN), and adaLN-Zero. adaLN-Zero won and is also the cheapest:
The condition vector c = t_emb + y_emb goes through SiLU and one Linear that outputs 6·d numbers per sample.
Those 6d values are split into (shift₁, scale₁, gate₁, shift₂, scale₂, gate₂) (called shift_attn … gate_mlp in the code), each of shape [B, d].
Shift/scale modulate the LayerNorm output, which has no learnable γ/β of its own: x̂ * (1 + scale) + shift.
The gate scales the sub-layer's output before it is added back: x = x + gate · sublayer(…).
Worked example (one channel of one token). LayerNorm gives x̂ = 0.8. For this sample's timestep the Linear outputs scale₁ = 0.5 and shift₁ = −0.1, so attention sees 0.8·(1 + 0.5) − 0.1 = 1.1. Say attention returns 0.4 for this channel and gate₁ = 0.25: the residual stream changes by 0.25·0.4 = +0.1. At initialization the Linear is all zeros, so scale = shift = gate = 0: attention sees 0.8 unchanged and the residual stream changes by 0·0.4 = 0.
The "Zero" in adaLN-Zero. The final Linear producing those 6d values is zero-initialized. At training start, all gates are 0, so every block is an identity function. The network begins as a no-op and only gradually learns to modulate. In the paper's ablation (DiT-XL/2, 400K training steps, FID-50K without guidance, lower is better): in-context 35.24, cross-attention 26.14, adaLN 25.21, adaLN-Zero 19.47, at about the same Gflops as plain adaLN.
How newer DiTs add text (as of Oct 2026). A class label is one vector, but a prompt is a sequence of tokens, so text-to-image and text-to-video DiTs keep adaLN-style modulation for the timestep and add a second path for the text tokens:
Model
Timestep (and pooled text)
Text tokens
DiT (2022)
adaLN-Zero (t + class)
— (class-conditional only)
PixArt-α (2023)
adaLN-style modulation
Cross-attention layers added to each DiT block
Stable Diffusion 3 / MMDiT (2024)
Modulation from t + pooled CLIP vector
Joint attention: text and image tokens are concatenated for attention, each modality keeps its own weights
Wan 2.1 video (2025)
adaLN: one MLP shared by all blocks predicts the six parameters, each block learns its own biases
Cross-attention to umT5 text embeddings
2.2 Patchify / Unpatchify
Same trick as ViT: a Conv2d with kernel=stride=patch_size splits the input into patches and projects them to hidden_dim in one kernel. At the end, unpatchify reshapes the per-patch output back to a spatial grid.
What to notice: a 2×2 patch of a 4-channel latent holds 2·2·4 = 16 values, so 32×32 → 16×16 = 256 tokens, and the final layer (adaLN + Linear) must output exactly 16 numbers per token to rebuild a [4, 32, 32] noise field. The latent is the VAE encoding of a 256×256 image.
3. Sampling Strategies
In plain words: generation cost = number of steps × cost per step. You can cut the steps with a smarter update rule (same network) or by training a network that can take bigger steps.
Training uses T = 1000 timesteps. Sampling doesn't have to visit all of them. How few steps you can get away with depends on two separate choices: the sampler (same trained network, different update rule) and whether the network was distilled or trained for few-step generation. The chart below uses real numbers from one paper so the two samplers are directly comparable:
What to notice: with the same trained model, the deterministic DDIM sampler degrades gracefully as steps drop (4.04 → 4.67 FID from 1000 to 50 steps), while the stochastic DDPM sampler degrades much faster (FID 8.0 at 50 steps, 41 at 10). Both axes are logarithmic. Source: DDIM paper, Table 1 (CIFAR-10). Below about 10 steps you need a different, distilled or few-step-trained network (§3.3); those methods report FIDs on other datasets, so they are not plotted here.
3.1 DDIM — the default
In plain words: at each step, guess the clean image, then re-noise that guess to a slightly lower noise level. Because no fresh randomness is added, you can take big jumps.
DDPM defines a Markov chain of 1000 small denoising steps, each adding fresh noise. DDIM keeps the same trained network but uses a deterministic update (it corresponds to integrating an ODE), which lets you jump over most timesteps:
The DDIM update (deterministic, σ = 0)
Intuition
Run the forward formula backwards to estimate x₀, then run it forwards again at the next, lower noise level, reusing the same predicted noise.
First, subtract the predicted noise (scaled by root-one-minus-alpha-bar-t) from x_t and divide by root-alpha-bar-t: that is the guess x-hat-zero of the clean sample. Then mix that guess with the same predicted noise using the coefficients of the next timestep t′. All tensors have the latent's shape.
Why it exists
DDPM's sampler adds fresh noise at every one of its 1000 steps. DDIM's update adds none, so it follows a smooth (ODE) path and you can subsample the timesteps, e.g. [999, 979, 959, …, 19] for 50 steps, with the same trained network.
Tiny example
Continue the pixel from §1: at t = 500, x_t = −0.9292 (from x₀ = 0.8, ε = −1.2). Suppose ε̂ = −1.2 exactly.
x̂₀ = (−0.9292 − 0.9603·(−1.2)) / 0.2789 = 0.8000
x_250 = 0.7221·0.8000 + 0.6918·(−1.2) = −0.2525
That is exactly the value the forward process gave at t = 250: with a perfect ε̂, DDIM slides back along the same noise direction, so 2 steps or 50 land in the same place. With an imperfect ε̂ (off by 0.05) the guess becomes x̂₀ = 0.6279: the error is multiplied by √((1−ᾱ)/ᾱ) = 3.44 at t = 500. Fewer, larger steps give the network fewer chances to correct such errors, which is the real cost of skipping steps.
Same network, no retraining. In the DDIM paper (CIFAR-10), 50 DDIM steps reach FID 4.67, against 4.04 for 1000 DDIM steps and 3.17 for the original 1000-step DDPM sampler: close to full quality at 20× less compute. DDIM-style deterministic samplers, and higher-order ODE solvers such as DPM-Solver++ and UniPC, became the default way to sample ε-prediction models.
3.2 Flow matching — the modern alternative
In plain words: instead of asking "what noise was added?", ask "which way should I walk?". Training draws straight lines from noise to data and teaches the network the direction (velocity) along them; sampling follows those directions in small steps.
Rather than predict noise ε̂, predict a velocity vector along a straight-line path from noise to data:
Convention for the rest of the repo: flow time t runs from t = 0 (noise) to t = 1 (data), the opposite direction to the DDPM timestep of §1. The clean sample is written x_data, not x₀, because the point at t = 0 is the noise ε. The VLA and robot modules use the same direction, with the actions a in place of x_data. SD3 and FLUX use the opposite direction (see the box below).
# Training (t ∈ [0, 1], continuous; t = 0 is noise, t = 1 is data):
x_t = (1 - t) * ε + t * x_data # linear interpolation
target_v = x_data - ε # constant velocity along the path
loss = MSE(model(x_t, t), target_v)
# Sampling: Euler integration of dx/dt = vfor i inrange(num_steps):
t = i / num_steps
v = model(x, t)
x = x + v * (1 / num_steps)
Intuition with a single data point. If the whole dataset were one point x_data, the best velocity at (x, t) is (x_data − x)/(1 − t): it points straight at x_data. One Euler step from t = 0 with step size 1 gives x + (x_data − x) = x_data exactly. Real data has many points, so the learned field averages over all the straight lines that pass near x, and the trajectories bend. That is why practical samplers still take tens of steps.
Why flow matching is now the default for new models. The objective is simple (plain MSE on a velocity) and the training paths are straight, so the learned trajectories are straighter than DDPM's and a plain Euler solver works. The same DiT backbone serves both: only the loss and the sampler change. Stable Diffusion 3 and FLUX are rectified-flow transformers; FLUX.1 [dev]'s reference example uses 50 sampling steps (FLUX.2 [dev]'s card notes 28 as a good trade-off), and π0 (Module 8) uses 10 Euler steps for robot actions. Watch the direction convention: SD3/FLUX write x_t = (1−t)·x_data + t·ε (with x₀ for the data in their papers), so their t = 1 is noise and the velocity flips sign. This repo uses t = 0 for noise throughout.
3.3 Few-step models (as of Oct 2026)
Below about 10 steps you need a network trained for it, usually distilled from a many-step teacher. The student is a different set of weights with the same DiT/U-Net architecture, so the inference engine does not change; only the loop gets shorter.
Method
Steps
Idea
Consistency models (2023), LCM (2023)
1 or a few (LCM: 2–4)
Train the network to map any point on an ODE trajectory straight to its end point
ADD / SDXL-Turbo (2023), SDXL-Lightning (2024)
1–4 (ADD); one or a few (Lightning)
Distillation plus an adversarial (GAN) loss to keep 1–2-step samples sharp
DMD2 (2024)
1 or a few
Match the teacher's output distribution, not its individual trajectories
sCM (2024)
2
Continuous-time consistency models, scaled to 1.5B parameters
Learns the average velocity over an interval; trained from scratch, no teacher
4. Classifier-Free Guidance (CFG)
In plain words: ask the network twice, once with the label and once without, and push the prediction further in the direction the label points.
To steer generation toward the condition without training a separate classifier, train one model on both conditional and unconditional examples: DiT's code replaces the class label with a learned "null" class 10% of the time. At inference, run the model twice per step and extrapolate away from the unconditional prediction:
What to notice: guidance is just an extrapolation between two predictions; its price is a second forward pass at every step. Tip: batch the conditional and unconditional inputs into one forward of batch 2B: fewer kernel launches and one weight read, but the FLOPs still double.
Classifier-free guidance
Intuition
The difference ε̂_cond − ε̂_uncond is "what the label changes". Guidance adds w times that difference to the unconditional guess.
ε = εuncond + w · ( εcond − εuncond )
Read it aloud
Start from the unconditional prediction and add w times the difference that the label makes. w is the guidance scale (a single number); every other term has the latent's shape.
Why it exists
It makes samples follow the condition more strongly without a separate classifier, and the quality gain is large: DiT-XL/2 goes from FID 9.62 without guidance to 2.27 with w = 1.5 (DiT uses 4.0 for showcase images). The price is two forwards per step, and too large a w gives saturated, samey images.
Tiny example
ε̂_uncond = 0.10 and ε̂_cond = 0.30. w = 0 gives the unconditional model (0.10); w = 1 gives plain conditional (0.30, no guidance); w = 1.5 gives 0.40; w = 4 gives 0.10 + 4·(0.30 − 0.10) = 0.90, past the conditional prediction, away from "generic image" towards "very much this class".
Code
eps = model(torch.cat([x, x]), torch.cat([t, t]), torch.cat([y, y_null]))
eps_c, eps_u = eps.chunk(2) # one batched forward of size 2B
eps = eps_u + w * (eps_c - eps_u)
Guidance distillation: train a student that takes w as an extra input and reproduces the guided output in one forward pass (Meng et al., 2023). FLUX.1 [dev] and FLUX.2 [dev] are released this way: their guidance_scale is fed to the network, so each step is a single forward.
Guidance on part of the trajectory only: Kynkäänniemi et al. (2024) found guidance harmful at high noise and largely unnecessary at low noise, and apply it only in the middle interval, which improves FID and skips the second forward for the other steps.
5. Code Walkthrough
Core classes from diffusion.py. Click to expand.
NoiseSchedule — the forward process▼
Purpose: Precompute ᾱ_t from a β schedule (DiT's linear one by default, cosine optional), and provide the q_sample function that jumps directly to a noisy timestep.
Key point: at training time we never actually iterate forward — we pick a random t and jump there. The Markov chain interpretation is for the reverse process at sampling time.
TimestepEmbedding — turning scalar t into a vector▼
Purpose: Convert an integer timestep into a hidden_dim vector the DiT blocks can condition on. Uses the same sinusoidal pattern as Transformer position embeddings, followed by a small MLP.
The sinusoidal embedding gives the network a smooth, continuous representation of "how noisy is this?" — nearby timesteps get similar embeddings.
DiTBlock — transformer block with adaLN-Zero▼
Purpose: The reusable building block. Same skeleton as a Transformer block (attn + MLP + residuals) but every LayerNorm is modulated by the condition vector, and residuals are gated.
defmodulate(x, shift, scale):
return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
classDiTBlock(nn.Module):
def__init__(self, hidden_dim, num_heads, mlp_ratio=4.0):
super().__init__()
# elementwise_affine=False — modulation replaces learnable γ,β
self.norm1 = nn.LayerNorm(hidden_dim, elementwise_affine=False, eps=1e-6)
self.attn = nn.MultiheadAttention(hidden_dim, num_heads, batch_first=True)
self.norm2 = nn.LayerNorm(hidden_dim, elementwise_affine=False, eps=1e-6)
mlp_hidden = int(hidden_dim * mlp_ratio)
self.mlp = nn.Sequential(
nn.Linear(hidden_dim, mlp_hidden),
nn.GELU(approximate="tanh"),
nn.Linear(mlp_hidden, hidden_dim),
)
# 6 modulation params per block: shift/scale/gate for both attn and mlp
self.adaLN_modulation = nn.Sequential(
nn.SiLU(),
nn.Linear(hidden_dim, 6 * hidden_dim, bias=True),
)
# The "Zero" in adaLN-Zero
nn.init.zeros_(self.adaLN_modulation[-1].weight)
nn.init.zeros_(self.adaLN_modulation[-1].bias)
defforward(self, x, c):
shift_a, scale_a, gate_a, shift_m, scale_m, gate_m = \
self.adaLN_modulation(c).chunk(6, dim=1)
# Attention path with modulated LN + gated residual
x_mod = modulate(self.norm1(x), shift_a, scale_a)
x = x + gate_a.unsqueeze(1) * self.attn(x_mod, x_mod, x_mod, need_weights=False)[0]
# MLP path, same pattern
x_mod = modulate(self.norm2(x), shift_m, scale_m)
x = x + gate_m.unsqueeze(1) * self.mlp(x_mod)
return x
Why zero-init matters: with gates initialized to 0, every block starts as an identity function. Training begins from a well-behaved neutral state. In Peebles & Xie's ablation (DiT-XL/2, 400K steps) zero-initializing the modulation took FID from 25.21 (adaLN) to 19.47 (adaLN-Zero).
DiT — the full model▼
Purpose: Tie everything together. Input is noisy data + timestep + optional class; output is predicted noise of the same shape as the input.
classDiT(nn.Module):
# in __init__: fixed 2D sin-cos table, a buffer (saved, never trained)# self.register_buffer("pos_embed", get_2d_sincos_pos_embed(d, H // P).unsqueeze(0))defforward(self, x, t, y=None, train=False):
x = self.patch_embed(x) + self.pos_embed # [B, N, d]
c = self.t_embedder(t) # [B, d]if y is notNoneand self.y_embedder is notNone:
c = c + self.y_embedder(y, train=train) # add class condfor block in self.blocks:
x = block(x, c) # [B, N, d]
x = self.final_layer(x, c) # [B, N, P²·C_out]
x = self.unpatchify(x) # [B, C_out, H, W]return x
The whole model is one function: takes a noisy input and returns something the same shape. What it means (noise prediction or velocity) is determined by the loss you trained with, not by the architecture.
DDIMSampler — the reverse process with CFG▼
Purpose: Iterative denoising loop. Run DiT K times (K = num_steps), each time moving a bit closer to the data distribution. Supports classifier-free guidance by batching conditional + unconditional into a single forward.
classDDIMSampler:
@torch.no_grad()
defsample(self, shape, y=None, guidance_scale=1.0, device="cpu"):
B = shape[0]
x = torch.randn(shape, device=device)
use_cfg = guidance_scale > 1.0and y is notNonefor i inrange(self.num_steps):
t, t_next = self.timesteps[i], self.timesteps[i + 1]
t_batch = torch.full((B,), t, device=device, dtype=torch.long)
if use_cfg:
# Batch cond + uncond into 2B for a single forward
x_cat = torch.cat([x, x], dim=0)
y_null = torch.full_like(y, self.model.y_embedder.num_classes)
y_cat = torch.cat([y, y_null], dim=0)
t_cat = torch.cat([t_batch, t_batch], dim=0)
eps = self.model(x_cat, t_cat, y_cat)
eps_cond, eps_uncond = eps.chunk(2, dim=0)
eps = eps_uncond + guidance_scale * (eps_cond - eps_uncond)
else:
eps = self.model(x, t_batch, y)
# DDIM reverse step (deterministic, σ=0)
α_t = self.schedule.alphas_cumprod[t].to(device)
α_next = self.schedule.alphas_cumprod[t_next].to(device) if t_next > 0 \
else torch.tensor(1.0, device=device)
x_0_pred = (x - (1 - α_t).sqrt() * eps) / α_t.sqrt()
x = α_next.sqrt() * x_0_pred + (1 - α_next).sqrt() * eps
return x
6. Complexity Calculator
Try different DiT sizes, step counts and guidance. Defaults are DiT-XL/2 at 50 DDIM steps with CFG. FLOPs and parameters use exactly the formulas of compute_flops_per_step() and count_parameters() in diffusion.py (multiply-add = 2 FLOPs; the DiT paper's "Gflops" are half of these).
Latent size 32 corresponds to a 256×256 image with an 8× VAE. "INT8 / FP8" means INT8 on Orin (Ampere has no FP8) and FP8 on the RTX 4090; FP32 uses the CUDA cores only. Time = max(compute time at the chosen % of peak, time to stream the weights once per step), a roofline lower bound that ignores activation traffic, kernel launches and the text encoder. Peaks used: Jetson Orin Nano Super 17 TFLOPS FP16, 33 TOPS dense INT8, 2.1 TFLOPS FP32 (1024 CUDA cores × 2 × 1.02 GHz), 102 GB/s; RTX 4090 165.2 TFLOPS FP16 and 330.3 TFLOPS FP8 (both with FP32 accumulate), 82.6 TFLOPS FP32, 1008 GB/s. Real kernels sustain less than 100%: measure yours and lower the percentage.
7. Critical Optimizations for Inference
In plain words: total cost = steps × forward passes per step × cost of one forward, plus one VAE decode at the end. Each lever below shrinks one of those factors.
The general techniques used here (quantization, FlashAttention, kernel fusion, static-shape compilation, the roofline model) are explained step by step in the Memory & inference efficiency cookbook; this section covers what is specific to diffusion.
7.1 Step reduction — the single biggest lever▼
Total cost is linear in the number of network evaluations. Going from 1000 DDPM steps to 50 DDIM steps is a 20× saving for a small quality loss (§3); distilled students go further, to 1–4 steps. Typical step counts, as of Oct 2026:
Method
Typical steps
Trade-off
Use when
DDIM
50
Small quality loss vs 1000-step DDPM (FID 4.67 vs 3.17 on CIFAR-10)
ε-prediction models, no retraining
DPM-Solver++ / UniPC
10–20 (DPM-Solver++: 15–20 for guided sampling)
Higher-order ODE solvers; same network
Same, when you need fewer steps
Flow matching (Euler-type ODE solver)
28–50 (FLUX [dev] examples)
Requires a flow-matching-trained model
New training runs
Consistency / LCM
2–4
Requires distillation
Real-time applications
ADD (Turbo), FLUX.1 [schnell], DMD2
1–4
Requires (adversarial) distillation; less diversity
Interactive UIs, edge
DPM-Solver's title promises sampling "in around 10 steps"; how few steps are acceptable for your model and prompt is something to measure, not assume.
7.2 Guidance distillation — remove the 2× CFG cost▼
CFG doubles per-step compute because you run conditional and unconditional passes. Meng et al. (2023) first train a single student that takes the guidance scale w as an input and matches the combined guided output, then progressively distill it to fewer steps; for latent models such as Stable Diffusion they report good images in 1–4 steps.
This is now common in released models: FLUX.1 [dev] and FLUX.2 [dev] are "trained using guidance distillation" (model cards), so the guidance value you pass is just another conditioning input and each step costs one forward. In the calculator above, that is "1 forward per step".
7.3 Latent diffusion — always use it, and count the decoder▼
A 512×512 RGB image has 786,432 values; Stable Diffusion's VAE turns it into a 64×64×4 latent with 16,384 values: 64× fewer spatial positions (48× fewer numbers). With the same patch size the DiT then has 64× fewer tokens, so the linear layers do 64× less work and the N² attention term 4096× less.
# Training: encode once, diffuse in latent space
latent = vae.encode(image).latent_dist.sample() # [B, 4, 64, 64] for a 512×512 image
x_t, noise = schedule.q_sample(latent, t)
pred_noise = dit(x_t, t, class_label)
loss = mse(pred_noise, noise)
# Sampling: diffuse in latent, decode at the end
latent = sampler.sample(shape=(1, 4, 64, 64), y=class_label)
image = vae.decode(latent).sample # [1, 3, 512, 512]
The decoder is not free. It runs once per image, but it is a big convolutional network. Counting it with PyTorch's FLOP counter on the SD/LDM f=8 decoder architecture (49.5M parameters) gives about 0.62 TFLOP for a 256×256 image and 2.5 TFLOP for 512×512 (2 FLOPs per multiply-add). That is 13.5 DiT-B/2 forward passes. With a 50-step sampler the decoder is a rounding error; with a 4-step distilled model it costs more than the whole denoising loop. On the edge, a lighter decoder can matter as much as fewer steps.
7.4 FlashAttention and SDPA▼
DiT blocks are plain transformer blocks, so FlashAttention applies directly. For DiT-XL/2 at 256 tokens the attention matrix is small (256² × 16 heads × 2 bytes = 2 MiB per layer per sample) and the score FLOPs are only about 3.6% of a block, so the win is modest at 256×256. It grows quickly with resolution: at 1024 tokens the matrix is 16× larger, and video DiTs attend over tens of thousands of spatio-temporal tokens. PyTorch SDPA picks a fused kernel automatically where supported.
import torch.nn.functional as F
# Uses FlashAttention / memory-efficient kernels when the GPU, dtype and shapes allow
x = F.scaled_dot_product_attention(q, k, v) # no causal mask for DiT
7.5 Static shape compilation (TensorRT)▼
Unlike LLM decoding, a diffusion step has static shapes: fixed latent size, fixed token count, fixed batch (2 with CFG), and the same network is called every step. That makes it a good fit for an ahead-of-time TensorRT engine:
Build one engine per resolution and batch; no dynamic-shape profiles needed
Capture the step as a CUDA graph to remove per-kernel launch overhead
On Orin, dense INT8 peak is about 2× FP16 (33 TOPS vs 17 TFLOPS on Orin Nano Super), so INT8 or mixed INT8/FP16 can help if quality holds
Export the VAE decoder too: it can dominate few-step pipelines (7.3)
The calculator gives a lower bound (DiT-B/2, one forward: 46 GFLOPs ≈ 2.7 ms at the 17 TFLOPS FP16 peak). Compare it with what trtexec reports on your board to see the utilization you actually reach (exercise 6).
7.6 Other levers (as of Oct 2026)▼
4-bit weights and activations. SVDQuant (2024) moves weight outliers into a small high-precision low-rank branch and runs the rest in 4 bits, with the two branches fused into one kernel; on the 12B FLUX.1 models it reports 3.5× lower memory and a 3.0× speedup over 4-bit weight-only quantization on a 16 GB laptop RTX 4090.
Reuse work across steps. Consecutive steps see similar inputs, so training-free caching methods reuse earlier outputs. TeaCache (2024, video diffusion) estimates from the timestep-modulated inputs when the output will barely change and reuses the cached result then; it reports up to 4.41× speedup on Open-Sora-Plan with negligible quality loss.
Guidance only where it helps (§4): apply CFG in the middle noise interval and run one forward elsewhere.
8. Differences from LLMs and VLMs
Property
LLM decode
DiT step
Bottleneck at batch 1
Memory bandwidth: each weight is used once per token (≈1 FLOP/byte in FP16)
Mostly compute: each weight is reused by all N tokens (≈N FLOP/byte); near Orin's ridge for small DiTs at 256×256
KV cache
Yes (grows per token)
No (each step is stateless)
Sequence length
Grows with the output
Fixed by the latent size and patch size
Output representation
Discrete tokens (softmax over vocab)
Continuous (MSE regression on ε or velocity)
Conditioning method
Tokens in the sequence
adaLN modulation for t (+ class); text via cross-attention or joint attention (§2.1)
Network calls per sample
One forward per generated token
One or two forwards per step; 1–50 steps
Quantization in practice
Weight-only INT4/INT8 common
INT8/FP8 common; 4-bit weights and activations shown by SVDQuant
Biggest take-away: a DiT step behaves like an LLM prefill, not like decode. Every linear layer multiplies all N tokens by the same weights, so FP16 arithmetic intensity is about N FLOPs per weight byte. For DiT-B/2 at 256 tokens: 46 GFLOPs per forward over 261 MB of FP16 weights ≈ 176 FLOP/B, just above the Orin Nano Super ridge of 17 TFLOPS ÷ 102 GB/s ≈ 167. CFG (batch 2) doubles the intensity, and so does every 2× in token count, so larger images and video are firmly compute-bound: Tensor Core utilization and lower-precision arithmetic matter most, not KV-cache tricks.
9. Connection to VLA (Flow Matching on DiT)
In plain words: a robot arm's next second of motion is just another tensor to denoise. Swap the image latent for an action chunk and the same loop generates actions.
The same recipe (a transformer trained with flow matching to denoise a continuous tensor) generates robot actions in vision-language-action models such as π0, covered in Module 8:
What to notice: only the tensor being denoised and the source of the condition change; the flow-matching loop (predict a velocity, take an Euler step, repeat) is identical.
Image generation: the input is a noisy VAE latent ([16, 128, 128] for a 1024² SD3 or FLUX image), the output a velocity of the same shape; text enters through joint text-image attention (MMDiT); after K Euler steps you have a clean latent.
Robot action (π0): the input is a noisy action chunk [H, d_a] (H = 50 future steps, d_a = action dimension), the output a velocity of the same shape. The ~300M action expert's tokens attend to the VLM's tokens in every layer (shared self-attention, separate weights); the time τ is mixed in by an MLP, not adaLN; 10 Euler steps.
Going from "flow-matching transformer for images" to "flow-matching expert for robot actions" changes three things: the shape of the tensor being denoised (an action chunk instead of a latent image), where the condition comes from (the VLM's tokens, read through attention in every layer, instead of a class or prompt), and how the timestep enters (π0 uses an MLP on the action tokens; many image DiTs use adaLN). The sampling loop, the loss and the inference costs you learned here carry over directly, which is why this module comes before the VLA module.
10. On Edge Hardware
Lower-bound budget on a Jetson Orin Nano Super (17 TFLOPS dense FP16 Tensor-Core peak, 102 GB/s LPDDR5), computed with the calculator's roofline model at 100% of peak, FP16, for one 256×256 image (32×32×4 latent):
Config
Network evals
DiT FLOPs
DiT time ≥
VAE decode ≥
Verdict
DiT-XL/2 in pixel space (P = 2 → 16,384 tokens), DDIM 50 + CFG
100
4.9 PFLOP
≈ 4.8 min
—
❌ hopeless (attention is 70% of each block)
DiT-XL/2 latent, DDIM 50 + CFG
100
23.7 TFLOP
1.40 s
37 ms
Slow but possible
DiT-B/2 latent, DDIM 50 + CFG
100
4.6 TFLOP
271 ms
37 ms
OK for non-interactive use
DiT-B/2 latent, 28 steps, guidance-distilled
28
1.3 TFLOP
76 ms
37 ms
Interactive
DiT-B/2 latent, 4-step distilled
4
0.18 TFLOP
11 ms
37 ms
The decoder is now ~3/4 of the time
Real numbers will be higher: kernels rarely sustain peak, the text encoder is not counted, and power mode matters. Measure, then set the calculator's "% of peak" to what you observe. The shape of the result does not change: latent space + few steps (flow matching or distillation) + no 2× CFG + a cheap decoder is what fits on edge hardware. Notice also that DiT-B/2 without CFG needs 2.7 ms of compute per step but already 2.6 ms just to stream its 261 MB of FP16 weights once: at 256×256 and batch 1, a small DiT on Orin sits right at the compute/bandwidth balance point. INT8 therefore helps twice: half the weight bytes to stream and, if activations are INT8 too, twice the Tensor-Core peak.
11. Recap, Self-check & Exercises
Key takeaways
Training is regression: noise a sample to a random t in one line (x_t = √ᾱ_t·x₀ + √(1−ᾱ_t)·ε) and teach the network to predict ε (or a velocity).
DiT = ViT-style patchify + transformer blocks + unpatchify. The output has the input's shape; what it means (ε or velocity) is set by the loss.
adaLN-Zero turns (t, class) into per-channel shift/scale/gate vectors; zero-initializing them makes every block start as the identity (FID 19.47 vs 25.21 for plain adaLN in the paper's ablation).
Cost = network evaluations × FLOPs per evaluation. Samplers (DDIM, DPM-Solver++), flow matching and distillation attack the first factor: 1000 → 50 → 28 → 1–4.
CFG doubles the evaluations; guidance distillation (FLUX [dev]) or guiding only part of the trajectory removes most of that.
A DiT step is like an LLM prefill: ≈N FLOPs per weight byte, so it is compute-bound once N (tokens × batch) exceeds the GPU's ridge point (≈167 on Orin Nano Super in FP16).
The schedule's end matters: x̂₀ divides by √ᾱ_t, which magnifies ε̂ errors 157× at t = 999 on DiT's linear schedule and ~20,000× on cosine.
On the edge, count the VAE decoder: at 256×256 it costs about as much as 13 DiT-B/2 steps.
Self-check
Try each question before opening the answer.
1. Why can training jump straight to timestep t without simulating steps 1…t−1?
Answer
Each forward step adds independent Gaussian noise and scales the signal, and a sum of independent Gaussians is Gaussian. So q(x_t | x₀) has the closed form N(√ᾱ_t·x₀, (1−ᾱ_t)·I) with ᾱ_t = Π(1−β_s): one multiply-add and one noise sample.
2. With DiT's linear schedule, √ᾱ_500 = 0.2789. What fraction of x_500's variance is signal, and what is the SNR in dB?
Answer
ᾱ_500 = 0.2789² ≈ 0.078, so about 7.8% of the variance is signal. SNR = ᾱ/(1−ᾱ) ≈ 0.084, i.e. 10·log₁₀(0.084) ≈ −10.7 dB.
3. DiT-XL/2 on a 32×32 latent has N = 256 tokens. How many tokens with patch size 4, and roughly how do the FLOPs per forward change?
Answer
(32/4)² = 64 tokens. The linear layers scale with N (4× fewer) and attention with N² (16× fewer), so FLOPs drop about 4.1×: 237.2 → 58.1 GFLOPs per forward with compute_flops_per_step's formula. Parameters barely change.
4. ε̂_uncond = 0.10, ε̂_cond = 0.30. What does CFG give for w = 0, 1 and 4, and what does w = 4 cost?
Answer
0.10, 0.30 and 0.10 + 4·0.20 = 0.90. Any w ≠ 1 needs both predictions, so two forward passes per step (2× FLOPs), unless the model is guidance-distilled.
5. At initialization, what does a DiT block output for input x, and why is that useful?
Answer
Exactly x. The Linear that produces shift/scale/gate is zero-initialized, so both gates are 0 and both residual branches add 0. A deep stack of identities is a stable starting point; in the paper this initialization gave a clearly better FID than adaLN without it.
6. Why does DDIM with the cosine schedule become fragile if its first step is at t = 999?
Answer
x̂₀ = (x_t − √(1−ᾱ_t)·ε̂)/√ᾱ_t, so an ε̂ error δ becomes δ·√((1−ᾱ)/ᾱ) in x̂₀. Cosine (β capped at 0.999) has ᾱ_999 ≈ 2.4×10⁻⁹, a gain of ≈ 20,000; DiT's linear schedule has ᾱ_999 ≈ 4.0×10⁻⁵, a gain of ≈ 157.
7. On a Jetson Orin Nano Super, is a DiT-B/2 step at 256×256 compute-bound or memory-bound? Compare with an LLM decode step.
Answer
Ridge point = 17 TFLOPS / 102 GB/s ≈ 167 FLOP/byte. DiT-B/2: 46 GFLOPs over 261 MB of FP16 weights ≈ 176 FLOP/byte, just compute-bound (2.7 ms compute vs 2.6 ms to read the weights); with CFG it is 352 FLOP/byte. LLM decode at batch 1 does ≈1 FLOP/byte, deep in memory-bound territory.
8. A 4-step distilled DiT-B/2 makes 256×256 images on Orin. Where does the time go?
Answer
DiT: 4 × 46 GFLOPs = 184 GFLOPs ≈ 11 ms at peak. SD-style VAE decoder: ≈ 622 GFLOPs ≈ 37 ms. The decoder is ~3/4 of the work, so a lighter decoder now matters more than fewer steps.
9. With a single training point x_data, flow matching gives v(x, t) = (x_data − x)/(1 − t). Show that one Euler step from t = 0 is exact. Why do real models still need many steps?
Answer
Start from noise z at t = 0 and take one step of size 1: z + 1·(x_data − z)/(1 − 0) = x_data. With many data points, the learned velocity at (x, t) averages the straight lines towards all plausible x_data, so the field bends and a single large Euler step lands between modes (blurry samples).
10. π0 and an MMDiT image model both use flow matching. Name two architectural differences in how they are conditioned.
Answer
π0's action tokens attend to the VLM's tokens inside every layer (shared self-attention with separate expert weights), while MMDiT attends jointly over text and image tokens; and π0 mixes the timestep into the action tokens with an MLP, while DiT/MMDiT use adaLN-style modulation.
Hands-on exercises
🔧 Build it yourself
labs/lab06.html is a guided lab: build a tiny diffusion model from scratch (noising, the ε-prediction loss, a sampler) and watch it learn. Setup is in labs/index.html. The exercises below then work with diffusion.py.
All exercises use diffusion.py (CPU is fine). Use torch.float64 when comparing numbers.
1. Read the schedules (easy)
Print √ᾱ_t for both schedules and find where the SNR first drops below 0 dB.
Build a tiny DiT, check that a block returns its input and the model returns zeros, then give the adaLN Linear random weights and watch both change.
m = DiT(input_size=8, patch_size=2, hidden_dim=64, depth=2, num_heads=4, num_classes=10).eval()
h = m.patch_embed(x) + m.pos_embed; c = m.t_embedder(t) + m.y_embedder(y)
assert torch.equal(m.blocks[0](h, c), h) and (m(x, t, y) == 0).all()
3. Test DDIMSampler with an exact denoiser (medium)
For data x₀ ~ N(0, s²) the best possible ε-predictor is ε̂(x_t) = b/(a²s² + b²)·x_t with a = √ᾱ_t, b = √(1−ᾱ_t). Wrap it in an object with a __call__(x, t, y) and run the sampler with 50 steps on 4096 samples of shape (1, 2, 2), s = 0.5. Then add Gaussian noise of std 0.01 to ε̂ and compare schedules.
out = DDIMSampler(oracle, NoiseSchedule(1000, "linear"), 50).sample((4096, 1, 2, 2))
assert abs(out.std() - 0.5) < 0.05 # ≈ 0.47
# with 0.01 noise on ε̂: linear stays ≈ 0.47, cosine grows to ≈ 3.1 (§1.1 pitfall)
4. Flow matching on 2-D toy data (medium)
Train a small MLP v_θ(x, t) (input: x and t, 2 hidden layers of 128, SiLU) with the loss of FlowMatchingTrainer.training_step on a mixture of two 2-D Gaussians at (±2, 0) with std 0.3 (Adam, lr 1e-3, 3000 steps of batch 512 take seconds on a CPU). Sample with 1, 4 and 20 Euler steps and count how many samples land between the modes.
# single-point sanity check first: with v = (x_data - x) / (1 - t), one Euler step is exact
assert (euler(v_exact, x_noise, steps=1) - x_data).abs().max() < 1e-6
between = lambda x: (x[:, 0].abs() < 1).float().mean()
assert between(sample(4000, steps=1)) > 0.5 # one step averages the two modes
assert between(sample(4000, steps=20)) < 0.05 # (our run: 1.00 / 0.14 / 0.016 for 1 / 4 / 20 steps)
5. Add η to DDIM (harder)
Generalize the update to DDIM's family: σ_t = η·√((1−ᾱ_next)/(1−ᾱ_t))·√(1−ᾱ_t/ᾱ_next) and x_next = √ᾱ_next·x̂₀ + √(1−ᾱ_next−σ_t²)·ε̂ + σ_t·z. Check that η = 0 reproduces the current sampler bit-for-bit (same seed), and use the exact denoiser from exercise 3 to compare η = 0 and η = 1 at 10 and 50 steps.
torch.manual_seed(0); a = sampler.sample(shape)
torch.manual_seed(0); b = sampler_eta.sample(shape, eta=0.0)
assert torch.equal(a, b)
6. Measure utilization on your GPU or Jetson (harder)
Export dit_s_2() (fixed shapes: x [2, 4, 32, 32], t [2], y [2]) with torch.onnx.export, build an FP16 engine with trtexec --onnx=dit_s2.onnx --fp16, and compare the reported latency with the calculator's lower bound for DiT-S/2 (one step with CFG = 24.2 GFLOPs). Utilization = lower bound ÷ measured time.
# correctness first: TensorRT FP16 output vs PyTorch FP32 output on the same inputs
assert np.allclose(trt_out, torch_out, atol=1e-2)