Skip to content
LearnAI

7.3Vision-language models

How a vision encoder, a small projector and an ordinary LLM combine into a model that can read your screenshot, and what every image costs in tokens.

⏱ 14 minIntermediate

From matching to talking

CLIP can tell you which caption best fits an image, but it can’t hold a conversation about it. Ask it “what’s the total on this receipt?” and it has nothing to say: it only outputs a single embedding vector. Meanwhile, large language models can reason, explain and follow instructions, but they are blind.

A vision-language modelVision-language model (VLM)A model that takes images (and text) as input, typically an image encoder connected through a projector to an LLM. (VLM) joins the two. You give it an image and some text, and it answers in text: describing a photo, reading a chart, transcribing a handwritten note, finding the bug in a screenshot of code. Under the hood, the most common recipe is surprisingly modest. Take a pretrained vision encoder and a pretrained LLM, and train a small adapter between them. This lesson is about that adapter, the training stages that make it work, and the arithmetic of how many tokens an image costs.

ANALOGY· A photographer, an interpreter and a writer

A newspaper writer needs to describe a scene she can’t visit. A photographer goes instead and comes back with detailed notes written in his own shorthand. The writer can’t read shorthand, so an interpreter rewrites the notes, sentence by sentence, in the writer’s language. The writer then answers the editor’s questions using those notes as if they were her own observations.

The photographer is the vision encoder: it already knows how to see. The interpreter is the projector, a small trained module that converts one representation into another. The writer is the LLM, which never sees the scene itself, only the interpreted notes. Make the interpreter summarize too much and details are lost; translate every word and the writer drowns in pages.

The three-part architecture

1. Vision encoder. Almost always a Vision Transformer, pretrained contrastively as in CLIP or SigLIP. Popular choices include CLIP ViT-L/14 and SigLIP So400m/14. The VLM keeps all the patch outputs (one vector per patch), not just one pooled summary, because questions like “what’s written in the top-right corner?” need spatial detail. A 336×336 image through a /14 encoder gives 24×24=57624 \times 24 = 576 patch vectors.

2. Projector. The vision encoder’s vectors live in its own space with its own width (1,024 for ViT-L). The LLM expects vectors in its embedding space, say 4,096 wide. The projectorProjector (vision-language connector)The module that turns vision-encoder outputs into vectors the LLM can consume: a linear layer or MLP, a Q-Former/resampler, or cross-attention layers. bridges the gap. There are three main styles:

  • Linear layer or MLP (LLaVA). Each patch vector goes through a linear map (LLaVA) or a two-layer MLP (LLaVA-1.5) and becomes one LLM token. Simple, and it preserves every patch, at the price of many tokens. A variant used by Qwen2-VL first concatenates each 2×2 group of neighboring patches and then applies an MLP, cutting the count by 4×.
  • Q-Former / resampler (BLIP-2). A small Transformer holds a fixed set of learned query vectors, 32 in BLIP-2. The queries cross-attend to the image features and come out as 32 tokens, regardless of how many patches went in. That’s a strong compression, but fine details such as small text can get squeezed out.
  • Cross-attention into the LLM (Flamingo). The image never enters the token sequence. Instead, new cross-attention layers are inserted between the frozen LLM’s layers, so text tokens can “look at” the image features directly. Flamingo first compresses each image to 64 vectors with a Perceiver Resampler, and gates each new layer with a tanh gate initialized at zero. At the start of training the LLM therefore behaves exactly as before, and the gates open gradually.

3. LLM. A standard decoder-only language model. With the first two projector styles, the projected image vectors are spliced into the sequence of token embeddings, usually between special image-start and image-end marker tokens, and the LLM processes them like any other tokens. To the LLM, an image is a run of a few hundred “words” that don’t come from its vocabulary.

INTERACTIVEVLM architecture builder
Vision encoder
Projector
Resolution
① Image → patches1024×7681 crop · 576 patches of 14px
② Vision encoderCLIP ViT-L/14 @336576 patch vectors out, 1024-d each
③ ProjectorMLPLLaVA-1.5 style: one LLM token per patch
④ Into the LLM578image tokens in the sequence (incl. 2 boundary markers)≈ 1,365 original pixels per token
LLM input sequence (596 tokens; each square = 3 tokens)
text tokens (18)image tokens (578)
Context consumed by this one image + question596 / 32,768 (1.8%)
About 54 image(s) like this fit, leaving 1K tokens for text. Squash the whole image to the encoder’s native square resolution.
Choose a vision encoder, a projector and a resolution strategy, then pick an input image. The flow animates from patches to visual tokens to the LLM's input sequence, with a live count of image tokens and how much of the context window one image uses.

