Session S22

Vision Transformers & Multimodal Models

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.

HW3 is due today, and Quiz 3 is next session

Three course items come first.

  • HW3 (Transformer from scratch) is due today at 11:59 PM Pacific; the 12-hour grace period applies.
  • Quiz 3 is next session (S23), in the final 30 minutes of class (6:45–7:15 PM), in Canvas, with closed materials. It covers Module 3, S13–S22, today included. Online (Web) students and students with flexible-time arrangements may use their assigned flexible completion window.
  • Project: the proposal is due at the end of this week (the S23 week). If your project classifies images with little labeled data, Part 2 today bears on your choice of architecture.

Next session's lecture, before the quiz, opens Module 4; the quiz does not cover it.

S21 aligned a model by changing its distribution itself

After S20's decoding, in the same class, S21 turned a pretrained model that completes text toward an assistant.

  • Demonstrations and comparisons: supervised fine-tuning (SFT) trains S18's next-token loss on the response tokens of human-written demonstrations; the reward model, the LLM with a scalar output, learns ranked comparisons through Bradley–Terry.
  • Optimizing the preferences: RLHF maximizes \(r_\phi\) minus \(\beta\) times the KL divergence to the SFT model (PPO in InstructGPT). DPO solves that objective's optimum for the reward; \(\log Z\) cancels, and one classification-style loss on preference pairs trains the model directly, with no reward model and no RL.
  • What it does not buy: it aligns to what labelers preferred, not to truth; a learned reward can be hacked (length, sycophancy); aligned models are judged by preference, with the judge's biases controlled.

Every model so far read and wrote text. Today the same Transformer reads images.

Today's route answers the five questions in order, then closes

Each part answers one clause of the title page's question.

partthe question it answers, and how
1 · Patches as tokensHow 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 biasWhat 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 mapsWhat 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 beyondWhat does that space make possible? Classes typed at test time, where that fails, and four ways to join vision and language.
6 · CloseSix 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.

Separate models for images and text now share one architecture

Part 1 · Patches as tokens. Through most of the 2010s, vision and language used different networks (S09–S17):

most of the 2010safter the Transformerpixelsconvolutionswordsrecurrence, then attentionimagepatchestextsubword tokensTransformer(the same block, with a causal mask)TransformerViTlanguage models(S16–S21)
  • ViT (Vision Transformer; Dosovitskiy et al., ICLR 2021): cut an image into patches and feed them to a plain Transformer encoder as tokens. It matches and exceeds the best CNNs, provided there is enough data.

The first step is to turn an image into a sequence of tokens.

One token per pixel is far too many; \(16\times16\) patches give 196 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:

  1. Pixels as tokens: \(224\cdot224=50{,}176\) tokens and \(50{,}176^2\approx2.5\times10^{9}\) scores. Far too expensive.
  2. Non-overlapping \(16\times16\) patches: \((224/16)^2=14^2=196\) tokens, an ordinary sequence length, and \(196^2=38{,}416\) scores.
  3. The saving: a patch holds \(16^2=256\) pixels, so 256 times fewer tokens and \(256^2=65{,}536\) times fewer scores.
  4. One vector per token: flattened, a patch is \(16\cdot16\cdot3=768\) numbers (three color channels).

The patch size trades resolution against compute: smaller patches give more tokens.

ViT runs a standard Transformer encoder on the patch 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:

drawn as 4 × 4 patches;224 × 224 with 16 × 16patches gives 14 × 14flatten………16 · 16 · 3 = 768 values eachlinearprojection(224/16)² = 196 patch tokens[CLS]123…196+ learned position embeddings, one per tokenstandard Transformerencoder[CLS]image summaryApart from patching: no convolutions,no pooling pyramids, nothing else image-specific.
  • A [CLS] token (for classification): one learnable vector placed first. Its last-layer output is the image summary the classifier reads.
  • Learned position embeddings: one learnable vector per position, added to its token.

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 values

Reading 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.
  • In row-major order, patches are numbered row by row, each row left to right.

Patch 0 becomes one row of 48 values, channel 0 first

Patch 0 of the first image, followed through patchify:

0127…863reshape to (B, C, H/p, p, W/p, p)then permute(0, 2, 4, 1, 3, 5)(B, H/p, W/p, C, p, p)patch 03 channels (RGB), 4 × 4 eachreshapeone row of the output, 48 values:channel 0: rows 0–3 of the patch, row by rowchannel 1channel 264 rows of 48 per image, shape (2, 64, 48)

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 exact

The 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
  
  • One row of \(4\cdot4\cdot3=48\) values per patch; max error 0.0, so every value returns to its place and the tokens lose nothing.

