Session S22
A Transformer reads a sequence of tokens. How does it read an image, what does it lose without a CNN's built-in assumptions, what can its attention weights tell us, how do images and captions come to share one space, and what does that space make possible?
Deep Learning · CS 4715/5715 · University of Idaho
The last session of Module 3.
Three course items come first.
Next session's lecture, before the quiz, opens Module 4; the quiz does not cover it.
After S20's decoding, in the same class, S21 turned a pretrained model that completes text toward an assistant.
Every model so far read and wrote text. Today the same Transformer reads images.
Each part answers one clause of the title page's question.
| part | the question it answers, and how |
|---|---|
| 1 · Patches as tokens | How does a Transformer read an image? It cuts the image into patches and runs a standard encoder on them; we check the code. |
| 2 · Inductive bias | What does it lose without a CNN's built-in assumptions? Accuracy when data is scarce: the paper's three data scales, then a CNN and a ViT trained on a CPU. |
| 3 · Attention maps | What can its attention weights tell us? Where the model puts its weight, scored against known locations, and why that does not explain a decision. |
| 4 · CLIP (Contrastive Language-Image Pretraining) | How do images and captions come to share one space? Two encoders and a cross-entropy over the rows and columns of a similarity matrix, then a run. |
| 5 · Zero-shot and beyond | What does that space make possible? Classes typed at test time, where that fails, and four ways to join vision and language. |
| 6 · Close | Six common mistakes, today's answer, next time. |
Each of Parts 1–5 ends on a self-check. First, why an image needs tokens at all.
Part 1 · Patches as tokens. Through most of the 2010s, vision and language used different networks (S09–S17):
The first step is to turn an image into a sequence of tokens.
Self-attention scores every pair of tokens: \(T\) tokens give \(T^2\) scores per head and layer (S14). For a \(224\times224\) RGB image:
The patch size trades resolution against compute: smaller patches give more tokens.
"An Image is Worth 16x16 Words": a linear projection maps each flattened patch to the model width \(D\); then a [CLS] token in front, positions added, and the encoder:
[CLS] token (for classification): one learnable vector placed first. Its last-layer output is the image summary the classifier reads.Beyond cutting patches, nothing in the model is specific to images. Next, the cut in code.
patchify splits each axis into blocks, then gathers each patch's valuesReading 3.8's script, at a size that runs anywhere:
import torch
import torch.nn as nn
torch.manual_seed(0)
B, C, H, W = 2, 3, 32, 32 # batch of 2 RGB images, 32x32
P = 4 # patch size
D = 96 # embedding dimension
n_patches = (H // P) * (W // P) # 8 * 8 = 64 patches per image
imgs = torch.randn(B, C, H, W)
def patchify(x, p):
"""(B, C, H, W) -> (B, n_patches, p*p*C), row-major patch order."""
B, C, H, W = x.shape
x = x.reshape(B, C, H // p, p, W // p, p) # (B, C, H/p, p, W/p, p): split H and W into blocks
x = x.permute(0, 2, 4, 1, 3, 5) # (B, H/p, W/p, C, p, p)
return x.reshape(B, (H // p) * (W // p), C * p * p)
permute reorders dimensions and moves no value: new dimension \(k\) is the old dimension given by its \(k\)-th argument, counting from 0.Patch 0 of the first image, followed through patchify:
A patch's 48 values stay together in one row, in the order channel, row, column.
patchify only rearranges values, so the round trip is exactThe script continues; unpatchify undoes the three steps in reverse order:
def unpatchify(patches, p, c, h, w):
"""Inverse of patchify."""
B = patches.shape[0]
x = patches.reshape(B, h // p, w // p, c, p, p)
x = x.permute(0, 3, 1, 4, 2, 5) # inverse of permute(0, 2, 4, 1, 3, 5)
return x.reshape(B, c, h, w)
patches = patchify(imgs, P)
print(f"images : {tuple(imgs.shape)}")
print(f"patches : {tuple(patches.shape)} (expect ({B}, {n_patches}, {C * P * P}))")
# round-trip check: patchify must lose no information
recon = unpatchify(patches, P, C, H, W)
print(f"round-trip max |x - unpatchify(patchify(x))| = {(imgs - recon).abs().max().item():.1f}")
images : (2, 3, 32, 32)
patches : (2, 64, 48) (expect (2, 64, 48))
round-trip max |x - unpatchify(patchify(x))| = 0.0
Why test the round trip? The shortcut imgs.reshape(B, n_patches, -1) also returns (2, 64, 48):
patchify, the round trip's max error is not 0.Run the round-trip test before training, in your projects too.
[CLS] and positions turn 64 patches into 65 tokens of width 96The script continues; one nn.Linear maps each patch's 48 values to \(D=96\):
# linear projection to embeddings + [CLS] token + position embeddings
proj = nn.Linear(C * P * P, D)
cls_token = nn.Parameter(torch.zeros(1, 1, D))
pos_embed = nn.Parameter(torch.randn(1, n_patches + 1, D) * 0.02)
tokens = proj(patches) # (B, 64, 96)
# (1, 1, 96) viewed as (B, 1, 96), no copy
tokens = torch.cat([cls_token.expand(B, -1, -1), tokens], dim=1)
tokens = tokens + pos_embed
print(f"tokens : {tuple(tokens.shape)} (expect ({B}, {n_patches + 1}, {D}))")
tokens : (2, 65, 96) (expect (2, 65, 96))
torch.cat puts the [CLS] vector first: (2, 64, 96) becomes (2, 65, 96). pos_embed, (1, 65, 96), adds one vector per position, broadcast over the batch.[CLS] output does not change, so the classifier cannot tell where a patch came from.A convolution with kernel size and stride \(P\) visits each patch once (S09). Give it proj's weights:
# the same projection as a strided convolution (the trick real ViTs use)
conv = nn.Conv2d(C, D, kernel_size=P, stride=P)
with torch.no_grad():
conv.weight.copy_(proj.weight.reshape(D, C, P, P))
conv.bias.copy_(proj.bias)
conv_tokens = conv(imgs).flatten(2).transpose(1, 2) # (B, 64, 96)
diff = (conv_tokens - proj(patches)).abs().max()
print(f"max |Linear-on-patches - strided Conv2d| = {diff.item():.2e}")
max |Linear-on-patches - strided Conv2d| = 0.00e+00
proj is the patch embedding: it plays the role of S17's embedding table, but a patch is 48 real values, not an integer id, so the table becomes a linear map.patchify orders a patch's 48 values by channel, row, column, as a kernel's axes are ordered (S09). Production ViTs skip patchify: they apply this convolution to the image directly and flatten its (B, 96, 8, 8) output into 64 tokens, as the conv_tokens line does.proj's weightsWhy the convolution and the projection give the same numbers:
Same windows, same weights and the same order of values give the same 64 tokens.
Three questions on Part 1.
(a) A \(32\times32\) RGB image with \(P=8\): how many patch tokens, values per patch, and tokens into the encoder?
(b) The same image with \(P=4\): how many tokens, and how many times (a)'s attention scores?
(c) patchify returns (2, 64, 48), yet training stalls. What do you run?
(a) \((32/8)^2=16\) tokens of \(8\cdot8\cdot3=192\) values; 17 with [CLS].
(b) \((32/4)^2=64\), 4 times (a)'s tokens, so \(4^2=16\) times its scores.
(c) The round trip: a wrong reshape keeps the shape and scrambles the patches.
Patches become tokens by a reshape that keeps each patch whole; a round-trip test catches a wrong one, and the shapes do not.
Part 2 · Inductive bias. An inductive bias (a prior) is an assumption built into the architecture before any data arrives.
What the ViT does not assume, it must learn from examples.
The ViT paper (Dosovitskiy et al.) pretrained at three data scales (reading 3.8):
An empirical trade, not a law that priors hurt.
Reading 3.8's experiment: is the hidden \(3\times3\) shape a plus or an X? Both models get AdamW at learning rate 0.003, batches of 64, 400 steps and the same seed; trained on 256 or 4,096 images, tested on the same 1,000.
| SmallCNN | \(3\times3\) convolutions with 16 and 32 filters, ReLU, a max pool, a global average pool, a linear head |
| SmallViT | \(4\times4\) patches by a strided convolution (16 tokens of width 48), learned positions, two encoder layers with 4 heads, the mean over tokens (instead of a [CLS] token), a linear head |
Predict: which model wins at 256 images? At 4,096, does the gap grow or shrink?
The script's last lines; make_data, SmallCNN, SmallViT and train_eval are slide 18's data, models and recipe, with their code in reading 3.8. gen is the random generator; Xte, yte are the 1,000 test images and labels:
print(f"{'train size':>10} {'model':>9} {'params':>8} {'test acc':>9}")
for n_train in [256, 4096]:
Xtr, ytr = make_data(n_train, gen)
for name, cls in [("CNN", SmallCNN), ("ViT", SmallViT)]:
torch.manual_seed(0) # identical init treatment
model = cls()
n_params = sum(p.numel() for p in model.parameters())
acc = train_eval(model, Xtr, ytr, Xte, yte)
print(f"{n_train:>10} {name:>9} {n_params:>8,} {acc:>9.4f}")
train size model params test acc
256 CNN 4,866 0.9960
256 ViT 58,226 0.8790
4096 CNN 4,866 0.9990
4096 ViT 58,226 0.9920
The printout as a plot; the vertical axis starts at 0.85:
On small data, CNN-style priors still help.
Three questions on Part 2.
(a) Name the two assumptions a \(3\times3\) convolution builds in, and one structure a ViT still has.
(b) A from-scratch ViT on 500 labeled images trails a small CNN. A bug? What do you change?
(c) Does the toy table show that CNNs beat ViTs on images?
(a) Locality and translation equivariance. The ViT shares weights across positions and has the patch grid and positions.
(b) Not a bug: 500 images are too few for the ViT to learn what the CNN's inductive bias builds in. Use the CNN, a pretrained ViT, or the DeiT recipe.
(c) No: the task matches the CNN's inductive bias; one seed, one learning rate. It shows a penalty that shrinks with data.
CNN assumptions pay off on little data; with enough data a ViT catches up.
[CLS] weight? Read it from the attention matrixPart 3 · Attention maps. Reading 3.8 trains a third model, a ViT with a [CLS] token (model), on 4,096 plus-or-X images with slide 18's recipe; each block keeps its softmax weights as last_att. On 500 new test images Xte (labels yte):
with torch.no_grad():
acc = (model(Xte).argmax(1) == yte).float().mean()
# CLS row of the last block's attention, averaged over heads: (B, 17)
cls_att = model.blocks[-1].last_att.mean(dim=1)[:, 0, :]
patch_att = cls_att[:, 1:] # drop CLS->CLS
| expression | shape | what it holds |
|---|---|---|
last_att | (500, 4, 17, 17) | per image and head (dim 1: the 4 heads), a \(17\times17\) softmax matrix: row \(t\) is how token \(t\) weights the 17 tokens |
.mean(dim=1) | (500, 17, 17) | the 4 heads averaged |
[:, 0, :] | (500, 17) | row 0: how [CLS] weights every token |
cls_att[:, 1:] | (500, 16) | its weights on the 16 patches, row by row over the \(4\times4\) grid |
The script's test: does the top patch, patch_att[i].argmax(), overlap the shape, whose position the data generator recorded?
The script's first two printed lines; the figure shows image 0's weights:
test accuracy: 0.9880
most-attended patch overlaps the shape: 483/500 (96.6%) [chance would be ~13%]
"The model attends to X" is often read as "X explains the decision". Reading 3.8's reasons against that step:
[CLS] through other tokens (above).Reading 3.8 gives two more reasons not to read an attention map as an explanation:
Pair any attention map with a quantitative check, such as occlusion, ablation or known locations.
Three questions on Part 3.
(a) last_att is (500, 4, 17, 17). Give the shape of .mean(dim=1)[:, 0, :], and say what one row holds.
(b) Why is chance for the overlap test about 13%, not \(1/16\)?
(c) An attention map, drawn over a photo, puts high weight on the dog's head. What do you add before writing "it decides by the head"?
(a) (500, 17): for one image, how [CLS] weights the 17 tokens, averaged over heads; it sums to 1.
(b) Any patch the shape covers counts: \((19/13)^2\approx2.1\) of the 16 on average (slide 23), and \(2.1/16\approx0.13\).
(c) Occlude or ablate those patches and measure the change in the output.
An attention map shows where weight goes, not why; pair it with a quantitative check.
Part 4 · CLIP. CLIP (Contrastive Language-Image Pretraining; Radford et al., ICML 2021) learns from about 400 million (image, text) pairs from the internet, not class labels.
The cosine similarity \(\cos(\mathbf{u},\mathbf{v})=\mathbf{u}\cdot\mathbf{v}/(\lVert\mathbf{u}\rVert\,\lVert\mathbf{v}\rVert)\) lies between \(-1\) and 1; for unit-length vectors it is the dot product \(\mathbf{u}\cdot\mathbf{v}\).
The logits are \(s_{ij}/T\), with a temperature \(T\) (S20) that CLIP learns. Row \(i\) asks which caption belongs to image \(i\), column \(j\) which image belongs to caption \(j\); the answer is the diagonal entry:
\[L_{\text{img}}=-\frac1N\sum_{i}\log\frac{e^{s_{ii}/T}}{\sum_{j}e^{s_{ij}/T}},\qquad L_{\text{txt}}=-\frac1N\sum_{j}\log\frac{e^{s_{jj}/T}}{\sum_{i}e^{s_{ij}/T}}\]Each row has one positive and \(N-1\) negatives; fewer negatives make the choice easier (slide 37).
Reading 3.8's script. Pair \(i\)'s "image" and "caption" are two random linear maps of one concept vector, plus noise; each encoder is one linear layer:
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(0)
N, D_IMG, D_TXT, D = 64, 48, 32, 16 # 64 pairs, different raw dims, shared space
g = torch.Generator().manual_seed(1)
z = torch.randn(N, 8, generator=g)
img_map = torch.randn(8, D_IMG, generator=g)
txt_map = torch.randn(8, D_TXT, generator=g)
imgs = z @ img_map + 0.1 * torch.randn(N, D_IMG, generator=g)
txts = z @ txt_map + 0.1 * torch.randn(N, D_TXT, generator=g)
img_proj = nn.Linear(D_IMG, D)
txt_proj = nn.Linear(D_TXT, D)
z is (64, 8); imgs (64, 48) and txts (64, 32) have different raw sizes, as images and text do; both projections map to \(D=16\).The script continues; the learned scale multiplies the cosines by \(1/T\):
# log of the learnable logit scale 1/T, like CLIP
log_temp = nn.Parameter(torch.tensor(0.0))
def clip_loss():
ie = F.normalize(img_proj(imgs), dim=-1) # unit-norm embeddings
te = F.normalize(txt_proj(txts), dim=-1)
logits = ie @ te.T * log_temp.exp() # (N, N) similarity matrix
labels = torch.arange(N) # pair i matches pair i
loss_i = F.cross_entropy(logits, labels) # image -> which caption?
loss_t = F.cross_entropy(logits.T, labels) # caption -> which image?
return (loss_i + loss_t) / 2, ie, te
ie, te are \(U\), \(V\), (64, 16) each; logits is \(S/T\), with \(1/T=e^{0}=1\) at the start; loss_i is \(L_{\text{img}}\), loss_t is \(L_{\text{txt}}\).The script's last lines: Adam on both projections and log_temp, 301 steps, a log line every 75:
params = list(img_proj.parameters()) + list(txt_proj.parameters()) + [log_temp]
opt = torch.optim.Adam(params, lr=1e-2)
print(f"chance-level loss for batch of {N}: ln({N}) = {math.log(N):.4f}")
for step in range(301):
loss, ie, te = clip_loss()
opt.zero_grad(); loss.backward(); opt.step()
if step % 75 == 0:
with torch.no_grad():
sims = ie @ te.T
matched = sims.diag().mean()
mismatched = (sims.sum() - sims.diag().sum()) / (N * N - N)
top1 = (sims.argmax(dim=1) == torch.arange(N)).float().mean()
print(f"step {step:3d} loss {loss.item():.4f} "
f"matched sim {matched.item():+.4f} "
f"mismatched sim {mismatched.item():+.4f} "
f"retrieval@1 {top1.item():.4f}")
Predict the loss at step 0. Where should the matched and the mismatched mean similarity end?
Answer: about \(\ln64\); matched near 1, mismatched near 0. retrieval@1: the share of images whose nearest caption is their own.
chance-level loss for batch of 64: ln(64) = 4.1589
step 0 loss 4.1620 matched sim +0.0298 mismatched sim -0.0012 retrieval@1 0.0000
step 75 loss 2.2355 matched sim +0.9993 mismatched sim -0.0158 retrieval@1 1.0000
step 150 loss 0.6498 matched sim +0.9995 mismatched sim -0.0157 retrieval@1 1.0000
step 225 loss 0.1396 matched sim +0.9994 mismatched sim -0.0153 retrieval@1 1.0000
step 300 loss 0.0548 matched sim +0.9993 mismatched sim -0.0142 retrieval@1 1.0000
Why the mismatched mean stops near 0. Uses: unit vectors and dot products; \(\mathbf u_i\), \(\mathbf v_i\) are row \(i\) of slide 28's \(U\) and \(V\), so \(s_{ij}=\mathbf u_i\cdot\mathbf v_j\).
Once the matched pairs align, the mismatched mean is as low as \(N\) unit vectors allow; the rest is temperature.
Two settings follow from the loss on the previous pages (reading 3.8). The first is the temperature:
| step | 0 | 75 | 150 | 225 | 300 |
|---|---|---|---|---|---|
| learned \(1/T\) | 1.0 | 2.3 | 5.8 | 9.8 | 12.4 |
The toy run of slide 34, logged at the same steps.
Bounded cosines need a learned \(1/T\); on a small, noisy dataset a large \(1/T\) can overfit.
The second is the batch size (reading 3.8):
Compare contrastive runs at one batch size, and evaluate retrieval on a large pool.
Reading 3.8 also tests a loss without the softmax over each row:
| retrieval@1 on 256 held-out pairs, reading 3.8's second, noisier toy (512 training pairs), learned temperature | batch 8 | batch 64 |
|---|---|---|
| softmax (InfoNCE) | 0.5547 | 0.5781 |
| sigmoid (SigLIP) | 0.6602 | 0.6172 |
At batch 8 the sigmoid loss retrieves better (0.66 against 0.55); at 64 its edge is smaller. One seed: read the direction, not the decimals.
Three questions on Part 4.
(a) \(N=128\) pairs: the shape of logits, the matched and mismatched counts, the chance-level loss?
(b) Why does one labels vector serve both logits and logits.T?
(c) Batches of 8: training loss near 0, poor retrieval on a 10,000-image pool. Why?
(a) (128, 128); 128 and \(128^2-128=16{,}256\); \(\ln128\approx4.85\).
(b) The matches are on the diagonal: row \(i\)'s answer is column \(i\), and column \(j\)'s is row \(j\).
(c) Each row chose among 8 (chance \(\ln8\approx2.08\)): few, easy negatives. Use larger batches or SigLIP.
Each image must pick its own caption among \(N\); the learned temperature and the batch size decide what a low loss means.
Part 5 · Zero-shot and beyond. The text encoder maps any string into the shared space, so a classifier can be defined at test time:
Slide 40's classifier fails when the image's nearest text embedding belongs to the wrong class. An example with counting:
A failure is a wrong nearest neighbor, not an error message: the classifier always returns some class.
Where such failures occur, and why, from the CLIP paper and reading 3.8:
A zero-shot number is a claim about a pretraining distribution and a prompt.
Beyond one shared space, three other designs join the two modalities. The first two of reading 3.8's four patterns:
Late fusion (dual encoders): CLIP
Images embedded once, searched with one text embedding; one number per pair is too little for detailed questions.
Cross-attention bridge: Flamingo (2022)
Richer than one score; only the bridge is trained.
Projector into the token stream: LLaVA (Large Language and Vision Assistant, 2023)
The lightest recipe; the common open-source pattern for chat about images.
Early fusion: Chameleon
Image tokens are discrete, from a separately trained quantizer. Both modalities can in principle be generated; the rest is trained from scratch.
Of a new system, ask where the modalities first meet and what was frozen.
Three questions on Part 5.
(a) With a trained CLIP, classify one image as cat, dog or trombone. What do you compute?
(b) Your zero-shot accuracy beats the paper's number for the same model. What do you check first?
(c) Which pattern searches a billion images with one text query, and why?
(a) Three prompt embeddings, the image embedding, three cosines; the largest wins.
(b) The prompts: rerun with the paper's templates and report yours.
(c) Late fusion: images are embedded once, without the query; a search is one text embedding and a nearest-neighbor lookup.
A zero-shot result needs its prompts, and a billion-image search needs late fusion.
Part 6 · Close. Reading 3.8's pitfalls:
| symptom | cause | fix |
|---|---|---|
| shapes fine, but the ViT trains poorly; reconstructed patches look scrambled | a wrong reshape or permute order in patchify | the round-trip test before training |
| a from-scratch ViT badly trails a small CNN on a small dataset | not a bug: missing priors cost accuracy when data is scarce | the DeiT recipe, pretrained weights, or the CNN |
| an attention map is offered as the reason for a prediction | attention weights are one layer's mixing weights, not a causal account | occlusion, ablation, or known locations |
| contrastive loss falls, but all embeddings look alike | collapse: a missing normalization, too-easy negatives | normalize; log matched and mismatched similarity |
| great training loss with small batches, poor embeddings downstream | few, easy negatives in each batch | evaluate on a large pool; hold the batch size fixed, or use SigLIP |
| zero-shot accuracy moves by several points for one model | the wording of the prompts | fix and report the prompts; use the paper's templates |
[CLS] first and learned positions added, through a standard encoder. The projection is one strided convolution.[CLS] puts its weight (on the shape in 96.6% of the toy's images), not why the model decided.Module 3 ends here: RNNs (S13), attention and the Transformer (S14–S17), LLMs (S18–S21), images (S22). Its idea: tokenize everything and let one architecture handle it.