The Complete Beginner's Path

Understand Vision-Language
Models

How vision-language systems connect visual representations with language models to describe images, answer questions, and process multimodal prompts.

Prerequisites: Basic transformer intuition + Curiosity about multimodal AI. That's it.
10
Chapters
8+
Simulations
0
Jargon Assumed

Chapter 0: Two Modalities, One Model

A Vision-Language Model (VLM) accepts visual and language inputs and produces outputs conditioned on both. The term covers multiple architectures: some connect separately pretrained components, while others train multimodal components jointly.

One engineering challenge is the interface. Images begin as spatial arrays of continuous pixel values, while language models consume sequences of vectors associated with discrete tokens. A VLM needs a defined path that turns visual evidence into features the downstream predictor can use.

One common pattern: A vision encoder produces features, a connector adapts them, and a language model predicts text conditioned on visual and textual inputs. Other VLMs use cross-attention, joint multimodal training, or different encoders and output heads.

The Data Flow at a Glance

Here's the entire VLM pipeline in concrete tensor shapes (we'll unpack each box in later chapters):

Image
[3, 336, 336] — RGB pixels
↓ CLIP ViT-L/14 (304M params, frozen)
Visual Features
[576, 1024] — 576 patch tokens
↓ LLaVA-1.5 MLP projection (~31.5M params for Vicuna-13B)
Projected Tokens
[576, 5120] — Vicuna-13B input width
↓ concatenate with text embeddings [T, 5120]
Vicuna-13B
[576 + T, 5120] → autoregressive text generation
Two Modalities Merging

Watch projected image features and text embeddings form one LLaVA-style input sequence. The teal nodes are visual, orange nodes are textual.

Check: What is the core challenge of building a VLM?

Chapter 1: Vision Encoders — Teaching AI to See

The vision encoder converts a raw image into a sequence of feature vectors. The systems studied here commonly use a ViT (Vision Transformer): split the image into fixed-size patches, embed each patch, add position information, and process the sequence with transformer layers.

The output has a sequence axis like text embeddings, but its feature width and learned representation can differ. LLaVA's connector supplies the language model's required width before concatenation.

patches = split(image, patch_size)  →  z = ViT(patches + pos_embed)

Tensor Shapes: CLIP ViT-L/14 Walkthrough

Let's trace the shapes for LLaVA-1.5's CLIP ViT-L/14@336. It takes a 336×336 image and uses 14×14 pixel patches:

Input Image
[1, 3, 336, 336] — RGB, 336px square
↓ split into 14×14 patches
Patch Embedding
(336/14) × (336/14) = 24 × 24 = 576 patches
Each patch: 14×14×3 = 588 pixels → projected to d=1024
Shape: [1, 576, 1024]
↓ + positional embeddings [576, 1024]
Transformer (24 layers)
Self-attention over 576 tokens of dim 1024
Output: [1, 576, 1024] — 576 visual tokens
The resolution scaling problem: In a plain ViT grid with 14-pixel patches, 336×336 gives 576 patch tokens and 672×672 gives 2,304. Full self-attention within that grid compares 16× as many token pairs. Systems therefore cap, tile, pack, merge, or prune visual tokens. LLaVA-NeXT uses AnyRes tiling; Qwen2-VL uses Naive Dynamic Resolution, mapping different input resolutions to different token counts and then merging adjacent 2×2 visual tokens.
Image Patchification

See how an image is sliced into patches. Each patch becomes a token for the transformer. Adjust patch size to see the trade-off between resolution and sequence length.

Patch size4
16 patches → 16 tokens
Key trade-off: For a fixed image size, smaller patches produce more tokens and retain a finer spatial grid, but increase attention work. VLMs use many patch sizes, resolutions, tiling schemes, and token-merging strategies; 14-pixel patches at 224 or 336 pixels are concrete CLIP/LLaVA examples rather than a universal rule.
Published systemVision componentRelevant output handling
Original LLaVACLIP ViT-L/14Selected grid features, class token excluded; width 1024
LLaVA-1.5CLIP ViT-L/14@336Layer -2 patch features; 576 positions, width 1024
FlamingoFrozen contrastively trained NFNet-F6Flattened feature grid enters a 64-output Perceiver Resampler
Qwen-VLOpenCLIP ViT-bigG initializationSingle-layer 256-query visual receptor
Qwen2-VL675M ViT trained for image/video2D-RoPE and adjacent 2×2 token merge
Check: What does a Vision Transformer do to an image first?
🔗 Pattern Recognition
The Vision Encoder Is Just CLIP's Image Side
This Lesson (VLM)
CLIP ViT-L/14 takes image → [576, 1024] patch tokens. The spatial structure (24×24 grid) encodes position.
CLIP & Contrastive Learning
CLIP forms its global image representation from the class-token state and a learned projection. LLaVA instead selects grid-token hidden states and excludes the class token. → CLIP lesson