A wrong reshape gives the same shape and scrambled patches

Why test the round trip? The shortcut imgs.reshape(B, n_patches, -1) also returns (2, 64, 48):

right: patchify(imgs, 4)0123patch 0 is this4 × 4 square, in eachof the 3 channels:48 values01Both give shape (2, 64, 48); the round-trip test tells them apart, and the shapes do not.wrong: imgs.reshape(B, n_patches, -1)012348 values fromparts of two imagerows of one channel01Each strip shows rows 0–3 of channel 0, all 32 columns.Computed from the deck's patchify and a direct reshape of a (2, 3, 32, 32) tensor.
  • Its patch 0 is image row 0 and half of row 1, from channel 0 only. Such tokens train poorly while every shape check passes.
  • With the shortcut in place of patchify, the round trip's max error is not 0.

Run the round-trip test before training, in your projects too.

Projection, [CLS] and positions turn 64 patches into 65 tokens of width 96

The 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.
  • Why positions: without them, self-attention is permutation-equivariant (S16). Shuffle the patches and their outputs shuffle the same way; the [CLS] output does not change, so the classifier cannot tell where a patch came from.

The patch embedding is exactly one strided convolution

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.

The windows are the patches, and the filters are proj's weights

Why the convolution and the projection give the same numbers:

kernel 4, stride 4:the windows tile theimage with no gapand no overlap,8 × 8 = 64 positionsproj.weight (96, 48)reshapeconv.weight (96, 3, 4, 4)the same 96 filtersConv2d(C, D, kernel_size=P, stride=P)conv output(2, 96, 8, 8)flatten(2).transpose(1, 2)→ (2, 64, 96)= proj(patchify(x)),max difference 0.00e+00

Same windows, same weights and the same order of values give the same 64 tokens.

Self-check on token counts and a bug the shapes miss

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.

A CNN assumes locality and translation equivariance; a ViT assumes far less

Part 2 · Inductive bias. An inductive bias (a prior) is an assumption built into the architecture before any data arrives.

