Diffusion transformers: patches, conditioning and residual gates
扩散 Transformer
Trace a tiny patch transformer and distinguish frozen-feature regression from full DiT training.
diffusion-transformersReplace the denoiser, not the diffusion process
A diffusion model needs a function that predicts something useful about a noisy state. That function need not be a U-Net. A transformer can read patches of the noisy latent, use the noise level and class as conditions, and return a spatial prediction.
Peebles and Xie’s DiT paper, first posted in December 2022, explores this architecture systematically; we read its March 2023 revision. DiT changes the denoising backbone. It does not make diffusion autoregressive or replace the diffusion objective with next-token prediction. Read latent diffusion, vision transformers and self-attention first.
A patch size is also a compute decision
For a noisy I×I latent with C channels, split the grid into nonoverlapping p×p patches and project each flattened patch to width d. Add position embeddings so that spatial arrangement remains available:
For I=32, p=8 gives 16 tokens, p=4 gives 64, and p=2 gives 256. Halving p quadruples N and multiplies the number of pairwise attention scores by sixteen. It does not necessarily multiply total model FLOPs by sixteen, because projections and feed-forward layers scale differently:
where h is the number of heads. Memory-efficient attention can avoid materializing the full score matrix, but the expression identifies the pairwise interaction count. The paper compares patch size together with depth and width; these are distinct scaling choices.
Give the same time and class information to every patch
The original design compares in-context conditioning, cross-attention, adaptive layer normalization and adaLN-Zero. In the last design, an embedding of time and class produces shift, scale and gate vectors. For one residual attention branch:
The vectors broadcast across tokens. A separate shift, scale and gate controls the feed-forward residual branch. The official implementation predicts six d-dimensional vectors in each block and uses ordinary per-token layer normalization without learned affine parameters inside that normalization.
For a single attention head:
Setting the residual gates to zero initializes a block as the identity. It does not mean that a complete model outputs its input: the final prediction head is a separate operation. The official model also initializes its final linear head to zero. A zero residual gate blocks the first backward signal to that branch’s internal weights, while the gate itself can receive a gradient; after it changes, the branch can start learning. Zero initialization therefore has a specific location and purpose, rather than meaning “set every transformer weight to zero.”
Put each predicted patch back in its spatial position
The paper’s decoder produces both noise and diagonal-covariance parameters, so each token emits p²·2C numbers before unpatchifying:
These are model outputs that must be interpreted by the chosen diffusion loss and sampler. A raw covariance parameter is not automatically a positive variance without that parameterization. In particular, the teaching program’s zero second channel is an untrained control channel, not a claim that the generative conditional variance should be zero.
DiT retains the noise-regression objective and, in the paper’s configuration, a learned-covariance variational term. For a noise-only readout experiment we can isolate:
where M counts all scalar target entries. This last equation describes the small frozen-feature experiment below, not the full DiT training objective.
Trace every tensor through a tiny block
Save as diffusion_transformers.py with Python 3.12 and NumPy 1.26.4. The program uses 4×4 one-channel synthetic latents, 2×2 patches, four tokens of width four, one attention head, a gated feed-forward branch and sinusoidal spatial positions. It implements the forward operations directly. The block weights stay fixed; only sixteen noise-readout weights are fitted. This makes the measured training result easy to check against an independent least-squares solution.
Thirty-two synthetic clean/noise pairs use seed 17 and retained signal power .4. The conditions distinguish two labels, but the synthetic clean distribution itself is the same for both labels; this is a conditioning-path test, not evidence of learned class semantics. The second output channel is held at zero to check pixel/channel packing. No learned covariance, image decoder, full sampling trajectory or image benchmark is implemented.
Patch packing matters: each pixel’s channels must be adjacent before the token is rearranged spatially. Concatenating an entire noise patch with an entire second-channel patch and then assuming interleaved channel order would silently scramble the output. The program’s decoder and tests explicitly verify both channels.
"""Original tiny patch transformer; frozen features and trained noise readout only."""
import json
import numpy as np
D=4
def patchify(images,size=2):
x=np.asarray(images,float)
if x.ndim!=4 or x.shape[1]!=x.shape[2] or type(size) is not int or size<1 or x.shape[1]%size or not np.all(np.isfinite(x)):raise ValueError('Finite B,H,H,C images and dividing patch size required.')
b,h,_,c=x.shape;n=h//size
return x.reshape(b,n,size,n,size,c).transpose(0,1,3,2,4,5).reshape(b,n*n,size*size*c)
def unpatchify(tokens,size=2,channels=1):
x=np.asarray(tokens,float)
if x.ndim!=3:raise ValueError('B,N,features required.')
b,n,f=x.shape;side=int(np.sqrt(n))
if side*side!=n or f!=size*size*channels:raise ValueError('Square token grid with matching features required.')
return x.reshape(b,side,side,size,size,channels).transpose(0,1,3,2,4,5).reshape(b,side*size,side*size,channels)
def norm(x):
centered=x-x.mean(axis=-1,keepdims=True)
return centered/np.sqrt(np.mean(centered**2,axis=-1,keepdims=True)+1e-6)
def softmax(x):
p=np.exp(x-x.max(axis=-1,keepdims=True));return p/p.sum(axis=-1,keepdims=True)
def weights(seed=9):
rng=np.random.default_rng(seed)
return dict(q=rng.normal(0,.3,(4,4)),k=rng.normal(0,.3,(4,4)),v=rng.normal(0,.3,(4,4)),out=rng.normal(0,.3,(4,4)),ff1=rng.normal(0,.3,(4,8)),ff2=rng.normal(0,.3,(8,4)),mod=rng.normal(0,.15,(4,24)))
def block(tokens,condition,p,zero_gates=False):
if tokens.shape[-1]!=4 or condition.shape!=(tokens.shape[0],4):raise ValueError('Four-dimensional matching conditions required.')
mod=(condition/(1+np.exp(-condition)))@p['mod'];shift,scale,gate,shift2,scale2,gate2=np.split(mod,6,axis=-1)
if zero_gates:gate=np.zeros_like(gate);gate2=np.zeros_like(gate2)
h=norm(tokens)*(1+scale[:,None,:])+shift[:,None,:]
q,k,v=h@p['q'],h@p['k'],h@p['v'];attention=softmax(q@k.transpose(0,2,1)/np.sqrt(D))
y=tokens+gate[:,None,:]*((attention@v)@p['out'])
h=norm(y)*(1+scale2[:,None,:])+shift2[:,None,:]
z=h@p['ff1'];gelu=.5*z*(1+np.tanh(np.sqrt(2/np.pi)*(z+.044715*z**3)))
return y+gate2[:,None,:]*(gelu@p['ff2']),attention
def features(images,time,labels,p):
tokens=patchify(images);b,n,_=tokens.shape
if n!=4:raise ValueError('Teaching model expects a4 by4 latent grid.')
positions=np.array([[0,0],[0,1],[1,0],[1,1]])
pos=np.column_stack([np.sin(positions[:,0]),np.cos(positions[:,0]),np.sin(positions[:,1]),np.cos(positions[:,1])])
c=np.column_stack([np.full(b,np.sin(time)),np.full(b,np.cos(time)),labels,np.ones(b)])
return norm(block(tokens+pos,c,p)[0])
def readout_objective(theta,h,target):
theta=np.asarray(theta,float)
if theta.shape!=(4,4) or not np.all(np.isfinite(theta)):raise ValueError('Finite4 by4 readout required.')
x=h.reshape(-1,4);y=target.reshape(-1,4);error=x@theta-y
return float(.5*np.mean(error**2)),x.T@error/error.size
def experiment():
rng=np.random.default_rng(17);clean=rng.normal(size=(32,4,4,1));noise=rng.normal(size=clean.shape);noisy=np.sqrt(.4)*clean+np.sqrt(.6)*noise
h=features(noisy,.7,np.arange(32)%2,weights());target=patchify(noise);theta=np.zeros((4,4));losses=[readout_objective(theta,h,target)[0]]
for i in range(600):
theta-=.3*readout_objective(theta,h,target)[1]
if (i+1)%100==0:losses.append(readout_objective(theta,h,target)[0])
return theta,h,target,losses
def decode_heads(h,theta):
noise=h@theta
# Pack each pixel with its two channels before restoring the spatial grid.
packed=np.stack([noise,np.zeros_like(noise)],axis=-1).reshape(*noise.shape[:2],8)
return unpatchify(packed,channels=2)
def demo():
theta,h,target,losses=experiment();tokens=patchify(np.arange(16.).reshape(1,4,4,1));c=np.array([[.2,.5,1,1]])
zero,_=block(tokens,c,weights(),True);one,a=block(tokens,c,weights());two,_=block(tokens,c+np.array([[0,0,1,0]]),weights())
configs={str(p):dict(tokens=(32//p)**2,attention_pairs=(32//p)**4) for p in [8,4,2]}
return dict(readout_half_mse=losses,identity_gate_error=float(np.max(abs(zero-tokens))),conditioning_effect=float(np.max(abs(one-two))),attention_rows=a.sum(axis=-1).tolist(),output_shape=list(decode_heads(h,theta).shape),patch_cost=configs,scope='Single-head frozen synthetic block; only16 noise-readout weights trained. Variance-head outputs zero placeholders, not learned variances or an image-generation claim.')
if __name__=='__main__':print(json.dumps(demo(),indent=2))
Six hundred readout updates at rate .3 reduce half-MSE from .4924145863 to .3175367178. The predictions match independent least squares, yet residual error remains because the fixed features cannot represent every target. All sixteen readout gradients are checked by finite differences.
Zero gates give exact block identity. With the fixed nonzero gates, changing the class coordinate changes the example output by a maximum .0272828292; this checks that a path exists, not that it represents a meaningful class. Attention rows sum to one. The two-channel output shape is 32×4×4×2. At latent side 32, patch sizes 8, 4 and 2 give 256, 4,096 and 65,536 pairwise scores per head respectively.
Architecture, initialization and training are separate claims
A patch transformer is not automatically a well-trained generator. Positional encoding, conditioning, optimization, data, objective and sampler still matter. The original DiT design space does not establish that all later diffusion transformers use its class conditioning, covariance head or normalization.
The fixed author code also contains an implementation-specific CFG convention: for reproducibility it guides only three output channels by default, with an alternative for all input channels commented nearby. That is a detail of that implementation, not the mathematical definition of CFG or a universal DiT requirement. We reference the noncommercial upstream code without copying or executing it.
Our single-head, frozen-feature regression cannot substantiate the paper’s scaling results, FID scores or image-generation capability. The paper’s patch-size/FLOP comparisons require its stated model sizes, datasets and evaluation conditions; a larger token count alone is not a guarantee of quality.
Follow the dimensions and the gradients
- Size. A 32×32 latent uses p=4. How many tokens are there, and what changes at p=2? Answer: 64 becomes 256. Pairwise scores per head rise from 4,096 to 65,536; total FLOPs also include terms linear in token count.
- Initialization. Do zero residual gates make the complete denoiser an identity map? Answer: They make those blocks identities. Patch projection, positions and the final prediction head still remain; a separately zeroed output head initially predicts zero.
- Hand calculation. For p=2 and C=4, how many values must each token emit for a two-head spatial output? Answer: p²·2C=4·8=32. Preserve the declared per-pixel channel order when unpatchifying.
- Evidence. The frozen-feature readout reaches its least-squares optimum. Does that prove a DiT image model was trained? Answer: No. Only sixteen output weights were fitted on synthetic data. The transformer, covariance prediction and image generation were not trained or evaluated.
Compare the design space with the exact code version
Read Section 3.2 for patchification, conditioning variants and the output head, then compare the block, initialization and CFG implementation. We used the official v2 HTML after bounded PDF retrieval failed. Selected architecture and code sections were inspected; the full experimental programme and third-party attention dependency were not audited or reproduced.
Make a prediction, then check
Halving patch size changes token count by what factor?
Learning objectives
- Track patch and output shapes.
- Compare token and attention costs.
- Explain adaLN-zero gates.
- Verify a sixteen-weight readout.
Prerequisites & connections
Explore related knowledge →References
- Scalable Diffusion Models with Transformers (v2 HTML)
William Peebles; Saining Xie · 2023 - dit-models method reference at ed81ce2
facebookresearch/DiT contributors · 2023
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author checked DiT v2 selected preliminaries/section3.2 and fixed author models.py. Six paired equations and four explained exercises; original frozen single-head block and16 trained readout weights, all gradients, independent least-squares prediction, zero gates, patch/token complexity and interleaved channels. The second output channel is a zero control, not a learned variance.
- Single AI author checked DiT v2 selected preliminaries/section3.2 and fixed author models.py. Six paired equations and four explained exercises; original frozen single-head block and16 trained readout weights, all gradients, independent least-squares prediction, zero gates, patch/token complexity and interleaved channels. The second output channel is a zero control, not a learned variance.
- Four computed SVG variants per topic. Eleven numeric/geometry tests and36 responsive cases passed; twelve final Chinese-mobile/English-desktop screenshots actually inspected. Mobile-title and cost-axis corrections preserved. Full article acceptance recorded separately.
Source locations checked:
- Scalable Diffusion Models with Transformers (v2 HTML) · Read selected preliminaries and Section3.2 patchify, conditioning, adaLN-Zero and2C output. First2022-12-19; v2 dated2023-03-02. Bounded PDF failed; HTML used. No scaling benchmark reproduction.
- dit-models method reference at ed81ce2 · Read 101-143,204-217,250-268: adaLN-zero block, output projection, zero initialization and3-channel CFG convention. CC BY-NC4.0 title/opening only, not full audit. Fixed public commit; reference only, no copied/executed code.
Related topics