A 256 by 256 photo is 196,608 numbers. A transformer that reads it as 2 by 2 pixel patches compares 268 million token pairs in every layer. Compress the photo to a 4 by 32 by 32 latent first, and it compares 65,536.
Pick a pipeline and watch the token count and the attention bill change. Then we build, piece by piece, the network that outputs a velocity image, its time input, the U-Net, the Diffusion Transformer and the compressed latent space they run in.
You need Lecture 3 of this series (a generative model follows a learned velocity field from noise to data), matrix multiply and a little Python. We build the rest from zero.
Lecture 4 of 5 in our follow-along of MIT 6.S184: Generative AI with Stochastic Differential Equations (Holderrieth and Shprints). Every idea is re-taught here in our own words and devices. Before: Lecture 3, Score Matching and Guidance. Next: Lecture 5, Discrete Diffusion.
The latent shape 4×32×32 for a 256×256 image and the 2×2 latent patches are the setup of DiT-XL/2 (Peebles and Xie, 2023). Attention pairs are tokens squared. The picture is an illustrative toy scene.
Chapter 0
Grow an image and watch a dense network's weight count explode
In Lectures 1 to 3 the velocity field moved dots on a flat plane. Each dot had 2 numbers, so a small dense network did the job. Now the dot is a photo. A 256 by 256 colour photo has 3 × 256 × 256 = 196,608 numbers.
A dense layer connects every input number to every output number. Our network must output one number per input number, so its first dense layer needs 196,608 squared weights: about 38.7 billion.
Warm is the number of pixel values. Blue bars are the weights of one layer. Drag the side length.
Exact counts. The convolution maps 3 colour channels to 64 feature channels with a 3×3 filter plus one bias per output channel: 3 × 3 × 3 × 64 + 64 = 1,792 weights. Memory assumes 4 bytes per weight.
The dense layer is hopeless twice. It does not fit in memory. It also ignores two facts about images: nearby pixels matter most, and a pattern looks the same anywhere. A convolution slides one small filter over the whole image, so its weight count does not grow with the image.
The lecture has two jobs. The first is architecture: shape a network whose input and output are both images, and feed it the time. The second is latent space: squeeze each image into far fewer numbers, run the whole flow there, and expand back to pixels once.
The symptom is an out-of-memory error before the first training step. Measure it by multiplying the weight count by 4 bytes: 155 GB for one dense layer at 256 pixels. The fix is weight sharing (Chapters 3 and 4) and compression (Chapters 5 to 7).
Chapter 1
Step a tiny image along its velocity and count the network calls
Before any architecture, fix the contract. The network takes three inputs: the noisy image x, a time t from 0 to 1, and an optional condition y, such as a class label or a prompt. It returns a velocity: one number per pixel that says which way that pixel moves, and how fast.
Why must the velocity have the image's shape? Because the sampler adds it to the image. Call the step size h, the time between two updates.
x at t plus h equals x-t plus h times u-theta-t of x-t given y.
Run the network on x-t. Multiply its velocity by h. Add the result to x-t pixel by pixel. That is x at t plus h.
With made-up numbers: a pixel at 0.200, velocity 0.8, h = 0.02. The new value is 0.200 + 0.02 × 0.8 = 0.216. With h = 0.02, one sample takes 50 such steps.
Each cell is a pixel. The pink tick is its velocity. Choose the number of steps and press Sample. Then try a network that outputs one number.
Illustrative toy. The velocity is the straight-line flow toward one fixed picture, target minus start, as in Lecture 2. A real network learns it from data.
Two facts make this harder than classification. A classifier reads a big image and outputs one label, so it can shrink as it goes. Our network must carry the full resolution to the output. And a classifier runs once; a sampler runs the network once per step.
The condition needs its own path in. A class label becomes a learned vector, one per class. A text prompt goes through a frozen, pretrained text encoder, which returns one vector per prompt token.
The symptom is a shape error at the add, or a model that outputs a smaller image. Measure it with one assert: the output shape equals the input shape. The fix is an architecture that maps an image to an image.
Chapter 2
Stack waves of many speeds and read the time off them
Near t = 0 the input is noise, and the network sketches the layout. Near t = 1 it fixes fine detail. So it must know t. But t is one number beside 196,608 pixel values, and a linear layer gives it only a small, nearly linear effect.
Borrow the trick from transformer position codes: map t to a vector of cosines and sines at many speeds. Call the length of that vector d, and call the speed of wave i its frequency wi, in cycles per unit of time.
TimeEmb of t equals root two over d, times the list of cos two pi w-i t for every i, then sine two pi w-i t for every i.
For each frequency w-i, turn t into an angle of 2 pi w-i t. Write down its cosine and its sine. Scale the whole list by root two over d.
Take d = 4, frequencies 1 and 4, and t = 0.25. The angles are π/2 and 2π. The list is [0, 1, 1, 0]. Times √(2/4) = 0.707 it is [0, 0.707, 0.707, 0], length 1.
Why length 1 for every t? Each speed adds cos² + sin² = 1 to the squared length. There are d/2 speeds, so the sum is d/2, and the scale 2/d brings it to 1.
Which speeds? Slow waves tell early from late. Fast waves tell 0.30 from 0.31. So the lecture spaces them as a ladder: each rung multiplies the last by the same ratio. Call the slowest wmin and the fastest wmax.
w-i equals w-min times w-max over w-min, to the power i minus one over d-halves minus one.
Start at w-min. Climb in d/2 rungs. Each rung multiplies by the same ratio, so the top rung lands on w-max.
d/2 = 4 rungs, w-min = 1, w-max = 8. The ratio per rung is 8 to the one third, which is 2. The rungs are 1, 2, 4 and 8.
Each row is one wave; slow rows at the bottom. The yellow line is your t, and the strip on the right is the vector the network gets.
Exact formula with w-min = 1. Similarity is the cosine of the angle between two embeddings: 1 means the same direction, 0 means unrelated.
The symptom is a model that ignores t: early and late steps get the same velocity. Measure the similarity of the embeddings of t = 0.1 and t = 0.9; near 1 means they look alike. The fix is a wider ladder (a larger w-max) or more speeds.
Chapter 3
Add levels to a U-Net and cut its skip wires to see what they carry
The first network that made image diffusion work was the U-Net, built in 2015 for medical image segmentation (Ronneberger et al.). Its input and output are both images, so it meets the contract by design.
It has three parts. The encoder halves the height and width at each level and adds channels. The lecture's example takes a 3 × 256 × 256 image to 512 × 32 × 32. The midcoder works at that smallest size, where each position sees a large part of the image. The decoder doubles the size back, level by level, to a 3 × 256 × 256 velocity.
Blue boxes are feature maps, each labelled channels × height × width. Dashed teal wires are skip connections. Add levels, then switch the skips off and look at the output.
Channel counts are illustrative; with 3 levels they match the lecture's example, which ends at 512 × 32 × 32. The output preview is an illustrative toy: without skips it rebuilds the edge pattern from the smallest level only.
Halving throws away exact edge positions. The decoder cannot invent them back. So each decoder level also gets a skip connection: a copy of the encoder's feature map at the same size. With skips the output is sharp; without them it blurs. The wires across the diagram give the U its name.
The time and the condition enter every level. Each goes through a small learned projection. The network adds the result to the feature maps, so every convolution knows the step.
| What the task needs | How the U-Net gives it |
|---|---|
| Image in, image out | Encoder and decoder mirror each other |
| Local detail, cheaply | Convolutions share one small filter |
| Layout and texture at once | Coarse levels for layout, skips for texture |
The symptom is soft, smeared samples with the right layout. Measure the error on edges alone, or compare a denoised test image with and without the skips. The fix is to keep a skip at every level.
Chapter 4
Cut a latent into patches and watch the token count and the attention bill move
A transformer reads a sequence of vectors. The Diffusion Transformer, or DiT (Peebles and Xie, 2023), turns an image into one. It cuts the image into square patches of side P and flattens each patch into a token. This step, patchify, comes from the Vision Transformer.
Call the input's channels C, its height H and its width W. Call the number of tokens N and the numbers in one token C′.
N equals H over P times W over P, and C-prime equals C times P squared.
Count the patches across, H over P, and down, W over P. Multiply to get N. Each patch holds P times P cells with C numbers each, so C-prime is C times P squared.
A 4 × 32 × 32 latent with P = 2: N = 16 × 16 = 256 tokens, C′ = 4 × 4 = 16 numbers each. With P = 4: 64 tokens of 64 numbers.
Left: the latent with its patch grid. Right: the tokens in a row, with the time and class vector feeding every block. Pick a patch size.
Shapes from the DiT paper: a 4 × 32 × 32 latent of a 256 × 256 image and patch sizes 2, 4 and 8. The latent picture is illustrative.
A linear layer maps each token to the model width. Then a stack of DiT blocks runs self-attention: every token compares itself with every other token, so the cost per layer grows as N squared. A text model adds cross-attention, where image tokens look up the prompt's vectors. At the end, depatchify maps each token back to C′ numbers and puts the patches back in place: the velocity image.
The time enters by adaptive layer norm (AdaLN). Add the time embedding and the class embedding to get one condition vector c. A small network turns c into a scale a and a shift b for each channel.
h-prime equals a of c times norm of h, plus b of c.
Normalise h. Stretch it by a and move it by b. Both a and b depend on the time and the class, so the same weights act differently at each step.
With made-up numbers: h = 2.0, token mean 1.0, standard deviation 0.5, so norm(h) = 2.0. With a = 1.5 and b = −0.2, h′ = 1.5 × 2.0 − 0.2 = 2.8.
The symptom is out-of-memory or slow training after you halve P. Measure N squared: halving P multiplies N by 4 and the attention pairs by 16. The fix is a larger patch or a smaller input, which Chapter 5 gives.
Chapter 5
Raise the resolution and the compression and watch two bills split apart
A 1024 by 1024 photo has 3,145,728 numbers. A video multiplies that by the frame count. The lecture names three problems with running a flow model on raw pixels.
And the costs multiply: the network output is as large as its input, and the sampler calls it once per step. The way out is a map from pixels to a smaller latent and back. Call the image channels C, the latent channels c, and the factor by which the latent's height and width are smaller f.
r equals C H W over c times H over f times W over f, which equals C f squared over c.
Count the numbers in the image and in the latent. Divide. H and W cancel, so r depends only on C, f and c.
Stable Diffusion: C = 3, f = 8, c = 4, so r = 3 × 64 / 4 = 48. A 3 × 256 × 256 image (196,608 numbers) becomes a 4 × 32 × 32 latent (4,096 numbers).
Warm bars are pixel space; teal bars are latent space. Each pair is one bill on a log scale. Drag the resolution and pick f.
Exact counts for 4 latent channels, 50 sampling steps and 2×2 patches. The latent diffusion paper (Rombach et al., 2022) tried f from 1 to 32 and found 4 to 8 the best trade.
Look at the last pair. Shrinking each side by f cuts the tokens by f squared. So attention pairs fall by f to the fourth: 4,096 times at f = 8. But f has a ceiling. A latent too small cannot hold the detail, and the decoder blurs it.
The symptom is a training run that fits one image per GPU. Measure the numbers per call times the steps. The fix is a smaller working space: compress first.
Chapter 6
Turn up the KL weight and watch a clumpy latent become easy to sample
An autoencoder is two networks. The encoder maps an image x to a small latent z. The decoder maps z back to an image x̂ (x-hat). Train both so that x̂ matches x: that is the reconstruction loss.
That alone is not enough for us. We will train a flow model on the latents, and the reconstruction loss says nothing about their shape. The latents can come out in far-apart clumps with empty space between. A sample from a simple distribution then lands in a hole, and the decoder returns garbage.
The variational autoencoder (VAE) fixes the shape. Its encoder outputs a mean μ and a spread σ for each latent number, and the encoder draws z from that bell curve. A second loss, the KL divergence, measures how far that bell curve is from the standard one, N(0, 1). Call its weight β.
L-VAE equals the squared length of x-hat minus x, plus beta times KL.
Encode x, draw z, decode to x-hat. Add the squared error to beta times the KL. A larger beta pulls the latents toward one round bell curve; a smaller beta keeps the images sharper.
With made-up numbers: error 0.05, KL 0.82, β = 0.1. The loss is 0.05 + 0.1 × 0.82 = 0.132.
Where does 0.82 come from? For one latent number with mean μ and spread σ, the KL to N(0, 1) has a closed form.
KL equals one half of mu squared plus sigma squared minus one minus log sigma squared.
Square the mean. Add the variance, subtract 1 and subtract the log of the variance. Halve it. Mean 0 and spread 1 give exactly 0.
μ = 1, σ = 0.5: ½(1 + 0.25 − 1 − ln 0.25) = ½(0.25 + 1.386) = 0.82. With μ = 0 and σ = 1 it is 0.
Teal clouds are the latents of three kinds of image. Dots are samples from N(0, 1): green ones land on data, red ones fall in a hole. Drag β.
Illustrative toy in two latent dimensions. The cluster centres and spreads are a made-up function of β, chosen to show the trade; a real VAE learns them.
To train through the random draw, write z = μ + σ · ε, with ε drawn from N(0, 1). The randomness now sits in ε, so gradients flow through μ and σ. This is the reparameterization trick. The latent diffusion paper uses only a slight KL penalty, so images stay sharp.
The symptom is a flow model that trains on latents but samples garbage. Measure the latents' mean and spread per channel. The fix is a KL term, or rescaling the latents to spread 1 before training.
Chapter 7
Step through training and sampling and count each time the model touches pixels
A latent diffusion model runs the whole flow inside the VAE's latent space (Rombach et al., 2022). The lecture gives the recipe in five steps.
The warm lane is pixel space; the teal lane is latent space. Press Step to move one stage, or Run to sample with 50 steps.
Shapes for a Stable Diffusion autoencoder (f = 8, 4 channels) on a 256 × 256 image: 3 × 256 × 256 in, 4 × 32 × 32 latent. 50 steps is an illustrative choice.
Work the bill for one sample. The flow model runs 50 times on 4,096 numbers: 204,800 numbers of network input. In pixel space it would be 50 × 196,608 = 9,830,400. The decoder runs once, after the last step.
The lecture's key sentence is "exact same recipe as before, just with a transformed dataset". Flow matching, score matching and guidance do not change. The flow model never sees a pixel. The lecture adds that virtually all AI-generated images and videos come from latent spaces.
| Stage | Space | Shape | Runs |
|---|---|---|---|
| Encoder | pixel to latent | 3×256×256 to 4×32×32 | once per training image |
| Flow model | latent | 4×32×32 in and out | once per step |
| Decoder | latent to pixel | 4×32×32 to 3×256×256 | once per sample |
The symptom is speckled samples. One cause is decoding a random draw instead of the decoder's mean. Measure it by decoding one latent twice and comparing; the outputs should match. The fix is to use the mean at decode time.
Chapter 8
Compress an image and a clip with the published autoencoders and count the tokens
Two large systems show every part of this series at once. Read each row against the lectures.
| Part | Stable Diffusion 3 (images) | Movie Gen Video |
|---|---|---|
| Objective | straight-path flow matching (Lecture 2) | flow matching (Lecture 2) |
| Autoencoder | 16 latent channels, f = 8 | temporal autoencoder, 8× in time, height and width, 16 channels |
| Backbone | MM-DiT on 2×2 latent patches | transformer on 1×2×2 latent patches |
| Text in | joint attention: text and image tokens in one sequence, separate weights | cross-attention in every block |
| Text encoders | CLIP-L/14, CLIP-G/14, T5-XXL | UL2, ByT5, Long-prompt MetaCLIP |
| Size | largest model 8B parameters | 30B parameters, up to 6,144 H100 GPUs |
The SD3 MM-DiT (multimodal DiT) is the one new part. It does not look up the text from the side. It joins the text tokens and the image tokens into one sequence for attention, and keeps separate weights for each kind. Guidance from Lecture 3 steers both systems.
The warm block is the input; the teal block is the latent, drawn to scale by volume. Pick a system.
Channels, factors and patch sizes are from the SD3 paper (Esser et al., 2024) and the Movie Gen paper (Meta, 2024); SD 1.x uses a 4-channel latent at f = 8 and a U-Net. The 128-frame 256×256 clip is an illustrative input size.
Work SD3 at 1024 by 1024. The latent is 16 × 128 × 128 = 262,144 numbers: 12 times fewer than 3,145,728. Its 2×2 patches give 64 × 64 = 4,096 tokens. What changes for video? One more axis. The temporal autoencoder squeezes it, and the patches span it.
The symptom is a video model that runs out of memory on a few seconds of footage. Measure the tokens: frames ÷ 8 × (side ÷ 16)² for Movie Gen's setup. The fix Movie Gen uses is compression along time as well as space.
Chapter 9
Choose an image, a patch size and a latent size, and see what each costs
Here are the two moves of the lecture on one 32 by 32 image. Patchify turns it into tokens for a DiT. Compression keeps a small code and rebuilds the image from it, the job of the VAE.
Left: the image and its patch grid. Middle: rebuilt from the code. Right: the error, brighter where it is worse. Shrink the code and watch which detail goes first.
The compressor is a linear stand-in for a VAE: it keeps the k × k slowest cosine waves of the image (a 2-D DCT) and drops the rest. A real VAE learns a nonlinear code and does far better.
Three things to try. Halve P and the tokens go up 4 times, so attention goes up 16 times. Shrink k on the blob: edges blur first and the layout survives, which is why a latent loses little. Now try the checker: fine detail needs a large code. A learned autoencoder exists to keep the detail people notice.
Every modern generator runs on this pattern. The image becomes a small latent, a DiT moves patch tokens of that latent along the flow, and one decode returns the picture.
Chapter 10
Keep the terms, the numbers, the checks and the core code in one place
The velocity field is now a real network. It is a U-Net or a DiT, it reads an embedded time and condition, and it runs in a VAE's latent space.
| Term | What it is | Number to remember |
|---|---|---|
| Interface | image, time and condition in; same-shape velocity out | 50 steps means 50 network calls |
| TimeEmb | cosines and sines of t on a frequency ladder | length exactly 1 |
| U-Net | convolutional encoder, midcoder, decoder, skips | 3×256×256 to 512×32×32 |
| DiT | patchify, transformer blocks with AdaLN, depatchify | 4×32×32 latent, P = 2: 256 tokens |
| Compression | r = C f² / c | Stable Diffusion 48×, SD3 12×, Movie Gen 96× |
| VAE | reconstruction plus β times KL to N(0, 1) | KL(μ = 1, σ = 0.5) = 0.82 |
| Latent diffusion | encode the data, train on latents, decode once | 204,800 versus 9,830,400 numbers per sample |
python import numpy as np def time_emb(t, d=32, w_min=1.0, w_max=16.0): # scalar -> (d,) unit vector i = np.arange(d // 2) w = w_min * (w_max / w_min) ** (i / (d // 2 - 1)) a = 2 * np.pi * w * t return np.concatenate([np.cos(a), np.sin(a)]) * np.sqrt(2 / d) def patchify(x, P): # (C,H,W) -> (N, C*P*P) C, H, W = x.shape g = x.reshape(C, H // P, P, W // P, P).transpose(1, 3, 0, 2, 4) return g.reshape((H // P) * (W // P), C * P * P) def adaln(h, a, b, eps=1e-6): # h: (N, width); a, b: (width,) n = (h - h.mean(-1, keepdims=True)) / (h.std(-1, keepdims=True) + eps) return a * n + b def sample(net, decoder, steps=50, shape=(4, 32, 32), y=None): z, h = np.random.randn(*shape), 1.0 / steps # start from noise in latent space for k in range(steps): z = z + h * net(z, time_emb(k * h), y) # Euler step, same shape in and out return decoder(z) # one decode: (4,32,32) -> (3,256,256) x = np.random.randn(4, 32, 32) print(patchify(x, 2).shape) # (256, 16) print(round(float(np.linalg.norm(time_emb(0.3))), 6)) # 1.0
Based on Lecture 4 of MIT 6.S184: Generative AI with Stochastic Differential Equations (Holderrieth and Shprints). Model facts come from the U-Net (Ronneberger et al., 2015), latent diffusion (Rombach et al., 2022), DiT (Peebles and Xie, 2023), SD3 (Esser et al., 2024) and Movie Gen (Meta, 2024) papers.
Now press Present or Teach. Explain from memory: the same-shape rule, TimeEmb, the U-Net's skips, patchify and AdaLN, the ratio C f² / c and the VAE's KL term. Then go back to the hero, press Latent, and say why the attention bill fell 4,096 times.