Lecture 11 · Multimodal I: Vision Encoders and Vision–Language Models

Advanced Natural Language Processing · Lecture 11。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: CMU 11-711 Spring 2026, Lecture 11 (02/17), slides anlp-s2026-11-multimodal.pdf; course code 11_multimodal_i/ (vit.ipynb, clip.ipynb). Readings: A. Dosovitskiy et al., An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale (ICLR 2021); A. Radford et al., Learning Transferable Visual Models From Natural Language Supervision (ICML 2021). Additional: H. Liu et al., Visual Instruction Tuning (NeurIPS 2023, LLaVA); M. Deitke et al., Molmo and PixMo (2024); L. Beyer et al., PaliGemma (2024). Sources: the public slides and notebooks, the readings, and the papers cited in each section. Every number labelled “measured” comes from code/lecture11/, run on the author’s machine (Apple M4 Pro, Python 3.13, PyTorch 2.14, one CPU thread). Code: code/lecture11/ — four demos, each under two minutes. Reading time: ~110 minutes for the prose; ~25 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Turn an image into a sequence of vectors the way a Vision Transformer does (patches → linear patch embedding → [CLS] + position embeddings → Transformer encoder), compute its sequence length and parameter count, and explain what it gives up compared with a CNN (inductive bias) and what it gains (scale).
  2. Explain CLIP: two encoders, one shared space, the symmetric InfoNCE loss; why learning from text beats learning from labels; how zero-shot classification with prompts works and why prompt wording matters.
  3. Explain what a single pooled image vector cannot represent (attribute binding and relations), and how hard negatives are supposed to help.
  4. Describe how a vision–language model connects a vision encoder to an LLM: projector, image tokens, two-stage training (feature alignment, visual instruction tuning), and the design choices of LLaVA, Molmo and PaliGemma.
  5. Read a VLM result against the right baselines: a blind model, and the information the vision encoder actually keeps.

0.2 Prerequisites and scope

  • Prerequisites:
    • Lecture 5 (Transformers, position encodings): the ViT is Lecture 5’s encoder with patches as tokens.
    • Lecture 6 (pretraining and transfer, linear probes).
    • Lecture 8 (instruction tuning).
    • Lecture 10 (dense retrievers trained with InfoNCE): CLIP is a dual encoder across modalities.
  • Scope: multi-to-text, meaning images (and text) in, text out.
  • Not in scope:
    • Generating images: Lecture 12 (tokens) and Lecture 15 (diffusion).
    • Agents that act on screens: Lecture 18.
    • Video and audio.

0.3 Section → code map

SectionIdeaDemo in code/lecture11/
§1.3Shape World: images whose contents are known exactlyshape_world.py
§2.1–2.2patch arithmetic; patch embedding = strided convolution01_vit.py Part A (+ vit.py)
§2.3inductive bias vs data: CNN vs ViT at 2k / 8k / 32k images01_vit.py Part B
§2.4position embeddings: none vs learned; what they learn01_vit.py Part C
§2.5mean attention distance01_vit.py Part D
§3.2–3.4CLIP training, zero-shot, prompts, probes02_clip.py Parts A–B
§3.5captions vs labels as supervision02_clip.py Part C
§3.6binding and relations; probes; twins; hard negatives02_clip.py Part D, 03_binding.py
§4.2–4.5a LLaVA-style VLM: blind baseline, stages, token choices, the encoder bottleneck04_vlm.py (+ vlm.py)

0.4 Notation

SymbolMeaning
x∈RH×W×Cx \in \mathbb{R}^{H \times W \times C}an image (height, width, channels); here H=W=S=24H = W = S = 24, C=3C = 3
PPpatch side; N=HW/P2N = HW/P^2 patches
xp∈RN×(P2C)x_p \in \mathbb{R}^{N \times (P^2 C)}the flattened patches
We∈RD×P2CW_e \in \mathbb{R}^{D \times P^2 C}the patch embedding; DD the model width
z0,z1,…,zNz_0, z_1, \dots, z_Nencoder outputs; z0z_0 belongs to the [CLS] token
fI,fTf_I, f_Timage and text encoders (CLIP); τ\tau the temperature
(xn,yn)n=1B(x_n, y_n)_{n=1}^{B}a batch of image–text pairs
WpW_pthe VLM projector from vision width to LM width

1. Why multimodal, and the key problem

1.1 Four kinds of model

The slides arrange the next lectures by what goes in and what comes out:

text outimage out
text intext-to-text (Lectures 1–10)
text + image inmulti-to-text (today)multi-to-image, multi-to-multi (Lectures 12, 15)

Multi-to-text models are already everywhere:

  • Chat with images. AI2’s Molmo interface answers “where is…” by pointing at pixels.
  • Agents on screens. Web agents (VisualWebArena) and computer-use agents (OSWorld) read screenshots (Lecture 18).
  • Visual reasoning. MathVista (Lu et al., 2024) asks math questions about charts, plots and geometry figures.

1.2 The key problem: an image as a sequence of vectors

An LM consumes text as a sequence of vectors, its token embeddings. To let it consume an image we need an image encoder:

fenc(ximage)→z1,…,zL,f_{\text{enc}}(x_{\text{image}}) \to z_1, \dots, z_L,

and that needs two things: a neural architecture that maps pixels to vectors, and a learning algorithm that makes the vectors useful. Today’s three papers supply them:

  • ViT (architecture);
  • CLIP (learning from text);
  • LLaVA (plugging the result into an LM).

1.3 Our laboratory: Shape World

The course notebooks run pretrained ViT and CLIP models on a photo of two cats. That shows the models working, but not why they work or where they fail. As in Lectures 7–10, these notes use a world whose ground truth is known. Shape World (shape_world.py) draws 24×24 images:

  • each image has one or two shapes;
  • 4 shapes (circle, square, triangle, cross) × 5 colors × 2 sizes;
  • two shapes sit side by side or one above the other.

Every image comes with:

  • its scene;
  • captions (“a big red circle left of a small blue square”, or the same fact as “a small blue square right of a big red circle”);
  • questions with answers (“where is the circle ?” → “left”).
...RRRRRRR..............      rows 5-13 of the self-test's scene: a big red circle left of a small
..RRRRRRRRR.............      blue square (one character per pixel, '.' = gray background)
..RRRRRRRRR.............
..RRRRRRRRR.............
..RRRRRRRRR.....BBBBB...
..RRRRRRRRR.....BBBBB...
..RRRRRRRRR.....BBBBB...
..RRRRRRRRR.....BBBBB...
...RRRRRRR......BBBBB...

At this resolution a big circle differs from a big square only at its corners: the circle’s corner pixels are partly covered, so they get blended colors, which this one-letter print rounds away. Shape is therefore the hardest attribute in Shape World, much as fine-grained distinctions are in real images.

parse() goes the other way: it reads an image back into its scene, exactly for every rendered image. Lecture 12 uses it to judge generated images. Real images have none of this cleanliness. What Shape World buys is that every claim below — the model knows color, the model does not know the side — is a measurement.


2. The Vision Transformer

2.1 From pixels to patch tokens

Intuition. A sentence is a sequence of words; ViT’s insight is to make an image a sequence of “visual words” (Dosovitskiy et al. 2020, An Image is Worth 16x16 Words):

  1. Cut the image x∈RH×W×Cx \in \mathbb{R}^{H \times W \times C} into N=HW/P2N = HW/P^2 non-overlapping P×PP \times P patches.
  2. Flatten each into a vector: xp∈RN×(P2C)x_p \in \mathbb{R}^{N \times (P^2 C)}.
  3. Map each by one shared linear layer, the patch embedding We∈RD×(P2C)W_e \in \mathbb{R}^{D \times (P^2 C)}: x=xpWe⊤∈RN×Dx = x_p W_e^\top \in \mathbb{R}^{N \times D}.
  4. Prepend a learned [CLS] vector, add position embeddings, and run a standard Transformer encoder (no causal mask; every patch sees every patch).
  5. Train the outputs z0,…,zNz_0, \dots, z_N for a task; for classification, put a linear head on z0z_0.

The slides’ arithmetic, checked (demo 01 Part A):

modelimagepatchNNpatch vector P2CP^2CWeW_epatch embeddings
slides’ example120×120×340×4094,8001024 × 48009 × 1,024
ViT-B/16224×224×316×16196768768 × 768196 × 768
CLIP ViT-L/14 @336 (used by Molmo)336×336×314×145765881024 × 588576 × 1,024
this lecture24×24×36×61610864 × 10816 × 64

ViT-B/16 thus feeds 196 + 1 = 197 tokens to a 12-layer, D=768D = 768 Transformer. Counting every weight gives 86.6M parameters with a 1,000-class head (measured by formula), the “86M” of the paper.

A patch embedding is a convolution. A linear map applied to each non-overlapping P×PP \times P patch is exactly a convolution with kernel size PP and stride PP. Demo 01 copies WeW_e into a Conv2d(3, 64, kernel_size=6, stride=6) and gets the same outputs (max difference 4.8×10−74.8 \times 10^{-7}). Real implementations (including the Hugging Face ViT in the course notebook) write it that way.

2.2 Why a Transformer, given that CNNs worked?

Background. From 2012 to 2020, image recognition meant convolutional networks (AlexNet, ResNet). A convolution builds two assumptions into every layer:

  • Locality: a unit looks at a small neighbourhood.
  • Weight sharing / translation equivariance: the same filter is applied everywhere, so a shifted cat produces shifted features.

These are an inductive bias (归纳偏置): knowledge about images that the network does not need to learn from data.

ViT’s bet. A Transformer has almost none of that. Only the patching and the per-position MLP are local; self-attention is global from the first layer, and the 2-D layout must be learned from the position embeddings. Dosovitskiy et al.’s result:

  • On ImageNet (1.3M images) alone, ViTs trail ResNets of comparable size by a few points.
  • Pretrained on ImageNet-21k (14M) or JFT-300M (300M images), they overtake them (ViT-H/14: 88.55% on ImageNet).
  • At equal accuracy, ViT needs 2–4× less pretraining compute.

In their words, “large scale training trumps inductive bias”. The slides’ figure of performance versus pretraining compute is this result. The same bet, generality plus scale, is the one LLMs made with text.

