Simple Algorithm
Artificial Intelligence · Deep Layer · 26 min

Vision–Language Models & Grounding

Models that see and talk.

A vision–language model is a language model that has learned to read a few dozen to a few thousand extra "words" produced by an image encoder. Where those words come from, how many there are and how they are trained determine what the model can see, what it costs to run, and how often it describes objects that are not there.

What you’ll learn

  • Formalize a VLM as a conditional language model, compare prefix, cross-attention and query-bottleneck designs, and prove that masked self-attention over the concatenated sequence computes cross-attention exactly.
  • Explain Flamingo's resampler and zero-initialized gates (including which parameters receive gradient at the first step), BLIP-2's two-stage Q-Former training, and LLaVA's visual instruction tuning.
  • Describe grounding with location tokens, and bound the IoU lost to coordinate quantization.
  • Model object hallucination as prior dominance, and evaluate it with CHAIR and POPE while avoiding blind-baseline and contamination pitfalls.

Architectures as conditional language models

DerivationProof, and what each choice costs
  1. outi=∑j=1Mexp⁡(xiWQ(zjWK)⊤/dk)∑j′=1Mexp⁡(xiWQ(zj′WK)⊤/dk) zjWV=XAttn⁡(X;Z)i\mathrm{out}_i=\sum_{j=1}^{M}\frac{\exp\big(x_iW_Q(z_jW_K)^\top/\sqrt{d_k}\big)}{\sum_{j'=1}^{M}\exp\big(x_iW_Q(z_{j'}W_K)^\top/\sqrt{d_k}\big)}\,z_jW_V=\operatorname{XAttn}(X;Z)_i

    At text position ii, masked self-attention takes a softmax over the allowed keys only. Under the mask these are the visual positions j=1,…,Mj=1,\dots,M, with keys zjWKz_jW_K and values zjWVz_jW_V:

  2. O((M+L)2d)⏟prefix or early fusionO(MLd)+O(L2d)⏟cross-attentionO(KMd) once + O(KLd)⏟resampler, then cross-attention\underbrace{\order{(M+L)^2d}}_{\text{prefix or early fusion}}\qquad\underbrace{\order{MLd}+\order{L^2d}}_{\text{cross-attention}}\qquad\underbrace{\order{KMd}\ \text{once}\ +\ \order{KLd}}_{\text{resampler, then cross-attention}}

    So prefix designs (LLaVA, early fusion) are at least as expressive per layer as cross-attention designs given the same visual tokens. An ordinary decoder lets text attend to visual tokens and earlier text in one softmax, mixing the two, and two layers can separate them. The real difference is cost. Per layer, with LL text tokens and a resampler of KK latents:

  3. Prefix designs also spend the language model's context on images, while cross-attention keeps the context for text but needs new layers inside the model. Resolution multiplies the prefix: tiling a 672×672672\times672 image into four 336×336336\times336 crops plus a downscaled view of the whole, each encoded into 24×2424\times24 patches, gives 5×576=2,8805\times576=2{,}880 visual tokens, 25 times the attention cost of a single view's 576.

Training recipes: Flamingo, BLIP-2, LLaVA

Flamingo (Alayrac et al., 2022). The Perceiver resampler's K=64K=64 learned latents attend, layer by layer, to the concatenation of the visual features (with learned temporal embeddings for video frames) and the latents themselves, followed by feed-forward layers, so any number of frames becomes a fixed 64 tokens. Gated blocks, each a gated cross-attention sublayer followed by a gated feed-forward sublayer, are inserted between frozen layers of the language model, and a per-image mask restricts each text token to the visual tokens of the most recent preceding image.

Proof. (i) tanh⁡0=0\tanh0=0, so every block is the identity. (ii) ∂y/∂ϕ=tanh⁡(α) ∂g/∂ϕ=0\partial\mathbf y/\partial\phi=\tanh(\alpha)\,\partial g/\partial\phi=0 at α=0\alpha=0, while ∂y/∂α=(1−tanh⁡2α) g=g\partial\mathbf y/\partial\alpha=(1-\tanh^2\alpha)\,g=g. The gates therefore move first, and the branches start learning from the next step on, in a model that still has all of the frozen language model's competence.