LLaVA-1.5's released configuration selects layer -2 patch features. CLIP's transformer retains a state at every token position; its separate global image representation selects the class-token state and applies a learned projection.

Where else do you see the same encoder used with different amounts of its output? (Hint: think about how the Transformer lesson shows hidden states at every layer.)

Checkpoint — Before you move on
A 672×672 image with 14×14 patches produces how many tokens? What dimension is each token? If you doubled the patch size to 28×28, what happens to token count and per-token information?
✓ Gate cleared
Model Answer

672/14 = 48 patches per side, so 48×48 = 2,304 tokens, each of dimension 1024 in this illustration. That is 4× as many positions as the 336-pixel case. A plain full-attention grid therefore compares 23042/5762 = 16× as many position pairs; end-to-end runtime also depends on the implementation and hardware.

If patch size changes to 28×28, the grid becomes (672/28)2 = 24×24 = 576 positions. Each patch covers 28×28×3 = 2,352 pixel values instead of 588, producing a coarser spatial grid with fewer attention pairs. Measure task accuracy to determine how that change affects fine details.

Chapter 2: The Projection Bridge

A pretrained vision encoder and language model can expose different feature widths and interfaces. LLaVA therefore uses a learned connector before supplying visual features to the language model.

Original LLaVA uses one linear projection; LLaVA-1.5 uses a two-layer MLP; Flamingo combines a Perceiver Resampler with gated cross-attention. Each interface produces the features its downstream language component consumes; none requires a patch to correspond to one word.

LLaVA-1.5 Projection: Exact Shapes

LLaVA-1.5 uses a 2-layer MLP to project from CLIP's 1024-dim space to Vicuna-13B's 5120-dim space:

Vision Encoder Output
[576, 1024] — 576 tokens, each 1024-dim
↓
Linear(1024, 5120)
W1: [1024, 5120] + bias [5120] = 5.25M params
↓ GELU activation
Linear(5120, 5120)
W2: [5120, 5120] + bias [5120] = 26.22M params
↓
Projected Tokens
[576, 5120] — now at Vicuna-13B hidden width
Parameter count: For Vicuna-13B, the two affine layers contain 31,467,520 parameters, about 0.24% of a nominal 13-billion-parameter LLM. The count describes connector capacity, while the response objective determines how its features are used.

Projection Strategies Compared

ConnectorVerified configurationVisual outputsExample
Linear1024→5120, about 5.25M parameters for Vicuna-13B256 at CLIP@224Original LLaVA
Two-layer MLP1024→dLLM→dLLM; about 31.5M for d=5120576 at CLIP@336LLaVA-1.5-13B
Perceiver ResamplerLearned latents cross-attend to a variable visual feature map64Flamingo
Visual receptorCross-attention with learned query embeddings256Qwen-VL
The Perceiver trade-off: Flamingo's Perceiver Resampler converts a variable-size visual feature map to 64 outputs before text-to-vision cross-attention. This fixes the number of visual keys and values seen by those layers. Measure the resulting accuracy on the target task because compression quality depends on the checkpoint, data, and visual detail.
Why use a projector? The vision and language components expose different widths and were trained separately. A learned connector produces vectors at the LLM's input width and adapts them through the response objective. The mapping acts on every selected patch feature without assigning each patch to a single word.
A Toy Linear Map in 2D

The real connector maps 1024 dimensions to 5120. This two-dimensional sketch isolates one property of a learned linear map: changing its weights moves every input point coherently.

Toy rotation angle45°
Check: What does the projection layer do?
🔨DerivationLLaVA-1.5 Projector Parameter Count▶✓ ATTEMPTED

