SANA makes a 4096 by 4096 image in 9.6 seconds on one A100 GPU. Flux-dev takes 1,023. The gain comes from a smaller latent, cheaper attention and a faster sampler.
Learn how a diffusion model turns noise into a picture and why that costs hundreds of network passes. Then see how a smaller latent and linear attention cut the bill.
Pick a build, then press Generate. Watch your build race Flux-dev while the points find their shape. Then we build, piece by piece, the noise, the denoiser, the sampler, guidance, the latent space and the efficient architecture.
You need a little Python and what a probability is. We build the rest from zero.
Based on Lecture 17 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Lecture 17 slides, on the course site. Every idea is re-taught here in our own words and devices. It follows Lecture 16, Vision Transformers and leads into Lecture 18, Diffusion Models II.
Latencies are the lecture's (slide 50, from the SANA paper), for 4096 by 4096 on an A100. Flux-dev takes 1,023 s and the SANA baseline 469 s. Each added piece brings it to 41, 24, 21 and 9.6 s. The race runs 100 times faster than real time. The cloud is a toy: 260 points denoised by an exact two-dimensional model, not an image.
Chapter 0
Tell a model that sorts pictures from a model that makes them, and see why making one costs so much
You type "a cyberpunk cat with a neon sign that says MIT". Seconds later you get four pictures no camera took. A model that sorts cat photos from dog photos cannot do this. It knows where the border between cats and dogs is. It does not know what a cat looks like.
A discriminative model learns the label given the input. A generative model learns the distribution of the data: which pictures are likely and which are not. Then it can draw a new sample from it.
| Discriminative | Generative | |
|---|---|---|
| Estimates | P(y | x), the label given the input | P(x | y), the data given the label |
| Learns | A decision boundary | Where the data lives |
| Examples | Logistic regression, SVMs | GANs, VAEs, diffusion models |
| Tasks | Text classification, detection | Image generation, inpainting |
Blue and purple are two classes of data. Pick a model. The generative one can press Sample and add new points that look like the data.
Toy data made for this page: eight Gaussian clusters on a ring, alternate clusters in two classes. The same data appears in every device below.
Making a sample is the expensive part. A classifier runs its network once per picture. The diffusion model in this lecture, DDPM, runs its network once per step, and the DDPM paper uses 1,000 steps. One picture costs 1,000 passes of a large network.
When it fails. The symptom is a generator that takes minutes per image. Measure it as passes per image times cost per pass. Fix either factor: the lecture cuts the cost per pass here, and Part II cuts the passes.
Chapter 1
Destroy a picture in a thousand small steps, and choose the step sizes so the end is pure noise
Drop ink into water. Each second the drop spreads a little. After an hour the glass is an even grey, and nothing tells you where the drop started. A diffusion model copies this, with pictures and Gaussian noise.
DDPM has two processes. The forward process is fixed: it adds a little noise at each of T steps, until the picture is noise. The reverse process uses a trained network: it removes the noise, step by step, and so makes a picture from noise.
Call the clean picture x0 and the picture after t steps xt. Call the amount of noise added at step t βt. Call one draw of standard Gaussian noise, mean 0 and variance 1 for each pixel, ε.
x-t equals the square root of one minus beta-t, times x-t-minus-one, plus the square root of beta-t, times epsilon.
Shrink the last picture x-t-minus-one a little. Add a little fresh noise epsilon, scaled by root beta-t. Repeat for every step.
With made-up numbers: a pixel x-t-minus-one = 1.0, beta-t = 0.02, epsilon = 0.5. Then x-t = 0.990 × 1.0 + 0.141 × 0.5 = 1.061. One step moves the pixel by 6 percent.
Why shrink before adding? The two variances, 1 − βt and βt, add to 1. So a picture with variance 1 keeps variance 1, and the numbers never blow up. The list of βt values is the noise schedule. It is fixed before training and sets how fast the picture dissolves.
Each line is one pixel value over 1,000 steps. It starts at the data, near −1.25 or +1.25. Drag the last β of the schedule and see whether the end is pure noise.
The schedule is linear from 0.0001 to the last β, over 1,000 steps. At 0.02 it is DDPM's schedule (Ho et al., 2020, section 4). The start values are toy data.
When it fails. If the last β is too small, xT still remembers the data. Sampling later starts from pure noise, a start the model never saw in training. Measure how much of x0 survives at T, as the read-out does. The fix is a schedule that ends near zero signal.
Chapter 2
Fold a thousand small noise steps into one formula, so training never has to loop
Training needs a noisy picture at a random step, say t = 731. Running 731 forward steps for every training example would waste time. Is there a shortcut?
There is. Two independent Gaussian noises add to one Gaussian noise, and their variances add. So the t small noises collapse into one draw of ε. Call αt = 1 − βt the share of signal kept at step t. Multiply all of them up to step t and call the product ᾱt, "alpha-bar".
x-t equals the square root of alpha-bar-t, times x-zero, plus the square root of one minus alpha-bar-t, times epsilon.
Shrink the clean picture x-zero by root alpha-bar-t. Add one draw of epsilon, scaled by root of one minus alpha-bar-t. That is x-t, with no loop.
On DDPM's schedule at t = 500, alpha-bar-t = 0.079. So root alpha-bar-t = 0.280 and the noise scale is 0.960. With made-up x-zero = 1.0 and epsilon = 0.5, x-500 = 0.280 + 0.480 = 0.760.
Halfway through, the noise is already 3.4 times larger than the signal. The lecture calls this formula the diffusion kernel. DDPM picks the schedule so that ᾱT ends near 0. Then xT is plain Gaussian noise.
The left panel is the data jumped to step t in one move. The right panel shows the signal share in blue and the noise share in grey. Drag t.
The curves come from DDPM's linear schedule, 0.0001 to 0.02 over 1,000 steps. Each point keeps one fixed noise draw, so you can follow it as t moves.
When it fails. A common bug uses αt for the step where ᾱt belongs. Then the noise at t = 1000 is 0.14 where it should be 1.00, and the model trains on pictures that are almost clean. Measure it: at t = T, the noisy pictures should have variance near 1 and no link to x0.
Chapter 3
Turn generation into a regression problem: show a noisy picture, ask for the noise inside it
To run the film backwards, we need to undo one noise step. When each βt is small, the step back is also close to a Gaussian. We know its spread: DDPM sets its variance to βt. Its center is unknown, and depends on the picture. A network learns it.
DDPM asks the network a simpler question: what noise is in this picture? If you know the noise, you know the center. Call the network εθ. It takes the noisy picture xt and the step t, and returns a guess of ε with the same shape as the picture.
L equals the squared length of epsilon minus epsilon-theta of x-t and t.
Subtract the network's guess epsilon-theta from the true noise epsilon. Square each entry and add them. That is L, and gradient descent makes it smaller.
With made-up numbers for a 2-pixel picture: epsilon = (0.5, −1.0), guess = (0.4, −0.7). L = 0.12 + 0.32 = 0.01 + 0.09 = 0.10.
The training loop has five lines. It is the same loop for every step t, so one network serves all 1,000 steps.
Left: one example. Blue is x0, the grey arrow is the true noise, warm is the guess. Right: the loss of every draw against t. Draw many and find where the loss stays high.
The guess is the exact best guess of the noise for this toy data, the answer a perfect network would learn. Real networks only approach it.
pythondef train_step(model, x0, abar, opt): # x0: (B, C, H, W), abar: (T,) t = torch.randint(0, len(abar), (x0.shape[0],)) eps = torch.randn_like(x0) a = abar[t].view(-1, 1, 1, 1) xt = a.sqrt() * x0 + (1 - a).sqrt() * eps # the jump, no loop loss = ((eps - model(xt, t)) ** 2).mean() # MSE on the noise opt.zero_grad(); loss.backward(); opt.step() return loss.item()
When it fails. The loss stalls above zero and you think training is broken. Measure the loss per step t, as the device does. Even the perfect guess keeps a loss at small and middle t. Near t = 0, a tiny noise looks like the cluster's own spread. In the middle, the guess cannot tell which cluster a point came from.
Chapter 4
Start from noise and remove a thin slice of predicted noise at every step, and count what that costs
To make a new picture, draw xT from pure noise. Then step back from t = T to t = 1. At each step the network guesses the noise in xt. We remove a thin slice of that guess, then add a little fresh noise z so the walk stays random.
x-t-minus-one equals one over root alpha-t, times the quantity x-t minus beta-t over root of one minus alpha-bar-t times epsilon-theta of x-t and t, plus sigma-t times z.
Ask the network for the noise in x-t. Remove a thin slice of it. Divide by root alpha-t to undo the shrink. Add a little fresh noise sigma-t z.
DDPM's schedule at t = 500: beta-t = 0.0100, alpha-t = 0.9900, alpha-bar-t = 0.079. With made-up x-t = 0.40, guess = 0.50 and z = −1: the slice is 0.0105 × 0.50 = 0.0052. Then (0.40 − 0.0052) / 0.9950 = 0.397, plus 0.100 × (−1), gives x-499 = 0.297.
Each step moves the picture a little, so DDPM needs all 1,000. Each step is one full pass of the network. The cost of one picture is the number of steps times the cost of one pass.
Grey dots start as noise. Pick the step count and press Sample. Points that land on a cluster turn green. Find the fewest steps that still work.
Fewer steps here means the same 1,000-step schedule taken in larger strides, with the update above. The guess is the exact toy denoiser. The 50 ms per pass is a made-up figure that turns passes into seconds.
When it fails. Cut the steps too far and every point lands on the average of the data: the center of the ring. In images this is a gray blur. Measure the share of samples that look like data, as the read-out does. The fix is a smarter sampler or a distilled model, which Part II covers.
pythondef sample(model, shape, beta): # beta: (T,) schedule alpha = 1 - beta; abar = torch.cumprod(alpha, 0) x = torch.randn(shape) # x_T: pure noise for t in reversed(range(len(beta))): # T network passes eps = model(x, t) x = (x - beta[t] / (1 - abar[t]).sqrt() * eps) / alpha[t].sqrt() if t > 0: x = x + beta[t].sqrt() * torch.randn_like(x) return x
Chapter 5
Tell the denoiser what to draw, push it harder toward that, and pay two passes per step
So far the model draws any picture. You want a corgi. A conditional model takes one more input, the condition c: a class label, a text prompt or a picture. The network becomes εθ(xt, t, c). Sampling is the same loop.
A conditional model often follows c too loosely. Classifier guidance (Dhariwal and Nichol, 2021) trains a separate classifier on noisy pictures and adds its gradient at each step, scaled by a guidance strength ω. It has two limits: it needs an extra network, and it works only for class labels.
Classifier-free guidance (Ho and Salimans, 2021) removes the classifier. Bayes' rule writes the classifier as the conditional model divided by the unconditional one. In log form, the guided model is (ω + 1) times the conditional log-probability minus ω times the unconditional one. In noise terms:
epsilon-tilde equals omega plus one, times epsilon-theta of x-t, t and c, minus omega times epsilon-theta of x-t and t.
Run the network twice: once with c, once without. Move the guess past the conditional one, away from the unconditional one, by omega.
With made-up numbers: conditional guess 0.6, unconditional 0.2, omega = 4. Epsilon-tilde = 5 × 0.6 − 4 × 0.2 = 2.2. Fifty steps now cost 100 passes.
One network does both jobs. In training, the condition is sometimes dropped, so the same weights learn both answers. The slide's note: combining the two passes doubles the FLOPs of every step.
The conditional model here is weak: asked for blue, it puts 40 percent of its mass on purple. Drag ω and count how many samples land in the asked class.
A toy: 240 samples, 50 steps, exact denoisers for a weak conditional model and the unconditional data. The "spread" is the mean distance to the cluster center, against the data's own.
When it fails. Large ω buys quality and costs diversity. On the lecture's slide, classifier guidance at ω = 10 scores FID 12.0 against 33.0 at ω = 1 (lower FID is better), but the samples look more alike. Measure both: a quality score and the spread of samples. Pick ω where the spread is still acceptable.
Chapter 6
Compress the picture once, run all the steps on the small code, and decode once at the end
A 1024 by 1024 color picture has over three million numbers. Every one of the 1,000 steps processes all of them. Most of those numbers describe fine texture that a decoder could fill in. Why denoise them a thousand times?
Latent diffusion (Rombach et al., CVPR 2022) uses a pre-trained autoencoder. Its encoder E compresses a picture to a small latent z. Its decoder D rebuilds the picture from z. The autoencoder trains first, on a reconstruction loss, and then stays frozen. The diffusion model works on z alone.
Call the picture's height and width H and W, and the factor by which the autoencoder shrinks each side f. The denoiser sees each latent cell as one token.
n equals H over f, times W over f.
Divide the height H and the width W by the factor f. Multiply the two results. That is n, the token count of every step.
The lecture's case: H = W = 512. With f = 8, n = 64 × 64 = 4,096 tokens. With f = 64, n = 8 × 8 = 64 tokens, 64 times fewer.
Pick a picture size and a compression factor. The pink grid is the latent, one cell per token. Watch the token count and the attention pairs.
Token counts follow the formula above, one token per latent cell, as on slide 39. "Attention pairs" is n squared, the size of one softmax attention table per layer per step. The f1 case is for scale; nobody runs a transformer on raw 4096 px pixels.
On slide 39 this pays off directly. At 512 px, diffusion on 4,096 SD-VAE tokens makes 17.5 images per second. Diffusion on 64 DC-AE tokens makes 335, 19 times more. ImageNet FID also improves, from 3.55 to 2.66.
When it fails. The decoder sets a ceiling: the model cannot generate detail the decoder cannot rebuild. Measure rFID, the FID of decoded pictures against the originals (lower is better), before you train any diffusion model. If rFID is poor, fix the autoencoder first. Chapter 7 does that.
Chapter 7
Make an autoencoder that shrinks each side 64 times and still rebuilds faces and text
Why not push f higher with the usual autoencoder? Slide 33 answers. The SD-VAE design gets rFID 0.90 at f8, 2.04 at f32 and 28.3 at f64. At f64 the faces melt and the eye-chart letters turn to scribbles. High-compression autoencoders are hard to optimize.
The Deep Compression Autoencoder (DC-AE, Chen et al., ICLR 2025) keeps rFID under 1 up to f128: 0.69 at f32, 0.81 at f64 and 0.96 at f128. Two ideas do it.
Residual autoencoding. Each downsample block gets a shortcut with no weights. Space-to-channel moves each 2 by 2 patch of pixels into 4 channels, so the size shrinks and no number is lost. Channel averaging then matches the block's output width. The learned layers only add a correction on top. The decoder mirrors this with channel-to-space.
Decoupled high-resolution adaptation. Training runs in three phases:
The y axis is rFID on a log scale; lower is better, and red marks a failed reconstruction. Pick an experiment, then slide the compression factor.
All values are labels on the lecture's charts (slides 34 and 37). At 256 px: without residual autoencoding 0.90, 2.04, 28.3; with it 0.51, 0.49, 0.50. At 1024 px: without decoupled adaptation 0.19, 0.24, 7.40; with it 0.18, 0.17, 0.20.
Phase 3 matters too. On slide 36, training without a GAN loss gives FID 3.82. Full training with a GAN loss gives 0.82, and the local refinement phase gives 0.69. DC-AE 1.5 then orders the latent channels: the first channels hold object structure, the later ones hold detail. Diffusion training converges 6 times faster. On slide 41, a 2B model reaches gFID 2.18 against 2.90 with 4 times the training throughput.
When it fails. Train a plain f64 autoencoder at 1024 px and rFID jumps to 7.40, with blurred faces and text. Measure rFID at the resolution you will use, not only at 256 px. The fix is the phase 2 adaptation, which brings it to 0.20.
Chapter 8
Reorder one matrix product so attention cost grows with the token count, not its square
A diffusion transformer (DiT) runs attention over all n tokens at every step. Softmax attention compares every token with every other token: an n by n table. Double the picture's side and n grows 4 times, the table 16 times.
SANA (Xie et al., ICLR 2025) replaces softmax attention with ReLU linear attention. Softmax scores a pair by exp(Q KT / √d). SANA scores it by ReLU(Q) ReLU(K)T, where ReLU sets negative entries to zero. Call the query, key and value matrices Q, K and V, each n rows of width d.
phi of Q times phi of K transpose, all times V, equals phi of Q times the product of phi of K transpose and V.
Both sides give the same n by d answer. The left side builds the n by n table first. The right side builds a d by d summary first, which is small when n is large.
A 4096 px picture through an f32 autoencoder gives n = 128 × 128 = 16,384 tokens. With a made-up width d = 64, the left side needs 2 × n2 × d = 34.4 billion multiply-adds. The right side needs 2 × n × d2 = 134 million, 256 times fewer.
You can group a chain of matrix products either way: (ab)c = a(bc). Softmax blocks this, because exp acts on each entry of the n by n table. ReLU acts on Q and K before the product, so the regrouping is legal. The cost drops from O(n2) to O(n).
The left boxes show the table each method builds. The bars show multiply-adds on a log scale. Drag n.
Counts are per attention head per layer per step, with d = 64 (illustrative). Real speedups are smaller than the count ratio because other layers and memory traffic also cost time.
SANA adds more efficiency choices. Its Mix-FFN puts a 3 by 3 convolution inside the feed-forward block. It drops the positional embedding, uses a small language model as the text encoder, and trains on captions written by several vision-language models. Slide 50 adds each piece to a baseline, at 4096 by 4096 on an A100:
| Build | Latency (s) | Step gain |
|---|---|---|
| Flux-dev, 12B | 1,023 | reference |
| SANA baseline | 469 | start |
| + Deep Compression AutoEncoder | 41 | 11.4× |
| + Linear DiT | 24 | 1.7× |
| + Kernel fusion | 21 | 1.1× |
| + Flow DPM-Solver, SANA 0.6B | 9.6 | 2.2× |
The total is 106 times faster than Flux-dev, at GenEval 0.64 against 0.67. At 1024 px, SANA-0.6B takes 0.9 s against Flux-dev's 23.0 s.
When it fails. Linear attention is weak at local detail, because the d by d summary blurs which token sat next to which. The fix is local mixing: Mix-FFN's 3 by 3 convolution here, and a temporal convolution in SANA-Video.
Chapter 9
Generate a minute of video chunk by chunk, with a cache that never grows
A video is a stack of frames, so its token count is the image count times the frames. SANA-Video makes long video as a chain of chunks. Inside a chunk, diffusion denoises the frames together. Between chunks, generation is autoregressive: each chunk takes the chunks before it as its condition.
Softmax attention over earlier chunks needs a KV cache: the keys and values of every past token, kept in memory. It grows with every chunk. Linear attention needs only the running d by d summary from Chapter 8. Each new chunk adds into it, so the cache has a fixed size.
Grey is block full attention, teal is block linear attention. The dashed line is 80 GB, where the chart marks out of memory. Drag the length.
Measured points are the lecture's chart labels (slide 55). Full attention needs 15, 26, 46 and 76 GB at 1, 10, 30 and 60 s, and runs out of memory at 65 s. Linear attention needs 7.2 GB at every length. Between points we draw a straight line.
SANA-Video adds a temporal convolution, because linear attention is weak at local motion. At 720p its linear attention is about 4 times faster than full attention. It scores 83.71 on text-to-video VBench and runs 16 times faster than SkyReels-V2 (36 s against 568 s).
The same tools carry on. SANA-WM, a controllable world model, makes 60 s of video on one H100. Its sampling steps show the step cost from Chapter 4:
| SANA-WM, 60 s on one H100 | Steps | Total time |
|---|---|---|
| Base model | 60 | 21.8 min |
| + step distillation | 4 | 48 s |
| + attention sink | 4 | 34 s |
That is 38 times faster overall. The denoiser alone gets 27 times faster from the cut in steps. LongLive makes interactive long video in real time. It keeps the first frames as an attention sink, re-caches keys and values when the prompt changes, and tunes on long streams. LongLive 2.0 runs in NVFP4, a 4-bit float format, at 45.7 frames per second with 2 sampling steps.
When it fails. The symptom is out of memory partway through a long video. Measure peak memory against length, as in the device. The fix is a constant-size state: linear attention, or a short window plus an attention sink.
Chapter 10
Keep the terms, the numbers, the code and the checklist in one place
A diffusion model learns to remove noise. The forward process adds it in T fixed steps, and one formula jumps to any step. A network learns to guess the noise. Sampling runs that network once per step, so the cost of one picture is steps times passes times the cost of a pass. The lecture cuts the cost of a pass: fewer tokens with DC-AE, cheaper tokens with linear attention, and a constant memory for long video.
| Term | Meaning |
|---|---|
| Forward process | Fixed: adds Gaussian noise over T steps. |
| Reverse process | Learned: removes noise one step at a time. |
| βt, noise schedule | The noise added at step t; DDPM uses 0.0001 to 0.02. |
| ᾱt | Product of (1 − β) up to t: the signal share squared. |
| Diffusion kernel | xt = √ᾱt x0 + √(1 − ᾱt) ε, one jump. |
| εθ | The network that guesses the noise in xt. |
| Classifier-free guidance | (ω + 1) conditional guess − ω unconditional; two passes per step. |
| Latent diffusion | Diffuse the autoencoder's latent z, decode once. |
| f, token count | Shrink per side; n = (H / f)(W / f). |
| rFID | FID of reconstructions against originals; lower is better. |
| Residual autoencoding | Weight-free space-to-channel shortcuts around each resize. |
| Linear attention | ReLU(Q)(ReLU(K)TV): cost O(n), not O(n2). |
| Quantity | Value |
|---|---|
| DDPM steps | T = 1,000 (Ho et al., 2020) |
| Classifier guidance FID | 33.0 at ω = 1, 12.0 at ω = 10 |
| Tokens at 512 px | 4,096 with f8, 64 with f64 |
| Throughput, 512 px | 17.5 images/s SD-VAE, 335 DC-AE (19×) |
| rFID at f64 | 28.3 SD-VAE, 0.81 DC-AE |
| SANA, 4096 px, A100 | 9.6 s against Flux-dev 1,023 s (106×) |
| SANA-Video memory | 7.2 GB at any length; full attention out of memory at 65 s |
| SANA-WM, 60 s | 21.8 min at 60 steps, 34 s at 4 steps with a sink |
| LongLive 2.0 | 45.7 FPS, 1.84× inference speedup in NVFP4 |
pythonimport torch T = 1000 beta = torch.linspace(1e-4, 0.02, T) # DDPM schedule alpha = 1 - beta; abar = torch.cumprod(alpha, 0) def guided_latent_sample(model, decoder, c, w, shape): # shape: latent (B, C, H/f, W/f) z = torch.randn(shape) for t in reversed(range(T)): e_c = model(z, t, c) # pass 1: with the condition e_u = model(z, t, None) # pass 2: condition dropped e = (w + 1) * e_c - w * e_u # classifier-free guidance z = (z - beta[t] / (1 - abar[t]).sqrt() * e) / alpha[t].sqrt() if t > 0: z = z + beta[t].sqrt() * torch.randn_like(z) return decoder(z) # one decode at the end def relu_linear_attention(q, k, v): # (n, d) each q, k = q.relu(), k.relu() kv = k.T @ v # (d, d): made first norm = q @ k.sum(0, keepdim=True).T + 1e-6 # (n, 1) return (q @ kv) / norm # O(n d^2), never n by n
This lesson follows Lecture 17 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Read the lecture on the course site, which links the slides. The lecture cites DDPM (Ho et al., NeurIPS 2020), Dhariwal and Nichol (NeurIPS 2021) and Ho and Salimans (2021). It also cites latent diffusion (Rombach et al., CVPR 2022), DC-AE (Chen et al., ICLR 2025), SANA (Xie et al., ICLR 2025), SANA-Video, SANA-WM and LongLive. All explanations, devices and worked examples are our own, except where we say a number is the slide's.
Now press Teach and explain, from memory, why one diffusion picture costs a thousand network passes, and two ways to make each pass cheaper. Then go back to the race at the top and add SANA's pieces one at a time.