Things to try:

  1. CLIP ViT-L/14 @336, MLP, fixed resize. The LLaVA-1.5 recipe: every image costs 576 tokens (plus 2 markers), whether it’s a tiny icon or a full-page document squashed to 336×336.
  2. Switch the projector to Q-Former. The cost drops to 32 tokens per crop. Then think about the document page: 2,200 pixels of height summarized into 32 vectors.
  3. Pick the document page with tiling (AnyRes). The page is cut into encoder-sized tiles plus an overview image. Detail is preserved, but the token count multiplies.
  4. Dynamic resolution with MLP + 2×2 merge. This is the Qwen2-VL style. A 1920×1080 screenshot becomes about 2,700 tokens. Try the 8K context: one screenshot uses a third of it.
  5. Cross-attention. Zero image tokens in the sequence. The cost moves elsewhere: every cross-attention layer reads all the image features, and the new layers add parameters.

Training in stages

Gluing pretrained parts together needs a careful order, otherwise the randomly initialized projector sends garbage into the LLM and the LLM’s language skills can be damaged. The LLaVA recipe, which many open models adapted, uses two stages.

Stage 1: alignment pretraining. Freeze the vision encoder and the LLM. Train only the projector on plain image–caption pairs: the LLM must produce the caption given the image tokens. LLaVA used about 595,000 filtered image–caption pairs. The projector learns to translate “vision-speak” into vectors the LLM already understands, while nothing else changes.

Stage 2: visual instruction tuningVisual instruction tuningFine-tuning a vision-language model on image+instruction→answer examples so it follows requests about images, introduced by LLaVA.. Unfreeze the LLM (and keep training the projector). Train on conversations about images: “What’s unusual about this picture?”, “Extract the table as CSV”, multi-turn dialogues. LLaVA’s key trick was generating about 158,000 such examples with GPT-4, which only saw text descriptions of images (captions and bounding boxes), not the images themselves. This is the multimodal version of instruction tuning.

Modern VLMs extend this recipe: they also unfreeze the vision encoder, add a large stage of interleaved image–text documents, and mix in OCR, charts, video and grounding data. Some recent model families go further and train on images and text together from the start of pretraining, rather than bolting vision onto a finished LLM.

Resolution: the hardest trade-off

A fixed 336×336 input is fine for “is there a dog in this photo?” It is terrible for a scanned contract. Shrinking a 1700×2200 page to 336×336 scales it down about 6.5-fold, so lowercase letters end up only two or three pixels tall, far below what any encoder can read. There are three common strategies:

  • Fixed resize. Simple and cheap, but loses detail and distorts aspect ratio.
  • Tiling (“AnyRes”). Popularized by LLaVA-NeXT: pick a grid of encoder-sized tiles that fits the image’s aspect ratio, encode each tile separately, and add one downscaled overview image for global context. Detail survives, but tokens multiply with the number of tiles.
  • Dynamic (native) resolution. Encode the image at close to its real size and aspect ratio as one variable-size grid of patches. Qwen2-VL did this with 2D rotary position embeddings in its ViT. A 224×224 image costs 66 tokens there (64 plus 2 markers), while a large screenshot can cost thousands. Implementations cap the total with configurable minimum and maximum pixel limits.

What an image costs

Image tokens aren’t free. Each one goes through every LLM layer during prefill, and each one occupies KV cache memory for the rest of the conversation. Rough figures for a few setups:

setuptokens per image
ViT + Q-Former (BLIP-2 style)32
CLIP ViT-L/14 @336 + MLP (LLaVA-1.5)576
AnyRes, 2×2 tiles + overview, 576 eachabout 2,880
Dynamic res + 2×2 merge, 1920×1080 screenshotabout 2,700

Video multiplies all of this by the number of sampled frames, which is why video VLMs sample sparsely and merge tokens across neighboring frames. A whole research area is devoted to token compression: pooling, merging similar tokens, or dropping tokens the model doesn’t attend to.

Reading documents, charts and screens

High-resolution VLMs have absorbed much of what used to be a separate OCR pipeline. Rather than “detect text boxes, run OCR, feed text to an LLM”, a single model reads the page image and answers questions about it. It can follow tables, charts, handwriting, math notation and user interfaces, which is the foundation of “computer use” agents that act on screenshots.

The failure modes are worth knowing. VLMs can hallucinate text that looks plausible but isn’t on the page, especially when text is small relative to patch size. They are often weak at counting objects and at precise spatial relations (“is the cup left of the plate?”). They may also describe objects that commonly co-occur with the scene but aren’t actually present, a known problem called object hallucination. More pixels per character helps with the first; better training data helps with the rest.

A few landmark models

  • Flamingo (DeepMind, 2022) introduced interleaved image–text prompting with a frozen LLM and gated cross-attention layers, and showed strong few-shot performance.
  • BLIP-2 (Salesforce, 2023) connected frozen encoders and LLMs with a lightweight Q-Former.
  • LLaVA (2023) and LLaVA-1.5 made the simple “CLIP encoder + MLP + open LLM + visual instruction tuning” recipe the default open baseline. LLaVA-NeXT added AnyRes tiling.
  • The Qwen-VL series (Alibaba): Qwen-VL (2023), Qwen2-VL (2024, dynamic resolution and multimodal rotary position embeddings), Qwen2.5-VL and Qwen3-VL. The later models come in a range of dense and mixture-of-experts sizes and support long contexts suitable for video and long documents; see the Qwen deep dive for details.