The official LLaVA projector builder implements mlp2x_gelu as Linear(vision width, LLM hidden width) → GELU → Linear(LLM hidden width, LLM hidden width). For CLIP width 1024 and Vicuna-13B width 5120, calculate the parameter count including biases.

(1024×5120 + 5120) + (5120×5120 + 5120).

Layer 1 has 5,248,000 parameters. Layer 2 has 26,219,520. Total: 31,467,520 ≈ 31.5M, about 0.24% of a nominal 13-billion-parameter LLM. A 4096-wide version has about 21.0M parameters and matches a 7B-width LLaMA/Vicuna model, not Vicuna-13B.

💻 Build It Implement the Vision-to-Language Projection ▶ ✓ ATTEMPTED
Implement the LLaVA-1.5 mlp2x_gelu connector. The module takes [batch, n_patches, vision_dim] and outputs [batch, n_patches, llm_dim]. This connector preserves token count.
signature class VisionProjection(nn.Module): """ Projects vision encoder output to LLM embedding space. Args: vision_dim: dimension of vision encoder output (e.g., 1024) llm_dim: dimension of LLM hidden/input space (5120 for Vicuna-13B) Forward: Input: [batch, n_patches, vision_dim] Output: [batch, n_patches, llm_dim] """ def __init__(self, vision_dim: int, llm_dim: int): ... def forward(self, x: torch.Tensor) -> torch.Tensor: ...
Test case: LLaVA-1.5 with Vicuna-13B
proj = VisionProjection(1024, 5120)
x = torch.randn(2, 576, 1024)
out = proj(x)
assert out.shape == (2, 576, 5120)
assert sum(p.numel() for p in proj.parameters()) == 31_467_520
assert [(m.in_features, m.out_features) for m in proj.mlp if isinstance(m, nn.Linear)] == [(1024, 5120), (5120, 5120)]
assert any(isinstance(m, nn.GELU) for m in proj.mlp)
LLaVA-1.5 uses llm_dim as the intermediate dimension too. So both layers output llm_dim. The architecture is: Linear(vision_dim, llm_dim) → GELU() → Linear(llm_dim, llm_dim).
python
import torch
import torch.nn as nn