2.3 Measured: inductive bias versus data

Demo 01 Part B poses a task that needs both what and where: in a two-object image, which shape is on the left (or on top), and are the objects side by side or stacked? There are 8 classes, so chance is 12.5%. Every model trains for the same 1,500 steps of 64 images.

model2,000 images (test / train)8,00032,000
small CNN (25,880 params)91.3% / 100%——
ViT (157,000 params)30.1% / 100%73.7% / 94.2%78.5% / 81.9%

With 2,000 images, the ViT fits its training set perfectly and generalizes at 30.1%. It memorizes, because nothing tells it that a circle on the left and a circle on the right are the same thing. The CNN, told so by construction, reaches 91.3%. Give the ViT 16× more images and it reaches 78.5%. With 32,000 images and twice the steps, a prototype run reached 95.5%. This is Dosovitskiy et al.’s plot in miniature: the gap closes with data, not with cleverness. It is also why every ViT in a VLM is a pretrained one.

2.4 Position embeddings: a Transformer sees a set

Why they are needed. Self-attention is permutation-equivariant (Lecture 5 §3), and the [CLS] output is invariant to the order of the patches. Without position embeddings, a ViT sees a bag of patches. Demo 01 shuffles the 16 patches of 500 images: the no-position model’s outputs are identical, while the learned-position model changes 78.8% of its predictions.

Measured (32,000 images):

ViTtest accuracyaxis (h / v) rightfirst shape right
learned 1-D position embeddings78.5%99.7%78.7%
no position embeddings33.6%64.7%50.8%

Without positions, which shape comes first is a coin flip (50.8%). The model still finds the axis 64.7% of the time. A patch shows where inside it an object sits, and two objects stacked vertically share that horizontal offset. Information leaks through every crack a model can find.

What learned 1-D embeddings learn. ViT uses one learned vector per patch index, with no 2-D structure built in. After training, their cosine similarities have recovered the grid (demo 01; the slides show the same figure for ViT-L/32):

grid distance (rows + columns)123456
mean cosine of position embeddings0.33−0.02−0.14−0.23−0.41−0.50

Patches in the same row are more alike (0.27) than those sharing neither row nor column (−0.22). This is why Dosovitskiy et al. found that hand-designed 2-D or relative position embeddings bring nothing over 1-D learned ones. In their ablation, those three variants were within a fraction of a point of each other, while dropping position embeddings cost about 3 points. The data teaches the geometry.

Practical consequence. To run a ViT at a higher resolution, you get more patches than position embeddings, so the learned embeddings are 2-D-interpolated to the new grid. That only makes sense because they learned a smooth 2-D layout.

2.5 What do the heads look at?

Dosovitskiy et al. (their Fig. 7) measure each head’s mean attention distance: the pixel distance between a query patch and the patches it attends to, weighted by attention. Some heads in low layers are local, like convolutions; others are global from layer 1; the distance grows with depth. The slides’ annotated version reads: early layers attend to either large or narrow regions, later layers mostly to large ones.

Measured (demo 01 Part D): 11.4, 12.7 and 12.4 px for our three layers, with heads between 11.0 and 12.9, against 12.0 px for uniform attention. In a 16-patch image every head can afford to look everywhere, so no local heads emerged. This is an honest limitation of the miniature: locality pays off when there are hundreds of patches.


3. Learning image representations from text: CLIP

3.1 Motivation: labels are a narrow channel

Before CLIP, a vision encoder was pretrained to classify ImageNet: 1.28M images, 1,000 fixed classes. Two problems:

  • One label carries little information. “Cat” says nothing about the couch, the color, the second cat or the remote control. A caption written by a person says much more.
  • Labels do not scale. Hand-labeling is the bottleneck, while the web holds billions of images with alt-text.

CLIP’s goal, in the slides’ words, is a pretraining objective that learns from text and keeps improving as compute is added (Radford et al., 2021).

3.2 Why contrastive?

The obvious way to learn from captions is to generate them: an image encoder plus a language model predicting the caption. Radford et al. tried this first:

  • A Transformer caption-LM learned zero-shot ImageNet 3× more slowly than a model predicting the caption’s bag of words.
  • Replacing prediction with a contrastive objective, “which caption goes with which image in this batch?”, made it another 4× more efficient.

The intuition: generating a caption means predicting its exact words, most of which are unpredictable details of phrasing. Matching captions to images only requires knowing what distinguishes them.

3.3 The model and the loss

  • An image encoder fI(x)→zIf_I(x) \to z_I (a ResNet or a ViT) and a text encoder fT(y)→zTf_T(y) \to z_T (a Transformer; the vector at its end-of-text token), each followed by a linear projection into a shared space and L2-normalized.
  • Data: 400 million (image, text) pairs from the web.
  • For a batch of BB pairs, the logits are the scaled cosine similarities sij=fI(xi)⊤fT(yj)/τs_{ij} = f_I(x_i)^\top f_T(y_j) / \tau, and the loss is symmetric InfoNCE:

L=−12B∑n=1B[log⁡exp⁡snn∑jexp⁡sjn+log⁡exp⁡snn∑jexp⁡snj].\mathcal{L} = -\frac{1}{2B}\sum_{n=1}^{B}\left[\log \frac{\exp s_{nn}}{\sum_j \exp s_{jn}} + \log \frac{\exp s_{nn}}{\sum_j \exp s_{nj}}\right].

The first term is a softmax over images (which image matches text nn?), the second a softmax over texts. Each is a cross-entropy whose target puts all its mass on the correct pair. The loss pushes up the diagonal (matched pairs) and pushes down everything else.

  • Temperature. τ\tau is learned, initialized to 0.07, and the logit scale 1/τ1/\tau is capped at 100.
  • Batch size. CLIP trained with a batch size of 32,768. More negatives make the task harder, and the representation finer.

This is exactly Lecture 10’s dense-retriever loss, with images on one side. vit.CLIP and vit.clip_loss implement it. The self-test checks that perfect logits give a loss near 0 and uniform logits give log⁡B\log B.

3.4 Zero-shot classification and prompts

How it works. Turn each class name into a sentence (“a photo of a dog”), embed all of them with fTf_T, and classify an image by its most similar sentence. No training example of the task is used; the classifier is written in language. CLIP’s best model reached 76.2% zero-shot on ImageNet, matching the original ResNet-50 trained on all 1.28M labeled images.

Prompts matter. On the web, a label rarely appears alone; it appears in a sentence. Radford et al. report:

  • “A photo of a {label}.” added 1.3 points on ImageNet.
  • Prompt ensembling (averaging the text embeddings of 80 templates) added 3.5 more.
  • Together they gave almost 5 points.

Measured (demo 02). Our CLIP trains for 2,000 steps on 20,000 Shape World images with randomly phrased captions (get_clip(), cached in out/). Zero-shot accuracy grows like this:

step2505001,0001,5002,000
zero-shot color100%100%100%100%100%
zero-shot shape35.0%37.5%52.5%77.9%83.2%

Color is a property of single pixels and is learned at once. Shape is a property of how patches combine, the slow part for a ViT (§2.3). Prompt wording, for zero-shot shape on new one-object images:

promptzero-shot shape
“circle” (the bare label)83.9%
“a circle”83.6%
“a photo of a circle” (“photo” never appears in training)75.5%
ensemble “a red circle”, “a green circle”, …84.4%
ensemble over colors and sizes (10 prompts)85.8%

A prompt helps when it looks like the training text and hurts when it does not. “Photo” is an unseen word here, so its untrained embedding just adds noise. This is the same logic by which “A photo of a {label}.” helped real CLIP: web alt-text is full of “a photo of”.

Zero-shot vs labels (demo 02 Part B). A linear probe on the frozen CLIP features needs about 16 labeled examples per class to pass zero-shot:

linear probe on CLIP features1/class4/class16/class64/class
shape accuracy57.7%76.1%93.6%98.6%

A ViT trained from scratch on the same 256 labeled images reaches only 37.2%. Pretraining is what makes few labels enough. Radford et al. found zero-shot CLIP matching a 4-shot linear probe on average across datasets.

Limits of real CLIP. It is weak at counting, at fine-grained classes (car models, flower species), at abstract or synthetic tasks, and even at MNIST digits (88%). Zero-shot is only as good as the coverage of the web’s captions.

3.5 Measured: captions versus class labels

The slides’ argument that a description carries more than a label can be tested directly. Demo 02 Part C trains the same CLIP for 1,000 steps on captions that only name the shapes (“circle square”), like a multi-label classifier, and compares it with the caption-trained model at the same step:

text used in trainingzero-shot colorzero-shot shapeprobe color (16/class)probe shape (16/class)
captions (“a big red circle left of …”)100.0%57.1%100.0%74.9%
labels only (“circle square”)18.6%98.3%97.8%97.2%

The labels-only model cannot be asked about color: 18.6% against 20% chance. Its image features still contain color (a probe finds it 97.8% of the time), but nothing ever tied the word “red” to red pixels. A caption supervises every attribute it mentions; a label supervises one. The table also shows the price of the richer signal: captions spread the learning over many attributes, so at step 1,000 the labels-only model is far ahead on the one thing it was taught (shape 98.3% vs 57.1%).

3.6 What one vector cannot say: binding and relations

The worry. CLIP compares one image vector with one text vector. Can one vector say which attribute goes with which object, and where? Two well-known evaluations say no:

  • ARO (Yuksekgonul et al., 2023). On relations (“the horse is eating the grass” vs “the grass is eating the horse”), CLIP scored about 59%, close to the 50% chance level. On word order it was even below chance. The authors argue that contrastive pretraining on retrieval can be solved without order information, so models behave like bags of words.
  • Winoground (Thrush et al., 2022). With two images and two captions that use the same words, CLIP matches both correctly less often than chance.

Measured (demo 02 Part D). On 1,000 two-object test images, does CLIP prefer the right caption over the same words rearranged?

swapexampleprefers the right onetext cosine
colors swapped“a red square above a yellow circle” vs “a yellow square above a red circle”98.0%0.596
objects swapped“a red square above a yellow circle” vs “a yellow circle above a red square”50.5%0.997

