DiT (Diffusion Transformer) replaces the noise-predicting network of a diffusion model, previously a U-Net, with a Transformer. Like Latent Diffusion, it diffuses in the latent space of an autoencoder, and it splits that latent into patches like ViT and processes them with a Transformer. Its defining feature is that the quality of generated images improves steadily as the model gets larger.
It was introduced in 2022 by Peebles and Xie in the paper "Scalable Diffusion Models with Transformers" and accepted at ICCV 2023.
Until then, diffusion models used the convolutional U-Net inherited from DDPM in a mostly fixed form. Meanwhile, in language and image recognition, the Transformer had replaced many specialized architectures and shown the property that performance keeps growing as scale increases (scalability). The paper confirms two things.
The inductive bias of the U-Net is not essential: diffusion models train well even when it is replaced with a standard Transformer that faithfully follows ViT's conventions.
Image quality improves as computation increases: increasing the computation of one forward pass (Gflops), either by making the Transformer deeper or wider or by increasing the number of input tokens, consistently lowers the FID.
The largest model, DiT-XL/2, achieved an FID of 2.27 on class-conditional 256 × 256 generation on ImageNet, surpassing all diffusion models of the time.
Theory
The diffusion part of DiT is the same as Latent Diffusion. An image x is mapped to a latent z=E(x) by the autoencoder's encoder, noise is added in latent space as in DDPM, and the network is trained to guess the added noise. Only the inside of the noise-predicting network changes.
Diffusion settings
Latent space: uses Stable Diffusion's pretrained VAE (which shrinks height and width to 1/8). For a 256 × 256 × 3 image, the latent is 32 × 32 × 4.
Noise schedule: tmax=1000 steps, with the variance increasing linearly from 1×10−4 to 2×10−2 (the same as ADM).
Training objective: the network outputs both the noise ϵθ and the diagonal covariance Σθ of the reverse process. ϵθ is trained with the same simple squared error Lsimple as DDPM, and Σθ with the full variational bound L.
Network flow
Split into patches (patchify): the I×I×C latent is split into p×p patches, and each patch is linearly embedded into d dimensions. The number of tokens is T=(I/p)2. p = 2, 4, and 8 are tried.
Add position embeddings: the same sinusoidal (sin and cos) position embeddings as ViT are added to all tokens.
Pass through N DiT blocks: each block processes the tokens while feeding in the conditions of step t and class y.
Restore the original shape: finally, layer normalization (adaLN) is applied, a linear layer turns each token into p×p×2C, and the tokens are rearranged into the original spatial layout. The first C channels are the noise prediction and the last C channels the covariance prediction.
Halving p makes the number of tokens 4 times larger and the computation more than 4 times larger. The number of parameters, on the other hand, barely changes.
How conditions are fed in: adaLN-Zero
The paper compared four ways of feeding step t and class y into the blocks (Section 3.2).
Block
How the conditions are fed in
Added computation
In-context
The embeddings of t and y are appended to the input sequence as two tokens (like ViT's [class] token)
Almost none
Cross-attention
The embeddings of t and y form a length-2 sequence that is referenced by cross-attention after self-attention
About 15% more
adaLN
Instead of learning the scale γ and shift β of layer normalization, regress them from the sum of the embeddings of t and y
The least
adaLN-Zero
In addition to adaLN, also regress a per-dimension scale α applied just before the residual addition, and initialize the MLP that outputs α to 0
The least
The adaLN-Zero DiT block produces γ1,β1,α1,γ2,β2,α2 with an MLP from the condition embedding c (the sum of the embeddings of t and y), and computes as follows. LN is layer normalization (without its own scale and shift), and ⊙ is the per-dimension product.
Attn is self-attention with multi-head attention, and FFN is the position-wise fully connected network. Since α starts at 0, every block is an identity map that passes its input through unchanged at the start of training. This follows the finding that starting the scale of the last normalization in each ResNet block at 0 speeds up large-scale training.
adaLN applies the same γ, β, and α to all tokens. It cannot feed in conditions that differ by image location, but conditions that apply to the whole image, such as the class or step, can be fed in with almost no added computation.
Model sizes
Following ViT, four configurations are used that scale the number of layers N, the hidden dimension d, and the number of heads together (Table 1). The "/2" in the name is the patch size p.
Model
Layers N
Hidden dim d
Heads
Parameters (p=2)
Computation (p=2, 256 × 256)
DiT-S
12
384
6
33M
6.06 Gflops
DiT-B
12
768
12
130M
23.01 Gflops
DiT-L
24
1024
16
458M
80.71 Gflops
DiT-XL
28
1152
16
675M
118.64 Gflops
Parameters and computation are the values from Table 4 in the appendix and do not include the VAE (84M parameters).
Why it works
The reasons DiT works can be summarized in three points.
It directly inherits the scalability of Transformers: DiT is built to follow ViT's conventions as faithfully as possible, so the property established for Transformers, "the bigger, the better", carries over to diffusion models. Across the paper's 12 models (S, B, L, XL × patch 8, 4, 2), the correlation coefficient between computation and FID was −0.93 (Figure 8).
Computation matters more than the number of parameters: making the patches smaller at the same model size increases only the computation while the parameters stay nearly the same, yet the FID dropped greatly. Models with similar computation, such as DiT-S/2 and DiT-B/4, also had similar FIDs. In other words, for DiT the key to better performance is increasing the computation of a single forward pass.
adaLN-Zero feeds in conditions cheaply and effectively: in 400K training steps of XL/2, the FID of adaLN-Zero was about half that of the in-context approach (Figure 5). The zero initialization also matters, giving a large improvement over plain adaLN.
As an everyday analogy, a U-Net is a specialized tool crafted for images, and DiT is a large general-purpose machine tool. The specialized tool is handy at a small scale, but the general-purpose machine shows its power more and more as the scale grows, and techniques refined in other fields can be brought over as they are.
Increasing the number of generation steps after training did not let small models catch up with large ones. DiT-XL/2 with 128 steps (15.2 Tflops per image) achieved a better FID than DiT-L/2 with 1000 steps (80.7 Tflops) at one-fifth of the computation (23.7 vs. 25.9, Figure 10).
Experimental results
The experiments used class-conditional generation on ImageNet. Training used AdamW (constant learning rate 1×10−4, no weight decay), batch size 256, horizontal flips as the only data augmentation, and an exponential moving average of the weights (decay 0.9999) for evaluation. There was no learning rate warmup and no regularization, and training was stable for all configurations. FID is computed from 50,000 images generated with 250 DDPM steps.
Block comparison (excerpt from Table 4 in the appendix; FID over training is in Figure 5; DiT-XL/2, 400K training steps, no classifier-free guidance)
Block
Computation
FID
In-context
119.37 Gflops
35.24
Cross-attention
137.62 Gflops
26.14
adaLN
118.56 Gflops
25.21
adaLN-Zero
118.64 Gflops
19.47
ImageNet 256 × 256 (Table 2; "-G" means classifier-free guidance was used, and cfg is its scale)
DiT-XL/2 was trained for 7M steps. With classifier-free guidance, it lowered the previous best FID of 3.60 by LDM to 2.27, the lowest FID among all generative models including the GAN StyleGAN-XL. Even at 2.35M training steps, about the same as ADM, the FID was 2.55. Its computation is 118.6 Gflops, about the same as LDM-4 (103.6 Gflops), a U-Net in latent space, and far less than ADM in pixel space (1120 Gflops).
ImageNet 512 × 512 (Table 3)
Model
FID
IS
StyleGAN-XL
2.41
267.75
ADM-G, ADM-U
3.85
221.72
DiT-XL/2-G (cfg = 1.50)
3.04
240.82
At 512 × 512, the latent becomes 64 × 64 × 4, and with patch size 2 the model processes 1024 tokens (524.6 Gflops). Even so, it surpassed previous diffusion models with less computation than ADM (1983 Gflops) or ADM-U (2813 Gflops).
Practical notes
Keep the following points in mind when using DiT.
Smaller patches greatly increase computation: halving p makes the tokens 4 times as many, and the self-attention computation grows even more. Choose p by balancing image quality and computation. The paper's best result uses p=2.
Initialize the last linear layer to 0: the paper initializes the last linear layer to 0 and uses ViT's standard initialization elsewhere. The MLP that outputs adaLN-Zero's α also starts at 0.
More generation steps cannot make up for a small model: a large model with few steps gave better computational efficiency and image quality than a small model with more steps.
The latent space relies on Latent Diffusion's VAE: the fine details of generated images depend on the quality of the VAE decoder. The paper shows that as long as the encoder is the same, the decoder alone can be swapped without retraining the diffusion model (Appendix D).
The paper's results are for class-conditional generation on ImageNet. The only conditions are the class and step, and text-to-image generation is not covered (the paper leaves it as future work). Also, adaLN applies the same transformation to all tokens, so feeding in conditions with length, such as text, as they are requires a different mechanism such as cross-attention.
Comparison with other methods
The following compares DiT with closely related diffusion models from the same viewpoints.
Computation and FID are strongly correlated; scales steadily
DiT replaces only the noise-predicting network in the Latent Diffusion framework with a Transformer. The training objective and generation procedure do not change, so generation methods such as DDIM can be used as is.
Rough guidelines for choosing:
To push diffusion model performance by spending compute: DiT, whose performance grows steadily with computation, is a good fit.
To reuse Transformer training conventions and implementations as they are: DiT, built like ViT, is an easy choice.
To generate with conditions that have position or length, such as text or images: the Latent Diffusion U-Net, with cross-attention and concatenation, can be used as is.
With limited compute and a small model: at small scales the inductive bias of the U-Net can help, so compare at the same computation before choosing.
PyTorch example
▶Show code
python
import math
import torch
import torch.nn as nn
"""
A small implementation of DiT from Peebles & Xie (2023), written to follow Section 3.2 of the paper.
Splits the latent (e.g., 32×32×4) into p×p patches, processes them with a Transformer, and outputs the noise eps and covariance Sigma.
The condition is the sum of the embeddings of step t and class y, fed in through adaLN-Zero blocks
"""
def modulate(x, shift, scale):
"""Scale and shift: gamma * LN(x) + beta (many implementations use scale = 1 + output so that gamma = 1 at the start)"""
return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
def timestep_embedding(t, dim):
"""Sinusoidal embedding of step t"""
half = dim // 2
freqs = torch.exp(-math.log(10000) * torch.arange(half, device=t.device) / half)
args = t.float()[:, None] * freqs[None]
return torch.cat([torch.cos(args), torch.sin(args)], dim=1)
class DiTBlock(nn.Module):
"""adaLN-Zero DiT block: regresses gamma1, beta1, alpha1, gamma2, beta2, alpha2 from c"""
def __init__(self, d, heads, mlp_ratio=4.0):
super().__init__()
self.norm1 = nn.LayerNorm(d, elementwise_affine=False, eps=1e-6) # no own gamma/beta, since they come from the condition
self.attn = nn.MultiheadAttention(d, heads, batch_first=True)
self.norm2 = nn.LayerNorm(d, elementwise_affine=False, eps=1e-6)
# position-wise fully connected network. The width (4x) and activation are not given in the paper, so they are placed here as an example
self.ffn = nn.Sequential(nn.Linear(d, int(d * mlp_ratio)), nn.GELU(approximate="tanh"), nn.Linear(int(d * mlp_ratio), d))
self.ada = nn.Sequential(nn.SiLU(), nn.Linear(d, 6 * d))
nn.init.zeros_(self.ada[-1].weight) # Zero: alpha = 0, so the block starts as an identity map
nn.init.zeros_(self.ada[-1].bias)
def forward(self, x, c):
b1, g1, a1, b2, g2, a2 = self.ada(c).chunk(6, dim=1)
h = modulate(self.norm1(x), b1, g1)
x = x + a1.unsqueeze(1) * self.attn(h, h, h, need_weights=False)[0]
x = x + a2.unsqueeze(1) * self.ffn(modulate(self.norm2(x), b2, g2))
return x
class DiT(nn.Module):
def __init__(self, input_size=32, patch=2, in_ch=4, d=384, depth=12, heads=6, num_classes=1000):
super().__init__() # defaults are the size of DiT-S/2
self.p, self.c, self.n = patch, in_ch, input_size // patch
self.patchify = nn.Conv2d(in_ch, d, kernel_size=patch, stride=patch) # linearly embed p×p patches
self.register_buffer("pos", self.sincos_2d(d, self.n), persistent=False)
self.t_mlp = nn.Sequential(nn.Linear(256, d), nn.SiLU(), nn.Linear(d, d))
self.y_emb = nn.Embedding(num_classes + 1, d) # the last index is "unconditional" for classifier-free guidance
self.blocks = nn.ModuleList([DiTBlock(d, heads) for _ in range(depth)])
self.norm = nn.LayerNorm(d, elementwise_affine=False, eps=1e-6)
self.ada = nn.Sequential(nn.SiLU(), nn.Linear(d, 2 * d))
self.out = nn.Linear(d, patch * patch * 2 * in_ch) # each token -> p×p×2C (noise and covariance)
nn.init.zeros_(self.out.weight) # initialize the last linear layer to 0
nn.init.zeros_(self.out.bias)
@staticmethod
def sincos_2d(d, n):
"""2D sinusoidal position embedding, as in ViT (half for height, half for width)"""
def one_d(dim, pos):
omega = 1.0 / 10000 ** (torch.arange(dim // 2, dtype=torch.float64) / (dim / 2))
out = pos.reshape(-1, 1).double() * omega[None]
return torch.cat([torch.sin(out), torch.cos(out)], dim=1)
gy, gx = torch.meshgrid(torch.arange(n), torch.arange(n), indexing="ij")
return torch.cat([one_d(d // 2, gy), one_d(d // 2, gx)], dim=1).float()[None]
def forward(self, z_t, t, y):
x = self.patchify(z_t).flatten(2).transpose(1, 2) + self.pos # (B, T, d), T = (I/p)^2
c = self.t_mlp(timestep_embedding(t, 256)) + self.y_emb(y) # condition: sum of the embeddings of step t and class y
for blk in self.blocks:
x = blk(x, c)
shift, scale = self.ada(c).chunk(2, dim=1)
x = self.out(modulate(self.norm(x), shift, scale)) # the final layer normalization is also adaLN
B = x.size(0)
x = x.view(B, self.n, self.n, self.p, self.p, 2 * self.c) # restore the original spatial layout
x = x.permute(0, 5, 1, 3, 2, 4).reshape(B, 2 * self.c, self.n * self.p, self.n * self.p)
eps, sigma = x.chunk(2, dim=1) # first half: noise prediction, second half: covariance prediction
return eps, sigma
model = DiT()
z_t = torch.randn(2, 4, 32, 32) # latent of a 256×256 image (VAE shrinks height and width to 1/8)
eps, sigma = model(z_t, torch.randint(0, 1000, (2,)), torch.randint(0, 1000, (2,)))
FAQ
Q. How do DiT and Latent Diffusion differ?
A.
The space of diffusion (the autoencoder latent) and the training objective are the same; only the noise-predicting network differs. Latent Diffusion uses a convolutional U-Net with added cross-attention, while DiT splits the latent into patches and processes them with a Transformer built like ViT. The DiT paper uses the same VAE latent space as Stable Diffusion.
Q. What is adaLN-Zero?
A.
adaLN is a method that produces the scale γ and shift β of layer normalization with an MLP from the embedding of the conditions (step t and class y), rather than as learned parameters. adaLN-Zero additionally produces a scale α applied just before the residual addition, and initializes the part that outputs α to 0. At the start of training every block passes its input through unchanged, which stabilizes training, and in the paper it gave a better FID than the other ways of feeding in conditions.
Q. What does "XL/2" in a DiT name mean?
A.
"XL" is the model size configuration (S, B, L, XL); XL has 28 layers, a hidden dimension of 1152, and 16 heads. "/2" is the patch size p, meaning the latent is split into 2 × 2 patches. Splitting the latent of a 256 × 256 image (32 × 32 × 4) into 2 × 2 patches gives 256 tokens. The smaller the patch, the more tokens, and the higher both the computation and the image quality.