Transformers for images and long inputs: ViT, Swin, Perceiver, Mixer
Four answers to "how do I feed this to a Transformer?" Cut an image into patch tokens, attend inside shifted windows, squeeze a long input through a few latents, or drop attention for two small mixing networks.
What runs in CodeSplash
- DNN020Vision Transformer (ViT) Runs in CodeSplash (Experimental)
- DNN021Swin Transformer Explained here
- DNN022Perceiver Explained here
- DNN023MLP-Mixer Explained here
- Image classifier (pretrained ResNet-50 or DINOv2) Experimental
- Image embeddings, map and neighbors (DINOv2 or ResNet-50) Experimental
You will be able to
- Turn an image into patch tokens and count them
- Explain how windowed attention cuts cost and how shifting windows restores mixing
- Describe the Perceiver's latent bottleneck and its cost
- Contrast token mixing and channel mixing in MLP-Mixer
Read first
Images as patch tokens
ReadA vision transformerVision transformer (ViT)Cuts an image into fixed-size patches, turns each into a token with a position embedding, and runs a Transformer on them. cuts an image into fixed-size patches, flattens each, projects it to a token with one shared matrix, and adds a learned position embedding. From there it's an ordinary Transformer, usually with a [CLS] token whose output feeds the head.
The program cuts a 4 × 4 image into four 2 × 2 patches and projects each to three numbers: a token matrix of 4 × 3. The top-left patch becomes (0.375, 0.427, 0.479). With no built-in sense of neighborhood, a ViT needs lots of data or pretraining to beat a CNN.
import numpy as np
im = np.arange(16.).reshape(4, 4) / 16
patches = np.array([im[i:i + 2, j:j + 2].ravel() for i in [0, 2] for j in [0, 2]]) # 4 patches × 4 pixels
W = np.arange(12.).reshape(4, 3) / 12 # shared projection
tokens = patches @ W
print(tokens.shape, tokens)im <- matrix(0:15, 4, 4, byrow = TRUE) / 16
patches <- t(sapply(list(c(1, 1), c(1, 3), c(3, 1), c(3, 3)), function(p)
as.vector(t(im[p[1]:(p[1] + 1), p[2]:(p[2] + 1)])))) # row-major, like Python
W <- matrix(0:11, 4, 3, byrow = TRUE) / 12
tokens <- patches %*% W
print(dim(tokens)); print(tokens)Cut an image into patches, then shuffle them with and without position embeddings.
DExplorable · Vision transformer patches
How does a transformer read an image, and what does it lose without positions?
Image
Image size
Patch size P
A patch size that doesn't divide the image cuts off its border.
Each patch becomes a vector of this many numbers.
The sequence the transformer reads; numbers are each patch's place in the image
Attention pairs for each patch size (log scale)
Score 1.5622 · change when shuffled 0.1421
- Tokens
- 16
- Attention pairs
- 256
- Embedding weights
- 520
- Pixels dropped
- 0
- Score
- 1.5622
- Change when shuffled
- 0.1421
- Puzzle: Pick an image size and patch size that cut off part of the image.
32 × 32 pixels in 8 × 8 patches make 16 tokens, so attention compares 256 pairs. With position embeddings, shuffling the patches changes the score by 0.1421.
Swin: attend inside windows
ReadGlobal attention over N patches costs N². The Swin TransformerSwin TransformerA vision transformer that attends inside local windows and shifts the windows every other block, so cost grows with image area. attends only inside local windows of M × M patches, so cost grows linearly with image area. Every other block shifts the windows by half a window, so information crosses window borders over two blocks. Patches are merged between stages, building a pyramid like a CNN's.
In the reference program, eight tokens attend in two windows of four. Window one's outputs stay near 0.19–0.26, window two's near 0.70–0.77: no token mixed with the other window. A shifted next block would let them.
Perceiver: a few latents read everything
ReadThe PerceiverPerceiverCross-attends a small, fixed set of learned latent tokens to a long input, so cost grows linearly with input length. keeps a small, fixed set of L learned latent tokens. They cross-attend to the N input tokens (latents are the queries, inputs the keys and values), costing L × N instead of N², then run ordinary self-attention among themselves. Any input that can be tokenized fits: pixels, audio samples, point clouds.
In the reference program, two latents read five inputs and come out as a 2 × 3 summary whose first row starts at 0.446. The bottleneck is the trade: everything the model knows about the input must fit in L tokens.
MLP-Mixer: no attention at all
ReadMLP-MixerMLP-MixerReplaces attention with two small networks: one mixes information across patches, the other across channels. keeps the patch tokens and replaces attention with two small networks per block. Token mixing runs across patches, one feature at a time; channel mixing runs across features, one patch at a time. Each has layer norm and a residual add.
Token mixing uses fixed learned weights per position pair, not weights computed from the input as attention does. The reference program's 4 × 3 output starts with −0.220; it's a component demo with linear mixers, not a trained model.
How many tokens?
PredictPredict first
A ViT reads 224 × 224 images with 16 × 16 patches. How many patch tokens per image, before [CLS]?
Reveal
196: 224/16 = 14 patches per side, 14 × 14 = 196. Global attention compares 196 × 196 pairs; halving the patch size quadruples the tokens and multiplies attention cost by 16.
What runs here
Read| Entry | In CodeSplash |
|---|---|
| Vision Transformer (DNN020) | Runs in CodeSplash as a pretrained backbone: DINOv2-small (14 × 14 patches) in the image classifier and image embedder, after a one-time download |
| Swin Transformer (DNN021) | Explained here |
| Perceiver (DNN022) | Explained here |
| MLP-Mixer (DNN023) | Explained here |
Check: Transformer families
CheckpointCheck yourself
What becomes a token in a vision transformer?
Show the answer
Answer: a
Patches keep the token count manageable. The position embedding tells the Transformer where each patch was.
Check yourself
Why does a ViT trained from scratch on a small dataset usually lose to a CNN?
Show the answer
Answer: a
Convolutions build in locality and weight sharing. With pretraining on huge datasets, ViTs make up for it.
Check yourself
Where can you use a vision transformer in CodeSplash?
Show the answer
Answer: a
DINOv2-small is a pretrained ViT. The classifier can fine-tune it lightly or train a head on its features.
Check yourself
Why does Swin shift its windows every other block?
Show the answer
Answer: a
Fixed windows would isolate each region forever. Shifting by half a window links neighboring windows.
Check yourself
How does windowed attention's cost grow with the number of patches N, for a fixed window size?
Show the answer
Answer: a
Each patch attends to the M² patches of its window: N × M² comparisons in all.
Check yourself
A Perceiver with 64 latents reads 10,000 input tokens. Roughly how many query–key comparisons does its cross-attention make?
Show the answer
Answer: a
64 × 10,000. Full self-attention over the inputs would need 10,000², about 156 times more.
Check yourself
In a Perceiver's cross-attention, which side supplies the queries?
Show the answer
Answer: a
Latents ask, inputs answer. That's why the output has as many tokens as there are latents.
Check yourself
What does MLP-Mixer's token-mixing network mix?
Show the answer
Answer: a
Token mixing replaces attention's job of moving information between positions; channel mixing plays the feed-forward network's role.
Check yourself
How does token mixing in MLP-Mixer differ from self-attention?
Show the answer
Answer: a
Fixed per-position weights make Mixer simpler and tied to one input size; attention adapts its pattern to the content.
Recap
Recap- ViT: patches → tokens → a Transformer; needs data or pretraining.
- Swin: attention in shifted local windows, linear cost, a CNN-like pyramid.
- Perceiver: few latents cross-attend to a long input, L × N cost, a bottleneck by design.
- MLP-Mixer: token and channel mixing networks, no attention.
- In CodeSplash, DINOv2-small brings a pretrained ViT to the image classifier and embedder; the others are explained here.
Concepts in this lesson