Multimodal Models
Connecting text, images, audio and video.
Type "a dog catching a frisbee at dusk" and a search engine can return photos that nobody ever labeled with those words; show a model a chart and it will answer questions about it, sometimes describing a bar that is not there. Both behaviors rest on one move: map images, text and sound into representations that a single model can compare or attend over. This lesson covers how modalities are fused, how CLIP aligns images with text and classifies without task-specific labels, how vision–language models graft an image encoder onto a language model, and how to measure when they hallucinate.
What you’ll learn
- Compare late, early and cross-attention fusion, including what each costs and what it can precompute.
- Derive CLIP's symmetric contrastive loss and its gradient, and show that zero-shot classification is a linear classifier whose weights are text embeddings.
- Explain how Flamingo, BLIP-2 and LLaVA connect a vision encoder to a language model, and count the visual tokens each passes on.
- Measure object hallucination with CHAIR and POPE, and read POPE's metrics correctly.
Modalities, encoders and fusion
A multimodal model processes more than one kind of input. Each modality first passes through its own encoder: an image becomes patch embeddings from a vision transformer or a CNN feature map (Computer Vision), text becomes token embeddings, audio becomes frames of a spectrogram or codec tokens (Speech & Audio), and video becomes patches over space and time.
The hard part is combining them. Baltrušaitis, Ahuja and Morency (2019) list five challenges: representation, alignment (which words go with which regions), fusion, translation (generating one modality from another) and co-learning. Paired data is the fuel: web pages supply hundreds of millions to billions of image–text pairs, loosely aligned through alt-text and captions.
| Strategy | How | Cost per layer ( visual, text tokens, width ) | Strength | Examples |
|---|---|---|---|---|
| Late fusion (dual encoder) | separate encoders, combined only at the end, e.g. by a dot product of two embeddings | and inside the encoders, then per image–text pair | embeddings can be precomputed and indexed: fast retrieval over millions of items | CLIP, ALIGN |
| Early fusion | one transformer over the concatenated token sequence | every token can interact with every other from the first layer | early-fusion token models such as Chameleon (2024) | |
| Cross-attention | text tokens query visual tokens inside the language model | for the cross-attention | the language model's sequence stays short; images can be compressed first | Flamingo |
| Projection (visual prefix) | map visual features to tens or hundreds of pseudo-tokens and prepend them to the text | , with the projected count | simple; reuses a pretrained language model almost unchanged | BLIP-2, LLaVA |
A photo library holds 10 million images, and users type free-text queries. Which design answers a query fastest?
- Early fusion: run one transformer on the query concatenated with each image
- A dual encoder: embed every image once offline, then embed the query and rank images by cosine similarity
- Cross-attention from the query's tokens to every image's tokens
- Generate a caption for every image at query time and match the captions
Show the answer
B. A dual encoder: embed every image once offline, then embed the query and rank images by cosine similarity
Late fusion runs the expensive image encoder once per image, offline. A query then costs one text encoding plus 10 million dot products, which approximate nearest-neighbor indexes cut further (Prompting, Retrieval & Tool Use). Joint models need a forward pass per image–query pair, 10 million per query, so they are used to re-rank a short list instead.
Contrastive alignment: CLIP
CLIP (Radford et al., 2021) trains an image encoder and a text encoder , each followed by a linear projection into a shared -dimensional space and normalized to unit length, on about 400 million image–text pairs collected from the web. For a batch of matching pairs it computes the matrix of scaled cosine similarities and asks each image to pick out its own caption among the texts, and each caption its own image. This is contrastive learning with the InfoNCE loss of Representation Learning, applied in both directions. The paper used batches of 32,768 pairs and learned the temperature.
import torch
import torch.nn.functional as F
def clip_loss(img_emb, txt_emb, log_scale):
# img_emb, txt_emb: (N, d) projections of N matching image-text pairs
I = F.normalize(img_emb, dim=-1)
T = F.normalize(txt_emb, dim=-1)
logits = log_scale.exp() * I @ T.t() # (N, N) matrix s_ij / tau
labels = torch.arange(I.shape[0], device=I.device)
loss_img = F.cross_entropy(logits, labels) # image i must pick text i
loss_txt = F.cross_entropy(logits.t(), labels) # text i must pick image i
return (loss_img + loss_txt) / 2The learnable log_scale is ; CLIP initialized and capped the scale at 100. The other pairs in the batch are the negatives, so a larger batch makes the matching task harder.
With unit embeddings and and logits , the loss averages a row-wise and a column-wise cross-entropy:
Each logit's gradient is prediction minus target in both directions, with the softmax of row and the softmax of column . Every mismatched pair is pushed apart in proportion to how confusable it currently is:
Zero-shot classification. For classes , write one prompt per class, such as "a photo of a dog.", and embed it once, . Classify an image by a softmax over its similarities to the prompts:
That is multinomial logistic regression on the image features, with no bias and with weights written by the text encoder instead of learned from labeled images. Prompt ensembling averages the normalized embeddings of many templates per class ("a sketch of a dog.", "a close-up photo of a dog."). A linear probe instead learns from labeled features, and the prompt-built is a good place to start it.
How good is a classifier written in language? In the CLIP paper, the largest model matched the ImageNet accuracy of a supervised ResNet-50 without using any of ImageNet's 1.28 million training labels, and zero-shot classifiers matched, on average across datasets, linear probes trained on about four labeled examples per class in the same feature space. Zero-shot models also lost much less accuracy under natural distribution shifts (sketches, renditions, new photos of the same classes) than ImageNet-trained models of equal in-distribution accuracy, a large gain in effective robustness (Distribution Shift & Robustness). Later work traced most of that robustness to the diversity of the training data rather than to language supervision itself (Fang et al., 2022). ALIGN (Jia et al., 2021) showed that the recipe tolerates noise: over a billion alt-text pairs with only simple filtering trained comparable encoders.
Fusion inside a language model: cross-attention
To generate language about an image, visual information must reach the language model. Attention is the mechanism. In self-attention, queries, keys and values all come from one sequence; in cross-attention the queries come from the text tokens and the keys and values from visual tokens :
Flamingo (Alayrac et al., 2022) adds two components between a frozen vision encoder and a frozen pretrained language model. A Perceiver resampler turns any number of visual features, from one image or many video frames, into a fixed set of 64 visual tokens: 64 learned latent queries cross-attend to the visual features. Gated cross-attention layers, inserted between the frozen language-model layers, let the text tokens attend to those 64 tokens through a residual branch scaled by , where is a learnable scalar initialized at 0:
A vision transformer with patches encodes a image. How many visual tokens does it produce, not counting a class token?
Show the answer
576
, and at the same encoder gives . Doubling the resolution quadruples the tokens, and self-attention over them costs , which is why some designs compress images to a fixed few dozen tokens (Flamingo's 64, BLIP-2's 32) while others accept long visual prefixes (LLaVA).
Vision–language models: three designs
A vision–language model (VLM) is a conditional language model, , trained with next-token cross-entropy on the response tokens. Three influential designs differ in how the image becomes something the language model can read.
| Model | Visual pathway | What is trained, on what | Visual tokens per image |
|---|---|---|---|
| Flamingo (Alayrac et al., 2022) | frozen contrastively pretrained image encoder → Perceiver resampler → gated cross-attention into a frozen LM | resampler and cross-attention layers, on interleaved web pages and image–text and video–text pairs | 64 |
| BLIP-2 (Li et al., 2023) | frozen image encoder → Q-Former, a small transformer whose 32 learned queries cross-attend to the image features → linear map into a frozen LLM's input space | the Q-Former in two stages: image–text contrastive, matching and captioning losses, then generation through the frozen LLM | 32 |
| LLaVA (Liu et al., 2023) | CLIP ViT-L/14 patch features → linear projection → prepended to the LLM's token embeddings | the projection alone on 595K image–caption pairs, then projection and LLM on 158K instruction-following examples written by text-only GPT-4 from captions and object boxes | 256 at |
Visual instruction tuning was LLaVA's key idea. A language-only model, given an image's captions and box coordinates as text, wrote conversations, detailed descriptions and reasoning questions about the image, and these became supervised targets. It made instruction-following VLMs cheap to train, but it also means some targets describe details nobody checked against the pixels, one route to hallucination.
When a model sees what is not there
A model trained to produce fluent, likely text will sometimes mention objects that are absent from the image: object hallucination. Two measurements are standard.
- CHAIR (Rohrbach et al., 2018) checks generated captions against an image's object annotations. is the fraction of mentioned objects that are not in the image, and the fraction of captions with at least one such object. Longer captions mention more objects, so the scores depend on length.
- POPE (Li et al., 2023) polls the model with yes/no questions, "Is there a … in the image?". Half the questions name annotated objects; the other half name absent objects, sampled at random, from the dataset's most frequent objects ("popular"), or from objects that often co-occur with the image's objects ("adversarial"). It reports accuracy, precision, recall and F1 for "yes", plus the fraction of "yes" answers.
POPE's finding was that models hallucinate most on adversarial negatives and tend to over-answer "yes": the objects a VLM wrongly reports are disproportionately those that usually accompany what is there, like a fork beside a plate. That points to language priors and co-occurrence statistics overriding weak visual evidence, which Vision–Language Models & Grounding turns into a precise statement.
On a POPE split with equally many positive and negative questions, a VLM answers "yes" to every question. What is its F1 score for the "yes" class?
Show the answer
B.
Precision is 0.5, since half the questions are positive, and recall is 1, so , while accuracy is 0.5. An F1 above one half looks respectable for a model that never looks at the image, which is why POPE also reports accuracy and the yes-ratio: a yes-ratio far from 0.5 on a balanced split exposes the bias.
Evaluation has further traps. Many visual questions can be answered from the question alone ("What color is the banana?"), so VQA v2 paired each question with a similar image that has a different answer (Goyal et al., 2017), and a blind baseline that never sees the image belongs in any benchmark report. Benchmarks also leak into web-scale training data, and open-ended answers are increasingly scored by language-model judges with biases of their own (Evaluating Language Models).
Key takeaways
- Fusion design trades interaction for cost: dual encoders precompute embeddings for retrieval, early fusion lets all tokens interact at quadratic cost, and cross-attention costs while keeping the text sequence short.
- CLIP applies InfoNCE in both directions over an similarity matrix; zero-shot classification is logistic regression whose weights are prompt embeddings divided by .
- VLMs condition a language model on visual tokens: Flamingo through a 64-token resampler and zero-initialized gated cross-attention, BLIP-2 through a 32-query Q-Former, LLaVA through a linear projection and visual instruction tuning.
- Object hallucination is measured with CHAIR and POPE. Co-occurrence negatives are the hardest, and F1 on "yes" must be read together with accuracy and the yes-ratio.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In CLIP's zero-shot classification, what plays the role of the weight vector for class ?
- A vector learned by gradient descent on labeled images of class
- The normalized text embedding of a prompt naming class , divided by the temperature
- The average embedding of the training images of class
- A one-hot vector selecting output unit
Show the answer
B. The normalized text embedding of a prompt naming class , divided by the temperature
The logits are : a linear classifier on the image features whose -th weight vector is the prompt's embedding over . No labeled image is used. A linear probe would learn the weights from labeled features instead, and the prompt-built weights make a good initialization for it.
Flamingo's gated layers compute with initialized to 0. What does the whole model output at initialization?
- Random text, since the new layers are untrained
- A caption of the image
- Exactly the frozen language model's predictions, ignoring the images
- Nothing useful ever: the zero gate blocks every gradient
Show the answer
C. Exactly the frozen language model's predictions, ignoring the images
, so every gated layer is the identity and the network is the frozen language model. Training starts from the model's full linguistic competence instead of disrupting it with random cross-attention outputs. The gradient with respect to is not zero, so the gates open as soon as visual information lowers the loss.
Why are POPE's adversarial negatives, absent objects that often co-occur with the objects present, the hardest?
- They are smaller in the image
- They are rare words the language model hardly knows
- The questions are phrased differently
- A model that leans on co-occurrence statistics expects those objects to be present, so weak visual evidence of their absence loses to the prior
Show the answer
D. A model that leans on co-occurrence statistics expects those objects to be present, so weak visual evidence of their absence loses to the prior
The named object is absent in every split; what changes is how strongly the context predicts it. A fork is plausible beside a plate, so a model whose answers blend visual evidence with learned co-occurrence says "yes". Randomly chosen absent objects are implausible and easy to reject.
A VLM passes its visual tokens to the language model as a prefix. Raising the input resolution from to with the same patch size multiplies the number of visual tokens, and the self-attention cost over them, by which factors?
- 2 and 2
- 2 and 4
- 4 and 16
- 4 and 4
Show the answer
C. 4 and 16
The token count scales with the area, , and self-attention over tokens costs , so . That is why resamplers and Q-Formers compress images to a fixed few dozen tokens, and why high-resolution VLMs tile images and budget their tokens carefully.
Go deeper
- Contrastive Vision–Language Models · CLIP and zero-shot classification.
- Vision–Language Models & Grounding · Models that see and talk.
- World Models & Video Generation · Learning how the world evolves.
Further reading
- A. Radford et al., "Learning transferable visual models from natural language supervision," ICML (2021).
- J.-B. Alayrac et al., "Flamingo: a visual language model for few-shot learning," NeurIPS (2022).
- H. Liu, C. Li, Q. Wu & Y. J. Lee, "Visual instruction tuning," NeurIPS (2023).
- Y. Li, Y. Du, K. Zhou, J. Wang, W. X. Zhao & J.-R. Wen, "Evaluating object hallucination in large vision-language models," EMNLP (2023).