BLIP-2 (Li et al., 2023). The Q-Former is a BERT-sized transformer with 32 learned query embeddings that cross-attend to a frozen image encoder's features. Stage one trains it without any language model, with three losses that share the queries but use different self-attention masks: image–text contrastive learning (queries and text cannot see each other), image–text matching (a binary classifier over fully mixed queries and text, trained with hard negatives), and image-grounded text generation (text tokens see the queries; queries cannot see the text). Stage two passes the 32 query outputs through a linear layer into a frozen LLM as soft visual prompts and trains on generation. The 32-token bottleneck forces the Q-Former to keep the visual information that text can use.

LLaVA (Liu et al., 2023). A CLIP ViT-L/14 supplies patch features and a projection WW maps each into the LLM's embedding space. Stage one trains only WW, on 595K image–caption pairs filtered from CC3M. Stage two trains WW and the LLM on 158K instruction-following examples (58K conversations, 23K detailed descriptions, 77K complex-reasoning questions) that text-only GPT-4 wrote from COCO captions and boxes. LLaVA-1.5 (Liu et al., 2024) replaced WW by a two-layer MLP, raised the resolution to 336 pixels and added academic VQA data, a simple recipe that became a common baseline.

Check your understanding

At Flamingo's first training step, with every gate at α=0\alpha=0, which parameters receive a nonzero gradient?

  1. All new parameters: the resampler, the cross-attention layers and the gates
  2. Only the frozen language model
  3. Only the gates α\alpha
  4. None, so training cannot start
Show the answer

C. Only the gates α\alpha

Every new branch is multiplied by tanh⁡(α)=0\tanh(\alpha)=0, so its parameters, and the resampler that feeds it, get zero gradient. The derivative with respect to α\alpha pairs the branch's output with the upstream gradient and is generally nonzero, so the gates open first and the branches learn from the next step on. The language model is frozen by design.

Grounding: pointing with tokens

Grounding ties language to image regions. The standard tasks are referring expression comprehension, finding the box for "the man on the left holding a cup" (RefCOCO, RefCOCO+ and RefCOCOg; Kazemzadeh et al., 2014; Yu et al., 2016; Mao et al., 2016), scored as accuracy at IoU ≥0.5\ge0.5; phrase grounding, a box for every noun phrase of a caption; and grounded captioning. Two designs dominate. Detection-style models align words with region features: GLIP (Li et al., 2022) recasts detection as phrase grounding with a word–region contrastive loss. Generative VLMs instead write coordinates as tokens: Pix2Seq (Chen et al., 2022) quantizes each coordinate into bins, and Kosmos-2 (Peng et al., 2023) uses a 32×3232\times32 grid of location tokens and names a box by its top-left and bottom-right cells.

DerivationProof
  1. ∣A∩A^∣ ≥ (w−2δ)(h−2δ)\lvert A\cap\hat A\rvert\ \ge\ (w-2\delta)(h-2\delta)

    No edge moves inward by more than δ\delta, so both boxes contain the true box shrunk by δ\delta on every side, and so does their intersection:

  2. ∣A∪A^∣ ≤ (w+2δ)(h+2δ)\lvert A\cup\hat A\rvert\ \le\ (w+2\delta)(h+2\delta)

    No edge moves outward by more than δ\delta, so both boxes, and their union, lie inside the true box grown by δ\delta on every side:

  3. B=32, w=h=0.1:IoU ≥ (0.1−1320.1+132)2≈0.27B=32,\ w=h=0.1:\qquad\mathrm{IoU}\ \ge\ \Big(\frac{0.1-\tfrac{1}{32}}{0.1+\tfrac{1}{32}}\Big)^2\approx0.27

    Divide. With B=1000B=1000 bins the loss is negligible. With Kosmos-2's 32 cells per axis, δ=1/64\delta=1/64, a box spanning 20% of each side is only guaranteed an IoU of about 0.530.53, and one spanning 10% only 0.270.27: coarse location tokens can cap small-object accuracy before any learning error enters.

Predict before you look

With B=100B=100 bins per axis, what IoU does the bound guarantee for a box spanning 20% of the image's width and 20% of its height?

Show the answer

0.82

δ=1/200=0.005\delta=1/200=0.005, so the bound is (0.2−0.010.2+0.01)2=(0.19/0.21)2≈0.82\big(\frac{0.2-0.01}{0.2+0.01}\big)^2=(0.19/0.21)^2\approx0.82. The error per edge is fixed in absolute terms, so the relative damage grows as boxes shrink: the same grid guarantees only (0.04/0.06)2≈0.44(0.04/0.06)^2\approx0.44 for a box spanning 5%.