Attribute binding works here, but relations are at chance. The text encoder all but ignores which object comes first around “above” (cosine 0.997 between the two captions).

Where did the binding come from? Where did the relation go? Demo 03 runs three experiments.

  1. Probes on the frozen image encoder. The task is which shape comes first, and whether the layout is horizontal or vertical; chance is 12.5%.

    • From the [CLS] vector, which is what CLIP compares with text: 27.3% (axis 57.1%, order 48.5%).
    • From all 16 patch vectors in grid order: 65.5% (axis 86.9%, order 70.5%).

    The pooled vector discards the arrangement. The patch vectors keep the axis well and the order only partly.

  2. Twin-free batches. Retrain CLIP so that no batch ever contains a “twin”: the same words in another arrangement. On the web, such a hard negative almost never lands in a random batch; here it did for 30.3% of batch images. Color binding survives (95.1%), so it never came from twins. Single-object captions already force conjunction features, since “a red square” must beat “a red circle” and “a blue square” in the same batch. In Shape World, an object’s color and shape also live in the same patches. Real scenes, with overlapping objects and attributes spread over regions, are harder; ARO’s attribution test puts real CLIP only modestly above chance.

  3. NegCLIP-style hard negatives. Yuksekgonul et al.’s fix is to fine-tune with swapped captions as extra negatives; on ARO this raised relations from 59% to 81%. We fine-tune our CLIP for 400 steps with the object-swapped caption of every two-object image as an extra negative. Object binding: 50.4%, against 50.3% for a control without the extra negatives. The text cosine stays at 0.998. A prototype that fine-tuned for 1,000 steps did no better.

    The likely reason is a chicken-and-egg problem. The loss rewards separating the two captions only if the image vector differs for the two arrangements, and it rewards encoding the arrangement in the image vector only if the text vectors differ. NegCLIP starts from a CLIP trained on 400M pairs, whose encoders already carry some order. Ours carries almost none.

The lesson. A contrastive model learns the distinctions its negatives demand, and nothing more. What one pooled vector cannot say is often still somewhere in the patch vectors, which is why VLMs feed all of them to the LM.

3.7 Scale and successors

Zero-shot performance in CLIP rises smoothly with pretraining compute (the slides’ scaling plot). Open replications on LAION-2B (OpenCLIP, Cherti et al., 2023) found the same power laws. SigLIP (Zhai et al., 2023) replaces the batch-wide softmax with an independent sigmoid per pair, which decouples the loss from batch size. It is the encoder of PaliGemma (§4.4). CLIP encoders became the standard “eyes” of open VLMs, together with their blind spots (§4.5).


4. Connecting a vision encoder to a language model

4.1 The general pipeline

The slides’ recipe:

  1. Image preprocessing: split into patches (and possibly crops) and vectorize.
  2. Image encoding: use a pretrained encoder (e.g. CLIP’s ViT) and take its patch vectors.
  3. Provide the encodings to an LLM: a projector (linear layer or small MLP) maps each vector to the LLM’s embedding width; these “image tokens” are placed in the input sequence like words.
  4. Train / fine-tune on data with text and images; for image positions, skip the loss (they are inputs, not predictions).
<img> v_1 … v_16 </img>  q : where is the circle ? a :  left </s>
       image tokens        question (no loss)           answer (loss)

vlm.VLM implements exactly this on top of Lecture 5’s TransformerLM. It supports four image-token modes: all 16 patch vectors, 2×2-pooled (4 tokens), [CLS] only (1 token), or none (a blind baseline).

4.2 LLaVA: two stages

LLaVA (Liu et al., 2023) connects CLIP ViT-L/14 to the Vicuna LLM through a linear projector:

  • Stage 1, feature alignment. Freeze the encoder and the LLM; train only the projector, on 595K captioned images (filtered CC3M). The image tokens learn to “speak” in the LLM’s embedding space.
  • Stage 2, visual instruction tuning. Keep the encoder frozen; train the projector and the LLM on 158K visual instructions. These are conversations, detailed descriptions and reasoning questions, generated by a text-only GPT-4 from each image’s captions and bounding boxes: Lecture 8’s synthetic-data idea applied to images.
  • Details that matter. LLaVA takes the patch vectors from the second-to-last encoder layer. LLaVA-1.5 swapped the linear projector for a two-layer MLP, raised the resolution to 336 px, and added academic VQA data.

Measured (demo 04). Our setup:

  • The frozen CLIP from demo 02.
  • An MLP projector.
  • A 2-layer LM pretrained on text only: captions, and captions followed by questions and answers.
  • 10,000 training images; 1,000 test images (about 4,500 questions).

First, what the LM brings. Reading a written caption, it answers 94.8% of questions (color 100%, where 100%, shape 79.8%). That is the stand-in for an LLM’s reading comprehension. Then the stages:

modelcolorshapecountwhereexistsall
blind: question only, trained on the questions19.5%25.2%51.0%25.3%51.1%35.5%
stage 1 only (projector trained on captions), asked directly26.7%24.7%59.6%23.3%50.4%38.5%
stage 1 model writes a caption; the text LM answers from it74.0%51.8%51.0%24.3%73.5%58.4%

