Vision Transformers

A vision transformer cuts a picture into tokens and lets every token look at every other. At 2,048 pixels that costs about 4.5 times more than a version that looks locally.

Learn how a picture becomes tokens, why big pictures make attention expensive, four ways to cut the cost, and how the same ideas make image generation fast.

Pick a way to attend, then drag the image size. Watch what each one costs in multiply-adds. Then we build, piece by piece, the patches, the windows, the re-ordered maths, the pruning, and the fast generators.

You need a little matrix multiplication (rows times columns, shapes that must match) and a little Python for the code. We build the rest from zero.

Based on Lecture 16 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Lecture slides (PDF). Every idea is re-taught here in our own words and devices. It follows Lecture 15, long-context LLMs.

Price one image

224 px

Illustrative cost model of a 12-layer ViT-Base (hidden size 768, patch 16, 12 heads of 64), counting multiply-adds. Window uses 7 by 7 token windows, as on the lecture slide. Sparse keeps 25% of windows, the share the SparseViT slide shows. Real speed also depends on memory and hardware.

Chapter 0

A Picture Is a Pile of Tokens, and Every Pair Costs Money

See why an image model spends most of its budget on one step, and what the lecture does about it

A car's camera must label every pixel: road, car, person, sign. A child at the kerb may fill only a few dozen pixels. The model must see the whole street and the small detail at once, and do it fast.

A token is one piece of input that the model treats as one item. A vision model cuts the picture into square tiles, and each tile becomes a token, held as a short list of numbers called a vector. A transformer improves those vectors layer by layer. Its key step is attention: each token scores every token for how useful it is, then mixes in the useful ones.

So n tokens make an n by n table of scores. The cost grows with the square of the token count, which we call quadratic. Twice the tokens means four times the scores.

Count the scores

The dots are tokens in a ring. Each line is one score a token computes. Switch between looking at everyone and looking at near neighbours, then add tokens.

12

Toy ring, made up for this lesson. A token counts itself, so full attention gives n times n scores, and the local rule gives 5 times n.

With 12 tokens, everyone-to-everyone gives 144 scores and the local rule gives 60. At 24 tokens the first is 576, four times more. The second is 120, only twice more. The whole lecture lives in the gap between those two numbers.

Pictures make n large. A 224 pixel image cut into 16 pixel tiles gives 14 × 14 = 196 tokens. A 2,048 pixel image gives 128 × 128 = 16,384 tokens. That is 84 times the tokens and about 7,000 times the scores.

The lecture has two halves. The first half reads images and cuts the attention bill three ways. Window attention scores only nearby pairs. Linear attention reorders the maths so the table never exists. Sparse attention skips the empty parts. The second half makes images with autoregressive generation, one token at a time, then cuts the number of steps.

  1. Patches become tokens: the basic vision transformer, with its shapes.
  2. Why high resolution hurts: dense prediction, the quadratic bill and Segment Anything.
  3. Window attention: look locally, then shift the windows.
  4. Linear attention: change the order of the maths.
  5. EfficientViT: repair the weak spots and measure the speedups.
  6. Sparse attention: drop the windows that do not matter.
  7. Generation one token at a time: autoregression and the codebook.
  8. Parallel decoding: draw several tokens per step.
  9. Next-scale prediction: coarse first, then fine.
  10. Hybrid tokens: HART mixes discrete and residual tokens.
  11. The field guide: numbers, code and where to go next.
A model reads 100 tokens, and then reads 400 tokens with full attention. How many times larger is the score table?

Chapter 1

Cut the Picture into Patches and Call Each One a Token

Follow a 96 by 96 image through the patch step, and see what the choice of patch size costs you

The Vision Transformer (ViT) cuts an image into equal squares, called patches, and reads them in a row as tokens. Call the image height H and width W, in pixels, and the patch side p, the patch size. Two numbers follow: the token count n, and d-in, the raw numbers in one patch.

Say it aloud

n equals H over p, times W over p. d-in equals 3 times p squared.

n
n the number of tokens: one for each patch.
H, W
H and W the image height and width in pixels.
p
p the patch size in pixels. H and W must divide by it.
din
d-in the raw numbers in one patch, before the projection.
3
three the colour channels: red, green and blue.
In plain words

Count the patches down the image, H over p, and across it, W over p. Multiply them to get n. One patch holds p rows times p columns times 3 colours, which is d-in.

With numbers

The lecture's example: H = W = 96 and p = 32. Then n = 3 × 3 = 9 tokens, and d-in = 3 × 32 × 32 = 3,072 numbers in each.

The transformer wants every token at one fixed length, its hidden size: 768 here. One learned matrix, the linear projection, maps each 3,072-number patch to 768 numbers. It holds 3,072 × 768 = 2,359,296 weights, which the slide rounds to 2.36 million. Every patch uses the same matrix.

Cut the image

Pick a patch size and an image side. The warm square is a 24 pixel object.

224 px

We made up the object and its place. The counts are exact.

On a 224 pixel image, patch 16 gives 196 tokens, and the 24 pixel object spans 6 of them. Patch 32 gives 49 tokens, but the object shares 2 tiles with road and sky. Patch 8 gives it 16 tokens and grows the table to 784 × 784 = 614,656 scores per head.

The tokens enter a standard transformer encoder: blocks of attention, where tokens trade information, and an MLP, a small network for each token alone. A positional encoding, one learned vector per tile position, tells attention where each tile sat. A class token feeds the classifier. Shapes: image H × W × 3, patches n × 3p², tokens n × 768.

ViT-L/16 means ViT-Large with 16 by 16 patches. Size and patch size are separate dials.

ModelLayersHidden sizeMLP sizeHeadsParams
ViT-Base127683,0721286M
ViT-Large241,0244,09616307M
ViT-Huge321,2805,12016632M