Hallucination: priors against pixels

DerivationProof, and a worked number
  1. Pr⁡(O=1∣V,C)Pr⁡(O=0∣V,C)=p(V∣O=1)p(V∣O=0)⋅p(C∣O=1)Pr⁡(O=1)p(C∣O=0)Pr⁡(O=0)=p(V∣O=1)p(V∣O=0)⋅Pr⁡(O=1∣C)Pr⁡(O=0∣C)\frac{\Pr(O=1\mid V,C)}{\Pr(O=0\mid V,C)}=\frac{p(V\mid O=1)}{p(V\mid O=0)}\cdot\frac{p(C\mid O=1)\Pr(O=1)}{p(C\mid O=0)\Pr(O=0)}=\frac{p(V\mid O=1)}{p(V\mid O=0)}\cdot\frac{\Pr(O=1\mid C)}{\Pr(O=0\mid C)}

    Bayes' rule with p(V,C∣O)=p(V∣O) p(C∣O)p(V,C\mid O)=p(V\mid O)\,p(C\mid O), then Bayes' rule again for the context term:

  2. posterior log-odds=−0.69+1.39=0.69>0⟹"yes, there is a fork"\text{posterior log-odds}=-0.69+1.39=0.69>0\quad\Longrightarrow\quad\text{"yes, there is a fork"}

    Take logs. A dining table with plates makes a fork likely, say Pr⁡(fork∣C)=0.8\Pr(\text{fork}\mid C)=0.8, prior log-odds log⁡4≈1.39\log4\approx1.39. If the fork is absent but the relevant region is small and blurry, the visual evidence may favor absence by a likelihood ratio of only 2, Λ=−log⁡2≈−0.69\Lambda=-\log2\approx-0.69:

  3. Even an ideal reader hallucinates here, and a real model whose visual tokens blur small objects, or whose language model weighs context more than an ideal reader would, does so more often. The model predicts what POPE measures: errors concentrate on co-occurring (adversarial) negatives, where the contextual prior is high, and fall when the visual evidence sharpens, for instance at higher resolution.

Measuring it. CHAIR (Rohrbach et al., 2018) parses generated captions for objects from a fixed vocabulary (the 80 COCO categories with synonyms) and reports CHAIRi\mathrm{CHAIR}_i, the fraction of mentioned objects that are absent, and CHAIRs\mathrm{CHAIR}_s, the fraction of captions with at least one; both depend on caption length and vocabulary coverage. POPE (Li et al., 2023) turns the question into balanced yes/no polling with random, popular and adversarial negatives, so yes-ratio, accuracy and F1 can be compared across models. POPE measures recognition of objects named in the question, not what a model volunteers when generating freely, so the two metrics complement each other.

Mitigating it acts on the two terms. Higher resolution and better visual tokens strengthen Λ\Lambda. Cleaning training data removes targets that mention unseen objects. Preference optimization on judgments of faithful versus hallucinated answers (LLaVA-RLHF; Sun et al., 2023) teaches the model to weigh evidence. Decoding-time methods compare predictions given the image with predictions given a distorted version of it, and penalize tokens that the language prior alone would produce (visual contrastive decoding; Leng et al., 2024).

Evaluating honestly needs the same care as for language models: report a blind baseline that answers without the image, since many questions can be answered from priors (Goyal et al., 2017, rebalanced VQA for exactly this reason); check benchmarks for contamination by web-scale training data; and treat language-model judges as instruments with their own biases (Evaluating Language Models).