Three lessons:

  • Always report a blind baseline. Without the image, priors alone score 35.5%: count and yes/no questions are coin flips. VQA benchmarks have been gamed by such priors; VQA v2 was built with balanced pairs to fight them.
  • Stage 1 alone did not teach question answering here (38.5%). The LM learned to read caption words, and image tokens tuned to produce a caption are not such words. The real LLaVA’s stage 1 is a warm-up; its question-answering ability comes from stage 2.
  • Describe-then-answer works without any question training (58.4%). The stage-1 model writes a caption, cut at its first “q” (41.9% of captions ran on into a question, the LM’s habit), and the text LM reads it. Only 33.2% of these captions name exactly the right colored shapes, so the pipeline is limited by the captioner. This is the “Socratic models” idea (Zeng et al., 2022): compose models through language.

4.3 Which image tokens? LLaVA, Molmo, [CLS]

Stage 2 (projector + LM, 1,200 steps) with three choices of image tokens:

image tokenscolorshapecountwhereexistsall
16 patch vectors, after stage 1 (LLaVA)87.0%74.6%99.9%48.6%89.6%83.5%
4 vectors: 2×2-pooled patches (Molmo)85.3%75.5%99.2%26.7%87.8%80.4%
1 vector: [CLS] (what CLIP compares)77.3%75.7%99.9%24.9%90.1%79.1%

All three answer color, shape, count and existence. They differ on where: only the full patch grid gets above chance.

Molmo (Deitke et al., 2024) shows why token counts matter at scale:

  • CLIP ViT-L/14 at 336 px gives a 24×24 grid, which 2×2 pooling reduces to 12×12 = 144 tokens per crop.
  • Molmo encodes the full image plus 12 crops (high resolution for small text and details): 13×144=1,87213 \times 144 = 1{,}872 image tokens per image (demo 01 Part A).

Pooling is a trade between sequence length and spatial detail. On a 4×4 grid, 2×2 pooling leaves 2×2 tokens, and our “where” questions fall to chance. Molmo’s other contribution is its data (PixMo): detailed human-spoken captions and pointing annotations instead of text distilled from proprietary VLMs.

4.4 Train the encoder too? PaliGemma, and models without one

PaliGemma (Beyer et al., 2024) combines a SigLIP-So400m encoder with the Gemma-2B LM through a linear projector:

  • The image and the prompt get full (prefix) attention; only the answer is generated causally.
  • Training runs in stages: multimodal pretraining, then higher resolution, then transfer.
  • The slides’ highlight: updating both the image encoder and the LM was best. A frozen encoder caps what the LM can see.

Our test was inconclusive. A prototype that unfroze our small CLIP encoder during stage 2 did worse within the same 3,000 steps (shape 73% vs 86%), and “where” stayed at chance. Fine-tuning a pretrained encoder needs care: lower learning rates, more data. It is not in the demo.

“What if we got rid of the image encoder?” Fuyu-8B (Adept, 2023) projects raw patches straight into the decoder, with no separate encoder. Lecture 12’s early-fusion models (Chameleon) go further and turn images into discrete tokens in the same vocabulary as text.

4.5 The encoder is the ceiling

Why does “where” fail with CLIP features? Demo 04 compares CLIP’s patch vectors with oracle patch features, which say which object covers each patch. The LM and the training are the same:

image tokenswhere: right answerwhere: right axisall questions
CLIP patch vectors48.6%94.1%83.5%
oracle patch features73.7%96.9%89.1%

With CLIP features, the model finds the axis 94.1% of the time, but given the axis the side only 51.6%: a coin flip. With clean features, the same LM learns the question. Trained on “where” alone, a prototype reached 98%. The bottleneck is not the LM; it is what the encoder kept. CLIP was never trained to keep where (§3.6). Its patch vectors carry the side only weakly (a linear probe recovers the order 70.5% of the time), and the VLM does not dig it out.

This is what Tong et al. (2024, Eyes Wide Shut?) found in real systems. They collected “CLIP-blind” image pairs: images CLIP embeds almost identically although they differ visibly in orientation, direction, counts, position or state. GPT-4V and LLaVA-style models answered questions about them poorly, often below chance. Adding the features of a self-supervised encoder (DINOv2) next to CLIP’s (“mixture of features”) improved visual grounding. A VLM can only reason about what its eyes report.