convolution, layer 1sees its 3 × 3neighborhood, with thesame weights atevery positionself-attention, layer 1can attend to every patch;the 2D layout must belearned throughposition embeddings
  • CNN: each output sees a small neighborhood (locality; S09's receptive field), and the same weights apply everywhere, so a shifted image gives a shifted feature map (translation equivariance; S09).
  • ViT, fewer vision-specific priors but not none: its weights are shared across positions, but it is not translation-equivariant: each position adds its own learned embedding. The patch grid and position embeddings supply structure; local interactions are possible but not forced.

What the ViT does not assume, it must learn from examples.

ViT trails comparable ResNets on 1.3M images and leads on about 300M

The ViT paper (Dosovitskiy et al.) pretrained at three data scales (reading 3.8):

ImageNet top-1(schematic)pretraining images (log scale)ImageNet-1k1.3MImageNet-21k14MJFT-300M~300Mcomparable ResNetsViT: large ViTs surpass the state-of-the-artCNNs of the time; best reported 88.55%ViT modestly belowroughly evenThe ViT paper's reported ordering, drawn schematically: the y-axis has no scale, and 88.55%is the one reported value, given as a label. The large ViTs also used substantially less pretraining compute.
  • What it shows: data scale and the training recipe can make up for weaker vision-specific priors.
  • DeiT (Data-efficient image Transformers; Touvron et al., 2021) trained competitive ViTs on ImageNet-1k alone, with strong augmentation and distillation (training on a larger teacher model's outputs).

An empirical trade, not a law that priors hurt.

A small task where a CNN's assumptions are exactly right tests the trade

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.

plus: class 0X: class 116 × 16 pixels, one channel; a 3 × 3 shapeat a random position, under Gaussian noise(noise not drawn). The class depends onlyon the shape, wherever it sits.Dashed: the ViT's fixed 4 × 4 patch grid;the X on the right straddles four patches.A 3 × 3 convolution slides one filter overevery position: the structure of the task.
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?

At 256 images the CNN leads by 12 points; at 4,096 the gap nearly closes

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
  
  • Answer: the CNN, 0.9960 against 0.8790, though the ViT has \(58{,}226/4{,}866\approx12\) times the parameters. With 16 times the data, 0.9990 against 0.9920: the gap shrinks.

What the toy run shows, and what it means for a small-data project

The printout as a plot; the vertical axis starts at 0.85:

0.850.900.951.002564,096training imagestest accuracy0.99600.99900.87900.9920CNN, 4,866 parametersViT, 58,226 parameters
  • It shows a real low-data penalty for missing priors that shrinks with data: the shape of the paper's result.
  • It does not show that CNNs are better: one seed, one learning rate, no augmentation, a task built for convolution.
  • A few hundred labeled images: prefer a CNN or a pretrained ViT (S11's transfer recipe); a from-scratch ViT needs the DeiT recipe.

On small data, CNN-style priors still help.

Self-check on the assumptions and advice for a small project

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.

Which patches does [CLS] weight? Read it from the attention matrix

Part 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
  
expressionshapewhat 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 top patch overlaps the shape in 96.6% of the test images

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%]
  
1.30.72.11.61.00.71.02.51.11.10.51.71.41.074.24.800112233Image 0: [CLS] attention over its 16 patches,×100 (last block, mean of 4 heads).Outlined: the shape's patch. The shape's top-leftpixel is (12, 8), so it covers rows 12–14 andcolumns 8–10: patch row 3, column 2.74.2 of the 100 sit on that one patch.
  • Chance, about 13%: the generator draws the top-left row \(r\) from 0 to 12, and for 6 of the 13 (\(r \bmod 4\) is 2 or 3) the shape spans two patch rows: \((7\cdot1+6\cdot2)/13=19/13\) on average, and likewise columns, so \((19/13)^2\approx2.1\) of the 16 patches, and \(2.1/16\approx0.13\).

An attention map shows where weight goes, not why the model decided

"The model attends to X" is often read as "X explains the decision". Reading 3.8's reasons against that step:

after block 2, the lastafter block 1input tokens[CLS][CLS]123456[CLS]123456Block 2, the map you would plot: [CLS] puts its weight on token 5.Block 1: token 5 took its values mostly from patch 2, which holds the shape.Schematic: one route the plotted map cannot show.
  • Attention weights are one layer's mixing coefficients, not a causal account: after one block every token is a mixture, so a patch's information can reach [CLS] through other tokens (above).

Two more reasons, and the check that every attention map needs

Reading 3.8 gives two more reasons not to read an attention map as an explanation:

  • High weight, little effect: a head outputs the weighted sum of value vectors (S14), so a patch with a large weight but a small value vector changes the output little.
  • Artifact tokens: large ViTs put very high attention on a few uninformative background patches; Darcet et al. (2024) append a few extra learnable tokens, called registers, that absorb this attention.

Pair any attention map with a quantitative check, such as occlusion, ablation or known locations.

Self-check on reading the attention and judging an attention map

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.

CLIP trains an image encoder and a text encoder into one shared space

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.

caption itext encoder(Transformer)projectionunit lengthimage iimage encoder(ViT or ResNet)projectionunit lengthcontrastive objectiveN × N cosine similarities,scaled by a learnabletemperature (drawn N = 4)each row: which captionbelongs to this image?a cross-entropymatched pairseach column: which image belongs to this caption? a cross-entropythe loss averages the two
  • Each encoder (image: a ViT or a ResNet; text: a Transformer) ends in a projection into the shared space, and every embedding is normalized to unit length.

A batch of \(N\) pairs gives an \(N\times N\) matrix of cosine similarities

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}\).

image 1image 2image 3image 4U: one image per row(N, D)×(D, N)V⊤: one caption per column=(N, N)S = UV⊤entry (i, j): image i with caption j,a cosine, since every row is unit lengththe diagonal: the N matched pairsthe other N2 − N entries: mismatcheddrawn with N = 4, D = 6caption1234
  • Stack a batch's image embeddings as the rows of \(U\) and its caption embeddings as the rows of \(V\), both \(N\times D\). Then \(S=UV^\top\) is \(N\times N\), and \(s_{ij}\) compares image \(i\) with caption \(j\).
  • Training should make each matched \(s_{ii}\) the largest entry in its row and in its column.

The loss treats every row and every column as an \(N\)-way classification

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}}\]
  1. Each term is S03's cross-entropy on the softmax of a row or a column. The loss is their average, \(L=\tfrac12(L_{\text{img}}+L_{\text{txt}})\): the symmetric InfoNCE loss (the name Oord et al., 2018, gave this kind of loss).
  2. Chance level: random projections give the match no advantage, and cosines at \(T=1\) keep every softmax near uniform, about \(1/N\) per candidate. Each term is then about \(-\log(1/N)=\ln N\) (S12: uniform over \(K\) classes gives \(\ln K\)).
  3. For \(N=64\): \(\ln64\approx4.1589\), where the run should start.

The CLIP loss is one case of contrastive learning

