Level 3 In-Depth AI · Generative AI
Diffusion Transformers
A diffusion Transformer (DiT) replaces the convolutional U-Net inside a diffusion model with a plain Transformer that works on a sequence of small latent patches. It scales the way language models do, and it is the backbone of most leading image and video generators built since 2024.
- Level
- ●●●●● Advanced
- Reading
- 13 min
- To learn it well
- 1 hour to read, an hour to practise
- Builds on
- 32 concepts →
- Quiz
- 4 questions ↓
This leads to
Video GenerationThe full path from zero — 32 concepts before this one
- What Is AI?
- Probability Basics
- Vectors
- Derivatives and Slopes
- How Machines Learn
- Probability Distributions
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Convolutional Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- What Generative Models Do
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- Diffusion Models
- LSTMs and GRUs
- Residual Connections
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- Diffusion Transformers
Read them roughly in this order. See it on the concept map →
Why it matters
The first generation of diffusion models, from DDPM to Stable Diffusion 1 and SDXL, used a U-Net as the denoiser: a convolutional network with some attention layers mixed in (Diffusion Models). Meanwhile, the The Transformer had taken over language, then vision (Vision Transformers), with one big selling point: when you make a Transformer larger and train it on more data, it gets better in a smooth, predictable way (Scaling Laws).
In December 2022, William Peebles and Saining Xie showed that the same is true for diffusion. Their Diffusion Transformer (DiT) throws away the U-Net. It cuts the noisy latent into patches, treats them as tokens, and runs a standard Transformer. The bigger the DiT, and the more tokens it processes, the better its images, with no exceptions in their experiments.
That result reshaped the field. As of late 2026, most frontier image and video generators are diffusion Transformers or close variants. Stable Diffusion 3, the FLUX models, PixArt, Hunyuan-DiT, OpenAI's Sora (since discontinued), Meta's Movie Gen, and open video models such as Wan and HunyuanVideo all use them. Using a Transformer also lets image models borrow the whole toolkit built for LLMs: FlashAttention, model parallelism, mixed-precision recipes and scaling studies.
The intuition
A U-Net is a hand-designed machine for images. It shrinks the picture to see the big layout, grows it back to restore detail, and passes information across with skip connections. It builds in strong assumptions: nearby pixels matter most, and the same pattern means the same thing anywhere (Convolutional Neural Networks). Those assumptions help when data is limited, but they also cap how far the design can go.
A Transformer assumes almost nothing. It sees a set of tokens, and every token can look at every other token through attention. Given enough data and compute, it learns for itself which relationships matter. That is what happened in language and in image classification, and DiT showed the same for generation.
The recipe is the Vision Transformer recipe, applied to a noisy latent:
- Take the noisy latent from a Latent Diffusion and Stable Diffusion autoencoder, for example 32×32×4 for a 256×256 image.
- Patchify: cut it into small squares, say 2×2, giving 16×16 = 256 patches. Flatten each patch (2·2·4 = 16 numbers) and project it to a token vector.
- Run a stack of Transformer blocks over the 256 tokens. The noise level and the condition (a class label, or text) adjust every block.
- Unpatchify: turn each output token back into a 2×2×4 patch and reassemble the predicted noise (or velocity).
Key idea A DiT is a diffusion (or flow-matching) model whose denoiser is a plain Transformer over latent patches. It is conditioned on time and prompt by adaptive layer normalization. Its quality improves steadily as you add layers, width or tokens, which made it the standard backbone for large image and video models.
How it works
Patchify and the sequence length
With a latent of height , width and channels, and patch size , the number of tokens is:
Each token starts as numbers, projected by a learned linear layer to the model width (1,152 in DiT-XL). A position embedding is added so the model knows where each patch came from. DiT used fixed sinusoidal 2-D embeddings. Newer models use rotary embeddings (Positional Encodings).
Worked example. For a 256×256 image, the Stable Diffusion VAE gives a 32×32×4 latent.
| Patch size | Tokens | Numbers per patch | Self-attention table |
|---|---|---|---|
| 8 | 4 × 4 = 16 | 256 | 256 entries |
| 4 | 8 × 8 = 64 | 64 | 4,096 entries |
| 2 | 16 × 16 = 256 | 16 | 65,536 entries |
Halving the patch size gives 4 times as many tokens. The Transformer's linear layers cost about 4 times more, and the attention table grows 16-fold. For a 1024×1024 image (a 128×128 latent) with there are 4,096 tokens. This is why sequence length, and therefore attention cost, dominates the engineering of high-resolution and video models.
Conditioning: adaptive layer normalization
The denoiser has to know the noise level and the condition , such as a class label or a prompt. DiT's authors tried four ways to feed them in:
- In-context: append and as two extra tokens.
- Cross-attention: as in Stable Diffusion's U-Net (Latent Diffusion and Stable Diffusion), let image tokens attend to the condition.
- adaLN: let the condition set the scale and shift of each layer normalization.
- adaLN-Zero: adaLN plus a learned gate on each residual branch, with everything initialised to zero.
adaLN-Zero gave the best images at the lowest cost. It works like this. A small network turns the condition vector into six vectors per block: scales , shifts and gates . Each half of the block then computes:
- is the sequence of token vectors, and is layer normalisation without its own learned scale and shift.
- multiplies element by element, the same for every token. So the condition retunes every feature channel of the whole image at once: "at this noise level, for a golden retriever, amplify these features and damp those".
- gates how much each sub-layer adds to the residual stream. Initialising the network that produces them to zero makes every block start as the identity function. Training starts from "pass the input through unchanged" and gradually turns blocks on, which makes deep stacks stable.
Class labels and time steps fit neatly into one vector. A long text prompt does not, so text-to-image DiTs add text separately. PixArt-α kept adaLN for time and added cross-attention to text tokens. Stable Diffusion 3's MM-DiT (multimodal DiT) instead puts image tokens and text tokens into one sequence. Each modality has its own weights, and they share joint attention, so text and image tokens attend to each other in both directions at every layer. FLUX uses a similar design.
The scaling result
DiT came in four widths and depths: S (33M parameters), B (130M), L (458M) and XL (675M), each with patch sizes 8, 4 and 2. They were trained as class-conditional models on ImageNet at 256×256. The central finding was that sample quality tracked compute per forward pass (measured in Gflops, billions of floating-point operations), whether that compute came from a bigger model or from smaller patches. More Gflops meant lower FID in every comparison. Bigger models also made better use of each training step.
The largest model, DiT-XL/2 (XL with , about 119 Gflops per pass), reached an FID of 2.27 on class-conditional ImageNet 256×256 with classifier-free guidance. That beat every earlier diffusion model, including the much more heavily engineered U-Nets.
From images to video
Once a model works on a sequence of patches, nothing forces the patches to be flat. A video latent of shape can be cut into small spacetime patches (for example 1×2×2 or 2×2×2), producing one long token sequence. The same Transformer then attends across both space and time. OpenAI's Sora report described exactly this: a diffusion Transformer over spacetime patches of a compressed video latent, trained on videos of varied lengths, resolutions and aspect ratios. See Video Generation.
Why Transformers won
- Predictable scaling. Quality improves smoothly with compute, so labs can plan billion-parameter training runs (SD3's paper scaled to 8 billion parameters, FLUX.1 has 12 billion).
- Flexible shapes. Any resolution or aspect ratio is just a different number of tokens, and video adds a time axis.
- Shared infrastructure with LLMs: fused attention kernels, parallelism and quantisation all carry over.
- Easy multimodality. Text and image tokens can live in one sequence.
U-Nets are still widely used, especially at small scale and in older ecosystems (SD 1.5, SDXL), where their image-specific design is efficient.
In code
A tiny class-conditional DiT trained with Normalizing Flows and Flow Matching on scikit-learn's 8×8 digits. It is the full recipe at toy scale: patchify into 2×2 patches (16 tokens), position embeddings, Transformer blocks with adaLN-Zero, unpatchify, label dropout and classifier-free guidance. Training takes about a minute and a half on a laptop CPU. A logistic-regression classifier trained on real digits serves as the judge of whether each generated digit is the one requested.
import torch, torch.nn as nn
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
torch.manual_seed(0)
digits = load_digits()
X = torch.tensor(digits.data, dtype=torch.float32) / 8 - 1 # 1797 images, 64 pixels in [-1, 1]
Y = torch.tensor(digits.target)
patchify = lambda x: x.view(-1, 4, 2, 4, 2).permute(0, 1, 3, 2, 4).reshape(-1, 16, 4) # 8x8 -> 16 patches of 2x2
unpatchify = lambda p: p.view(-1, 4, 4, 2, 2).permute(0, 1, 3, 2, 4).reshape(-1, 64)
class DiTBlock(nn.Module):
def __init__(self, d):
super().__init__()
self.norm1, self.norm2 = nn.LayerNorm(d, elementwise_affine=False), nn.LayerNorm(d, elementwise_affine=False)
self.attn = nn.MultiheadAttention(d, num_heads=4, batch_first=True)
self.mlp = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d))
self.ada = nn.Linear(d, 6 * d) # adaLN-Zero: condition -> scales, shifts, gates
nn.init.zeros_(self.ada.weight); nn.init.zeros_(self.ada.bias)
def forward(self, h, c):
s1, b1, g1, s2, b2, g2 = self.ada(c).unsqueeze(1).chunk(6, dim=-1)
a = self.norm1(h) * (1 + s1) + b1
h = h + g1 * self.attn(a, a, a)[0]
return h + g2 * self.mlp(self.norm2(h) * (1 + s2) + b2)
class TinyDiT(nn.Module):
def __init__(self, d=64, depth=4):
super().__init__()
self.embed, self.pos = nn.Linear(4, d), nn.Parameter(0.02 * torch.randn(1, 16, d))
self.t_emb = nn.Sequential(nn.Linear(1, d), nn.SiLU(), nn.Linear(d, d))
self.y_emb = nn.Embedding(11, d) # digits 0-9, plus 10 = "no label"
self.blocks = nn.ModuleList([DiTBlock(d) for _ in range(depth)])
self.out = nn.Linear(d, 4)
def forward(self, x, t, y):
h, c = self.embed(patchify(x)) + self.pos, self.t_emb(t) + self.y_emb(y)
for block in self.blocks:
h = block(h, c)
return unpatchify(self.out(h))
model = TinyDiT()
print("parameters:", sum(p.numel() for p in model.parameters()))
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
for step in range(2001): # flow matching, 10% label dropout
i = torch.randint(0, len(X), (256,))
x1, y = X[i], torch.where(torch.rand(256) < 0.1, 10, Y[i])
x0, t = torch.randn_like(x1), torch.rand(256, 1)
loss = ((model((1 - t) * x0 + t * x1, t, y) - (x1 - x0)) ** 2).mean()
opt.zero_grad(); loss.backward(); opt.step()
if step % 1000 == 0: print(f"step {step} loss {loss.item():.3f}")
with torch.no_grad(): # 20 Euler steps, guidance scale 2
y = torch.arange(10).repeat(20); x = torch.randn(200, 64)
for k in range(20):
t = torch.full((200, 1), k / 20)
v_c, v_u = model(x, t, y), model(x, t, torch.full_like(y, 10))
x = x + (v_u + 2.0 * (v_c - v_u)) / 20
clf = LogisticRegression(max_iter=2000).fit(X.numpy(), Y.numpy()) # a judge trained on real digits
print("judge agrees with requested digit:", (clf.predict(x.clamp(-1, 1).numpy()) == y.numpy()).mean())
print("\n".join("".join(" .:#"[min(3, int((v + 1) * 2))] for v in row) for row in x[3].view(8, 8)))
# parameters: 305348
# step 0 loss 1.751
# step 1000 loss 0.423
# step 2000 loss 0.372
# judge agrees with requested digit: 1.0 <- all 200 generated digits classified as requested
# ###: <- a generated "3"
# ..:#
# ##
# ##.
# ##
# . #:
# : .#
# ####
Scale every number up (a 128×128×16 latent, 4,096 tokens, width 3,072, dozens of blocks, text tokens in the sequence) and you have the shape of a modern text-to-image model. In practice you would load one through diffusers. For example, StableDiffusion3Pipeline and FluxPipeline both wrap an MM-DiT-style Transformer with a flow-matching scheduler.
Common pitfalls
- Exploding sequence length. Doubling resolution quadruples the tokens and multiplies attention cost by 16. Budget memory before raising resolution, and use memory-efficient attention.
- Forgetting the position embeddings. Attention by itself has no sense of order or layout. Without position information, the DiT can't know which patch is where, and images scramble.
- Training at one resolution, sampling at another. Fixed position embeddings don't extend cleanly. Train on several resolutions and aspect ratios ("bucketing"), or use rotary or interpolated embeddings.
- Unstable deep stacks. Zero-initialising the gates (adaLN-Zero) and the final layer matters. Without it, large DiTs can diverge early.
- Confusing DiT with ViT. A ViT classifies an image. A DiT predicts noise or velocity for every patch, and needs the time step and condition at every block.
Watch out The scaling story cuts both ways. DiT-based image and video models with billions of parameters cost millions of dollars to train and need large GPUs to run. If your task is narrow (one product's photos, one style), fine-tune an existing open model with LoRA (Text-to-Image in Practice) instead of training from scratch.
Where it leads
- Video Generation: spacetime patches and long token sequences.
- Text-to-Image in Practice: using DiT-based models such as SD3 and FLUX in practice.
- Normalizing Flows and Flow Matching: the training objective used by most production DiTs.
- Multimodal LLMs: models that put text and image tokens in one Transformer for understanding rather than generation, and increasingly for both.
- Scaling Laws: the empirical rules that made the DiT result so consequential.
A bit of history
The Vision Transformers (Dosovitskiy and colleagues, 2020) showed that a plain Transformer over image patches could match convolutional networks at classification. Two 2022 papers brought the idea to diffusion: U-ViT (Bao and colleagues), which kept U-Net-style long skip connections in a Transformer, and DiT (Peebles and Xie, posted December 2022 and presented at ICCV 2023), whose clean scaling study made the bigger impression. Peebles went on to co-lead OpenAI's Sora (announced February 2024), whose report described a diffusion Transformer on spacetime patches.
In 2023 PixArt-α showed a text-conditioned DiT trained at a fraction of the usual cost. In 2024 Stable Diffusion 3 (Esser and colleagues) introduced MM-DiT with rectified flow, and FLUX.1 from Black Forest Labs followed. Meta's Movie Gen and open video models (HunyuanVideo, Wan) carried the architecture into video. By 2025 the DiT, trained with flow matching on a VAE latent, had become the default design for new generative models of images, video and, increasingly, audio.
Try it
- Change the patch size to 4 (4 tokens of 16 numbers each) by rewriting
patchifyandunpatchify, and retrain. Does the judge's score drop? How does the training time change?- Replace adaLN-Zero with "in-context" conditioning: append the condition vector
cas a 17th token and use plain LayerNorm. Compare the losses after 2,000 steps.- Set the guidance scale to 0, 1 and 4 and record the judge's agreement for each.
Hint for 1:
x.view(-1, 2, 4, 2, 4).permute(0, 1, 3, 2, 4).reshape(-1, 4, 16).
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Scalable Diffusion Models with Transformers
DiT: replacing the diffusion U-Net with a Transformer.
Scaling Rectified Flow Transformers for High-Resolution Image Synthesis
Stable Diffusion 3: rectified flow with a multimodal diffusion Transformer (MM-DiT).
Understanding Deep Learning
A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.
Diffusers documentation
The official guide to the diffusers library: pipelines for text-to-image, img2img, inpainting, ControlNet, LoRA loading, schedulers and training scripts.
Sander Dieleman's blog
Deep, intuitive essays on diffusion by a Google DeepMind researcher: guidance, noise schedules, perspectives on diffusion, and diffusion vs autoregression.
An Image is Worth 16x16 Words
The Vision Transformer: images as sequences of patches.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/generative/diffusion-transformers.md