5. Summary

  1. ViT: an image is a sequence of patch vectors (N=HW/P2N = HW/P^2; ViT-B/16: 197 tokens, 86M parameters), embedded by a linear map (= a strided convolution) and encoded by a Transformer.
    • Data vs inductive bias. It gives up the CNN’s locality and weight sharing and pays in data: measured, 30.1% vs the CNN’s 91.3% at 2,000 images, closing to 78.5% at 32,000.
    • Positions. Without position embeddings it sees a set of patches (33.6%). Learned 1-D position embeddings rediscover the 2-D grid.
  2. CLIP: two encoders, one space, symmetric InfoNCE over a batch.
    • Zero-shot. Classification is written in language, and prompts matter (an unseen word: 85.8% → 75.5%). Measured, 16 labels per class are needed for a linear probe to pass zero-shot.
    • Captions vs labels. Captions teach every attribute they mention. Labels-only training gives 18.6% zero-shot color, at chance, although the features contain color.
  3. Binding and relations. One pooled vector loses the arrangement.
    • Measured, object-swapped captions sit at chance (50.5%), although color binding works (98.0%).
    • Patch vectors keep the axis (86.9%) and part of the order (70.5%).
    • Hard negatives did not teach relations at our scale.
  4. VLMs: encoder → projector → LLM, with no loss on image positions.
    • LLaVA: stage 1 aligns the projector on captions; stage 2 tunes projector + LLM on visual instructions.
    • Molmo: multi-crop + 2×2 pooling (1,872 tokens).
    • PaliGemma: trains everything.
  5. Read VLM numbers against baselines.
    • A blind model scores 35.5%.
    • Stage-1 alignment alone did not transfer to questions (38.5%); describe-then-answer did (58.4%).
    • “Where” is limited by the encoder: 48.6% with CLIP features vs 73.7% with oracle features. These are the “CLIP-blind” failures of Tong et al.

Common pitfalls

  • Reporting a VLM’s accuracy without a blind (text-only) baseline. Priors can be worth a third of the score.
  • Training a ViT from scratch on a small dataset. Use a pretrained encoder or a CNN. Ours memorized 2,000 images (100% train, 30% test).
  • Forgetting position embeddings, or that they are learned per index. When the resolution changes, interpolate them.
  • Using a single pooled image vector for spatial questions. It loses the arrangement; keep the patch grid.
  • Prompts unlike the training text. One unseen word cost 10 points of zero-shot accuracy.
  • Concluding “the LM can’t do X” when the encoder never encoded X. Test with better features (an oracle, a probe) before blaming the LM.
  • Default initialization for small text encoders. Huge token embeddings drown the position signal; ours made word order invisible.
  • Pooling image tokens to save sequence length without measuring what is lost. Here 2×2 pooling took “where” to chance.

Exercises

  1. Tokens and parameters. A ViT-L/14 takes 224×224×3 images. How many patch tokens does it produce? What are the shape of WeW_e (with D=1024D = 1024) and the number of tokens with [CLS]? At 336×336?

    Answer224/14 = 16 → 256 patches; a patch vector is 14·14·3 = 588 numbers, so $W_e$ is 1024 × 588; with [CLS], 257 tokens. At 336: 24×24 = 576 patches (577 with [CLS]). Self-attention cost grows with the square of the token count, so 336 px costs ~5× more attention FLOPs than 224 px.
  2. Patch embedding as convolution. Show that Conv2d(C, D, kernel_size=P, stride=P) applied to an image equals a linear map applied to each flattened patch. What happens if the stride is smaller than the kernel?

    AnswerWith stride = kernel = P, the conv's receptive fields are exactly the non-overlapping patches, and each output vector is $W \cdot \text{vec}(\text{patch}) + b$ with the same $W$ everywhere: the linear patch embedding with $W$ reshaped to (D, C, P, P). With a smaller stride, the patches overlap, giving more tokens and redundant pixels. That is a "convolutional stem", which adds some locality bias back (Xiao et al., 2021, "Early convolutions help transformers see better").
  3. Why does the ViT memorize? In demo 01, at 2,000 images the ViT reaches 100% train / 30.1% test, and the CNN 100% / 91.3%. Explain the difference in terms of the hypothesis space each model searches.

    AnswerThe CNN's functions are translation-equivariant and local by construction: a circle detector learned at one position works at every position, so 2,000 images cover the task. The ViT can represent position-specific features at every patch and must *learn* that a circle on the left is a circle on the right. With few images, many functions fit the training set, most of them position-specific, and nothing favors the generalizing one. More data removes the wrong hypotheses: 73.7% at 8,000 and 78.5% at 32,000 images.
  4. The CLIP loss. With a batch of B=4B = 4 and logits all equal, what is the loss? With the diagonal 10 above every off-diagonal logit? Why is a large batch helpful, and what does SigLIP change?

    AnswerAll equal: each softmax is uniform, loss = log 4 ≈ 1.386. Diagonal +10: each term is $-\log(e^{10}/(e^{10}+3)) = \log(1 + 3e^{-10}) \approx 1.4\times10^{-4}$. A larger batch means more negatives per positive, so the model must make finer distinctions to get the softmax right. SigLIP scores each pair independently with a sigmoid (match / no match), so it needs no batch-wide normalization and works well with smaller batches.
  5. Prompt ensembling. Why might averaging the text embeddings of “a red circle”, “a blue circle”, … classify shapes better than “a circle”? When could it hurt?

    AnswerEach prompt's embedding = the concept + noise from the particular phrasing (and here, a color). Averaging over colors cancels the color direction and the phrasing noise, leaving the shape direction, much like averaging over CLIP's 80 templates. It hurts if some templates are unnatural for the data (an unseen word adds noise to the average) or if the class is ambiguous under some templates.
  6. The chicken-and-egg of hard negatives. Our NegCLIP fine-tuning left object binding at chance. Write the gradient that would push the two captions “X left of Y” and “Y left of X” apart, and explain why it vanishes if the image embedding is the same for both arrangements.

    AnswerThe hard negative adds the term $\exp(s(x, y^-))$ to the image-to-text softmax. Its gradient on the text encoder pushes $f_T(y^-)$ away from $f_I(x)$ and pulls $f_T(y^+)$ toward it. If $f_T(y^+) \approx f_T(y^-)$ (cosine 0.997), the two pulls cancel. And if $f_I(x)$ is identical for both arrangements, then making the texts differ cannot raise $s(x, y^+) - s(x, y^-)$ for both mirrored images at once. Each encoder needs the other to have already encoded order. Pretrained encoders that already carry a little order information break the symmetry.
  7. Reading a VLM table. A paper reports 70% VQA accuracy for its model. What two numbers would you ask for before believing the model “sees”? Use demo 04’s results to justify both.

    Answer(1) A blind (question-only) model trained on the same data. Here it scored 35.5%, so half of the 83.5% is not about the image. (2) A per-question-type breakdown, ideally with a stronger-features or oracle control. Overall accuracy hid that "where" was at chance (48.6% with the axis known 94%), and oracle features showed the gap comes from the encoder (73.7%).
  • Assignment 2 (end-to-end NLP system building) is in progress. Some projects use multimodal inputs: screenshots, figures, scanned documents. If yours does:

    • Compare against a text-only baseline.
    • Check what your vision encoder keeps (a linear probe is cheap) before tuning the LM.

    These notes do not provide assignment code.