Key takeaways

  • A VLM is a language model conditioned on visual tokens. Masked self-attention over the concatenated sequence computes cross-attention exactly, so the design choice is mainly about cost, context and training stability.
  • Flamingo's zero-initialized tanh⁡\tanh gates reproduce the frozen language model at initialization, and only the gates receive gradient at the first step; BLIP-2 compresses images to 32 query tokens through two-stage Q-Former training; LLaVA projects patch features and relies on visual instruction tuning.
  • Location tokens make grounding generative, but with BB bins the guaranteed IoU is (w−2δ)(h−2δ)(w+2δ)(h+2δ)\frac{(w-2\delta)(h-2\delta)}{(w+2\delta)(h+2\delta)} with δ=1/(2B)\delta=1/(2B), which hurts small objects most.
  • Hallucination can be modeled as visual evidence losing to a contextual prior; it concentrates on co-occurring objects, is measured by CHAIR and POPE, and must be evaluated with blind baselines and contamination checks.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Compared with a cross-attention design that uses the same MM visual tokens, a prefix design (visual tokens prepended to the text) is:

  1. less expressive, because self-attention cannot reproduce cross-attention
  2. cheaper, because it adds no new layers
  3. unable to handle more than one image
  4. at least as expressive per layer, but its attention cost grows like (M+L)2(M+L)^2 and the images consume context
Show the answer

D. at least as expressive per layer, but its attention cost grows like (M+L)2(M+L)^2 and the images consume context

With a mask restricting text positions to visual keys, masked self-attention over [Z;X][Z;X] computes cross-attention exactly, so expressivity is not lost. What changes is cost: quadratic in the combined length, plus context consumed by visual tokens. Cross-attention costs O(MLd)\order{MLd} per layer but adds layers to the language model.

Question 2

Why do coarse location tokens hurt small objects most?

  1. Small objects have fewer pixels for the encoder to see
  2. Quantization moves each edge by up to a fixed absolute amount δ\delta, which is a large fraction of a small box, so the guaranteed IoU (w−2δ)(h−2δ)(w+2δ)(h+2δ)\frac{(w-2\delta)(h-2\delta)}{(w+2\delta)(h+2\delta)} drops as ww and hh shrink
  3. Location tokens cannot represent boxes near the image border
  4. IoU is undefined for small boxes
Show the answer

B. Quantization moves each edge by up to a fixed absolute amount δ\delta, which is a large fraction of a small box, so the guaranteed IoU (w−2δ)(h−2δ)(w+2δ)(h+2δ)\frac{(w-2\delta)(h-2\delta)}{(w+2\delta)(h+2\delta)} drops as ww and hh shrink

The rounding error per edge depends only on the bin width, not on the box. For a large box it is negligible; for a box a few bins wide it can halve the IoU, so a 32-bin grid guarantees only about 0.27 for a box spanning 10% of each side.

Question 3

In the prior-dominance model, which change reduces hallucinations on co-occurring objects without changing the contextual prior?

  1. Training on captions that mention more objects
  2. Sharper visual evidence, such as higher-resolution features, so that ∣Λ(V)∣\abs{\Lambda(V)} grows for absent objects
  3. A higher sampling temperature
  4. Asking the question twice
Show the answer

B. Sharper visual evidence, such as higher-resolution features, so that ∣Λ(V)∣\abs{\Lambda(V)} grows for absent objects

The model says "yes" to an absent object when Λ(V)+prior>0\Lambda(V)+\text{prior}>0. With the prior fixed, only stronger evidence of absence, a more negative Λ\Lambda, flips the answer; higher resolution and better visual tokens aim to provide exactly that.

Question 4

A VLM is prompted to write longer, more detailed captions. Its CHAIRs\mathrm{CHAIR}_s rises while its POPE accuracy is unchanged. What is the most likely explanation?

  1. The model's perception got worse
  2. POPE is broken
  3. Longer captions mention more objects, giving more chances to name an absent one, while POPE measures recognition of named objects, which the prompt did not change
  4. CHAIR ignores caption length
Show the answer

C. Longer captions mention more objects, giving more chances to name an absent one, while POPE measures recognition of named objects, which the prompt did not change

CHAIRs\mathrm{CHAIR}_s counts captions with at least one hallucinated object, and every extra mention is another chance to hallucinate, so it grows with length even at constant per-object accuracy. POPE polls fixed questions, so it is insensitive to how verbose free generation is. The two metrics measure different behaviors.

Further reading

  • J.-B. Alayrac et al., "Flamingo: a visual language model for few-shot learning," NeurIPS (2022).
  • J. Li, D. Li, S. Savarese & S. Hoi, "BLIP-2: bootstrapping language-image pre-training with frozen image encoders and large language models," ICML (2023).
  • 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).
  • Z. Gan, L. Li, C. Li, L. Wang, Z. Liu & J. Gao, "Vision-language pre-training: basics, recent advances, and future trends," Foundations and Trends in Computer Graphics and Vision (2022).