MATH CORNER · optionalProjector math and the token budget

Let the vision encoder output Zv∈RN×dvZ_v \in \mathbb{R}^{N \times d_v} (NN patches). The LLaVA-1.5 projector is a two-layer MLP:

Hv=W2 GELU(W1Zv⊤) ,W1∈Rd×dv,  W2∈Rd×d,H_v = W_2\, \mathrm{GELU}(W_1 Z_v^\top)\,, \qquad W_1 \in \mathbb{R}^{d \times d_v},\; W_2 \in \mathbb{R}^{d \times d},

giving NN visual tokens of LLM width dd. A Q-Former-style resampler instead uses MM learned queries Q∈RM×dqQ \in \mathbb{R}^{M \times d_q} and cross-attention,

Hv=softmax ⁣(QWQ(ZvWK)⊤dk)ZvWV,H_v = \mathrm{softmax}\!\left(\frac{Q W_Q (Z_v W_K)^\top}{\sqrt{d_k}}\right) Z_v W_V ,

so the output has MM rows no matter how large NN is. (In BLIP-2 this happens inside a small Transformer, followed by a linear projection to the LLM width.)

Worked example: token count and KV-cache cost. Assume a 7B-class LLM with 32 layers, hidden size 4,096, standard multi-head attention and 16-bit values. Each token stores a key and a value per layer:

2×32×4096×2 bytes=524,288 bytes=0.5 MiB per token.2 \times 32 \times 4096 \times 2\ \text{bytes} = 524{,}288\ \text{bytes} = 0.5\ \text{MiB per token}.
image setupvisual tokensKV cache for the image
336² + MLP (576 patches)576288 MiB
336² + Q-Former3216 MiB
1920×1080, patch 14, 2×2 merge⌈1920/28⌉×⌈1080/28⌉=69×39=2,691\lceil 1920/28 \rceil \times \lceil 1080/28 \rceil = 69 \times 39 = 2{,}691about 1.3 GiB

Ten screenshots in one chat would need about 13 GiB of KV cache for this model, before a single word of text. Models with grouped-query attention shrink this several-fold, but the proportions remain: image tokens often dominate a multimodal context.

In code

Here is the heart of a LLaVA-style forward pass. Real implementations add batching, multiple images and attention masks, but the splice is the key idea:

import torch, torch.nn as nn

class TinyVLM(nn.Module):
    def __init__(self, vision_encoder, llm, d_vision=1024, d_llm=4096):
        super().__init__()
        self.vision = vision_encoder            # e.g. a CLIP ViT-L/14, often frozen
        self.llm = llm                          # a decoder-only LLM
        self.projector = nn.Sequential(         # LLaVA-1.5 style 2-layer MLP
            nn.Linear(d_vision, d_llm), nn.GELU(), nn.Linear(d_llm, d_llm))

    def forward(self, pixels, ids_before, ids_after):
        patches = self.vision(pixels)           # (B, 576, 1024): all patch outputs
        img_tok = self.projector(patches)       # (B, 576, 4096): "visual tokens"
        emb = self.llm.embed_tokens             # the LLM's normal embedding table
        seq = torch.cat([emb(ids_before), img_tok, emb(ids_after)], dim=1)
        return self.llm(inputs_embeds=seq)      # predicts the next *text* token

# Stage 1: freeze vision + llm, train only projector on captions.
# Stage 2: unfreeze llm (and projector) for visual instruction tuning.
COMMON MISCONCEPTIONS
  • “The LLM looks at the image.” The LLM only ever sees projected vectors, the interpreter’s notes. Anything the encoder didn’t capture, or the projector compressed away, is invisible to it.
  • “Image tokens are words from the vocabulary.” In encoder-plus-projector VLMs they are continuous vectors inserted directly into the embedding sequence. Only some early-fusion models turn images into discrete vocabulary tokens.
  • “More image tokens is always better.” More tokens preserve detail, but cost prefill compute and KV-cache memory, and they can crowd out text context. Good systems spend tokens where the task needs them, for example on documents rather than icons.
  • “VLMs read text as reliably as an OCR engine.” They often read well, but they can confidently produce text that isn’t there, especially at low resolution. For high-stakes extraction, verify the output.

Check your understanding

0/5 answered
  1. Q1.What is the job of the projector in a LLaVA-style VLM?

  2. Q2.A VLM uses a Q-Former with 32 learned queries. The input image yields 729 patch vectors. How many visual tokens reach the LLM?

  3. Q3.Why does LLaVA's first training stage freeze both the vision encoder and the LLM?

  4. Q4.Your VLM misreads small text in full-page document scans. Which change most directly addresses this?

  5. Q5.In a Flamingo-style model, how do images enter the language model?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.