The failure: too big a patch. The model labels a bus well and misses a distant sign. Measure it: with patch 32, a 24 pixel sign covers at most 24 × 24 / (32 × 32) = 56% of one tile. The fix is a smaller patch, but halving p from 32 to 16 costs 4 times the tokens and 16 times the attention table.

pythonimport numpy as np

def patchify(img, p):                    # img (H, W, 3) -> tokens before projection (n, 3*p*p)
    H, W, C = img.shape
    x = img.reshape(H // p, p, W // p, p, C)     # split rows and columns into tiles
    x = x.transpose(0, 2, 1, 3, 4)          # (H/p, W/p, p, p, C)
    return x.reshape(-1, p * p * C)         # (n, 3*p*p)

img = np.random.rand(96, 96, 3)
patches = patchify(img, 32)               # (9, 3072), as on the slide
Wp = np.random.randn(3072, 768) * 0.02    # 2,359,296 weights
tokens = patches @ Wp                     # (9, 768) tokens for the encoder
An image is 224 by 224 and the patch size is 16. How many tokens does the encoder see, and how long is each raw patch before projection?

Chapter 2

High Resolution Matters, and ViT Pays for It Quadratically

Learn what dense prediction is, see where the cost goes as images grow, and meet the model that made it urgent

A Cityscapes street image is 2,048 pixels wide. A pedestrian a block away may be 40 pixels tall. Shrink the image 4 times and she is 10 pixels tall, under one 16 pixel patch.

That matters for dense prediction, a label for every pixel. Semantic segmentation is the common case, scored by mIoU. For each class, divide the pixels that both model and truth mark by the pixels that either marks. Then average over the classes. With made-up counts, 60 right out of 80 marked, against 100 true, gives 60 / 120 = 0.50.

The lecture's cases are medical scans and driving. On Cityscapes, with a Jetson AGX Orin, TensorRT, fp16 and batch size 1 (slide 11):

ModelFrames per secondmIoU
SegFormer1.682.4
EfficientViT21.8 (13.6 times faster)82.7

Slide 12 shows a huge mIoU gap between low and high resolution, and ViT cost in GMACs (billions of multiply-adds) growing quadratically. Where does the cost go? Take one layer with n tokens, each a vector of length d, the hidden size.

Say it aloud

Two n squared d against twelve n d squared. The share equals n over n plus 6 d.

2 n² d
two n squared d attention work: build the n by n score table, then use it to mix the values. Two matrix products.
12 n d²
twelve n d squared all other work: the query, key, value and output matrices (4 n d²) and the MLP (8 n d²).
share
share the part of the layer's work that is attention.
n
n the number of tokens: 196 at 224 pixels with patch 16.
d
d the hidden size: 768 for ViT-Base.
In plain words

Divide the attention work by the total work. The factor 2 n d cancels and leaves n over n plus 6 d. Attention is a small share while n is far below 6 d, and most of the work once n passes it.

With numbers

ViT-Base has d = 768, so 6 d = 4,608. At 224 pixels, n = 196 and the share is 196 / 4,804 = 4%. At 1,024 pixels, n = 4,096 and the share is 47%. At 2,048 pixels, n = 16,384 and the share is 16,384 / 20,992 = 78%.

Split the bill

Each bar is one image size. Yellow is attention. Grey is everything else. Pick a size to see its totals.

Our numbers from the formulas above: a 12-layer ViT-Base, patch 16, global attention. Not the lecture's chart.

For 12 layers, total work goes from 17 GMACs at 224 pixels to about 6,300 at 2,048. The images that dense prediction needs are the images where ViT is slowest.

Segment Anything (SAM, Kirillov and colleagues, 2023) made this urgent. Click a point or draw a box, and it returns masks from three parts:

SAM is ambiguity-aware, so one click can return several masks. An automatic data engine built its training set.

The failure: shrinking to save money. Maps look smooth but miss thin poles and far pedestrians. Measure it: a 40 pixel person shrunk 4 times is 10 pixels, and slide 12 shows the mIoU gap. The fix: keep the resolution and change the attention.

A ViT-Base image goes from 1,024 to 2,048 pixels wide. What happens to the attention score table per head?

Chapter 3

Window Attention: Look Nearby, Then Slide the Windows

Cut the score table by letting each token see a small square, then fix the blind spot with a shift

To check one house on a street map, you look at its block, not the whole city. Window attention makes that habit a rule. Cut the token grid into fixed squares, called windows, for example 7 by 7 tokens. Each token attends only to the tokens in its own window.

How much does that save? Call the token count n, the hidden size d and the window side w, counted in tokens.

Say it aloud

Two n squared d becomes two n w squared d.

2 n² d
two n squared d global attention work in one layer: every token scored against every token.
2 n w² d
two n w squared d window attention work: every token scored against the tokens of its window only.
n
n the number of tokens in the image.
w²
w squared the tokens in one window: 49 for a 7 by 7 window, at any image size.
d
d the hidden size: the length of each vector.
→
becomes the change from global to window attention.
In plain words

Replace the second n with w squared. The window stays the same size while n grows with the image, so the cost now grows in a straight line with n. The slide calls this linear.

With numbers

A 2,048 pixel image with patch 16 has n = 16,384 tokens. Global attention scores 16,384 × 16,384 = 268,435,456 pairs per head. Windows of 7 by 7 score 16,384 × 49 = 802,816. That is 334 times fewer.

The rule has a blind spot (slide 19): no information crosses a window border. If a border runs through a car, the model labels each half without the other, and the label map shows a seam.

The Swin Transformer (Liu and colleagues, 2021) adds a shift. Block A cuts the grid into windows. Block B cuts it again with the lines shifted by half a window. Tokens that a line split in block A share a window in block B.

Slide the windows

Pick a window size and a block, then move the probe. Thick lines are window borders.

7
7

A toy grid with smaller edge windows in block B. Real Swin rolls the map at the edges and masks pairs that should not meet.

With an 8 by 8 window, the probe at column 7, row 7 sees 64 tokens in block A. Turn on the reach: after block A then block B, it can draw on all 256 tokens. With a 4 by 4 window, block A shows 16 tokens and two blocks reach 64.

Swin also merges neighbouring tokens stage by stage. On a 32 by 32 token map, an 8 by 8 window sees 6% of the map. After two 2 by 2 merges the map is 8 by 8, and one window covers all of it. Slide 21 reports better ImageNet accuracy than ViT, and easy use for detection and segmentation.

pythonimport numpy as np

def window_partition(x, w):                 # x (H, W, d) token grid -> (num_windows, w*w, d)
    H, W, d = x.shape
    x = x.reshape(H // w, w, W // w, w, d)
    x = x.transpose(0, 2, 1, 3, 4)
    return x.reshape(-1, w * w, d)

def window_block(x, w, shift, attn):         # attn works on (num_windows, w*w, d)
    if shift: x = np.roll(x, (-(w // 2), -(w // 2)), (0, 1))   # block B: move the cut lines
    out = attn(window_partition(x, w))              # each window scored on its own
    # ...merge windows back to (H, W, d) and undo the roll
    return out
A model uses only plain window attention in every layer, with no shift and no downsampling. What limits what one token can ever see?

Chapter 4

Linear Attention: Change the Order of the Maths

Skip the n by n table by multiplying the same three matrices in a different order, and see what that costs in sharpness

Matrix products obey the associative property: (a b) c = a (b c). The answer stays the same, but the work can change a lot.

Each token's query (what I look for), key (what I offer) and value (what I hand over) stack into matrices Q, K and V, each n × d. Softmax attention has three steps:

  1. Q times K-transposed gives the score table, n × n.
  2. Softmax turns each row of scores into positive weights that add to 1, using exp.
  3. The weights times V give the output, n × d.

Step 2 needs the whole table, so nobody can change the order: O(n²) on slide 24. ReLU linear attention scores a pair by ReLU(Q) ReLU(K)-transposed instead, where ReLU sets negatives to zero. With no exp in the middle, the output for token i, O-i, becomes:

Say it aloud

O-i equals ReLU of Q-i, times the sum over j of ReLU of K-j transposed times V-j, all over ReLU of Q-i times the sum over j of ReLU of K-j transposed.

Oi
O-i the output for token i: a vector of d numbers.
ReLU(Qi)
ReLU of Q-i token i's query with negatives set to zero. Shape 1 × d.
Σj
the sum over j add one term for every token j, from 1 to n.
ReLU(Kj)ᵀ Vj
ReLU of K-j transposed times V-j token j's key times its value, a d × d matrix. Summed over j it is one summary, the same for every i.
bottom line
the bottom line the query times the sum of all keys. It makes the weights add to 1.
In plain words

Build the summary once by adding up each key times its value. Add up the keys too. For each token i, multiply its query by the summary, and divide by its query times the key sum.

With numbers

With the made-up matrices below, the summary is [[1, 2], [2, 1]] and the key sum is (3, 2). Token 1 has query (1, 0). Top: (1, 0) times the summary = (1, 2). Bottom: (1, 0) · (3, 2) = 3. So O-1 = (0.33, 0.67).

Count the work without the bottom line. Take n = 3 and d = 2. After ReLU, Q' = [[1, 0], [0, 2], [1, 1]] and K' = [[1, 1], [2, 0], [0, 1]]. The values are V = [[1, 0], [0, 1], [1, 1]].

  1. Table first: Q' K'ᵀ = [[1, 2, 0], [2, 0, 2], [2, 2, 1]], then times V gives [[1, 2], [4, 2], [3, 3]]. That takes 18 + 18 = 36 multiplications.
  2. Summary first: K'ᵀ V = [[1, 2], [2, 1]], then Q' times it gives [[1, 2], [4, 2], [3, 3]]. That takes 12 + 12 = 24.

Same answer, less work. The table order costs 2 n² d and the summary order 2 n d². So the summary wins when n is larger than d: O(n) on slide 25.

Cost against sharpness

Cost: raise n and compare the two orders. Sharpness: give one token a strong match and compare the weights.

1,024

Cost: one head, d = 64. Sharpness is illustrative: nine tokens, one score pattern, each rule normalises it.

At n = 1,024 and d = 64, the table order needs 134.2 million multiplications and the summary order 8.4 million: 16 times fewer. At 16,384 tokens the gap is 256 times.

There is no free lunch (slides 26 and 27). In the sharpness view at strength 4, softmax puts 64% of the weight on the best token and the linear rule only 34%. It cannot make sharp distributions, so it catches global context but misses local detail. It also lacks multi-scale learning, and loses ImageNet accuracy.

pythonimport numpy as np

def relu_linear_attention(Q, K, V, eps=1e-6):   # Q, K, V: (n, d)
    Q, K = np.maximum(Q, 0), np.maximum(K, 0)
    kv = K.T @ V                          # (d, n) @ (n, d) -> (d, d), built once
    z = K.sum(0)                           # (d,) the denominator's key sum
    return (Q @ kv) / (Q @ z + eps)[:, None]   # (n, d)
Why can ReLU linear attention skip the n by n table, while softmax attention cannot?

Chapter 5

EfficientViT: Add Back What Linear Attention Lost

Repair the two weak spots with small convolutions, read the speedups, and see the same encoder speed up Segment Anything

Linear attention is a pair of binoculars: it sees the whole valley and blurs the tree. The EfficientViT module (Cai and colleagues, ICCV 2023) adds a magnifier. Slide 28 lists two repairs, one for each weakness from Chapter 4.

WeaknessRepair
No sense of scaleMulti-scale aggregation: blend each token with its neighbours to make extra Q, K and V tokens for small and large objects. A 3 by 3 depthwise convolution (one small filter per channel) and a grouped 1 by 1 convolution do the blending.
Weak local detailA depthwise convolution inside the FFN, the feed-forward network after attention, so each token also mixes with its neighbours.

Why depthwise? A normal 3 by 3 convolution on 64 channels has 3 × 3 × 64 × 64 = 36,864 weights. A depthwise one has 3 × 3 × 64 = 576, which is 64 times fewer. So the repairs cost little, and attention stays linear in the token count.

The data flow, from tokens n × d back to n × d:

  1. A linear layer makes Q, K and V.
  2. The convolutions make the multi-scale copies.
  3. ReLU linear attention runs on each scale, each O(n).
  4. A linear layer joins the outputs.
  5. The FFN with its depthwise convolution finishes the block.

On slide 28's ImageNet chart, plain linear attention sits below softmax, and the EfficientViT module sits above it.

On ImageNet (slide 29), EfficientViT-L shows a 4.2 times speedup in A100 throughput. On Cityscapes (slide 30), against SegNeXt and SegFormer, it is 5.8 times faster on a mobile CPU (Snapdragon 8 Gen 1). It is 2.8 times faster on a Jetson AGX Orin and 1.7 times on an A100.

EfficientViT-SAM (Zhang and colleagues, CVPR 2024 ELVM Workshop) changes only SAM's costly part, in three steps:

  1. Replace SAM's image encoder with EfficientViT.
  2. Distill the original encoder into it: train the small student to copy the big teacher's features. Lesson 9 of this course covers it.
  3. Train the whole model end to end on SA-1B: 11 million images with 1 billion masks.

Slide 33 headlines 48.9 times faster without performance drop, on zero-shot COCO mAP against A100 TensorRT throughput. SAM-ViT-H scores 46.5. EfficientViT-SAM-L scores 46.6 at 48.9 times its speed, and the XL model scores 47.8 at 16.5 times. In box, point and everything modes (slides 34 to 36), ViT-Huge runs at 11 images per second and EfficientViT-SAM-XL1 at 182.

Read the speedups

Each button is one measurement from the lecture. Grey is the baseline at 1. Purple is EfficientViT.

From the lecture: slide 30 for Cityscapes, slides 34 to 36 for SAM.

The win is biggest on weak hardware, and biggest of all for SAM, where a heavy encoder changed.

pythondef efficientvit_module(x, mods):             # x: (B, C, H, W) feature map, n = H*W tokens
    q, k, v = mods.qkv(x).chunk(3, 1)         # three (B, C, H, W) maps, 1x1 conv
    scales = [(q, k, v)]
    for agg in mods.aggregators:                # 3x3 DWConv then 1x1 grouped conv
        scales.append(agg(torch.cat([q, k, v], 1)).chunk(3, 1))
    outs = [relu_linear_attention(*s) for s in scales]   # O(n) each, Chapter 4
    x = x + mods.proj(torch.cat(outs, 1))      # residual, back to (B, C, H, W)
    return x + mods.ffn_dwconv(x)               # FFN with a depthwise conv inside

A sketch of slide 28, not the paper's code. The EfficientViT paper lesson walks the real design.

Which pair matches the two repairs that EfficientViT adds to ReLU linear attention?

Chapter 6

Sparse Attention: Skip the Windows That Show Nothing

Keep the full resolution but compute only where the picture has something to say, then learn how many windows each layer can drop

A dashcam frame is mostly grey road and sky, with one cyclist and one parked car. SparseViT (Chen and colleagues, CVPR 2023) computes only where the picture has something in it. This is the lecture's sparse attention.

Slide 38 compares two ways to spend the same budget:

WayResolutionPixels computed
Uniform resizinglow, 0.5 times the sidedense, 100%
Activation pruninghigh, 1 times the sidesparse, 25%

Halving each side leaves a quarter of the pixels, so both cost about the same. Pruning keeps the cyclist sharp. Shrinking blurs her.

Step I: window activation pruning (slide 39). SparseViT builds on window attention. It scores each window's importance as the L2 magnitude of its activations, the length of its feature vectors. It sorts the windows, gathers the top ones into a dense stack, and runs attention only on that stack. Skipped windows pass through unchanged. Each layer gets its own keep ratio, which the slide calls non-uniform sparsity.

Keep the windows that matter

96 windows, four warm objects: a car, two people and a sign. Drag the keep ratio, then switch to shrinking.

25%

A made-up 12 by 8 window grid. Shrinking scales the side by the square root of the ratio. An object under 0.75 of a window is lost.

At 25%, pruning keeps 24 of the 96 windows, and all four objects survive because their nine windows rank at the top. Switch to shrinking at the same cost: the image side halves, and both people and the sign fall under one window and vanish. Pruning still holds all four objects at 10%.

Step II: sparsity-aware adaptation (slide 40). The model saw only dense activations in training, so pruning at test time feeds it inputs it never saw. Fine-tune it with a random keep ratio for each layer at each step. Then one set of weights works at many sparsity settings.

Step III: resource-constrained search (slide 41). Find the best ratio for each layer under a latency budget. Sample a setting and time it. If it misses the budget, sample again: the slide calls this rejection sampling. An evolutionary search keeps the best settings and makes small changes to them. It finds good settings in fewer samples than random search.

Slide 42 reads each chart two ways:

TaskFaster, same mAPHigher mAP, same latency
3D detection, nuScenes1.5 times+1.3%
Instance segmentation, COCO1.3 times+2.0%

Slide 43 shows the masks at budgets of 24 ms and 19 ms. The tighter budget drops more background windows.

pythonimport numpy as np

def sparse_window_attention(win, keep, attn):    # win (num_windows, w*w, d); keep in (0, 1]
    imp = np.linalg.norm(win, axis=(1, 2))        # (num_windows,) L2 activation magnitude
    k = max(1, int(keep * len(win)))
    idx = np.argsort(-imp)[:k]                    # sort: the k most important windows
    out = win.copy()                                 # skipped windows pass through unchanged
    out[idx] = attn(win[idx])                        # gather, attend on (k, w*w, d), scatter
    return out

The failure: pruning a model that never saw sparsity. A good dense model gets worse when pruning turns on. Measure accuracy at several keep ratios: it falls as the ratio drops. The fix is Step II.

Why does SparseViT fine-tune with randomly chosen layerwise sparsity before it searches?

Chapter 7

Draw an Image One Token at a Time

Turn the vision transformer around so that it makes pictures, and learn why a codebook and a fixed order come with that

The second half turns the ViT around. A discriminative model maps visual tokens to a class label. A generative model maps a label or a prompt to visual tokens.

An autoregressive model writes an image the way you write a sentence, one token at a time. Call its tokens x-1 to x-n, in a fixed order, usually raster order: left to right, top to bottom. At step i, the network predicts each choice of x-i, given the tokens before it.

Say it aloud

p of x-1 through x-n equals the product over i of p of x-i, given x-1 through x-i-minus-1.

p(x1, …, xn)
p of x-1 through x-n how likely the whole image is, as a list of n tokens.
Πi
the product over i multiply one term for each token, i from 1 to n.
p(xi | …)
p of x-i given the earlier tokens what the network predicts at step i.
|
given the tokens after the bar are already chosen.
In plain words

Ask the network for the chance of token 1, then of token 2 given token 1, and so on to token n. Multiply all the chances to get the chance of the whole image.

With numbers

With made-up numbers for three tokens: p(x-1) = 0.5, p(x-2 given x-1) = 0.4 and p(x-3 given x-1 and x-2) = 0.9. The image has probability 0.5 × 0.4 × 0.9 = 0.18.

A language model picks a word from a list, but a patch is a vector of continuous numbers. Vector quantization (VQ, slide 47) makes the list: a codebook of K vectors, numbered 0 to K − 1. Each encoder vector becomes the number of its closest code, a discrete visual token.

Slide 48 calls this the reborn Deep Compression, which turned each 32-bit weight into a 2-bit index to one of four centroids. VQ does the same for whole vectors.

Look up the nearest code

The orange dot is an encoder vector. The line goes to its nearest code. Move the dot, then change the codebook size.

0.35
−0.20

A made-up 2-number space with a regular codebook. Real models learn the codebook. The average is over 400 random points.

With 4 codes at (±0.5, ±0.5), the vector (0.35, −0.20) is 0.90, 0.34, 1.10 and 0.72 from them. The nearest is code 1 at (0.5, −0.5), an error of 0.34. With 64 codes the error is 0.08, and the average error drops from 0.39 to 0.10. A token costs log2 K bits: 2 for 4 codes.

The price: speed (slide 49). A 16 by 16 token map needs 256 steps in a row, because step 5 cannot start before step 4 ends. A KV cache (Lecture 15) avoids recomputing old tokens, but the number of steps stays n.

pythonimport numpy as np

def quantize(z, codebook):                      # z (n, d) encoder output, codebook (K, d)
    d2 = ((z[:, None, :] - codebook[None]) ** 2).sum(-1)   # (n, K) squared distances
    idx = d2.argmin(-1)                        # (n,) integer tokens
    return idx, codebook[idx]                      # tokens, and their (n, d) vectors

def generate(model, cond, n):                   # n sequential steps, one token each
    toks = []
    for i in range(n):
        probs = model(cond, toks)                  # (K,) next-token distribution
        toks.append(np.random.choice(len(probs), p=probs))
    return toks

The failure: a codebook that is too small. Images lose hair and eye texture. Measure the average error: large at 4 codes, small at 64. Fix it with a bigger codebook, or with residual tokens (Chapters 9 and 10).

A 16 by 16 token image is generated autoregressively in raster order, one token per step. How many sequential steps does it need?

Chapter 8

Draw Several Tokens per Step, but Choose Them Wisely

Decouple what a token provides from what it predicts, then pick an order that keeps parallel tokens far apart and close to finished ones

Ten painters share a wall. If they paint ten neighbouring bricks at once, they clash. If they start in random corners, nobody has a hint of the pattern. The good plan paints near finished paint, but not elbow to elbow. That is Locality-aware Parallel Decoding (LPD, ICLR 2026 Oral).

Raster-order generation (slides 52 to 58) has a fixed input-output structure. Each token plays two roles at once:

With the two roles tied together, token k can only predict token k + 1.

LPD splits the roles (slides 59 to 66). Context comes from input tokens, the tokens made so far. Generation comes from position query tokens, P1, P2 and so on: placeholders that say which position to fill. Step 0 feeds the condition and queries P4. Step 1 feeds token 4 and queries P3 and P5 together. Step 2 feeds tokens 3 and 5 and queries P1, P2 and P6.

Training uses a special attention mask (slides 68 to 71). Context attention lets tokens see past context tokens. Query attention lets one step's position queries see each other, and hides them from later tokens. At inference, one fused pass writes last step's tokens to the KV cache and turns the new queries into logits.

Which positions go together? Attention maps from LlamaGen-XL show strong spatial locality (slide 75). Raster order with parallel steps draws neighbours together, so they depend on each other. Random order draws tokens far from any context, so conditioning is weak (slide 76). Slide 77 gives two locality principles: stay close to finished tokens, and keep the tokens of one step apart.

Order the 64 tokens

Blue tokens are done. Warm tokens belong to this step. Pick an order and the tokens per step, then scrub the steps.

4
5

Illustrative. Our locality rule is a simple greedy one, not the paper's schedule. An anchored token has a finished token within one cell.

At 4 tokens per step, every order takes 16 steps. Raster spaces same-step tokens 1.7 cells apart. Random spaces them 4.3 apart but leaves 7 tokens with no finished neighbour. Locality-aware spaces them 4.0 apart and leaves only 1: the first token, which has no context to use.

The lecture's speedups for LPD:

AgainstSettingSpeedup
Raster-order next-token predictionImageNet 256 by 256 (slide 79)13 times
Raster-order next-token predictionImageNet 512 by 512 (slide 79)21 times
Raster-order next-token predictiontext-to-image, 1,024 by 1,024 (slide 81)61 times
Earlier parallel autoregressive modelsFID against latency, batch size 1 (slide 80)3.4 times

FID, the Fréchet Inception Distance, scores how close generated images are to real ones. Lower is better.

pythondef lpd_step(model, cache, new_tokens, new_pos, query_pos):
    # new_tokens (a,) generated last step, new_pos (a,) their positions
    # query_pos (b,) positions to fill now, one position query token each
    ctx = model.embed(new_tokens) + model.pos(new_pos)      # (a, d) encode into the cache
    qry = model.query_embed(query_pos)                      # (b, d) "fill position P"
    h = model.transformer(cat([ctx, qry]), cache, mask="context+query")  # one fused pass
    logits = model.head(h[-len(query_pos):])               # (b, K) one distribution per queried position
    return sample(logits)                                   # b new tokens in one step

The failure: parallel tokens that depend on each other. Raster order with several tokens per step gives seams and broken objects. Measure the spacing of same-step tokens: 1.7 cells at 4 per step. The fix is the locality-aware order.

Which pair of rules defines a locality-aware generation order?

Chapter 9

Next-Scale Prediction: Sketch First, Then Add Detail

Replace the token-by-token order with a coarse-to-fine order, and work through the tokenizer on a four-number example

A painter blocks in sky and hill first, then windows, then the glint on the glass. VAR, Visual Autoregressive Modeling (Tian and colleagues, NeurIPS 2024), copies that habit. Each autoregressive step predicts a whole token map, small first, then larger. This is next-scale prediction.

With n tokens on a side, raster order takes O(n²) steps and O(n6) compute (slide 86). Next-scale prediction takes one step per scale, about ten.

The tokenizer is a multi-scale VQ-VAE with residual quantization. A residual is what is left after you subtract what you already explained. Call the encoder's feature map F, the leftover after scale k E-k, and scale k's contribution delta F-k.

Say it aloud

E-k equals E-k-minus-1 minus delta F-k. F is about the sum over k of delta F-k.

Ek
E-k the leftover after scale k. E-0 is F itself.
Ek−1
E-k-minus-1 the leftover before scale k: what scale k must explain.
ΔFk
delta F-k scale k's contribution: shrink the leftover to scale k, quantize it to tokens r-k, look them up, stretch back to full size.
F
F the encoder's feature map. The decoder turns it into the image.
≈
is about equal up to the quantization error.
Σk
the sum over k add the contributions of every scale, coarse to fine.
In plain words

Start with the leftover equal to F. At each scale, shrink the leftover, quantize it and stretch it back: that is delta F-k. Subtract it to get E-k. To rebuild, add every delta F-k.

With numbers

The slides' toy: F = [[2, 4], [6, 8]], codebook −3, −1, +1, +3, +5 for tokens 0 to 4. Scale 1 averages to 5, token 4, so delta F-1 is all 5s and E-1 = [[−3, −1], [1, 3]]. Scale 2 gives tokens [[0, 1], [2, 3]], so E-2 = 0. Five tokens rebuild F exactly.

Slide 92 warns that exact recovery is a property of this toy. Change one number below and watch the error appear.

Tokenize four numbers

Set the four values of F. The panels show each step. Codebook: −3, −1, +1, +3, +5 for tokens 0 to 4.

2
4
6
8

The lecture's toy. On a tie, the lower token wins here.

Raise the bottom right value from 8 to 9. The average becomes 5.25, still token 4. The leftover there is 4, exactly between +3 and +5. It takes token 3 and rebuilds as 8, so the error is 1.

Slide 93 sets the toy next to the real tokenizer:

PartToyStandard VAR, 256 by 256
Feature map2 × 2 × 116 × 16 × 32
Codebook5 scalar values4,096 vectors of 32 numbers
Scale sides1, 21, 2, 3, 4, 5, 6, 8, 10, 13, 16
Tokens and steps5 tokens, 2 steps680 tokens, 10 steps (raster: 256 steps)

For generation (slide 94), a VAR transformer uses a block-wise causal mask. Scale k sees scales 1 to k − 1, and all tokens of scale k come out together. For the slide's three scales, the sequence length is 1² + 2² + 3² = 14.

pythonimport numpy as np

def msrq(F, codebook, scales, down, up):         # F (h, w, c); codebook (K, c)
    E, tokens, recon = F.copy(), [], np.zeros_like(F)
    for s in scales:                             # e.g. [1, 2, 3, ..., 16], coarse to fine
        z = down(E, s)                              # (s, s, c) leftover at this scale
        d = ((z[..., None, :] - codebook) ** 2).sum(-1)   # (s, s, K)
        r = d.argmin(-1)                        # (s, s) integer tokens for this scale
        dF = up(codebook[r], F.shape[:2])       # (h, w, c) contribution, stretched
        E, recon = E - dF, recon + dF            # subtract, accumulate
        tokens.append(r)
    return tokens, recon                       # one token map per scale

The failure: discrete tokens cannot say everything. Fine detail looks soft. Measure it: the 8-to-9 case leaves an error of 1. Slides 95 and 96 show VAR's discrete tokenizer rebuilding poorly at 256, 512 and 1,024 pixels. The fix is Chapter 10.

In VAR's tokenizer, what does the second scale encode?

Chapter 10

HART: Discrete Tokens for the Big Picture, Residuals for the Fine Print

Fix the codebook's lost detail by adding a small continuous correction, and see why it can beat diffusion on speed

An artist inks bold outlines, then adds the glint in the eye with a fine pencil. HART, the Hybrid Autoregressive Transformer (Tang and colleagues, ICLR 2025), does the same. Slides 95 and 96 show VAR's discrete tokenizer losing detail that HART's hybrid tokenizer keeps.

On slide 98, discrete tokens carry the big picture and residual tokens carry fine detail such as eyes and hair. Call the encoder's full-precision feature map the continuous tokens.

Say it aloud

Continuous tokens equal the sum of the discrete tokens, plus the residual tokens.

continuous
continuous tokens the encoder's full-precision feature map: the best the decoder can get.
Σ discrete
the sum of the discrete tokens every scale's codebook contribution added up, as in Chapter 9.
residual
residual tokens what the discrete sum misses: Chapter 9's quantization error, kept instead of thrown away.
In plain words

Add up the discrete contributions of all scales. Subtract that sum from the continuous tokens. What is left is the residual, and a small model learns to predict it.

With numbers

Chapter 9's toy with a 9 in the corner: the continuous value is 9. The discrete sum is 5 + 3 = 8, so the residual is 1. A perfect residual predictor gives back 9.

The tokenizer (slides 99 to 102) has an encoder, a VQ quantizer and one decoder for either kind of token. At generation it decodes only continuous tokens, for the better quality limit that continuous rFID (reconstruction FID) shows. In training, the decoder sees discrete latents 50% of the time and continuous latents 50%.

Why both? The residual predictor is imperfect, so its outputs land between discrete and continuous latents. A decoder trained on continuous latents alone would see them as out of distribution.

Add the residual

Thin line: the continuous signal. Stairs: what discrete tokens can say. Add the residual, then make the predictor worse.

25%

A made-up signal. Error is the root mean square gap. Predictor error is noise as a share of one codebook step.

At 3 levels and 25% predictor error, discrete alone misses by 0.30, and the predicted residual cuts that to 0.14. At 100% error the hybrid is worse than discrete alone, at 0.55. A bad residual hurts.

The generator (slides 103 to 105) has two parts:

  1. A scalable-resolution AR transformer, like VAR, predicts the discrete tokens scale by scale. Text tokens from a frozen LLM go in front, which the slide calls more parameter efficient than AdaLN or cross-attention. HART turns VAR's absolute position embeddings into relative ones, so it can change resolution.
  2. A small residual diffusion MLP predicts the residual tokens at the last step, starting from noise.

Why is it fast (slide 106)?

ModelSampling stepsSteps at the highest resolution
DiffusionT, usually 20all of them, full transformer
HART10 to 14only the last

So HART reaches up to 9.6 times the throughput of diffusion models. Against SD-XL, PixArt-Sigma, SD3-Medium and FLUX-schnell it reaches 4.5 to 7.7 times at similar quality (slide 107). It runs at interactive speed on a laptop with a mobile RTX 4090.

pythondef hart_tokenizer_step(enc, vq, dec, img, p_discrete=0.5):
    z = enc(img)                                   # continuous tokens (h, w, c)
    zq = vq(z)                                     # sum of discrete scale contributions
    use_discrete = np.random.rand() < p_discrete   # 50% / 50% during training
    recon = dec(zq if use_discrete else z)
    return mse(recon, img)                         # decoder sees both kinds of latent

def hart_generate(ar, diff, dec, prompt):
    zq = ar(prompt)                                # discrete tokens, scale by scale (Ch. 9)
    res = diff(cond=ar.last_hidden(), steps=8)   # residual from noise, last scale only
    return dec(zq + res)                         # 100% continuous at decode time

We chose the sketch's 8 diffusion steps. The slides do not give the number.

The failure: a decoder that only saw clean latents. Generated images look worse than the tokenizer's own rebuilds. Measure it: at 100% predictor error the hybrid line falls below discrete alone. The fix: train the decoder on both kinds of latent, half and half.

Why does HART train its decoder on both discrete and continuous latents?

Chapter 11

The Field Guide: Efficient Vision Transformers on One Page

Review the numbers, the terms and the code, then pick a method for the image problem in front of you

The lecture in two paragraphs

A ViT cuts an image into p by p patches, projects each to a token and runs a transformer encoder. Attention builds an n by n table, so high-resolution dense prediction is slow. Window attention (Swin) limits each token to a window and shifts the windows. Linear attention drops softmax for ReLU and multiplies K-transposed by V first. EfficientViT repairs its two weaknesses. SparseViT skips weak windows, adapts to sparsity and searches ratios per layer.

For generation, autoregressive models predict discrete tokens from a VQ codebook. LPD fills several position queries per step in a locality-aware order. VAR predicts a whole scale per step. HART adds a residual from a small diffusion head.

The numbers that matter

WhatNumberWhy it matters
96 by 96 image, patch 329 tokens of 3,072 numbers; projection 2.36M weightsTokens and raw patch size (Ch 1)
224 by 224, patch 16196 tokens of 768 raw numbersThe standard ViT input (Ch 1)
Attention share4% at 224, 47% at 1,024, 78% at 2,048Our ViT-Base model: attention takes over as images grow (Ch 2)
Work per image17 GMACs at 224; about 6,300 at 2,048Our ViT-Base model: the quadratic bill (Ch 2)
SegFormer, EfficientViT1.6 against 21.8 FPS; 82.4 against 82.7 mIoUCityscapes: same accuracy, 13.6 times the speed (Ch 2)
7 by 7 windows802,816 scores against 268,435,456 at 16,384 tokens334 times fewer (Ch 3)
Linear attention8.4M against 134.2M multiplications at n = 1,024, d = 6416 times fewer; grows with n/d (Ch 4)
EfficientViT on Cityscapes5.8, 2.8, 1.7 times fasterMobile CPU, Jetson, A100 (Ch 5)
EfficientViT-SAM48.9 times faster (L), 16.5 times (XL); 11 to 182 images/sSwap only the image encoder (Ch 5)
SparseViT1.5 times faster or +1.3 mAP (nuScenes); 1.3 times faster or +2.0 mAP (COCO)25% of pixels, full detail (Ch 6)
LPD13 times at 256; 21 at 512; 3.4 over parallel AR; 61 text-to-imageFewer steps, local order (Ch 8)
VAR tokenizer680 tokens in 10 steps at 256 by 256, against 256 raster stepsOne step per scale (Ch 9)
HARTup to 9.6 times throughput; 4.5 to 7.7 times at similar qualityAR for structure, diffusion for the residual (Ch 10)

The terms

TermPlain meaningWhere
Patch, token, hidden sizeA square of pixels; its vector; the vector length1
Dense prediction, mIoUA label per pixel; overlap score averaged over classes2
Window, shifted windowA small square of tokens that attend together; windows cut again, offset by half3
Associative property(ab)c = a(bc): same answer, different work4
ReLU linear attentionAttention without exp, in O(n)4
Depthwise convolutionOne small filter per channel5
DistillationA small model copies a big one's features5
Window activation pruningSkip windows with weak features6
Autoregressive, raster orderOne token at a time, left to right, top to bottom7
Vector quantization, codebookReplace a vector by the index of its nearest table entry7
Position query tokenA placeholder that asks for one position8
Next-scale predictionPredict a whole token map, coarse to fine9
Residual tokenWhat discrete tokens could not say9, 10

A checklist before you choose

The core as code

A sketch of each idea, with shapes in the comments.

pythonimport numpy as np

def patchify(img, p):                          # (H, W, 3) -> (n, 3*p*p), n = (H/p)*(W/p)
    H, W, C = img.shape
    x = img.reshape(H // p, p, W // p, p, C).transpose(0, 2, 1, 3, 4)
    return x.reshape(-1, p * p * C)

def window_partition(x, w):                    # (H, W, d) -> (windows, w*w, d)
    H, W, d = x.shape
    x = x.reshape(H // w, w, W // w, w, d).transpose(0, 2, 1, 3, 4)
    return x.reshape(-1, w * w, d)

def relu_linear_attention(Q, K, V, eps=1e-6):  # (n, d) each, O(n d^2)
    Q, K = np.maximum(Q, 0), np.maximum(K, 0)
    kv = K.T @ V                                # (d, d), built once
    return (Q @ kv) / (Q @ K.sum(0) + eps)[:, None]

def keep_top_windows(win, keep):               # SparseViT step I: indices of kept windows
    imp = np.linalg.norm(win, axis=(1, 2))
    return np.argsort(-imp)[:max(1, int(keep * len(win)))]

def quantize(z, codebook):                     # (n, d), (K, d) -> tokens (n,)
    return ((z[:, None] - codebook[None]) ** 2).sum(-1).argmin(-1)

def residual_tokens(F, codebook, scales, down, up):   # Ch 9: one token map per scale
    E, out = F.copy(), []
    for s in scales:
        r = quantize(down(E, s).reshape(-1, F.shape[-1]), codebook)
        E = E - up(codebook[r], F.shape[:2])         # what is left for the next scale
        out.append(r)
    return out, E                                # E is HART's residual to model with diffusion

Run patchify on a 96 by 96 image with p = 32 to get shape (9, 3072). Multiply the Chapter 4 matrices in the summary order, without the bottom line, to get [[1, 2], [4, 2], [3, 3]].

Where this sits

The previous lecture cut the cost of long text by managing the KV cache. This one cuts the cost of long image token sequences by changing which pairs attend and the order of generation. For the basic model, see the Vision Transformer lesson and the ViT paper lesson.

Keep going

The takeaway. Count the tokens first. Then ask which pairs really need to talk (windows), whether the maths can be re-ordered (linear), where the picture is empty (sparse), and how many sequential steps generation needs (parallel, next-scale, hybrid).
You must segment 2,048 pixel street images on a small edge GPU, and the scenes are mostly empty road. Which pairing of problem and fix best fits the lecture?

Credit

This lesson follows Lecture 16 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 and in the lecture slides. The papers it teaches are An Image is Worth 16x16 Words (Dosovitskiy et al., 2021), Swin Transformer (Liu et al., 2021), EfficientViT (Cai et al., ICCV 2023), EfficientViT-SAM (Zhang et al., 2024), SparseViT (Chen et al., CVPR 2023), Segment Anything (Kirillov et al., 2023), Locality-aware Parallel Decoding (ICLR 2026), VAR (Tian et al., NeurIPS 2024) and HART (Tang et al., ICLR 2025). The explanations, devices and toy numbers here are ours. Numbers labelled illustrative are not the lecture's.

Now press Teach and explain, from memory, why linear attention can skip the n by n table and what it loses. Then go back to the cost curves at the top and drag the image size once more.

MIT 6.5940 Lecture 16: Vision Transformers
The course site · Lecture slides · Back to Lecture 15 · Back to Gleams