Module 26 · Part VII · Beyond Text
Vision-Language Models
Connectors, High-Resolution Tiling, 2D Positions, and Training on Images and Text Together
By the end you can build the input sequence of a VLM and train it correctly.
Check yourself ▸
Before you start, can you already…
- ☐turn an image into tokens, and explain how image and text encoders are aligned. (Module 25)
If any is shaky, the linked module teaches it.
Many real inputs are images: photos, scanned documents, charts, screenshots, video frames. A vision-language model (VLM) takes images and text together and answers in text. The idea throughout: once an image is a list of vectors of the right width, a transformer treats it like any other sequence. This module connects a ViT (section 25.2) to a language model (26.1), handles large images without running out of tokens (26.2 and 26.3), and trains the combination (26.4).
26.1 Connecting Vision to LanguageRun this section
A VLM usually joins a separately trained vision encoder, often a CLIP or SigLIP ViT (section 25.3) whose vectors already relate to words, and a decoder-only language model such as LLaMA, Gemma or Qwen. The encoder's vectors have their own width (not attention's value width ); the language model expects vectors of width that look like its token embeddings. A small trained connector converts one into the other.
In words. The vision encoder turns the image into vectors; the connector turns them into vectors the language model reads like token embeddings, alongside the text prompt.
Three Kinds of Connector
1. Linear or 2-Layer MLP Projection (LLaVA Style)
The simplest connector maps each image vector on its own. LLaVA (Liu et al., 2023) used a single matrix; LLaVA-1.5 uses a 2-layer MLP with GELU:
With and , each row changes width but the row count stays: . It is simple and keeps every detail, but every patch takes a token position: to per image for common encoders.
2. Perceiver Resampler / Q-Former (Flamingo & BLIP-2)
This connector outputs a fixed number of tokens however many patches go in. learned queries ( in Flamingo) cross-attend (section 8.1) to the image vectors, which supply the keys and values:
Each query gives one output, so hundreds of patches become tokens. Real resamplers stack several such layers with feed-forward networks.
3. Spatial Patch Merging / Pixel Unshuffle
A middle option: concatenate each block of neighboring patch vectors into width and map that to . The count drops (), and the grid keeps its shape, coarser: becomes .
The vision encoder produces a grid of patch vectors. Each connector turns them into a different number of tokens for the language model.
With a 32 × 32 patch grid, predict which connectors still fit comfortably in a 4,096-token context alongside a long prompt.
In words. For a chosen patch grid, each connector's token count as a bar against a four-thousand-token context, with what each keeps or loses.
26.2 High Resolution: AnyRes TilingRun this section
Documents, screenshots and diagrams need high resolution. A image in patches gives tokens, more than the whole 4,096-token context early VLMs such as LLaVA-1.5 were built on, and the ViT was trained at a fixed size such as . LLaVA-NeXT and InternVL use tiling (LLaVA-NeXT's AnyRes): encode a grid of tiles matching the image's shape at the ViT's own size, plus a shrunken copy of the whole image.
In words. The shrunken overview tile gives the layout; the full-size tiles give the detail. All their tokens are joined in order, with separators at the end of each grid row.
Seven tiles cost seven times a single tile's tokens, which is why tiling is often combined with patch merging.
The image is covered by a grid of 336 × 336 tiles chosen to match its shape, and a shrunken copy of the whole image is encoded too.
A wide 1008 × 336 image and a square 672 × 672 image hold the same number of pixels. Before trying them, predict which tile grid each gets and how many image tokens each costs at 576 tokens per tile, plus one overview tile.
In words. For an image size and tile size, the tile grid that best matches the image's shape, drawn with the overview tile beside it, and the tile and token counts with and without two-by-two patch merging.
26.3 2D RoPE for Image Patches
Numbered row by row, vertically touching patches end up a whole row apart: positions in a -wide grid. 2D RoPE gives each patch its row and column directly: for a patch at row , column , rotate the first half of the query (section 15.1) by and the second half by :
Keys are rotated the same way, so in each half only the difference survives: scores depend on how many rows and columns apart two patches are. That directly signals neighbors, helping layout tasks such as reading tables or locating objects. Qwen2-VL's vision encoder uses it to read images at their own size instead of fixed tiles.
26.4 Training on Images and Text TogetherRun this section
Merging Image and Text Into One Sequence
How "User: What is this? <image>\nAssistant: It's a red fox." becomes one sequence:
- Find the image marker, a special token with its own ID (say
32000). - Turn each part into vectors. The text tokens before it are looked up in , giving ; the image goes through the ViT and connector, giving (say 576 vectors, or the resampler's output count); the tokens after give .
- Stack them in order, the image vectors replacing the marker:
With , image vectors and , the language model sees positions and runs ordinary self-attention over all of them, image and text alike.
Which Tokens Count Toward the Loss
Visual instruction tuning fine-tunes on image-question-answer examples with section 20.1's masked loss: only the assistant's answer tokens count.
The mask is
Masked positions are still read as context. In PyTorch, set their labels to -100, the default ignore_index that F.cross_entropy skips (it also averages rather than sums, which only rescales the loss):
# prompt and image positions stay in the input as context; -100 drops them from the loss
labels[prompt_mask] = -100
loss = F.cross_entropy(logits.view(-1, vocab_size), labels.view(-1), ignore_index=-100)prompt_mask is true at every system-prompt, user-prompt and image position. Without it, the model would be trained to predict the question and to "predict" image positions, which are not vocabulary tokens at all.
Building a training example for a vision-language model
Tokens are written as strings for readability; a real pipeline works with ids and replaces the single image marker with the connector’s 576 output vectors.
One training example as a strip of positions, each segment drawn to scale. With the mask on, every position labelled −100 is skipped by the loss.
The sequence is a system prompt, a user question, 576 image positions and a short answer. Before switching the mask on, predict roughly what share of positions contribute to the loss.
In words. One training sequence as a strip of segments sized by length: system prompt, user text, image positions and answer. Switching the mask on greys out every position labelled minus 100, leaving only the answer, and the readout gives the scored share.
Exercises
An AnyRes image uses a 2 × 3 grid of tiles plus one overview tile, each encoded to 576 tokens. How many image tokens is that, and how many after 2 × 2 patch merging?
A 24 × 24 grid of patch vectors goes through 2 × 2 patch merging. How many tokens come out, and what width is each merged vector before its projection, if ?
Why does a Perceiver resampler output the same number of tokens for every image, whatever its resolution?
With 2D RoPE, why does the attention score between two patches depend only on how many rows and columns apart they are?
Core Academic References
- Liu et al. (2023): Visual Instruction Tuning (LLaVA). NeurIPS 2023. arXiv:2304.08485
- Liu et al. (2024): Improved Baselines with Visual Instruction Tuning (LLaVA-1.5). CVPR 2024. arXiv:2310.03744
- Liu et al. (2024): LLaVA-NeXT: Improved reasoning, OCR, and world knowledge. Project blog post, January 2024.
- Alayrac et al. (2022): Flamingo: a Visual Language Model for Few-Shot Learning. NeurIPS 2022. arXiv:2204.14198
- Li et al. (2023): BLIP-2: Bootstrapping Language-Image Pre-training with Frozen Image Encoders and Large Language Models. ICML 2023. arXiv:2301.12597
- Chen et al. (2024): InternVL: Scaling up Vision Foundation Models and Aligning for Generic Visual-Linguistic Tasks. CVPR 2024. arXiv:2312.14238
- Bai et al. (2023): Qwen-VL: A Versatile Vision-Language Model for Understanding, Localization, Text Reading, and Beyond. arXiv:2308.12966
- Wang et al. (2024): Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution. arXiv:2409.12191