Further reading

  • A. Dosovitskiy et al., “An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale”, ICLR 2021 (course reading).
  • A. Radford et al., “Learning Transferable Visual Models From Natural Language Supervision” (CLIP), ICML 2021 (course reading).
  • H. Liu, C. Li, Q. Wu, Y. J. Lee, “Visual Instruction Tuning” (LLaVA), NeurIPS 2023; H. Liu et al., “Improved Baselines with Visual Instruction Tuning” (LLaVA-1.5), CVPR 2024.
  • M. Deitke et al., “Molmo and PixMo: Open Weights and Open Data for State-of-the-Art Vision-Language Models”, 2024; L. Beyer et al., “PaliGemma: A versatile 3B VLM for transfer”, 2024.
  • M. Yuksekgonul et al., “When and Why Vision-Language Models Behave like Bags-of-Words, and What to Do About It?”, ICLR 2023; T. Thrush et al., “Winoground”, CVPR 2022.
  • S. Tong et al., “Eyes Wide Shut? Exploring the Visual Shortcomings of Multimodal LLMs”, CVPR 2024.
  • X. Zhai et al., “Sigmoid Loss for Language Image Pre-Training” (SigLIP), ICCV 2023; M. Cherti et al., “Reproducible scaling laws for contrastive language-image learning”, CVPR 2023.
  • A. Zeng et al., “Socratic Models: Composing Zero-Shot Multimodal Reasoning with Language”, 2022; P. Lu et al., “MathVista”, ICLR 2024.
  • T. Xiao et al., “Early Convolutions Help Transformers See Better”, NeurIPS 2021.

Preview of Lecture 12 — Multimodal II

Today the image was only ever an input. Lecture 12 makes images an output:

  • Autoregressive models over pixels (PixelRNN, Image GPT) and why sequence length kills them.
  • VAEs and the VQ-VAE, which learn a tokenizer that turns an image into a short sequence of discrete codes, and a de-tokenizer that turns codes back into pixels.
  • One Transformer over text and image tokens (DALL·E, Chameleon), which generates Shape World images from captions. Today’s parse() and CLIP will judge them.

术语表 (Glossary, English → 中文)

English中文
multimodal / multi-to-text多模态 / 多模态到文本
image encoder / vision encoder图像编码器 / 视觉编码器
Vision Transformer (ViT)视觉 Transformer
patch / patch embedding图像块 / 图像块嵌入
[CLS] token分类标记
position embedding (learned, 1-D / 2-D)位置嵌入(可学习,一维 / 二维)
convolutional neural network (CNN) / strided convolution卷积神经网络 / 步幅卷积
inductive bias / locality / weight sharing / translation equivariance归纳偏置 / 局部性 / 权重共享 / 平移等变性
permutation invariance置换不变性
mean attention distance平均注意力距离
contrastive language-image pretraining (CLIP)对比式语言-图像预训练
shared embedding space共享嵌入空间
symmetric InfoNCE / temperature对称 InfoNCE / 温度
zero-shot classification零样本分类
prompt engineering / prompt ensembling提示工程 / 提示集成
linear probe / few-shot线性探测 / 少样本
attribute binding / relation / compositionality属性绑定 / 关系 / 组合性
bag of words词袋
hard negative (NegCLIP)困难负例
vision–language model (VLM) / multimodal LLM视觉语言模型 / 多模态大语言模型
projector / connector投影层 / 连接器
image tokens图像词元
feature alignment / visual instruction tuning特征对齐 / 视觉指令微调
visual question answering (VQA)视觉问答
blind baseline / language prior无图基线 / 语言先验
token pooling / multi-crop词元池化 / 多裁剪
prefix-LM attention前缀语言模型注意力
early fusion早期融合
oracle features理想特征
CLIP-blind pairs / mixture of featuresCLIP 盲对 / 特征混合
← 返回课程目录