Simple Algorithm
Artificial Intelligence · Hidden Layer · 22 min

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.

StrategyHowCost per layer (MM visual, NtN_t text tokens, width dd)StrengthExamples
Late fusion (dual encoder)separate encoders, combined only at the end, e.g. by a dot product of two embeddingsO(M2d)\order{M^2d} and O(Nt2d)\order{N_t^2d} inside the encoders, then O(d)\order{d} per image–text pairembeddings can be precomputed and indexed: fast retrieval over millions of itemsCLIP, ALIGN
Early fusionone transformer over the concatenated token sequenceO((M+Nt)2d)\order{(M+N_t)^2d}every token can interact with every other from the first layerearly-fusion token models such as Chameleon (2024)
Cross-attentiontext tokens query visual tokens inside the language modelO(NtMd)\order{N_tMd} for the cross-attentionthe language model's sequence stays short; images can be compressed firstFlamingo
Projection (visual prefix)map visual features to tens or hundreds of pseudo-tokens and prepend them to the textO((M+Nt)2d)\order{(M+N_t)^2d}, with MM the projected countsimple; reuses a pretrained language model almost unchangedBLIP-2, LLaVA
Self-attention cost grows with the square of sequence length, so the number of visual tokens a design hands to the language model is one of its most consequential choices.
Check your understanding

A photo library holds 10 million images, and users type free-text queries. Which design answers a query fastest?

  1. Early fusion: run one transformer on the query concatenated with each image
  2. A dual encoder: embed every image once offline, then embed the query and rank images by cosine similarity
  3. Cross-attention from the query's tokens to every image's tokens
  4. 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 ff and a text encoder gg, each followed by a linear projection into a shared dd-dimensional space and normalized to unit length, on about 400 million image–text pairs collected from the web. For a batch of NN matching pairs it computes the N×NN\times N matrix of scaled cosine similarities and asks each image to pick out its own caption among the NN 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.

python
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) / 2

The learnable log_scale is log⁡(1/τ)\log(1/\tau); CLIP initialized τ=0.07\tau=0.07 and capped the scale 1/τ1/\tau at 100. The other pairs in the batch are the negatives, so a larger batch makes the matching task harder.

DerivationThe symmetric loss, its gradient, and the zero-shot classifier
  1. L=12N∑i=1N[−log⁡esii∑jesij−log⁡esii∑jesji]\mathcal L=\frac{1}{2N}\sum_{i=1}^N\Big[-\log\frac{e^{s_{ii}}}{\sum_je^{s_{ij}}}-\log\frac{e^{s_{ii}}}{\sum_je^{s_{ji}}}\Big]

    With unit embeddings ui=f^(xi)\mathbf u_i=\hat f(x_i) and vj=g^(tj)\mathbf v_j=\hat g(t_j) and logits sij=ui⊤vj/τs_{ij}=\mathbf u_i^\top\mathbf v_j/\tau, the loss averages a row-wise and a column-wise cross-entropy:

  2. ∂L∂sij=12N[(pij−1[i=j])+(qij−1[i=j])]\frac{\partial\mathcal L}{\partial s_{ij}}=\frac{1}{2N}\Big[\big(p_{ij}-\mathbf 1[i=j]\big)+\big(q_{ij}-\mathbf 1[i=j]\big)\Big]

    Each logit's gradient is prediction minus target in both directions, with pijp_{ij} the softmax of row ii and qijq_{ij} the softmax of column jj. Every mismatched pair is pushed apart in proportion to how confusable it currently is:

  3. p(y=k∣x)=exp⁡(wk⊤f^(x)/τ)∑k′exp⁡(wk′⊤f^(x)/τ)p(y=k\mid x)=\frac{\exp\big(\mathbf w_k^\top\hat f(x)/\tau\big)}{\sum_{k'}\exp\big(\mathbf w_{k'}^\top\hat f(x)/\tau\big)}

    Zero-shot classification. For classes 1,…,K1,\dots,K, write one prompt tkt_k per class, such as "a photo of a dog.", and embed it once, wk=g^(tk)\mathbf w_k=\hat g(t_k). Classify an image by a softmax over its similarities to the prompts:

  4. W=1τ[g^(t1)⋯g^(tK)]⊤a classifier written in languageW=\frac1\tau\begin{bmatrix}\hat g(t_1)&\cdots&\hat g(t_K)\end{bmatrix}^\top\qquad\text{a classifier written in language}

    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 WW from labeled features, and the prompt-built WW 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 Xt∈RNt×dX_t\in\R^{N_t\times d} and the keys and values from visual tokens Z∈RM×dZ\in\R^{M\times d}:

XAttn⁡(Xt,Z)=softmax⁡ ⁣((XtWQ)(ZWK)⊤dk) ZWV ∈RNt×dv\operatorname{XAttn}(X_t,Z)=\softmax\!\Big(\frac{(X_tW_Q)(ZW_K)^\top}{\sqrt{d_k}}\Big)\,ZW_V\ \in\R^{N_t\times d_v}
Each text token takes a weighted average of visual features, weighted by how well its query matches each key. The cost is O(NtMd)\order{N_tMd} per layer, and the text sequence does not get longer.

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 tanh⁡(α)\tanh(\alpha), where α\alpha is a learnable scalar initialized at 0:

y=x+tanh⁡(α) XAttn⁡(x,Z),αinit=0 ⟹ y=x\mathbf y=\mathbf x+\tanh(\alpha)\,\operatorname{XAttn}(\mathbf x,Z),\qquad\alpha_{\text{init}}=0\ \Longrightarrow\ \mathbf y=\mathbf x
At initialization every gated layer is the identity, so the model computes exactly the frozen language model's predictions; the gates open during training as visual information proves useful. A mask lets each text token attend only to the visual tokens of the most recent preceding image, so one sequence can interleave many images and texts; that is what makes few-shot prompting with image–text examples possible.
Predict before you look

A vision transformer with 14×1414\times14 patches encodes a 336×336336\times336 image. How many visual tokens does it produce, not counting a class token?

Show the answer

576

(336/14)2=242=576(336/14)^2=24^2=576, and at 224×224224\times224 the same encoder gives 162=25616^2=256. Doubling the resolution quadruples the tokens, and self-attention over them costs O(N2)\order{N^2}, 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, pθ(y1,…,yL∣image,prompt)=∏ℓpθ(yℓ∣y<ℓ,image,prompt)p_\theta(y_1,\dots,y_L\mid\text{image},\text{prompt})=\prod_\ell p_\theta(y_\ell\mid y_{<\ell},\text{image},\text{prompt}), 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.

ModelVisual pathwayWhat is trained, on whatVisual tokens per image
Flamingo (Alayrac et al., 2022)frozen contrastively pretrained image encoder → Perceiver resampler → gated cross-attention into a frozen LMresampler and cross-attention layers, on interleaved web pages and image–text and video–text pairs64
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 spacethe Q-Former in two stages: image–text contrastive, matching and captioning losses, then generation through the frozen LLM32
LLaVA (Liu et al., 2023)CLIP ViT-L/14 patch features → linear projection → prepended to the LLM's token embeddingsthe 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 boxes256 at 224×224224\times224
The trend runs from elaborate frozen machinery toward simple projections plus instruction tuning. LLaVA-1.5 (Liu et al., 2024) moved to a two-layer MLP projector at 336×336336\times336, 576 tokens per image.

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. CHAIRi\mathrm{CHAIR}_i is the fraction of mentioned objects that are not in the image, and CHAIRs\mathrm{CHAIR}_s 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.

Check your understanding

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?

  1. 0.50.5
  2. 0.670.67
  3. 11
  4. 00
Show the answer

B. 0.670.67

Precision is 0.5, since half the questions are positive, and recall is 1, so F1=2⋅0.5⋅10.5+1≈0.67F_1=\frac{2\cdot0.5\cdot1}{0.5+1}\approx0.67, 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 O(NtMd)\order{N_tMd} while keeping the text sequence short.
  • CLIP applies InfoNCE in both directions over an N×NN\times N similarity matrix; zero-shot classification is logistic regression whose weights are prompt embeddings divided by τ\tau.
  • 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.

Question 1

In CLIP's zero-shot classification, what plays the role of the weight vector for class kk?

  1. A vector learned by gradient descent on labeled images of class kk
  2. The normalized text embedding of a prompt naming class kk, divided by the temperature
  3. The average embedding of the training images of class kk
  4. A one-hot vector selecting output unit kk
Show the answer

B. The normalized text embedding of a prompt naming class kk, divided by the temperature

The logits are g^(tk)⊤f^(x)/τ\hat g(t_k)^\top\hat f(x)/\tau: a linear classifier on the image features whose kk-th weight vector is the prompt's embedding over τ\tau. 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.

Question 2

Flamingo's gated layers compute y=x+tanh⁡(α)XAttn⁡(x,Z)\mathbf y=\mathbf x+\tanh(\alpha)\operatorname{XAttn}(\mathbf x,Z) with α\alpha initialized to 0. What does the whole model output at initialization?

  1. Random text, since the new layers are untrained
  2. A caption of the image
  3. Exactly the frozen language model's predictions, ignoring the images
  4. Nothing useful ever: the zero gate blocks every gradient
Show the answer

C. Exactly the frozen language model's predictions, ignoring the images

tanh⁡(0)=0\tanh(0)=0, 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 α\alpha is not zero, so the gates open as soon as visual information lowers the loss.

Question 3

Why are POPE's adversarial negatives, absent objects that often co-occur with the objects present, the hardest?

  1. They are smaller in the image
  2. They are rare words the language model hardly knows
  3. The questions are phrased differently
  4. 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.

Question 4

A VLM passes its visual tokens to the language model as a prefix. Raising the input resolution from 224×224224\times224 to 448×448448\times448 with the same patch size multiplies the number of visual tokens, and the self-attention cost over them, by which factors?

  1. 2 and 2
  2. 2 and 4
  3. 4 and 16
  4. 4 and 4
Show the answer

C. 4 and 16

The token count scales with the area, (448/224)2=4(448/224)^2=4, and self-attention over NN tokens costs O(N2)\order{N^2}, so 42=164^2=16. 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

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