image i's embeddingits caption, the positive: pulled closerthe other N − 1 captions, the negatives: pushed apartunit length: each embedding ends on the circle
  • This is contrastive learning: pull each matched pair (the positive) together and push the \(N-1\) mismatched ones (the negatives) apart.
  • Self-supervised image models use the same kind of loss (InfoNCE) on two augmentations of one image (SimCLR, a Simple framework for Contrastive Learning of visual Representations; MoCo, Momentum Contrast).

Each row has one positive and \(N-1\) negatives; fewer negatives make the choice easier (slide 37).

A toy you can run has 64 pairs that share a hidden 8-number concept

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 loss in code is one matrix product and two cross-entropies

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
  
z[i]shared concept,8 numbers× img_map, + noise× txt_map, + noise…imgs[i]48 numbers…txts[i]32 numbersimg_projF.normalizetxt_projF.normalizeie[i]16, unit lengthte[i]16, unit lengthie @ te.T * log_temp.exp()logits, 64 × 64
  • 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}}\).

Training logs the loss, the two mean similarities, and retrieval

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?

The run starts at chance and ends with perfect retrieval

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
  
loss024075150225300stepchance: ln(64) = 4.15894.16200.0548mean cosine similarity00.51075150225300stepmatchedmismatchedretrieval@1: 0.0000 at step 0,1.0000 from step 75 onThe printout's five logged steps, drawn.
  • Retrieval is perfect because each pair shares a concept vector and little noise, so linear maps can align them; real pairs need deep encoders and do not align this cleanly.

Once matches align, mismatched pairs cannot average below \(-1/(N-1)\)

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\).

  1. Align every matched pair: \(\mathbf v_i=\mathbf u_i\), all unit vectors, so each \(s_{ii}=1\).
  2. All \(N^2\) entries: \(\sum_i\sum_j\mathbf u_i\cdot\mathbf v_j=\big(\sum_i\mathbf u_i\big)\cdot\big(\sum_j\mathbf v_j\big)=\lVert\sum_i\mathbf u_i\rVert^2\ge0\).
  3. Minus the diagonal's \(N\): the mismatched entries sum to \(\lVert\sum_i\mathbf u_i\rVert^2-N\ge-N\).
  4. Their mean, over \(N^2-N\) entries: \(\ge-N/(N^2-N)=-1/(N-1)\); \(N=64\): \(-1/63\approx-0.0159\).
  5. Step 75's \(-0.0158\) is at this floor; after it, the loss falls through a sharper \(1/T\) (slide 36).

Once the matched pairs align, the mismatched mean is as low as \(N\) unit vectors allow; the rest is temperature.

At scale the loss needs a learned temperature

Two settings follow from the loss on the previous pages (reading 3.8). The first is the temperature:

  • Why learn \(T\): cosines lie in \([-1,1]\), so at \(T=1\) a row's logits differ by at most 2. Even a match at 1 against 63 others at \(-1\) gives \(p=e^{2}/(e^{2}+63)\approx0.105\): a loss of at least 2.25. CLIP learns the scale \(1/T\), starting at \(1/0.07\), capped at 100. The toy's loss fell below 2.25 only because its learned \(1/T\) had reached 2.3 by step 75.
step075150225300
learned \(1/T\)1.02.35.89.812.4

The toy run of slide 34, logged at the same steps.

  • A second run in reading 3.8 (noisier pairs): with \(T\) fixed at 1 the training loss ends at 3.34; with the learned scale it ends at 0.23 (\(T\approx0.048\)). On held-out pairs the fixed \(T=1\) retrieved better, 0.676 against 0.578.

Bounded cosines need a learned \(1/T\); on a small, noisy dataset a large \(1/T\) can overfit.

At scale the loss also needs a large batch

The second is the batch size (reading 3.8):

  • Why a large batch: each row is an \(N\)-way choice. The right caption among 64 is far easier to find than among 32,768, CLIP's reported batch size. Small batches give easy negatives and a low loss that does not carry over to retrieval: by slide 29's rule, chance is \(\ln8\approx2.08\) at batch 8 against \(\ln64\approx4.16\) at batch 64, so a loss is comparable only at the same batch size.

Compare contrastive runs at one batch size, and evaluate retrieval on a large pool.

SigLIP takes the batch size out of the loss's definition

Reading 3.8 also tests a loss without the softmax over each row:

  • SigLIP (Sigmoid Loss for Language Image Pre-training; Zhai et al., 2023) scores each cell as its own binary classification, so the batch size is no longer part of the loss's definition.
retrieval@1 on 256 held-out pairs, reading 3.8's second, noisier toy (512 training pairs), learned temperaturebatch 8batch 64
softmax (InfoNCE)0.55470.5781
sigmoid (SigLIP)0.66020.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.