class VisionProjection(nn.Module):
    def __init__(self, vision_dim: int, llm_dim: int):
        super().__init__()
        self.mlp = nn.Sequential(
            nn.Linear(vision_dim, llm_dim),  # 1024 -> 5120
            nn.GELU(),
            nn.Linear(llm_dim, llm_dim),     # 5120 -> 5120
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        # x: [batch, n_patches, vision_dim]
        return self.mlp(x)  # [batch, n_patches, llm_dim]
Bonus challenge: Modify this to include a Perceiver-style resampler that compresses 576 tokens down to 64 learned queries using cross-attention. What new parameters do you need?

Chapter 3: Fusion Strategies

Once visual and text features are available, the model needs an explicit route for information to cross modalities. Published systems use several distinct routes:

MechanismHow it worksPublished example
Visual-prefix fusionProject visual features and concatenate them with text embeddings for a causal LLMLLaVA
Gated cross-attentionLanguage queries attend to resampled visual keys and values in new blocksFlamingo
Learned-query compressionQueries cross-attend to a visual feature map to produce a fixed-length interfaceFlamingo Perceiver; Qwen-VL receptor
Native dynamic-resolution prefixA vision transformer produces variable-length visual sequences for an LLMQwen2-VL
Fusion Architecture Comparison

Toggle between strategies to see how vision (teal) and text (orange) tokens interact.

Visual-prefix fusion: LLaVA projects visual features into the LLM input width and places them before text embeddings. Standard causal self-attention then lets later text positions use that visual prefix. Performance still depends on pretrained components, data, optimization, and evaluation.

What Happens Inside: The Attention Pattern

In early fusion, the LLM's self-attention sees a sequence like [v1, v2, ..., v576, t1, t2, ..., t50]. Because it's causal attention:

Visual positions (1-576):
• Attend to earlier visual positions under the decoder's causal mask
• Cannot attend to later question tokens
• Their LLM hidden states still change at every layer; they are question-independent at those positions, not "frozen"
Text positions (577+):
• Can attend to the visual prefix
• Attend to prior text positions under the causal mask
• Can combine visual and textual context when predicting later tokens
An important subtlety: In this image-first causal ordering, hidden states at visual positions cannot attend to later question tokens. Later text positions can attend to the visual prefix and the question. Flamingo uses a different route: queries come from language hidden states, while keys and values come from 64 resampled visual outputs. That is text attending to vision, not vision attending to the query.

Architecture Comparison: Who Builds the Bridge Differently?

Each approach makes fundamentally different engineering choices about what's frozen, what's trained, and how vision enters the LLM:

ModelVisual interfaceFrozen during reported multimodal training?Visual outputs
LLaVA-1.5-13BTwo-layer MLP into Vicuna-13BCLIP frozen; Vicuna tuned in Stage 2576 patch features
Flamingo-80BPerceiver Resampler + gated cross-attention/dense blocksNFNet-F6 and Chinchilla-70B frozen; new blocks trained64 resampler outputs
Qwen-VL256-query visual receptor into Qwen-7BFreeze policy changes across its three training stages256 query outputs
The token-count trade-off: LLaVA-1.5 supplies 576 patch features to its LLM, Flamingo resamples visual features to 64 outputs, and Qwen-VL uses 256 learned queries in its visual receptor. Token count affects later attention work, but it does not by itself rank accuracy or end-to-end speed across different architectures.
Check: In early fusion, how do vision and text tokens interact?
⚔ Adversarial: Your VLM hallucinates objects not in the image
A LLaVA-style model describes "a vase of flowers" when the vase is absent. Which conclusion is justified without a controlled ablation?
🔨Architecture CheckWho Queries Whom in Flamingo?▶✓ ATTEMPTED

Flamingo first maps a variable visual feature map to 64 outputs with a Perceiver Resampler. Its newly initialized gated cross-attention blocks are inserted between frozen language-model blocks. Identify the source of Q, K, and V.

Q comes from language hidden states. K and V come from the resampled visual outputs. All of these projections belong to the newly added cross-attention block; Q and O are not reused from the frozen language model. Exact widths, insertion frequency, and parameter counts differ across Flamingo-3B, -9B, and -80B.

Chapter 4: Visual Instruction Tuning

Visual instruction tuning trains on image, instruction, and response examples so the model learns the response formats represented in that data.

Original LLaVA supplements image-caption alignment with conversational, detailed-description, and complex-reasoning examples. This broadens the supervised task distribution; it does not guarantee general behavior outside that distribution.

Why Captioning Alone Isn't Enough

Caption alignment trains a different interface from instruction following: it rewards likely captions, not responses to arbitrary user requests. It may still acquire some reasoning capability from pretrained components, but caption data alone does not directly teach the conversational instruction-response format evaluated by LLaVA.

Training formatDirect supervisionWhat it does not directly supervise
Image-caption pairsGenerate or match a caption for an imageResponses to varied user instructions
VQA pairsAnswer questions from a task datasetOpen-ended dialogue outside that format
Instruction-response dataFollow the included instruction distributionGuaranteed behavior on unseen tasks
Input
[Image] + "How many people are in this photo?"
↓
VLM Processes
Vision encoder + projection + LLM forward pass
↓
Output
"There are three people in this photo, standing near..."
Data generation trick: Original LLaVA prompted language-only GPT-4 with captions and bounding boxes rather than pixels. The paper reports 158K unique language-image instruction-following samples: 58K conversation, 23K detailed-description, and 77K complex-reasoning samples.

The Training Signal: What Does the Loss Look Like?

During instruction tuning, the model receives a sequence like:

format
[IMG_1] [IMG_2] ... [IMG_576] [SYS] You are a helpful assistant. [USR] What animal is in this image? [ASST]

# Loss is computed ONLY on the assistant's response tokens:
"This image shows a golden retriever lying on grass..."

# Vision/prompt positions are excluded from direct target loss
# Gradients can still flow through their contribution to response predictions
# Assistant tokens: standard next-token prediction loss
Causal masking matters: The model can attend from text to vision tokens (allowing it to "look" at the image), but not from vision tokens to future text tokens. Vision tokens attend only to each other and to prior context. This ensures the visual features are processed before the text response is generated.
Instruction Diversity

See the variety of tasks a VLM must handle. Click to cycle through instruction types.

Check: What makes visual instruction tuning different from captioning?
🔨 Derivation The Visual Instruction Tuning Loss ▶ ✓ ATTEMPTED

Let E contain visual-prefix embeddings followed by system, user, and assistant token embeddings. Only assistant response tokens have vocabulary targets in this objective.

Your task: Define the labels, apply the causal one-position shift, normalize over valid labels, and explain why target masking does not detach the prefix.

Continuous visual embeddings have no vocabulary token IDs. Set labels to -100 at image, system, and user positions, and to token IDs at assistant response positions.
A standard causal-LM implementation compares logits[:, :-1] with labels[:, 1:]. Each retained logit predicts the next position.
Sum cross-entropy over shifted labels that are not -100, then divide by that valid-label count. Averaging zeroed losses over every position rescales the objective by valid_count/candidate_count.

Full derivation:

For sequence length L, define yj = -100 at image, system, and user positions and let yj be the assistant vocabulary token ID at response positions.

Let M be the number of valid shifted labels. Then L = -(1/M) ∑i=0L-2 1[yi+1 ≠ -100] log pθ(yi+1 | E≤i).

In tensor code, use logits[:, :-1] against labels[:, 1:], ignore -100, and divide the summed loss by the valid shifted-label count.

The key insight: The mask removes direct cross-entropy targets. It does not detach visual or prompt states. Assistant-token loss can still backpropagate through attention into trainable upstream components such as the projector.

Chapter 5: The LLaVA Architecture

Original LLaVA (2023) connected CLIP ViT-L/14 to Vicuna with one linear projection. LLaVA-1.5 later changed the worked configuration used below: CLIP ViT-L/14@336, 576 selected patch features, and a two-layer MLP connector.

For LLaVA-1.5-13B, each 1024-wide patch feature is projected to Vicuna-13B's 5120-wide input space, concatenated with text embeddings, and processed by the causal language model.

Which CLIP features? LLaVA-1.5 selects patch-token states from hidden layer -2 and excludes the class token. CLIP's ordinary global embedding instead selects the class-token state after the transformer. The two consumers read different outputs from the same encoder.
CLIP ViT-L/14
336×336 image → 576 visual tokens (d=1024)
↓
LLaVA-1.5 MLP Projector
Linear(1024, 5120) + GELU + Linear(5120, 5120)
↓
Vicuna-13B
[576 visual tokens] + [text tokens] → autoregressive output
LLaVA Forward Pass

Watch tokens flow through the architecture. Teal = vision, orange = text, green = output.

Why does simplicity win? Both CLIP and the LLM are already well-trained. CLIP learned to align images with text during pretraining. The LLM already knows language. The projection just needs to learn the "translation" between their embedding spaces — a much smaller problem than training from scratch.

The Complete Input to the LLM

Let's trace exactly what the LLM receives. For a question like "What is in this image?":

Visual Embeddings
576 × 5120 for LLaVA-1.5-13B
+
System + User Text
T × 5120; T depends on the prompt template and tokenizer
↓ concatenate
Vicuna-13B Input
(576 + T) × 5120
40 layers, hidden width 5120, 40 attention heads
Context budget: With an illustrative 50-token prompt, 576 visual embeddings are 576/(576+50) ≈ 92% of the prefill positions. The percentage changes with the prompt and output setup. More visual positions increase prefill work and KV-cache occupancy, motivating compression for multi-image and video inputs.

Where Inference Time Goes

End-to-end latency depends on hardware, precision, kernels, batch size, prompt length, and output length. Vision encoding and prompt prefill run mostly in parallel over their input positions; autoregressive decoding is sequential across generated tokens. Measure all three on the target deployment before naming a bottleneck.

Check: How many new components does LLaVA add to connect vision and language?

Chapter 6: The Training Pipeline

Original LLaVA uses a two-stage recipe. Other VLM families use different stage counts and freeze policies:

StageDataWhat TrainsPurpose
1. Pretraining alignment595K image-caption pairsProjection onlyAlign vision ↔ language spaces
2. Instruction tuning158K visual conversationsProjection + LLMTeach instruction following

Parameter Budget: Original LLaVA-13B

ComponentApprox. paramsStage 1Stage 2
CLIP ViT-L/14304MFrozenFrozen
Linear projector 1024→51205.25MTrainingTraining
Vicuna-13B13BFrozenTraining
Reported training setup: The original paper trained on 8 A100 GPUs. Its appendix reports under 4 hours for CC-595K alignment and under 10 hours for Instruct-158K fine-tuning. These are study-specific runtimes, not cloud-cost estimates.
Training Stage Visualization

Toggle stages to see which components are frozen (blue/frozen) vs trainable (green/active).

LLaVA-1.5 changed several variables together: It used CLIP ViT-L/14@336, a two-layer MLP connector, and a larger mixture including academic VQA data. Its gains across 11 reported benchmarks measure the combined recipe; isolating the connector, resolution, or data contribution requires the corresponding ablation.
Check: In Stage 1 of LLaVA training, what is trainable?
💥 Break-It Lab Vary the Original LLaVA Recipe ▶ ✓ ATTEMPTED
Toggle one design choice at a time. The canvas tracks which parameters and interfaces change; the notes identify what a real experiment must measure.
Unfreeze Vision Encoder OFF
Unfreezing changes the optimization: Gradients now update the vision encoder as well as downstream components, increasing memory and compute. Compare a named validation metric before and after unfreezing while controlling the data, learning rates, and regularization.
Remove Projection Layer OFF
Removing the connector: CLIP ViT-L features are width 1024 while Vicuna-13B inputs are width 5120, so direct concatenation is shape-incompatible. A different adapter or jointly designed interface could replace the projector; zero-padding is not an evaluated baseline here.
Skip Instruction Tuning OFF
Skipping Stage 2: On original LLaVA's GPT-4-judged synthetic LLaVA-Bench (COCO), the "No Instruction Tuning" ablation scored 21.5 versus 85.1 with full data. This comparison measures instruction tuning within that recipe and benchmark.

Chapter 7: Grounding & Spatial Understanding

Grounding means connecting words to specific regions in the image. When a VLM says "the red car on the left," grounding means it can also point to where that car is. This requires the model to output spatial coordinates, not just text.

Approaches include: outputting bounding box coordinates as text tokens (e.g., "[0.2, 0.3, 0.5, 0.7]"), using special location tokens, or predicting segmentation masks. Models like Kosmos-2 and Shikra showed VLMs can be trained to both describe and locate objects.

Three Levels of Spatial Understanding

LevelOutputExample TaskDifficulty
PointingSingle (x, y) coordinate"Point to the cat's nose"Easiest — one point
Bounding box(x1, y1, x2, y2)"Draw a box around each person"Medium — 4 numbers per object
SegmentationPixel-level mask"Segment the dog from background"Hardest — needs a mask decoder
Visual Grounding

Click on regions to see how a VLM grounds language to spatial locations. Each colored box is a detected object with its label.

Coordinate formats: Qwen-VL tokenizes normalized coordinate strings and adds boundary delimiters; Shikra uses natural-language coordinates without a new location vocabulary; Kosmos-2 uses dedicated location tokens. Each format depends on the named model and its grounded training data.

Grounding as Text: How It Works in Practice

Grounding formats are model-specific. Shikra emits coordinates in natural-language form without adding a vocabulary; Kosmos-2 represents boxes with dedicated location tokens; Qwen-VL normalizes box coordinates to [0,1000), tokenizes the coordinate string as text, and wraps it with special boundary tokens. The example below illustrates the Qwen-VL-style numeric format:

example output
# Input: "Where is the dog in this image?"
# Output:
The dog is on the left side of the image.
<box>(102,384),(298,571)</box>

# Coordinates: (x1, y1), (x2, y2), each in [0, 1000)
# Real position: top-left (10.2%, 38.4%) to bottom-right (29.8%, 57.1%)
Grounding through generation: These systems serialize locations so an autoregressive model can predict them, but they still require grounded training data and a defined coordinate encoding. Some reuse ordinary number tokens; others add special location or delimiter tokens. The encoding alone does not guarantee spatial reasoning.
Check: What does "grounding" mean in VLMs?

Chapter 8: Document Understanding

Documents are a special challenge for VLMs: they contain dense text, tables, charts, and layouts where spatial arrangement matters. "Revenue" next to "$5M" means something different from "Revenue" in a section header.

Key innovations: high-resolution encoding (documents need more pixels than photos), OCR-free reading (the vision encoder learns to read text directly), and layout-aware attention (understanding that rows and columns create relationships).

The Resolution Bottleneck for Documents

A standard document page at 300 DPI is roughly 2,550 × 3,300 pixels. A VLM at 336×336 resolution shrinks this by 10× in each dimension — a 12-point font becomes 1-2 pixels tall. Completely unreadable. This is why document understanding requires special resolution handling:

ApproachMechanismCost characteristic
Global resizeResize the full page to one encoder inputFixed token count; small glyphs may disappear
Tiling / sub-image decompositionEncode a global view plus multiple crops or tilesToken count grows with selected tiles
Native dynamic resolutionMap different input sizes to different visual sequence lengthsVariable token count bounded by implementation limits
Token merging or pruningReduce encoded visual positions before the LLMCompute/accuracy trade-off must be measured per model
The OCR question: OCR-free models predict text or markup directly from page images; pipeline systems combine a recognizer with layout or language processing. Which works better depends on resolution, script, layout, domain, and evaluation metric. Nougat is a concrete OCR model that converts scientific document images to markup.
Document Layout Parsing

A VLM must understand that spatial layout encodes meaning. Watch how different regions are classified.

Resolution matters: Global resizing can make small glyphs hard to recover. Document systems use several methods, including tiling, shape-adaptive encoding, and token compression. The exact preprocessing and sequence length must be stated per model rather than treated as one shared "dynamic resolution" algorithm.
Published systemDocument-relevant mechanismClaim scope
NougatVision encoder-decoder OCR from scientific document images to markupScientific-document transcription and markup
Qwen-VL448-pixel multi-task training including OCR and document VQA dataNamed text-oriented VQA benchmarks in its paper
Qwen2-VLNative dynamic resolution with variable visual-token countsDocVQA, ChartQA, InfoVQA, TextVQA, AI2D and OCRBench evaluations
Qwen2.5-VLDynamic resolution plus window attention and document omni-parsing dataTechnical-report evaluations; version-specific

What Breaks: Common VLM Failure Modes

Published VLM evaluations report errors on small details, object presence, counts, spatial relations, documents, and video. An observed error category does not identify one architectural cause.

Observed failurePlausible contributors to testUseful control
Small-detail or counting errorInput resolution, preprocessing, encoder features, data, or decodingHold the model fixed and vary only resolution or crop policy
Object hallucinationVisual ambiguity, language priors, data, alignment, optimization, or decodingAdd or remove the queried object in counterfactual images
Spatial-relation errorRepresentation, supervision, prompt, or benchmark ambiguityUse matched scenes with one relation changed
Long video or document failureSampling, visual-token budget, context length, retrieval, or compressionReport the exact preprocessing and ablate token reduction
Hallucination is multifactorial: Language priors and ambiguous visual evidence are plausible contributors, alongside training data, alignment, optimization, and decoding. A matched intervention or ablation is needed to assign cause in a particular model.
Check: Why is document understanding harder than photo understanding for VLMs?

Chapter 9: Published VLM Directions

The examples below are dated reference points from public papers and technical reports. Capabilities and architectures vary by system and version.

Published Architecture Reference Points

SystemPublished mechanismVersion scope
Original LLaVACLIP ViT-L/14 + linear projector + Vicuna2023 paper
LLaVA-1.5CLIP ViT-L/14@336 + two-layer MLP connector2023 improved-baselines paper/repo
FlamingoFrozen NFNet-F6 and LM; 64-output Perceiver Resampler; new gated text-to-vision cross-attention blocks2022 paper
Qwen2-VLNaive Dynamic Resolution, 2D-RoPE, 2×2 visual-token merge, M-RoPE2024 paper
Qwen2.5-VLNative dynamic resolution, window attention, dynamic frame-rate sampling, absolute-time MRoPE2025 technical report
Read public disclosures at their stated level: OpenAI describes GPT-4o as one model trained end to end across text, vision, and audio. Google's Gemini 1.0 report states joint multimodal training. Claude system cards publish behavior and evaluation details without specifying a projector, patch scheme, or freeze policy.

Resolution and Visual-Token Management

Several published VLMs use tiling or variable-length visual sequences instead of one fixed square resize. The exact supported sizes, aspect ratios, token limits, and reduction methods are model-specific.

How AnyRes works (LLaVA-NeXT): Preprocessing selects a supported grid for the image's aspect ratio. For a chosen number of encoded views, multiplying by 576 counts raw patch features. The global view, spatial unpadding, and inserted newline markers must be accounted for when computing final sequence length.

An Idealized Resolution Count

This arithmetic isolates how a plain 14-pixel patch grid grows before model-specific tiling, merging, pruning, or window attention:

Idealized square input14px patch gridPatch positionsFull-grid pair count vs 224
224 × 22416 × 162561×
336 × 33624 × 245765.06×
672 × 67248 × 482,30481×
1344 × 134496 × 969,2161,296×

These counts measure positions and position pairs in one uncompressed grid. OCR accuracy and runtime require separate measurements for the chosen tiling, windowing, merging, or pruning implementation.

Qwen2.5-VL's approach: Images are resized so height and width are multiples of 28, then encoded at native dynamic resolution; different image sizes therefore produce different token counts. Window attention limits most vision-encoder attention to local windows. Patch size stays fixed within an encoded image.
Build a comparison table, one metric at a time: Record the exact checkpoint, image preprocessing, prompt, split, and metric. Keep VQAv2 accuracy, an OCRBench aggregate score, and grounding accuracy at a stated IoU threshold in separate columns; their scales and tasks are not interchangeable. Compare rows only when the evaluation protocol matches.
Architectures remain diverse: Some systems connect pretrained specialists; others jointly train across modalities. This choice changes which components share gradients and training data. Hallucination and task accuracy still require named evaluations rather than an architectural label.

Video Token Counts

A naïve frame-by-frame count grows linearly with sampled frames. Published video systems use model-specific sampling and spatial or temporal reduction.

Illustrative inputFramesRaw count at 576 positions/frameInterpretation
Single image1576Before any model-specific compression
4 sampled frames42,304Linear growth in this naïve count
1 FPS for 30 seconds3017,280Motivates temporal/spatial reduction
30 FPS for 10 seconds300172,800Production systems generally do not pass every raw frame this way
Common strategies: Systems sample frames, lower per-frame resolution, merge or prune tokens, and learn temporal compression. The table isolates the raw 576-positions-per-frame arithmetic before those reductions. For version scope, Google's public 2M-token announcement applied to Gemini 1.5 Pro, while Gemini 2.0 Flash was described with a 1M-token context.

Connections

VLMs connect to many other topics:

• CLIP & Contrastive Learning — Original LLaVA and LLaVA-1.5 reuse CLIP visual features; other VLM families use different encoders or joint training.

• VLAs (Vision-Language-Action) — RT-2 is one published recipe that serializes robot actions as text tokens; other VLA interfaces differ.

• Transformers — The case studies here use transformer components, including ViT and causal language models.

• Diffusion Models — Multimodal systems can connect language-conditioned representations to image generators, but the generator and interface must be named by model.

"The biggest lesson that can be read from 70 years of AI research is that general methods that leverage computation are ultimately the most effective."
— Rich Sutton, The Bitter Lesson

You now have a source-grounded way to compare visual interfaces, fusion patterns, training stages, and token budgets across named VLM versions.

🏗Design ChallengePlan a Measured 4K Document VLM▶✓ ATTEMPTED
Design a deployment experiment for a 4K image plus long text on a 24GB GPU. State the model checkpoint, precision, maximum sequence length, visual preprocessing, batch size, and output length before estimating memory or latency.
1. Compare global resize, fixed tiling, native dynamic resolution, and region proposals on a task-specific validation set.
2. Measure peak allocated memory and latency; do not infer them from parameter count alone.
3. Include a negative control that removes high-resolution views, and report accuracy by object/text size.
4. Treat clinical deployment as a separate validation problem requiring domain data and human oversight.
Check: Which statement about current VLM architecture is best supported?
🔗 Pattern Recognition
VLM → VLA: Adding Actions to Vision-Language
This Lesson (VLM)
[Image tokens] + [Text tokens] → LLM → [Text response]
The model sees and speaks.
VLA (Vision-Language-Action)
[Image tokens] + [Text instruction] → LLM → [Action tokens]
RT-2 example: serialized action tokens. → VLA lesson

RT-2 co-fine-tuned vision-language models on robot trajectories and web-scale vision-language tasks, serializing actions as text tokens in the training data. This demonstrates one VLA recipe; VLA systems can use other action representations and need not share one projector or fusion mechanism.

What other domains could you target by simply changing what the LLM generates? (Hint: think music notation, CAD coordinates, chemical structures...)