Act IV · Generation and Perception
Part 22 of 31Images, Video and 3D
How do a transformer and a denoiser, built for sequences and points, make pictures, video and 3D scenes?
The part opens with a word drawn letter by letter by a diffusion transformer trained on one CPU core, on 20 x 20 capital letters from 24 system fonts. A picture is cut into patches and read as a sequence: a small ViT learns the grid from its position vectors, and is set against a CNN of about the same size on 3, 7 and 20 training fonts to measure what a convolution's built-in locality is worth. Generation moves into a smaller space: eight autoencoders show the reconstruction-generation dilemma, and REPA borrows a frozen encoder's eyes. The denoiser becomes a transformer told what to draw through adaLN-Zero gates that start at zero, and Stable Diffusion 3's resolution shift is derived from equal uncertainty about a flat picture and checked at 20, 40 and 80 pixels. The part turns from noise to tokens: raster order, MaskGIT's cosine schedule and VAR's coarse-to-fine scales, then one transformer that names, draws and edits. Video is the same in time: a bouncing letter drawn as a whole clip, by teacher forcing and by diffusion forcing, rolled out to four times the training length. It ends in 3D, with NeRF's volume-rendering integral and its quadrature, and with Gaussian splatting's projected covariance.
What you need. Linear algebra (covariances, Jacobians) and a first-order ODE; convolutions from Part 10, the transformer of Part 13 and Part 21's flow matching and guidance.
- Mathematics and history
- ViT, latent spaces, DiT, SD3, next-scale prediction, unified models, video autoencoders, diffusion forcing, NeRF, Gaussian splatting
- Models, data
- SD3/Flux, video models
What you will be able to do
Undergraduate
- Count a vision transformer's tokens for a given picture and patch size, and say how attention's cost grows when the patch halves.
- Explain what an inductive bias is and why a convolutional network may need fewer examples than a vision transformer.
Master's
- Write out an adaLN-Zero block and show that it is the identity when its gates are zero.
- Derive the resolution shift from equal uncertainty about a flat picture, and the drop of 2 log alpha in log signal-to-noise ratio.
- Derive the volume-rendering integral and its alpha-compositing quadrature.
Research
- Derive the projected covariance of a 3D Gaussian by linearizing the projection, and say when the linearization fails.
- Compare how representation alignment, representation autoencoders and unified models share one network between understanding and generation, and state what is still open.
Engineering
- Choose a latent size knowing the reconstruction-generation dilemma, and budget a model by tokens and multiply-adds.
- Diagnose exposure bias in an autoregressive video rollout and name the training change that reduces it.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 10 min · Master's 38 min · Research 47 min · Engineering 22 min.
- 0Letters from noiseUndergraduate2 min
- 1An image is a sequenceUndergraduate2 min
- 2Convolutions or attention?Undergraduate2 min
- 3A smaller spaceMaster's3 min
- 4Borrowed eyesResearch2 min
- 5U-Net or transformerEngineering2 min
- 6adaLN-ZeroMaster's3 min
- 7Words into picturesUndergraduate2 min
- 8Stable Diffusion 3 and FluxEngineering4 min
- 9Pictures as tokensMaster's3 min
- 10Coarse to fineMaster's2 min
- 11One model for words and picturesResearch3 min
- 12Squeezing timeEngineering3 min
- 13Frames that agreeMaster's2 min
- 14Rolling forwardEngineering2 min
- 15Light through a volumeMaster's3 min
- 16Gaussian splattingResearch3 min
- Recap, problems, and what comes nextAll tracks2 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
Letters from noiseUndergraduate2 min
Every letter here was drawn from pure noise by a small transformer we trained on this computer, asked for that letter. It sees each picture as a sequence of patches, the way a language model sees words, and it was trained by the flow matching of Part 21. The same recipe, a hundred thousand times larger, draws photographs, films, and whole scenes you can walk through.
How we got here. In 2012 a convolutional network, AlexNet, won the ImageNet contest by a wide margin, and Part 10 told that story. In 2014 came GANs, a generator trained against a judge, Part 20's story. In 2020 a plain transformer read images as sequences of patches. In 2021 DALL-E drew pictures from text, as tokens, and diffusion beat GANs on quality. 2022 brought DALL-E 2 and Imagen, and Stable Diffusion with open weights. By 2024 flow-matching transformers drew pictures, and Sora drew video. In 2025 video came with sound, one model could both read and draw, and video could be generated as fast as it plays. And in 2026, open models make sound and picture together.
This is Part 22 of AI, Built: images, video and 3D. First, how a transformer reads a picture, and when convolutions still win. Then the compressed spaces models draw in, and how borrowing a vision model's eyes speeds up training. The denoiser itself, and how the request gets in. Text to image, from DALL-E to Flux. Pictures written as tokens, and one model for words and pictures. Video. And 3D. Every model in this part is trained here, on letters, clips and a small scene, and we'll watch each one learn.
1An image is a sequenceUndergraduate2 min
A transformer reads sequences of tokens. So cut the picture into squares, called patches, and line them up. Each patch becomes a token: its pixels times a learned matrix, plus a learned vector that says where it was. From there it's Part 13's machinery, unchanged: attention and MLPs, layer after layer. The 2020 paper that did this, by Alexey Dosovitskiy and colleagues at Google, said it in its title: an image is worth sixteen by sixteen words.
We trained a small one, with thousand weights, to name the letter in each picture, on font files, and tested it on held-out font files. Here it is learning. By step it's right on percent of the held-out images, and at the end on percent. Meanwhile, watch the position vector of the centre patch, which starts at zero:
What do its attention weights show? The transformer adds one extra token, the summary token, which has no picture in it. Layer by layer it gathers from every patch, and its final vector alone names the letter. Here is where the summary token looks in the last layer, for four letters from a held-out font file: percent of its attention to patches falls on those with ink in them, which are percent of the picture. And here are the mean attention-weighted patch distances.
All twenty-five position vectors at the end of training: each tile shows how similar one patch's vector is to every other's. Neighbours average , patches far apart .
2Convolutions or attention?Undergraduate2 min
From 2012, convolutional networks ruled vision: AlexNet, then VGG and ResNet, Part 10's story. Attention crept in as an add-on. Then the 2020 vision transformer dropped convolutions altogether. Trained on ImageNet's million images alone, it fell a few points short of ResNets. Pretrained on three hundred million, it reached eighty-eight point five five percent. Their summary: large-scale training trumps inductive bias. Within months, DeiT trained one on ImageNet alone, with heavy augmentation and distillation, to eighty-three percent; Swin brought back local windows and a hierarchy. In 2022 ConvNeXt answered for convolutions, matching Swin. Later large vision encoders, including DINOv2, also used vision transformers.
What did the transformer change? An inductive bias is structure built in before data arrives. A convolution uses a local kernel with the same weights across positions. Translation equivariance depends on shifts compatible with the strides and boundary choices. Global attention lets any patch connect to any other through content-dependent weights. Patching and position encodings still build choices into the transformer. Structure suited to a task can reduce the examples needed. How the architectures compare also depends on the dataset and training recipe.
We can test that on our letters. Two models with about the same number of weights, the same training steps, batches and augmentations; one a vision transformer, one a convolutional network. They learn from font files, or , or all , and are tested on images from four held-out font files. Pause and predict: which wins with little data, and does that change with more?
Here are the results, three seeds each: every dot is one training run. The bands show the range of these three runs. They do not establish uncertainty across new font families or all choices of training recipe.
3A smaller spaceMaster's3 min
Real pictures have millions of pixels. Rombach and colleagues' latent diffusion work separates spatial compression from generative modeling. An autoencoder compresses a picture and rebuilds it, aiming to preserve perceptually important structure rather than guaranteeing invisible loss. A diffusion model learns the distribution of latent codes, which still carry appearance as well as content. Our toy instead uses flow matching with a deterministic autoencoder trained by pixel cross-entropy and a latent magnitude penalty; it has no KL or perceptual loss. Stable Diffusion's KL-f8 shrinks each spatial side eight times and keeps four latent channels: forty-eight times fewer scalar values, with a small KL penalty. This scalar count is not a compressed-file bitrate.
How small can the space be? We trained eight autoencoders, one seed each, on our letters. Each squeezes a picture to a grid of cells with some channels each, from 16 numbers to 100. Here is each one's pixel reconstruction RMSE on images from four held-out font files: from for by by to for by by .
Now run Part 21's flow matching inside each space, with the same hidden width, depth, steps and batch size, using two flow seeds. Input and output dimensions change the parameter count and random-number consumption. The distance uses our toy judge's features against its training images. The bars show only the range of two flow runs, not autoencoder uncertainty or human visual quality. Reconstruction and generative modeling can favor different representations.
Real models went both ways at once. Stable Diffusion 3 chose sixteen latent channels and reported that diffusion capacity must grow to model the larger representations. And in October 2024 Song Han's group squeezed much harder, thirty-two to a hundred and twenty-eight times on each side, with deep compression autoencoders. Their trick: fold each block of pixels into channels, which loses nothing, and let the network learn only what to change on top. At five hundred and twelve pixels on ImageNet, their UViT-H benchmark on an H100 reported nineteen point one times the inference speed with better FID than SD-VAE-f8. That is a specific benchmark, not a universal speedup. Balance spatial compression, reconstruction and generative modeling. The next chapter examines how representations can be shaped.
4Borrowed eyesResearch2 min
A diffusion transformer has to learn two things at once: what pictures are made of, and how to remove noise. But vision encoders trained on millions of images, like Part 24's DINOv2, already know the first. Probe a diffusion transformer's middle layers, and you find it does learn what pictures show, and slowly comes to resemble such an encoder, but it lags far behind. In October 2024 Sihyun Yu, Saining Xie and colleagues added one term to the loss. Take the denoiser's tokens after an early block, pass them through a small projector, and pull them toward the frozen encoder's tokens for the clean picture, by cosine similarity. They called it REPA, representation alignment. A large diffusion transformer reached the same quality seventeen and a half times sooner.
We tried it on our letters, with chapter 1's vision transformer as the frozen teacher: the same diffusion transformer, the same data, steps and seeds, with and without the extra term. The share of generated letters the judge reads as requested ends at percent with REPA and without.
The same idea then moved into the latent space itself. VA-VAE aligned an autoencoder's latents with a vision model's features, so the space is easy to rebuild from and easy to generate in. REPA-E trained the autoencoder and the denoiser together, with REPA keeping the space from collapsing. And in October 2025 representation autoencoders dropped the VAE altogether: keep DINOv2 frozen as the encoder, train only a decoder, and diffuse in the encoder's own features. The space a model generates in should already mean something.
5U-Net or transformerEngineering2 min
Who does the denoising? For the first diffusion models, a U-Net. Olaf Ronneberger and colleagues designed it in 2015 to outline cells in microscope pictures. Convolutions shrink the picture step by step, so each unit sees more of it; then the network grows it back, and skip connections carry the fine detail straight across the U, so it needn't survive the bottleneck. DDPM used one; in 2021 Prafulla Dhariwal and Alex Nichol enlarged it, with attention at low resolution and the noise level fed through every normalization, and diffusion beat GANs. Stable Diffusion's denoiser was a U-Net too.
In 2023 William Peebles and Saining Xie replaced the U-Net with a plain transformer, the diffusion transformer, DiT. The noisy picture is cut into patch tokens, as in chapter 1. Transformer blocks process them, and out comes the velocity, patch by patch. The noise level and the request come in through every block; how exactly is the next chapter. Its quality tracked its arithmetic: bigger models, or smaller patches, gave better pictures, and their largest set a record on ImageNet. It scales like a language model, and the image and video models since have nearly all been transformers.
So which is better? We trained a small U-Net and a small diffusion transformer with about the same number of weights, on the same letters, with the same steps, batches and seeds. The transformer's case was never that it wins small. It's that it keeps improving as it grows, with one simple recipe, the same as language models.
6adaLN-ZeroMaster's3 min
The denoiser must know the noise level and what it was asked to draw; call both together c. Peebles and Xie compared the ways in. In-context: append c to the sequence as extra tokens, and let attention find them. Adaptive layer norm: let c set the scale and shift of every normalization, so it reaches every token in every block. And adaLN-Zero: the same, plus a gate on each block's output, which starts at zero.
Here is adaLN-Zero exactly. The condition c sets a scale gamma and a shift beta for each normalization, and a gate alpha on each branch's output. All six come from one linear map of c, and that map starts at zero. So at the start every gate is closed, and every block passes its input straight through: a deep network that begins as the identity. Here are our model's gates during training: they start at zero and open, to an average size of 0.57 by the end, as the network finds a use for each block.
Here is ours learning: the same noise, asked for the same ten letters, A to J, drawn at checkpoints during its 8,000 steps, 4 times as many as the comparisons that follow. At step 0 every block is still the identity, so the noise passes straight through. At step 500 the judge reads 0 of the ten as the letters requested; at step 2,000, 7; at the end, 10. Meanwhile the loss falls from 1.86 to 0.17.
Does the way in matter? We trained all three, three seeds each, with the same data and steps; the adaLN versions carry extra weights for their scales, shifts and gates. In the paper, at four hundred thousand steps, adaLN-Zero's distance was nearly half that of in-context conditioning, at the same cost.
And here is our adaLN-Zero model, asked for each letter of the alphabet, with Part 21's guidance. Asked again from different noise, it draws the same letters in other styles: the request fixes what, the noise picks how.
7Words into picturesUndergraduate2 min
Until 2020, the sharpest generated pictures came from GANs, Part 20's BigGAN and StyleGAN. Text to image arrived from two directions. In January 2021 OpenAI's DALL-E treated it as language modelling: a twelve-billion-weight transformer wrote a caption's tokens, then a thirty-two by thirty-two grid of picture tokens. That May, Dhariwal and Nichol showed diffusion beating GANs on quality. In 2022 diffusion took over text to image: DALL-E 2 turned a caption into a CLIP picture embedding and decoded it by diffusion; Google's Imagen found that a bigger frozen language model, reading the prompt, helped more than a bigger denoiser; Parti kept the token route, at twenty billion weights; and Stable Diffusion put latent diffusion in everyone's hands, with open weights. In 2023 DALL-E 3 found the bottleneck was the data: it retrained on long, detailed captions written by a model, and followed prompts far better.
How does the prompt reach the denoiser? In Stable Diffusion, by cross-attention. A frozen text encoder turns the prompt into tokens. In every block, each picture token asks a question, its query, and the prompt's tokens supply the keys and values: so each patch pulls in the words that matter to it. It's Part 13's attention with queries from one sequence and keys from another. Notice the text is only read, never updated by the picture. The next chapter's model changes that.
And how hard should it listen? Part 21's classifier-free guidance pushes the denoiser away from its unconditional guess by a weight w; Stable Diffusion's default was seven and a half. We swept it on our letter transformer, using the letter as the prompt.
8Stable Diffusion 3 and FluxEngineering4 min
In March 2024 Patrick Esser, Robin Rombach and colleagues at Stability AI described Stable Diffusion 3: Part 21's rectified flow, with a new transformer, MM-DiT. It puts the prompt's tokens and the picture's patches into one sequence. Each kind keeps its own weights, since words and patches are different things; then a single attention runs over the joined sequence. So every patch can read every word, and, unlike cross-attention, the words are rewritten by the picture as it's drawn. Normalizing queries and keys kept training stable; three frozen text encoders read the prompt; the largest model had eight billion weights.
SD3 also changed how it samples training times. Uniform sampling gives equal time density. Our flow target is the data latent minus the noise; it need not vanish near either endpoint. A standard normal draw passed through a sigmoid gives logit-normal times, with more draws near the middle. This version had the best average non-dominated rank across SD3's twenty-four evaluation settings, rather than winning every metric. The paper reverses the time direction, but this symmetric density is unchanged. We compare both recipes in one fixed sixteen-number autoencoder, with three flow seeds each. FD uses our toy judge's training-image features. The line is arithmetic mean FD and the band is the three-run range. Neither measures human recognition or loss by training time.
One more thing changes with size. Use the same per-pixel noise level, with independent draws, for a small letter and a drawing of it with sixteen times the pixels. The big one looks clearer: average each four by four block, and the noise falls from to . Neighbouring pixels share their information, so a noise level that destroys a small picture leaves a large one legible. SD3's authors derived a simple scaling model. Write sigma for the share of noise. Take a flat-picture model: every pixel the same value c. Average the n pixels: the noise shrinks by the square root of n. So the uncertainty left about c is sigma over one minus sigma, over root n. Ask for the same uncertainty at m pixels and solve: the noise level shifts by a factor alpha, the square root of the ratio of pixel counts. In log signal-to-noise, it's a constant shift.
Does it hold for real pictures? We drew the same letter pictures at 20, 40 and 80 pixels a side, added noise, and measured the posterior probability assigned to the true picture, averaged over noisy draws. At 20 pixels this mean probability reaches one half at a noise level of ; at 40, at ; at 80, at . The formula predicts and . SD3's authors called the flat-picture assumption unrealistic, tested shifts with human raters, and settled on alpha equals three at a thousand and twenty-four pixels a side.
Several of SD3's authors went on to found Black Forest Labs. In August 2024 they released FLUX.1: twelve billion weights, MM-DiT blocks followed by single-stream blocks, rotary positions, and an open dev version trained with guidance distillation. In 2025 FLUX.1 Kontext edited pictures by joining the input picture's tokens to the sequence, and FLUX.2 grew to thirty-two billion, with a vision-language model reading the prompt and up to ten reference pictures. These FLUX models share a recipe: a latent space, rectified flow, one transformer over words and patches.
9Pictures as tokensMaster's3 min
Diffusion isn't the only way to draw. Language models write one token at a time; to do that with pictures, first turn a picture into tokens. Part 20's VQ-VAE and Part 23's codebooks do it: encode the picture into a small grid, and snap each cell to the nearest entry of a learned codebook. The entry's number is the token. In December 2020 Patrick Esser, Robin Rombach and Bjorn Ommer trained such a tokenizer with a perceptual loss and a GAN's judge, so a sixteen by sixteen grid of tokens rebuilt a sharp picture: VQGAN. Ours squeezes a letter into twenty-five tokens, each one of 128 codes, and rebuilds held-out letters with an error of 0.061.
Then write the tokens the way a language model writes words: left to right, top to bottom, each one predicted from the ones before. For us that's twenty-five passes through the network. It works: DALL-E and Parti did exactly this. But a thousand tokens take a thousand passes, and it's an odd order for a picture: the top rows are decided before anything below them exists.
In February 2022 Huiwen Chang and colleagues at Google trained a transformer like BERT instead: hide a random share of the tokens and predict them all at once, seeing every other token. MaskGIT. To draw, start fully masked. Predict every token; keep the ones it's surest of; mask the rest again, and repeat. A cosine schedule says how many to keep: few at first, then faster. Here is ours drawing four letters in eight passes. Each pass fixes tokens all over the picture at once, a few at first, then more. The paper drew ImageNet pictures in eight passes instead of two hundred and fifty-six, and better.
Here are the token models learning, three seeds each, including the one the next chapter is about. A uniform guess among 128 codes costs 4.85 nats a token; raster order ends at 0.86, MaskGIT at 2.62. The numbers mean different things: MaskGIT is graded only on the tokens it can't see, with all the others in view.
We trained both on the same tokens, with the same size of transformer and the same steps, three seeds each. The judge reads percent of raster order's letters as requested, and percent of MaskGIT's.
10Coarse to fineMaster's2 min
There's a more natural order for a picture: coarse to fine. In April 2024 Keyu Tian, Liwei Wang and colleagues at Peking University and ByteDance built a multiscale tokenizer. Ours uses five scales. The first scale is one token, for the whole picture's rough average; each next scale codes, on a finer grid, only what the coarser ones missed: a residual. Here is ours, on a held-out letter: the error falls from after one token to after all . In symbols: quantize what's left, averaged down to this scale; add it back, smoothed up.
Then train a transformer to predict each whole scale at once, from all the coarser ones: next-scale prediction, VAR. The attention mask is block-causal: every token sees its own scale and the coarser ones, never the finer. So a picture takes one pass per scale. Here is ours drawing four letters, in five passes: first a blur, then the shape, then the strokes.
All three, side by side: the same transformer size, steps and guidance, three seeds each.
On ImageNet, VAR's own raster-order baseline scored a distance of eighteen point six five; VAR scored one point seven three, beat the diffusion transformer, and drew about twenty times faster: ten scales, from one token up to sixteen by sixteen, six hundred and eighty tokens in ten passes, where raster order needs two hundred and fifty-six passes. Its loss fell as a power law in model size, like a language model's. It won the best paper award at NeurIPS 2024. Others dropped the codebook: MAR, from Kaiming He's group, makes continuous tokens, each drawn by a tiny diffusion model. And Infinity made each token a string of up to sixty-four bits, predicted by parallel binary classifiers: a vocabulary of up to two to the sixty-four. Tokens matter for another reason: they are how a language model can draw.
11One model for words and picturesResearch3 min
So far, one model reads pictures and another draws them. Can one network do both? Meta's Chameleon, in 2024, made pictures into tokens in the same vocabulary as words, and trained one next-token loss on everything. Transfusion, from Chunting Zhou and colleagues at Meta, kept the pictures continuous: one transformer with two losses, next-token prediction on the text and diffusion on the picture's patches. At seven billion weights, it scaled better than turning pictures into discrete tokens. DeepSeek's Janus found reading and drawing want different eyes, and gave it two encoders. And ByteDance's BAGEL gave the two jobs separate transformer experts sharing one attention, trained on trillions of mixed tokens; free-form editing emerged.
We built a Transfusion-inspired toy: one transformer, with separate drawing, naming and editing batches at every update. Draw: a font category and a letter, then a picture from noise. Name: a picture, then its letter and category as text. Categories follow filename rules: sans, serif or mono. Edit: a source picture, the word bold, then its matching bold target. Attention runs left to right, except inside a picture, whose patches all see each other. Text tokens get next-token cross-entropy; target picture patches get flow matching. Its blocks use chapter 6's adaLN-Zero. : it names percent of the reported held-out images. Our separate judge reads percent of drawings as the requested letter. The stored drawing guidance weight is . This recipe's editing flow is conditional without classifier-free guidance. These font-file tests do not establish generalization to new font families.
Here it is learning: four terms of one loss, all computed on every batch. The text terms are cross-entropies; the picture terms are flow matching's squared errors. The naming term falls to nats;
The stored editing split lists matched non-bold and bold font-file pairs: for training and held-out source pairs. Pair names alone do not verify whether source or bold target files also appeared in drawing and naming training. We therefore make no unseen-target-style or new-font-family claim. The rows show source pictures, conditional edit outputs, and bold targets. These are example edits; the reported metrics aggregate seeds. The source picture is more context tokens in the sequence. File-level holdout alone does not guarantee pixel-level separation.
Editing has become a kind of generation. In 2022 InstructPix2Pix trained a denoiser on edit pairs that other models had made. In March 2025 OpenAI's GPT-4o began drawing pictures natively, and editing the ones it was shown. FLUX.1 Kontext edits just as our letters do, with the picture to change joined to the sequence; Qwen-Image and Google's Gemini 2.5 Flash Image also take the input picture as context, so a face, a style or a product carries through the edit. Next: the same trick in time.
12Squeezing timeEngineering3 min
Video is pictures in time. In February 2024 OpenAI's Sora showed what a diffusion transformer could do with it: minute-long clips, trained on videos and images alike. Meta's Movie Gen followed, with thirty billion weights. Then open weights: Tencent's HunyuanVideo and Alibaba's Wan. In 2025 Google's Veo 3 and OpenAI's Sora 2 generated the sound with the picture. The open models kept pace, small enough for one consumer GPU, and in January 2026 Lightricks released LTX-2, sound and picture in one open model. Many published video models use three key pieces: squeeze time, position tokens in three dimensions, and denoise.
First the squeeze. As with pictures, an autoencoder compresses the video, now in time as well as space, and a token is a little block of both. The first frame is encoded alone, then subsequent frames in groups of four. With a typical squeeze, five seconds of 720p at sixteen frames a second is about tokens.
The squeeze comes from a video autoencoder, whose convolutions run in time as well as space. The little stencil a convolution slides over a picture becomes a small cube, sliding through the frames too, and looking only backward. Our toy is a deterministic autoencoder trained on clips of a bouncing letter. It encodes the first frame alone, then waits for each group of four frames. Latent frame k uses frames only through four k. This is causality between blocks; frames inside a block are encoded together. A clip can be encoded incrementally, one completed block at a time, and a still picture is just a one-frame video, so a video model can train on images too. Images are plentiful and teach appearance; videos teach motion; most video models train on both. Here pixels become numbers, times fewer, with a rebuild error of ; a still picture alone comes back at . Grouped frames can lose recognizable letter shapes. Pixel RMSE is not a recognizability score.
A token now has three coordinates: which frame, which row, which column. Part 13's rotary positions extend naturally. Split each head's pairs of numbers three ways: some are turned by the frame number, some by the row, some by the column, each group with its own frequencies. Since each group is a rotation, position enters the score through their relative offset in time, height and width; the tokens' content still matters, exactly as in one dimension. What doesn't extend gracefully is the cost: tokens means billion pairs for attention, in every layer, at every denoising step. Double the length and the pairs roughly quadruple. That's why video models lean on every trick from Parts 15 and 16.
13Frames that agreeMaster's2 min
Here, 'right letter' means our toy judge predicts the intended letter with confidence above one half. Held-out font files can share styles, and the judge can still make confident errors. This score is not a calibrated measure of human legibility.
Now let's make video ourselves. The clips are a letter moving one pixel a frame and bouncing off the walls. As real video models do, we work in an autoencoder's latent space: each frame squeezed to a hundred numbers. A small transformer sees one token per frame, and each frame's noise level reaches it through adaLN-Zero, as in chapter 6. The task: given the first frame, from a font the model never saw, draw the next seven. The first model denoises the whole clip at once: every frame at the same noise level, every frame attending to every other. That's full-sequence diffusion, the way Sora works.
We trained three models of this size, three seeds each: the whole-clip model, and two that write frame by frame, which the next chapter needs. Here they are learning. Their losses aren't comparable with each other, since each is asked something different, but all three settle. Now, pause and predict. Take the whole-clip model, and draw a clip's frames either together, or each from a separate run of the same model. Which clips keep one letter, moving one way?
Here's the catch with one frame: it doesn't say which way the letter is moving. The model has to choose, and every frame has to make the same choice. In each pair, the top row is a clip drawn together. The bottom row takes each frame from a different sample of the same model, as if the frames had been drawn one by one, independently. And the clip's length is fixed when the model is trained.
14Rolling forwardEngineering2 min
To go on past a fixed length, write the video frame by frame, like text: each frame from the ones before, with causal attention. The obvious way to train it is teacher forcing: give the model clean earlier frames, and teach it to denoise the next one. In July 2024 Boyuan Chen, Vincent Sitzmann and colleagues proposed diffusion forcing: give every frame its own random noise level, so the model learns to work from any mix of clean and noisy context. At generation time it can then treat its own earlier frames as slightly noisy, never quite trusting them.
We trained a teacher-forcing model and a diffusion-forcing model, the same size as the clip model, on the same eight-frame clips, three seeds each. Now give each model two real frames, which fix the motion, and ask for 30 more: four times the length any of them trained on. Here are the frames physics says should come, and each model's rollout: teacher forcing, diffusion forcing taking its own frames as clean, diffusion forcing taking them as slightly noisy, and the clip model, extended six frames at a time from the last two.
Measured over sixty-four clips and three seeds: how far the letter is from where physics puts it, frame by frame, and whether the judge still reads the right letter.
The cure for exposure bias is to train on what the model will actually see. In December 2024 CausVid distilled a slow model, whose frames attend both ways, into a causal one that needs four denoising steps per generated chunk. In June 2025 Xun Huang and colleagues went further with Self Forcing: during training, the model rolls out a whole clip from its own frames, and the whole clip is scored at once against a teacher. It generates seventeen frames a second on one H100 GPU, with the first frame in under half a second: video as fast as it plays. Make the frames respond to a player's actions, and you have an interactive world model, like Google DeepMind's Genie 3: that's Part 29.
15Light through a volumeMaster's3 min
So far, pictures and videos. Now the world behind them. Here is a small scene, a gold letter A and a blue ball, photographed from twenty-four cameras in a circle. Can a network learn the scene itself, so it can show it from anywhere? In 2020 Ben Mildenhall, Pratul Srinivasan, Matthew Tancik and colleagues represented a scene as a function: at every point in space, a density, how much stuff is there, and a colour, the light it gives off, which may depend on the viewing direction. A small network computes it: a neural radiance field, NeRF. To render a pixel, follow the ray through it and add up the light along the way.
Here is the sum, derived. A ray leaves the camera, and T of t is the chance light from depth t gets back unblocked. Across a sliver dt, a fraction sigma dt is stopped. So T's rate of change is minus sigma times T, and T is the exponential of minus the density accumulated so far. The pixel's colour is the light given off at each depth, sigma times c, times its chance of arriving, added up along the ray. To compute it, cut the ray into segments where density and colour are constant: each segment's integral is exact, its transmittance times one minus e to the minus sigma delta, times its colour. Sum the segments: each contributes its opacity alpha, times its colour, times the chance of getting through everything in front. That's alpha compositing, the way graphics has layered transparent pictures since the 1980s.
Why not just add sigma times delta? Check it on a ball of uniform density, where the exact answer is known.
Now train one: an MLP of four layers, 15,300 weights, fed the point's coordinates through sines and cosines of rising frequency, so it can draw sharp edges. Each step renders 512 random rays with 48 samples each, and compares them with the photographs' pixels. Here is a view it never saw, at checkpoints. Its PSNR, the higher the better, climbs from 6.8 decibels to 36.0 by step 500, and ends at 39.7; across three seeds, between 39.7 and 40.0. The same weights give depth for free: the scene's shape, learned from flat photographs.
16Gaussian splattingResearch3 min
NeRF's catch is speed: every pixel needs dozens of network evaluations along its ray. In 2023 Bernhard Kerbl, George Drettakis and colleagues replaced the network with a cloud of 3D Gaussians, millions of small soft blobs. Each has a position, a shape, a covariance built from a rotation and three scales so it always stays a valid one, an opacity and a colour. To render, project every blob onto the screen as a flat ellipse, and blend them front to back. No rays to march: the paper rendered at thirty frames a second or more, at 1080p.
What ellipse does a 3D Gaussian make on the screen? Derive it. First rotate into the camera's frame. Then the perspective projection: divide by depth. That isn't linear, and a Gaussian pushed through a nonlinear map isn't Gaussian. So linearize: near the mean, the projection is approximately its Jacobian, J. A linear map of a Gaussian is Gaussian, with covariance J W Sigma W transpose J transpose. This is the 2001 EWA splatting of Matthias Zwicker and colleagues, the graphics idea at the heart of the method.
Is the linearization good locally? Sample two hundred thousand points from a Gaussian whose largest standard deviation is one tenth of its mean depth, and project each point exactly. Only fifteen hundred are shown. Compare the sample ellipse with the Jacobian prediction. For the curve, each size uses four newly sampled Gaussian orientations, two hundred thousand draws each. We plot the median relative covariance discrepancy: percent at one tenth, and percent at in this run. Untruncated Gaussian depth can approach zero, so projected second moments diverge. Rare draws can dominate a finite sample. This check establishes neither a population covariance error nor a power law.
We fitted Gaussians to the same twenty-four photographs, by gradient descent through the renderer, moving faded ones next to busy ones as we went. Here is the held-out view as they settle: PSNR from decibels to .
NeRF and splatting fit one scene at a time, from carefully calibrated photographs. Instant-NGP made the fitting take seconds. Then transformers learned to see 3D directly: DUSt3R turned two uncalibrated photographs into 3D points, and VGGT, the best paper at CVPR 2025, predicts cameras, depth and points from hundreds of views in one pass, in under a second. Generate those views, and you can generate worlds, the subject of Part 29.
Recap, problems, and what comes nextAll tracks2 min
Let's take stock. A picture is a sequence of patches, and a transformer reads it, learning even the grid it came from. Models draw in a compressed space, and how small and how meaningful that space is shapes everything; borrowing a vision model's eyes speeds up learning to draw. The denoiser became a transformer, told what to draw through gated normalizations. Bigger pictures need their noise shifted, by a factor we derived and checked. Pictures can also be written as tokens, best coarse to fine, which lets one model read, draw and edit. Video is the same in time: frames drawn together agree, and frames drawn one by one can roll forward. And 3D is light added up along rays, or Gaussians splatted onto the screen.
All of this comes back. The image encoders, and the CLIP and SigLIP models that tie pictures to words, are Part 23, where every sense becomes a token. The self-supervised encoders whose eyes REPA borrows are Part 24. Diffusion over 3D structure returns in AlphaFold 3, Part 25. Video that responds to a player's actions is a world model, Part 29. And telling real pictures from generated ones is part of the last part, on trust.
Here are six problems, from counting a vision transformer's tokens to projecting a Gaussian. Pause here, and work through them; full solutions are in this part's notes.
Next time: every sense as a token. How text is cut into tokens, how sound becomes tokens too, how CLIP ties pictures to words, and how one transformer reads them all: Part 23.
Simon Prince's Understanding Deep Learning is a good next step for the image models, and Richard Szeliski's Computer Vision for the 3D. Thanks for watching, and see you in Part 23.
Where it goes next. The image encoders, and the CLIP and SigLIP models that tie pictures to words, are Part 23. The self-supervised encoders whose eyes REPA borrows are Part 24. Diffusion over 3D structure returns in AlphaFold 3 in Part 25, video that responds to a player's actions is a world model in Part 29, and telling real pictures from generated ones is part of Part 31.
Key results
The part's results in one place, for revision.
Try it
Lab 22 · Light through a volume, and a Gaussian on a screen
Render a ray through a uniform ball, whose colour is known exactly, by a Riemann sum and by NeRF's alpha-compositing sum; then project a 3D Gaussian through a pinhole camera and compare the covariance J W S W' J' (J from the series' autodiff) with the covariance of 200,000 exactly projected draws.
python -m videos.ai.labs 22
needs numpy, scipy, matplotlib · download lab22.py ·
source on GitHubriemann sum: mean |error| at N = 8, 32, 128 0.6735 0.1507 0.0363
nerf sum: mean |error| at N = 8, 32, 128 0.0098 0.0022 0.0006 (exact colour 0.9817)
Riemann sum, density 20, 4 segments colour 20.00: brighter than white
autodiff J against the formula largest difference 0.0e+00
covariance discrepancy at size/depth 0.02, 0.05, 0.1, 0.15 0.003 0.006 0.034 0.075
NeRF's sum is exact on every segment of constant density, so its only error is at the ball's edge; the splat's covariance is a linearization, right for small Gaussians and worse as they grow against their depth.
The code (116 lines; it asserts its own result)
"""Lab 22: add up light along a ray two ways, and project a 3D Gaussian onto a screen."""
import numpy as np
from videos.coursekit import labs
from explainer.ai.autodiff import Tensor
TITLE = "Light through a volume, and a Gaussian on a screen"
GOAL = ("Render a ray through a uniform ball, whose colour is known exactly, by a Riemann sum and by NeRF's "
"alpha-compositing sum; then project a 3D Gaussian through a pinhole camera and compare the covariance "
"J W S W' J' (J from the series' autodiff) with the covariance of 200,000 exactly projected draws.")
TASKS = [
"Raise the ball's density from 2 to 20. Which of the two sums still returns a colour between 0 and 1?",
"Put a second, blue ball behind the first and check that the weights T_i alpha_i split the pixel between them and the background.",
"Move the Gaussian off the optical axis (mu = (1, 0.5, 4)) and see which entries of J become non-zero and how the splat tilts.",
]
def render(t_edges, density, kind):
"""A white medium's colour along a ray sampled on segments [t_i, t_i+1], density read at each midpoint."""
delta = np.diff(t_edges)
sig = density(0.5 * (t_edges[:-1] + t_edges[1:]))
if kind == "nerf":
alpha = 1 - np.exp(-sig * delta)
T = np.concatenate([[1.0], np.cumprod(1 - alpha)])
else: # the Riemann sum of T sigma c dt
alpha = sig * delta
T = np.exp(-np.concatenate([[0.0], np.cumsum(sig * delta)]))
w = T[:-1] * alpha
return w.sum(), w, T
def jacobian(t, f):
"""The 2 x 3 Jacobian of (u, v) = (f t_x / t_z, f t_y / t_z), one backward pass per row."""
rows = []
for axis in (0, 1):
tt = Tensor(t, requires_grad=True)
(tt[axis] * f / tt[2]).backward()
rows.append(tt.grad.copy())
return np.array(rows)
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. a ray through the centre of a ball of radius 1 and density 2, entering at t = 1 and leaving at t = 3
dens, near, far = 2.0, 0.0, 4.0
density = lambda t: dens * ((t > 1.0) & (t < 3.0))
exact = 1 - np.exp(-dens * 2.0)
Ns = [8, 16, 32, 64, 128, 256]
err = {"riemann": [], "nerf": []}
for N in Ns:
for kind in err:
e = []
for _ in range(200): # NeRF's stratified sampling: one random cut in each of N equal bins
cuts = near + (far - near) * (np.arange(N) + rng.random(N)) / N
edges = np.concatenate([[near], cuts, [far]])
C, w, T = render(edges, density, kind)
e.append(abs(C - exact))
if kind == "nerf":
assert abs(w.sum() - (1 - T[-1])) < 1e-12, "the weights sum to 1 - T_(N+1)"
err[kind].append(np.mean(e))
for kind in err:
lab.row(f"{kind} sum: mean |error| at N = 8, 32, 128", " ".join(f"{err[kind][i]:.4f}" for i in (0, 2, 4)) +
(f" (exact colour {exact:.4f})" if kind == "nerf" else ""))
assert all(a < b for a, b in zip(err["nerf"], err["riemann"])), "alpha compositing beats the Riemann sum"
assert err["nerf"][-1] < 0.25 * err["nerf"][2] and err["nerf"][-1] < 0.005, "and converges"
C, w, _ = render(np.linspace(near, far, 5), lambda t: 10 * density(t), "riemann")
lab.row("Riemann sum, density 20, 4 segments", f"colour {C:.2f}: brighter than white")
assert C > 1 and render(np.linspace(near, far, 5), lambda t: 10 * density(t), "nerf")[0] <= 1
# 2. a Gaussian with covariance R S S' R' seen by a camera at the origin looking along z
f, depth = 1.0, 4.0
c, sn = np.cos(np.radians(55)), np.sin(np.radians(55))
q = np.array([[c, 0, -sn], [0, 1, 0], [sn, 0, c]]) # the long axis leans 55 degrees into the depth
shape = np.array([1.0, 0.6, 0.3])
mu = np.array([0.4, -0.3, depth])
J = jacobian(mu, f)
J_formula = np.array([[f / mu[2], 0, -f * mu[0] / mu[2] ** 2], [0, f / mu[2], -f * mu[1] / mu[2] ** 2]])
assert np.abs(J - J_formula).max() < 1e-12, "autodiff's Jacobian is the derived one"
sizes = [0.02, 0.05, 0.1, 0.15]
disc, keep = [], None
for s in sizes:
Sigma = q @ np.diag((s * depth * shape) ** 2) @ q.T
pts = rng.multivariate_normal(mu, Sigma, 200_000)
uv = f * pts[:, :2] / pts[:, 2:3] # the exact projection of every draw
sample, lin = np.cov(uv.T), J @ Sigma @ J.T
disc.append(np.linalg.norm(sample - lin) / np.linalg.norm(sample))
if s == 0.1:
keep = (uv[:1500], lin)
lab.row("autodiff J against the formula", f"largest difference {np.abs(J - J_formula).max():.1e}")
lab.row("covariance discrepancy at size/depth " + ", ".join(str(s) for s in sizes), " ".join(f"{d:.3f}" for d in disc))
lab.note = ("NeRF's sum is exact on every segment of constant density, so its only error is at the ball's edge; "
"the splat's covariance is a linearization, right for small Gaussians and worse as they grow "
"against their depth.")
assert disc[0] < 0.02, "small Gaussians: the linearization matches the exact projection"
assert disc[-1] > 3 * disc[0] and disc[-1] > disc[1], "larger Gaussians: it drifts"
fig, ax = labs.figure(2, size=(11, 4.2))
ax[0].loglog(Ns, err["riemann"], "o-", color=labs.RED, label="Riemann sum of T sigma c dt")
ax[0].loglog(Ns, err["nerf"], "o-", color=labs.GREEN, label="NeRF: sum of T_i alpha_i c_i")
ax[0].set(title="A ray through a uniform ball: error of the colour", xlabel="samples along the ray", ylabel="mean |error|")
ax[0].legend()
uv, lin = keep
centre = f * mu[:2] / mu[2]
ax[1].scatter(uv[:, 0], uv[:, 1], s=3, color=labs.BLUE, alpha=0.35, label="exactly projected draws")
vals, vecs = np.linalg.eigh(lin)
ang = np.linspace(0, 2 * np.pi, 200)
for k, ls in ((1, "-"), (2, "--")):
ell = centre[:, None] + vecs @ (k * np.sqrt(vals)[:, None] * np.array([np.cos(ang), np.sin(ang)]))
ax[1].plot(ell[0], ell[1], color=labs.GOLD, ls=ls, label=f"J W S W' J': {k} sd")
ax[1].set(title="A Gaussian of size/depth 0.1 on the screen", xlabel="u", ylabel="v", aspect="equal")
ax[1].legend(loc="upper right")
lab.fig = fig
return lab
Now change it
- Raise the ball's density from 2 to 20. Which of the two sums still returns a colour between 0 and 1?
- Put a second, blue ball behind the first and check that the weights T_i alpha_i split the pixel between them and the background.
- Move the Gaussian off the optical axis (mu = (1, 0.5, 4)) and see which entries of J become non-zero and how the splat tilts.
Problems, with solutions
Try each problem before opening its solution.
-
A ViT cuts a 224 × 224 picture into p × p patches. How many tokens for p = 16 and p = 8? By what factors do attention's and the MLPs' costs grow when p halves?
Solution
(224/16)² = 196 patch tokens (197 with the summary token); (224/8)² = 784. Halving p multiplies the number of tokens N by 4. Attention's score and mixing cost grows like N² d: 16 times. The MLPs and the projections cost about N d² per layer: 4 times. The patch embedding touches each pixel once either way, so its cost doesn't change.
-
In an adaLN-Zero block with every gate α = 0, show the block is the identity and the gradients of its attention weights vanish, but the gradient of the gate's map W can be nonzero.
Solution
The block computes h + α₁ ⊙ Attn(·) and then adds α₂ ⊙ MLP(·); with α = W c + b = 0 both branches vanish and the output is h. Any parameter θ inside a branch reaches the loss only through α ⊙ F(θ), so ∂L/∂θ = α ⊙ (∂L/∂out) ∂F/∂θ = 0 (this includes the branch's scale and shift γ, β). But ∂L/∂α = (∂L/∂out) ⊙ F(·), which is generally non-zero, and ∂L/∂W = (∂L/∂α) cᵀ can be nonzero. With nonzero upstream gradients and condition c, the gate can learn first; after it opens, the branches can learn. A zero loss gradient or zero condition is a counterexample to an unconditional claim that W's gradient must be nonzero. This statement is about the block; a zero-initialized downstream output layer can also block its upstream gradients on the first step.
-
Derive the resolution shift σ_m = ασ_n / (1 + (α − 1)σ_n) from equal uncertainty about a flat picture, show it lowers the log signal-to-noise ratio by 2 log α, and evaluate it for σ_n = 0.5, α = 3.
Solution
For a flat picture, every pixel z_i = (1 − σ) c + σ ε_i; averaging n pixels gives z̄ = (1 − σ) c + σ ε̄ with ε̄ ~ N(0, 1/n), so ĉ = z̄ / (1 − σ) has standard deviation σ / ((1 − σ)√n). Setting it equal at m and n pixels: σ_m / (1 − σ_m) = α σ_n / (1 − σ_n) with α = √(m/n); solving, σ_m = α σ_n / (1 + (α − 1) σ_n). With SNR = (1 − σ)²/σ², log SNR_m = 2 log((1 − σ_m)/σ_m) = 2 log((1 − σ_n)/(α σ_n)) = log SNR_n − 2 log α. For σ_n = 0.5, α = 3: σ_m = 1.5 / 2 = 0.75.
-
MaskGIT draws 256 tokens in T = 8 passes, leaving ⌊256 cos(π k / 2T)⌋ masked after pass k. How many are fixed in each pass? Compare a linear schedule.
Solution
Still masked after passes 0 … 8: 256, 251, 236, 212, 181, 142, 97, 49, 0; so the passes fix 5, 15, 24, 31, 39, 45, 48 and 49 tokens. A linear schedule fixes 32 every pass. The cosine schedule commits few tokens while the model knows least, and more once most of the picture is fixed.
-
For density σ and colour c constant on [t_i, t_i + δ], show ∫ T σ c dt = T_i (1 − e^{−σδ}) c, and that the weights T_i α_i sum to 1 − T_{N+1}.
Solution
On the segment T(t) = T_i e^{−σ(t − t_i)}, so ∫ T σ c dt = T_i c ∫₀^δ σ e^{−σs} ds = T_i c (1 − e^{−σδ}) = T_i α_i c. Since T_{i+1} = T_i (1 − α_i), T_i α_i = T_i − T_{i+1}, and the sum telescopes to T_1 − T_{N+1} = 1 − T_{N+1}: the weights sum to at most 1, and the rest is the background's share.
-
Compute the Jacobian of (u, v) = (f x / z, f y / z), and the projected covariance of an isotropic Gaussian s² I centred on the optical axis at depth z.
Solution
J = [[f/z, 0, −f x/z²], [0, f/z, −f y/z²]]. On the axis (x = y = 0), J = (f/z) [I₂ | 0], so Σ' = J (s² I) Jᵀ = (f s / z)² I₂: a circle whose radius shrinks like 1/z, as perspective requires.
Notes and sources
Glossary
| English | 中文 |
|---|---|
| vision transformer (ViT) | 视觉Transformer(ViT) |
| patch, patch embedding | 图块,图块嵌入 |
| summary token ([CLS]) | 汇总词元([CLS]) |
| learned position vector (position embedding) | 学到的位置向量(位置嵌入) |
| attention distance | 注意力距离 |
| inductive bias; locality; translation equivariance | 归纳偏置;局部性;平移等变 |
| latent space, latent diffusion | 潜空间,潜空间扩散 |
| perceptual and semantic compression | 感知压缩与语义压缩 |
| spatial compression factor (f8, f32), latent channels | 空间压缩倍数(f8,f32),潜变量通道 |
| deep compression autoencoder (DC-AE), space-to-channel | 深度压缩自编码器(DC-AE),空间到通道 |
| reconstruction–generation dilemma | 重建与生成的两难 |
| representation alignment (REPA), projector | 表示对齐(REPA),投影头 |
| representation autoencoder (RAE) | 表示自编码器(RAE) |
| U-Net, skip connection | U-Net,跳跃连接 |
| diffusion transformer (DiT) | 扩散Transformer(DiT) |
| adaptive layer norm (adaLN), adaLN-Zero, gate | 自适应层归一化(adaLN),adaLN-Zero,门控 |
| in-context conditioning | 上下文条件(作为额外词元) |
| cross-attention | 交叉注意力 |
| multiply-adds (MACs) per picture | 每张图片的乘加次数 |
| MM-DiT, joint attention, QK-norm | MM-DiT,联合注意力,QK归一化 |
| logit-normal timestep sampling | 对数几率正态(logit-normal)时间步采样 |
| resolution-dependent timestep shift (resolution shift) | 随分辨率的时间步平移(分辨率平移) |
| recaptioning | 重新标注(用模型写详细描述) |
| vector-quantized tokenizer, VQGAN | 向量量化分词器,VQGAN |
| raster order | 光栅顺序 |
| masked generative transformer (MaskGIT), cosine schedule | 掩码生成式Transformer(MaskGIT),余弦调度 |
| next-scale prediction (VAR), residual quantization, block-causal mask | 下一尺度预测(VAR),残差量化,块因果掩码 |
| bitwise tokens | 按位词元 |
| unified model, mixture of transformer experts (MoT) | 统一模型,Transformer专家混合(MoT) |
| in-context editing | 上下文编辑 |
| spacetime patches | 时空图块 |
| causal 3D autoencoder | 因果三维自编码器 |
| 3D rotary positions (3D RoPE) | 三维旋转位置编码(3D RoPE) |
| joint image–video training | 图像与视频联合训练 |
| full-sequence diffusion | 全序列扩散 |
| teacher forcing, diffusion forcing, self forcing | 教师强制,扩散强制,自我强制 |
| exposure bias, rollout | 暴露偏差,滚动生成(推演) |
| neural radiance field (NeRF) | 神经辐射场(NeRF) |
| volume rendering, transmittance, alpha compositing | 体渲染,透射率,阿尔法合成 |
| positional encoding (Fourier features) | 位置编码(傅里叶特征) |
| PSNR | 峰值信噪比(PSNR) |
| 3D Gaussian splatting, covariance projection, EWA splatting | 三维高斯泼溅,协方差投影,EWA泼溅 |
| Jacobian | 雅可比矩阵 |
| Fréchet distance (FD) on a judge's features | 评判网络特征上的弗雷歇距离(FD) |
Sources
Books: S. J. D. Prince, Understanding Deep Learning (2023), ch. 12 and 18; R. Szeliski, Computer Vision: Algorithms and Applications, 2nd ed. (2022); K. P. Murphy, Probabilistic Machine Learning: Advanced Topics (2023).
Papers and reports: Krizhevsky, Sutskever & Hinton, AlexNet (2012); Wang et al., Non-local Neural Networks (2018); Dosovitskiy et al., An Image Is Worth 16x16 Words (2020); Touvron et al., DeiT (2020); Liu et al., Swin (2021); Liu et al., ConvNeXt (2022); Dehghani et al., ViT-22B (2023); Oquab et al., DINOv2 (2023); Rombach et al., Latent Diffusion (2022); Chen et al., Deep Compression Autoencoder (2024); Xie et al., SANA (2024); Yu et al., REPA (2024); Yao, Yang & Wang, VA-VAE (2025); Leng et al., REPA-E (2025); Zheng, Ma, Tong & Xie, Diffusion Transformers with Representation Autoencoders (2025); Ronneberger, Fischer & Brox, U-Net (2015); Ho, Jain & Abbeel, DDPM (2020); Dhariwal & Nichol, Diffusion Models Beat GANs (2021); Peebles & Xie, DiT (2023); Ramesh et al., DALL·E (2021) and DALL·E 2 (2022); Nichol et al., GLIDE (2021); Saharia et al., Imagen (2022); Yu et al., Parti (2022); Betker et al., DALL·E 3 (2023); Ho & Salimans, Classifier-Free Guidance (2022); Esser et al., SD3 (2024); Black Forest Labs, FLUX.1 (2024), FLUX.1 Kontext (2025), FLUX.2 (2025); van den Oord et al., VQ-VAE (2017); Esser, Rombach & Ommer, VQGAN (2020); Chang et al., MaskGIT (2022); Tian et al., VAR (2024); Li et al., MAR (2024); Han et al., Infinity (2024); Chameleon Team (2024); Zhou et al., Transfusion (2024); Wu et al., Janus (2024); Deng et al., BAGEL (2025); Brooks, Holynski & Efros, InstructPix2Pix (2022); OpenAI, GPT-4o image generation system card addendum (2025); Qwen Team, Qwen-Image (2025); Google, Gemini 2.5 Flash Image (2025); OpenAI, Video generation models as world simulators (Sora, 2024); Meta, Movie Gen (2024); Kong et al., HunyuanVideo (2024) and HunyuanVideo 1.5 (2025); Wan Team, Wan (2025) and Wan 2.2 (2025); Lightricks, LTX-2 (2026); Yu et al., MAGVIT-v2 (2023); Su et al., RoFormer (2021); Chen et al., Diffusion Forcing (2024); Yin et al., CausVid (2024); Huang et al., Self Forcing (2025); Google DeepMind, Genie 3 (2025); Mildenhall et al., NeRF (2020); Tancik et al., Fourier Features (2020); Müller et al., Instant-NGP (2022); Porter & Duff, Compositing Digital Images (1984); Zwicker, Pfister, van Baar & Gross, EWA Splatting (2001); Kerbl, Kopanas, Leimkühler & Drettakis, 3D Gaussian Splatting (2023); Wang et al., DUSt3R (2024); Wang et al., VGGT (2025).
About this partfrom its README
Part 22 of a thirty-one-part series on how modern AI works and how it came to be (see the series plan and the syllabus), in Act IV, Generation and Perception. How the transformer of Part 13 and the diffusion and flow of Part 21 meet pictures, video and 3D scenes: from AlexNet to the vision transformer, from GANs to latent diffusion transformers, from DALL·E to Stable Diffusion 3 and FLUX.2, from Sora to real-time autoregressive video, and from NeRF to Gaussian splatting, with the 2025–26 frontier (representation autoencoders, unified models that read, draw and edit, open audio–video models). Part 21's samplers and theory are used, not repeated; Part 20's VAE, VQ-VAE and GANs and Part 24's self-supervised encoders are linked rather than retold.
Every model is trained here, on one CPU core, by compute.py: the pictures are Part 21's 20 × 20 capital letters from
24 system fonts (the last 4 held out); the videos are a 12 × 12 letter bouncing in a 20 × 20 box; the 3D scene is an
extruded gold letter A and a blue ball on a 64³ grid, photographed from 24 cameras. A judge (a small convolutional
classifier) reads generated letters. The original project text reported 96% on held-out font files; its historical
raw results remain unverified. "FD" is the Fréchet distance between Gaussians fitted to its 128 features for generated
and real letters (FID's formula on our own features). Each experiment states its step and batch budgets and seed
count; ranges show the observed replicate spread. Matched data order or initial weights are specific to the stated
comparison. Latent flows share hidden width and depth, while changing latent dimension changes their parameter
count and the random-generator stream used for later minibatches.
Chapter notes
- Letters from noise. A word drawn letter by letter by our diffusion transformer; how we got here, 2012–2026 (AlexNet, GANs, ViT, DALL·E, diffusion beating GANs, Stable Diffusion, SD3 and Sora, Veo 3 and BAGEL, LTX-2); the plan.
- 1. An image is a sequence. Patches as tokens, the summary token, learned positions (Dosovitskiy et al. 2020); a small ViT (155 thousand weights) trained on 20 fonts and replayed: held-out accuracy, what it calls eight unseen letters, and the centre patch's position vector at each checkpoint; where the summary token looks (share of its attention on inked patches); how far each head looks, against the distance between random patches; the 25 position vectors' similarities, neighbours against far patches.
- 2. Convolutions or attention? AlexNet to ViT (Krizhevsky et al. 2012; non-local networks 2018; ViT's 88.55% after JFT-300M and its deficit on ImageNet alone; DeiT 83.1% without external data; Swin; ConvNeXt 87.8%; ViT-22B, DINOv2); inductive bias defined (locality, translation equivariance); pause and predict; ViT against a CNN of about the same size (154,586 against 168,154 weights) (equal steps, batches, augmentations) on 3, 7 and 20 training fonts, three seeds, with their learning curves and their multiply-adds per picture.
- 3. A smaller space. Latent diffusion (Rombach et al. 2022), perceptual and semantic compression, KL-f8; eight convolutional autoencoders from 16 to 100 latent numbers on 1 × 1 to 10 × 10 grids: held-out rebuild error, equal numbers on coarse and fine grids, then flow matching in each space (two seeds): the reconstruction–generation dilemma; SD3's 16 channels; deep-compression autoencoders (Chen et al. 2024): space-to-channel shortcuts, f32–f128.
- 4. Borrowed eyes. REPA (Yu et al. 2024): the denoiser's early tokens aligned with a frozen encoder by cosine similarity; our DiT with and without REPA (chapter 1's ViT as the teacher), three seeds: right letters, FD and the alignment over training; VA-VAE (Yao et al. 2025), REPA-E (Leng et al. 2025), representation autoencoders (Zheng et al. 2025).
- 5. U-Net or transformer. The U-Net (Ronneberger et al. 2015), ADM (Dhariwal & Nichol 2021); DiT (Peebles & Xie 2023), quality tracking Gflops; our U-Net against our DiT at similar weights (370,281 against 320,848) and equal steps, three seeds, with the multiply-adds each spends.
- 6. adaLN-Zero. In-context tokens, adaLN and adaLN-Zero; the block written out, gates starting at zero; our gates opening during training; the training replay of the showcase model (adaLN-Zero trained 8,000 steps, four times the comparisons; same noise, ten requests, at checkpoints, read by the judge); the three conditionings at equal steps (their weights differ: the adaLN versions carry their scales, shifts and gates), three seeds; the alphabet.
- 7. Words into pictures. GANs to diffusion; DALL·E (12 billion weights, 256 text then 32 × 32 image tokens), diffusion beats GANs (FID 4.59 against 6.95), DALL·E 2, Imagen (a bigger text encoder helps more), Parti, Stable Diffusion, DALL·E 3 (recaptioning); cross-attention; classifier-free guidance swept on our DiT (right letters, variety).
- 8. Stable Diffusion 3 and Flux. MM-DiT (Esser et al. 2024): two streams, one joint attention; QK-norm; logit-normal t against uniform, three seeds; the resolution shift derived (σ' = ασ / (1 + (α − 1)σ), α = √(m/n)) and checked on letters drawn at 20, 40 and 80 pixels using the mean posterior probability of the true picture (not top-1 accuracy); α = 3 at 1024²; FLUX.1, FLUX.1 Kontext, FLUX.2.
- 9. Pictures as tokens. VQ-VAE and VQGAN (Esser et al. 2020); our tokenizer (25 tokens from 128 codes); raster order; MaskGIT (Chang et al. 2022) and its cosine schedule, our model drawing in 8 passes; the token models' training; raster against MaskGIT, three seeds.
- 10. Coarse to fine. VAR (Tian et al. 2024): residual tokens on five scales, the error after each; the block-causal mask; our VAR drawing in five passes; raster, MaskGIT and VAR side by side; VAR's FID 1.73, MAR (continuous tokens), Infinity (bitwise tokens, a vocabulary of up to 2⁶⁴).
- 11. One model for words and pictures. Chameleon, Transfusion, Janus, BAGEL; our tiny Transfusion (one transformer, next-token loss on text and flow matching on picture patches; causal attention except within a picture; adaLN-Zero blocks, each patch conditioned on its noise level and the prompt read so far; 8,000 steps) that names, draws and edits ("bold"), its four loss terms, and its edits on two font pairs it never saw; InstructPix2Pix, GPT-4o images, FLUX.1 Kontext, Qwen-Image, Gemini 2.5 Flash Image.
- 12. Squeezing time. Sora, Movie Gen, HunyuanVideo, Wan 2.1/2.2, Veo 3, Sora 2, HunyuanVideo 1.5, LTX-2; video tokens and their count; a causal video autoencoder trained here (the first frame alone, then four frames per latent frame; a still picture as a one-frame video); joint image–video training; 3D rotary positions; attention's cost.
- 13. Frames that agree. Video in a frame autoencoder's latents, one token per frame; three video models (whole clip, teacher forcing, diffusion forcing) trained and replayed, three seeds; pause and predict; from one given frame, frames drawn together against frames from separate samples: the letter kept, and the wobble of its path.
- 14. Rolling forward. Teacher forcing and diffusion forcing (Chen et al. 2024); rollouts from two given frames to 32 frames (4× the training length): distance from the physics and the letter kept, frame by frame, three seeds, including diffusion forcing with slightly noised context; exposure bias; CausVid, Self Forcing (17 frames a second on one H100), Genie 3 (Part 29).
- 15. Light through a volume. NeRF (Mildenhall et al. 2020); the volume-rendering integral derived, then its quadrature (alpha compositing); the Riemann sum against NeRF's sum on a uniform ball with a known answer; positional encoding; our NeRF trained on 24 photographs and replayed on a held-out view, PSNR, depth; three seeds.
- 16. Gaussian splatting. 3D Gaussian splatting (Kerbl et al. 2023): Σ = RSSᵀRᵀ; the projected covariance J W Σ Wᵀ Jᵀ derived (EWA, Zwicker et al. 2001) and compared with finite sample covariances from 200,000 exactly projected draws per sampled orientation (median over four orientations at each size), discrepancy against the Gaussian's size; 500 Gaussians fitted to the same photographs, replayed, against NeRF (PSNR, render time; three seeds); Instant-NGP, DUSt3R, VGGT. The untruncated Gaussian's depth can approach zero, so its exactly projected distribution has no finite covariance. These finite-sample discrepancies can be dominated by rare draws; they do not establish a population covariance error or a power law. The displayed cloud is one orientation at size/depth 0.1, with 1,500 of its 200,000 draws shown; its discrepancy need not equal the curve's four-orientation median. Each discrepancy is the relative Frobenius norm ‖Σsample − ΣJacobian‖F / ‖Σsample‖F.
- Outro. Eight pictures from the part's results, where the ideas come back (Parts 23, 24, 25, 29, 31), six problems, Part 23's teaser, references.
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- ViT.
- Latent spaces: KL-f8, deep-compression AEs, REPA and representation autoencoders.
- U-Net vs DiT (adaLN-Zero).
- SD3 MM-DiT; logit-normal t; the resolution shift derived; Flux.
- Autoregressive images: VQGAN, MaskGIT, VAR next-scale, Infinity.
- Unified models (Transfusion, Janus, BAGEL).
- Video: causal 3D VAE, 3D RoPE, joint image–video training, diffusion forcing, self-forcing, real-time autoregressive video.
- 3D: NeRF's volume-rendering integral derived; 3D Gaussian splatting (covariance projection).
中文讲义
本讲的中文部分(与英文版对应)。
习题(中文)
- ViT把224 × 224的图片切成p × p的图块。p = 16和p = 8时各有多少个词元?p减半时,注意力和MLP的计算量各增长多少倍?
- 在一个所有门控α = 0的adaLN-Zero块中,证明这个块是恒等映射,它的注意力权重的梯度为零,但门控映射W的梯度可以不为零。
- 由“对一张均匀图片的不确定性相同”推导分辨率偏移σ_m = ασ_n / (1 + (α − 1)σ_n),证明它把对数信噪比降低2 log α,并计算 σ_n = 0.5、α = 3时的值。
- MaskGIT用T = 8次前向传播生成256个词元,第k次之后还有⌊256 cos(πk/2T)⌋个被掩码。每一次固定多少个词元?与线性调度比较。
- 若密度σ和颜色c在[t_i, t_i + δ]上为常数,证明∫ T σ c dt = T_i (1 − e^{−σδ}) c,并证明权重T_i α_i之和等于1 − T_{N+1}。
- 求(u, v) = (f x / z, f y / z)的雅可比矩阵,以及中心在光轴上、深度为z的各向同性高斯s² I投影后的协方差。
解答
Solutions
- (224/16)² = 196个图块词元(加上汇总词元是197个);(224/8)² = 784个。p减半,词元数N变为4倍。注意力的打分和混合代价按 N² d增长:16倍。MLP和各个投影每层约为N d²:4倍。图块嵌入无论如何每个像素只碰一次,代价不变。
- 这个块先计算h + α₁ ⊙ Attn(·),再加上α₂ ⊙ MLP(·);α = W c + b = 0时两个分支都消失,输出就是h。分支内部的任何参数θ只通过 α ⊙ F(θ)影响损失,所以∂L/∂θ = α ⊙ (∂L/∂out) ∂F/∂θ = 0(分支的缩放γ和平移β也一样)。但∂L/∂α = (∂L/∂out) ⊙ F(·)一般 不为零,∂L/∂W = (∂L/∂α) cᵀ可以不为零。若上游梯度和条件c非零,门控可以先学习;门打开之后,分支才能学习。 若损失梯度或条件为零,W的梯度也可能为零。这里讨论的是单个块;下游输出层若初始化为零,第一步也会阻断上游梯度。
- 对一张均匀图片,每个像素z_i = (1 − σ) c + σ ε_i;对n个像素求平均得z̄ = (1 − σ) c + σ ε̄,ε̄ ~ N(0, 1/n),所以 ĉ = z̄ / (1 − σ)的标准差是σ / ((1 − σ)√n)。令m个和n个像素时两者相等:σ_m / (1 − σ_m) = α σ_n / (1 − σ_n),α = √(m/n); 解得σ_m = α σ_n / (1 + (α − 1) σ_n)。由SNR = (1 − σ)²/σ²,log SNR_m = 2 log((1 − σ_m)/σ_m) = 2 log((1 − σ_n)/(α σ_n)) = log SNR_n − 2 log α。σ_n = 0.5、α = 3时,σ_m = 1.5 / 2 = 0.75。
- 第0到第8次之后仍被掩码的个数:256, 251, 236, 212, 181, 142, 97, 49, 0;所以每次分别固定5, 15, 24, 31, 39, 45, 48, 49个词元。线性调度每次固定32个。余弦调度在模型知道得最少时只确定少数词元,等大部分图片已经确定后再加快。
- 在这一段上T(t) = T_i e^{−σ(t − t_i)},所以∫ T σ c dt = T_i c ∫₀^δ σ e^{−σs} ds = T_i c (1 − e^{−σδ}) = T_i α_i c。 由T_{i+1} = T_i (1 − α_i)得T_i α_i = T_i − T_{i+1},求和逐项相消,得T_1 − T_{N+1} = 1 − T_{N+1}:权重之和至多为1,其余是 背景的份额。
- J = [[f/z, 0, −f x/z²], [0, f/z, −f y/z²]]。在光轴上(x = y = 0),J = (f/z) [I₂ | 0],所以Σ' = J (s² I) Jᵀ = (f s / z)² I₂:一个圆,半径按1/z缩小,正如透视所要求的。
Build the film
python -m videos.ai.ai22.compute # the part's numbers, into .cache/ai22
python tools/build.py ai22 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py ai22 Hook # one chapter, silent, with a contact sheet
Scenes: videos/ai/ai22. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
From the repo root:
python tools/make.py ai22 # everything: the computations, then English and Chinese
python -m videos.ai.ai22.compute # the numbers only (about 11 hours of one core on a shared machine; resumable)
AI22_THREADS=2 python -m videos.ai.ai22.compute # torch threads (default 1; on a busy machine 1 is fastest)
AI22_QUICK=1 python -m videos.ai.ai22.compute # a smoke test of every code path with tiny budgets (.cache/ai22_quick)
AI22_UNI_SEEDS=1 python -m videos.ai.ai22.compute unified # one seed of `unified` (seeds can train in parallel)
python tools/build.py ai22 # English
python tools/build.py ai22 --lang zh # Chinese
Every random choice is seeded (numpy PCG64 and torch.manual_seed, one generator per run); there is no
multiprocessing. Items made of several trainings save each one as it finishes (CACHE.partial), so an interrupted
run resumes; items that need another item's model (the judge, the vision transformer, the showcase DiT, the tokenizers,
the frame autoencoder) load it from .cache/ai22/*.pt or compute it first. The longest items are denoisers (fifteen
trainings, the U-Nets the slowest), tokens, unified and clips (nine video models of width 192: a frame's 100 latent numbers must fit through the model's width, and at width 96 the letter was lost). showcase (8,000 steps) saves model, optimizer, schedule and generators every 500 steps and resumes exactly. Our NeRF gives the last sample on a ray its own segment length rather than NeRF's 10¹⁰: our backgrounds are empty, and the 10¹⁰ would paint them with whatever colour the network has at the far plane (held-out PSNR 13 dB with it, 40 dB without). The letters are drawn with Part 21's
glyph_images and its flow-matching mlp is borrowed; no other part's results are read.