Self-check on the matrix's size and a low loss at a small batch

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.

For zero-shot classification, type the class names, then pick the nearest

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:

an imageimageencodernearest text embedding: dogtextencodera photo of a doga photo of a trombone…
  1. Embed one prompt per class, such as "a photo of a dog", with the text encoder.
  2. Embed the image; pick the class whose text embedding has the largest cosine with it, the nearest neighbor, as retrieval@1 did in the toy.
  • Reported: 76.2% ImageNet top-1, matching the original ResNet-50 with no ImageNet image used for supervision, and better robustness on ImageNet-Sketch and ImageNet-R. The supervision came from 400 million captions.

A zero-shot failure: the nearest prompt is the wrong class

Slide 40's classifier fails when the image's nearest text embedding belongs to the wrong class. An example with counting:

three dogsimageencodercorrect✗ nearest, wrongtextencodera photo of three dogsa photo of two dogsa photo of one dog
  • Schematic, not a measurement: captions rarely state exact counts, so the two text embeddings sit close together and the pick is unreliable.

A failure is a wrong nearest neighbor, not an error message: the classifier always returns some class.

A zero-shot score depends on the captions and on the prompt's wording

Where such failures occur, and why, from the CLIP paper and reading 3.8:

  • Weak spots: fine-grained classes (car models, aircraft variants), counting, and data absent from the training distribution.
  • The space encodes what captions mention. Details people rarely write down, such as exact counts, spatial relations and negation ("no people in this photo"), are weakly encoded.
  • Prompt wording: "dog", "a photo of a dog" and an ensemble of prompts give different text embeddings, and accuracy moves by several points. Fix and report the exact prompts; use the paper's templates to compare with published numbers.

A zero-shot number is a claim about a pretraining distribution and a prompt.

Two ways to join vision and language late: a similarity score, or a bridge

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

imageimageencodertexttextencodercosone score

Images embedded once, searched with one text embedding; one number per pair is too little for detailed questions.

Cross-attention bridge: Flamingo (2022)

visionencoderfrozenLM layer · frozencross-attention · trainedLM layer · frozentext tokensimagefeatures

Richer than one score; only the bridge is trained.

Two ways to join them early: a projector, or one sequence from the start

Projector into the token stream: LLaVA (Large Language and Vision Assistant, 2023)

visionencoderprojectionpatch featurestext tokensimage tokensLLMself-attention

The lightest recipe; the common open-source pattern for chat about images.

Early fusion: Chameleon

image and text tokens, one sequenceone model, trained from scratchfusion at every layer

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.

Self-check on a three-word classifier and a fair comparison

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.

Six mistakes in your own work, each with its cause and its fix

Part 6 · Close. Reading 3.8's pitfalls:

symptomcausefix
shapes fine, but the ViT trains poorly; reconstructed patches look scrambleda wrong reshape or permute order in patchifythe round-trip test before training
a from-scratch ViT badly trails a small CNN on a small datasetnot a bug: missing priors cost accuracy when data is scarcethe DeiT recipe, pretrained weights, or the CNN
an attention map is offered as the reason for a predictionattention weights are one layer's mixing weights, not a causal accountocclusion, ablation, or known locations
contrastive loss falls, but all embeddings look alikecollapse: a missing normalization, too-easy negativesnormalize; log matched and mismatched similarity
great training loss with small batches, poor embeddings downstreamfew, easy negatives in each batchevaluate on a large pool; hold the batch size fixed, or use SigLIP
zero-shot accuracy moves by several points for one modelthe wording of the promptsfix and report the prompts; use the paper's templates

Today's answer takes the title page's question clause by clause

  • How it reads an image: as \(P\times P\) patches, projected, with [CLS] first and learned positions added, through a standard encoder. The projection is one strided convolution.
  • What it loses: built-in locality and translation equivariance, which costs accuracy on little data (toy: 0.8790 against 0.9960). Small project: a CNN or a pretrained ViT.
  • What attention shows: where [CLS] puts its weight (on the shape in 96.6% of the toy's images), not why the model decided.
  • One space: two encoders and a cross-entropy over each row and column of the \(N\times N\) cosine matrix, matches on the diagonal, starting at \(\ln N\).
  • What it makes possible: classes typed at test time (76.2% reported on ImageNet), retrieval, generation, assistants.

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.

For next time

  • Next session (S23), Wednesday: Module 4 begins with autoencoders and variational autoencoders (VAEs), which add latent variables and the reparameterization trick.
  • Read: 4.1 Autoencoders and VAEs.