◆ AI All-in-One

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
↗ Plan a path here

Read first

Diffusion ModelsThe Transformer

This leads to

Video Generation
The full path from zero — 32 concepts before this one
  1. What Is AI?
  2. Probability Basics
  3. Vectors
  4. Derivatives and Slopes
  5. How Machines Learn
  6. Probability Distributions
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. The Chain Rule
  10. Dot Product, Norms and Similarity
  11. Supervised, Unsupervised and Reinforcement Learning
  12. Gradient Descent
  13. Supervised Learning
  14. Linear Regression
  15. The Perceptron
  16. Logistic Regression
  17. Neural Networks
  18. Convolutional Neural Networks
  19. Recurrent Neural Networks
  20. Backpropagation
  21. Activation Functions
  22. What Generative Models Do
  23. Vanishing and Exploding Gradients
  24. Normalization Layers: BatchNorm and LayerNorm
  25. Diffusion Models
  26. LSTMs and GRUs
  27. Residual Connections
  28. Sequence-to-Sequence Models
  29. Attention
  30. Self-Attention and Multi-Head Attention
  31. Positional Encodings
  32. The Transformer
  33. 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:

  1. Take the noisy latent from a Latent Diffusion and Stable Diffusion autoencoder, for example 32×32×4 for a 256×256 image.
  2. 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.
  3. Run a stack of Transformer blocks over the 256 tokens. The noise level tt and the condition (a class label, or text) adjust every block.
  4. Unpatchify: turn each output token back into a 2×2×4 patch and reassemble the predicted noise (or velocity).
Noisy latent32 × 32 × 4 (a 256 px image) cut into 2 × 2 patches:16 × 16 = 256 patches Tokens256 of them ⋮ each: 2·2·4 = 16numbers → linear→ 1,152 + position time t + class or text N × DiT blockself-attention + MLP,conditioned by adaLN DiT-XL: N = 28,675M parameters Outputsper token unpatchify predicted noise32 × 32 × 4 Patch size sets the sequence length: p = 8 → 16 tokens, p = 4 → 64 tokens, p = 2 → 256 tokens. Halving p gives 4× the tokens and roughly 4× the compute.In the DiT paper, smaller patches always gave better images.
Fig. 1 A diffusion Transformer. The noisy 32×32×4 latent is cut into 2×2 patches, giving 256 tokens. Each token is a linear projection of its 16 numbers plus a position embedding. A stack of DiT blocks, conditioned on the time step and the class or text, processes them, and the outputs are reassembled into a predicted-noise latent of the same shape.

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 HH, width WW and CC channels, and patch size pp, the number of tokens is:

N=Hp⋅WpN = \frac{H}{p} \cdot \frac{W}{p}

Each token starts as p⋅p⋅Cp \cdot p \cdot C numbers, projected by a learned linear layer to the model width dd (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 pp Tokens NN Numbers per patch Self-attention table N×NN \times N
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 p=2p = 2 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 tt and the condition yy, such as a class label or a prompt. DiT's authors tried four ways to feed them in:

  1. In-context: append tt and yy as two extra tokens.
  2. Cross-attention: as in Stable Diffusion's U-Net (Latent Diffusion and Stable Diffusion), let image tokens attend to the condition.
  3. adaLN: let the condition set the scale and shift of each layer normalization.
  4. 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 c=embed(t)+embed(y)\mathbf{c} = \text{embed}(t) + \text{embed}(y) into six vectors per block: scales γ1,γ2\boldsymbol\gamma_1, \boldsymbol\gamma_2, shifts β1,β2\boldsymbol\beta_1, \boldsymbol\beta_2 and gates α1,α2\boldsymbol\alpha_1, \boldsymbol\alpha_2. Each half of the block then computes:

h←h+α1⊙Attention(LN(h)⊙(1+γ1)+β1)\mathbf{h} \leftarrow \mathbf{h} + \boldsymbol\alpha_1 \odot \text{Attention}\big(\text{LN}(\mathbf{h}) \odot (1 + \boldsymbol\gamma_1) + \boldsymbol\beta_1\big)
h←h+α2⊙MLP(LN(h)⊙(1+γ2)+β2)\mathbf{h} \leftarrow \mathbf{h} + \boldsymbol\alpha_2 \odot \text{MLP}\big(\text{LN}(\mathbf{h}) \odot (1 + \boldsymbol\gamma_2) + \boldsymbol\beta_2\big)
  • h\mathbf{h} is the sequence of token vectors, and LN\text{LN} is layer normalisation without its own learned scale and shift.
  • ⊙\odot 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".
  • α\boldsymbol\alpha 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.
tokens h 256 × 1,152 LayerNorm LayerNorm × (1 + γ₁) + β₁ × (1 + γ₂) + β₂ self-attention MLP × α₁ × α₂ residual connection residual connection to next block condition c embed(t) + embed(class or text) small MLP → six vectors γ₁, β₁, α₁, γ₂, β₂, α₂ initialised to zero, so each new block starts as "do nothing" scale, shift, gate
Fig. 2 A DiT block with adaLN-Zero conditioning. The condition (time step plus class or text embedding) is mapped to six vectors that scale and shift the normalised tokens before attention and before the MLP, and gate each branch before it is added back to the residual stream.

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 p=2p = 2, 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 T×H×W×CT \times H \times W \times C 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

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

  1. Change the patch size to 4 (4 tokens of 16 numbers each) by rewriting patchify and unpatchify, and retrain. Does the judge's score drop? How does the training time change?
  2. Replace adaLN-Zero with "in-context" conditioning: append the condition vector c as a 17th token and use plain LayerNorm. Compare the losses after 2,000 steps.
  3. 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).

Check your understanding

4 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A 32×32×4 latent is patchified with patch size 2. How many tokens does the DiT process?

  2. You halve the patch size from 4 to 2 on the same latent. What happens to the self-attention table?

  3. Why does adaLN-Zero initialise its gates to zero?

  4. What did the DiT scaling study find most strongly predicted sample quality?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Book

Understanding Deep Learning

Simon J. D. Prince · 2023 · Intermediate · Free

A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.

Docs

Diffusers documentation

Hugging Face · Intermediate · Free

The official guide to the diffusers library: pipelines for text-to-image, img2img, inpainting, ControlNet, LoRA loading, schedulers and training scripts.

Article

Sander Dieleman's blog

Sander Dieleman · Advanced · Free

Deep, intuitive essays on diffusion by a Google DeepMind researcher: guidance, noise schedules, perspectives on diffusion, and diffusion vs autoregression.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/generative/diffusion-transformers.md