Chapter 3: Language Model Backbone
Understand the language model architectures that serve as the reasoning engine in VLMs. From decoder-only transformers to encoder-decoder models, tokenization strategies for multimodal inputs, attention mechanisms over mixed sequences, popular LLM backbones, and the scaling laws that guide model selection.
- Topics
- 6
- Videos
- 3
- Min read
- 28
Chapter Overview
The language model is the reasoning engine of every Vision-Language Model. While the vision encoder perceives the world and the bridge module translates visual features, it is the LLM backbone that performs inference, generates text, follows instructions, and chains together multi-step reasoning over what the model "sees."
Modern VLMs inherit their language capabilities from pretrained LLMs---GPT-class decoder-only transformers, encoder-decoder models like Flan-T5, or mixture-of-experts architectures like Mixtral. The choice of backbone profoundly affects the VLM's ability to follow complex instructions, perform multi-turn dialogue, reason about spatial relationships, and generate accurate descriptions.
A critical design question is how to extend a text-only LLM to process visual tokens. The model must handle a mixed sequence of image tokens and text tokens under a unified attention mechanism. This requires careful tokenization, positional encoding, and attention masking strategies.
This chapter covers:
- Decoder-Only Transformers: The dominant architecture (GPT, LLaMA, Mistral) and causal attention
- Encoder-Decoder Models: The T5/Flan-T5 paradigm with cross-attention for VLMs
- Tokenization for Multimodal Input: How image tokens interleave with text in the input sequence
- Attention Mechanisms in VLMs: Causal self-attention over mixed image+text sequences
- Popular LLM Backbones: Vicuna, LLaMA, Mistral, Qwen, Phi---why each is chosen
- Scaling Laws & Model Selection: Parameter count vs. performance trade-offs and quantization
Chapter Roadmap
Click any topic to jump in
Decoder-Only Transformers
Autoregressive generation with causal masking — the dominant architecture behind GPT, LLaMA, and most modern VLMs.
Encoder-Decoder Models
Bidirectional encoding with cross-attention decoding — the T5/Flan architecture used in some VLMs like BLIP-2.
Multimodal Tokenization
How vision features become tokens the language model can process — visual tokens, delimiters, and multi-image sequences.
VLM Attention Mechanisms
Full causal self-attention vs gated cross-attention — how VLMs let language attend to visual information.
Which model and how large
Popular LLM Backbones
LLaMA, Mistral, Phi, Qwen — the specific models used as VLM language backbones and their tradeoffs.
Scaling Laws & Selection
Chinchilla scaling, VLM-specific compute allocation, and quantization — choosing the right model size.
Topics
6 topics in this chapter
Decoder-only transformers (GPT, LLaMA, Mistral, Qwen) are the dominant architecture for VLM backbones. They process a sequence of tokens autoregressively---each token can only attend to previous tokens and itself---and generate output one token at a time. This causal attention pattern is what makes them "decoder-only": there is no separate encoder; the same stack of transformer blocks handles both understanding and generation.
Key insight: In a VLM, the "prompt" to the decoder-only transformer includes both visual tokens (from the vision encoder + bridge) and text tokens. The causal mask ensures that when generating token , the model attends to all preceding image tokens and text tokens, but never to future tokens.
In this topic
- 1Autoregressive Generation
- 2Causal Attention Mask
- 3Next-Token Prediction Loss
Autoregressive Generation
A decoder-only model factorizes the joint probability of a sequence into a product of conditional probabilities. At each step, the model predicts the next token given all previous tokens. During training, all positions are computed in parallel using the causal mask. During inference, tokens are generated one at a time, each conditioned on the growing prefix.
The chain rule of probability gives the exact factorization . Each conditional is a categorical distribution over a vocabulary of size , so a single forward pass produces logits. The log-likelihood of the whole sequence decomposes into a sum of per-token log-probabilities, making gradient computation embarrassingly parallel across positions during training.
For the sequence "A dog sits on grass", write out the conditional factorization.
Causal Attention Mask
The causal mask is a lower-triangular matrix added to the raw attention scores before softmax. Positions where receive , which become zero after softmax, preventing token from attending to any future token . This is implemented efficiently as a single triangular boolean mask applied once per layer, with no additional parameters.
Adding to the upper triangle before softmax exploits the limit , giving exact zeros in the attention matrix without any approximation. The resulting lower-triangular weight matrix satisfies (rows sum to 1), forming a row-stochastic matrix that acts as a weighted average operator over the value vectors.
In a 4-token sequence, what does the causal mask matrix look like?
Next-Token Prediction Loss
Training minimizes the cross-entropy loss between the predicted distribution and the true next token at every position in the sequence. Because the causal mask prevents information leakage, all positions can be trained in a single forward pass (teacher forcing). This is the same objective used for pretraining the LLM; during VLM fine-tuning, the loss is typically computed only on the text generation tokens, not on the image tokens or the prompt.
The cross-entropy loss is an unbiased estimator of the negative log-likelihood. By the Kraft inequality, minimizing this loss is equivalent to learning an optimal prefix-free code for the data: the model's perplexity measures how many tokens the model is effectively "choosing between" at each step.
Why is the loss typically masked to exclude image tokens during VLM training?
Theory Exercise
Problem:
Explain why decoder-only transformers are preferred over encoder-decoder models as VLM backbones in recent architectures like LLaVA and GPT-4V. Consider computational efficiency, pretraining ecosystem, and instruction-following capability.
Hints:
- Think about the availability of strong pretrained decoder-only models
- Consider the simplicity of the architecture for multimodal input
- Think about what instruction tuning provides
Related Problems on PixelBank
Encoder-decoder transformers (T5, Flan-T5, mBART) use two separate stacks: an encoder that processes the full input with bidirectional attention (every token sees every other token) and a decoder that generates output autoregressively with causal attention. The bridge between them is cross-attention: the decoder's queries attend to the encoder's keys and values.
In VLMs, the encoder-decoder paradigm appears in models like BLIP-2 (where the Q-Former acts as a lightweight encoder) and CogVLM. While less common than decoder-only approaches in recent VLMs, encoder-decoder models offer unique advantages for tasks that benefit from bidirectional encoding of the visual input.
In this topic
- 1Bidirectional Encoder
- 2Cross-Attention Mechanism
- 3Sequence-to-Sequence Formulation
Bidirectional Encoder
The encoder uses full (bidirectional) self-attention: every token attends to every other token, including future positions. This produces richer representations because each token has full context. For VLMs, the visual tokens can attend to each other bidirectionally, capturing spatial relationships that causal masking would miss.
Full self-attention computes with no masking, yielding a doubly-stochastic-like matrix where information flows in all directions. Each output is a convex combination of all value vectors, giving the encoder a global receptive field in a single layer — unlike the causal case where layer has receptive field .
Why might bidirectional encoding of image patches be advantageous over causal encoding?
Cross-Attention Mechanism
Cross-attention is the key mechanism that connects the encoder and decoder. The decoder provides the queries (what information do I need?), while the encoder provides the keys and values (what information is available?). This allows every generated token to dynamically select which parts of the encoded input to focus on.
Cross-attention factorizes as , where queries come from a different distribution than keys. This computes a soft retrieval: for each decoder token, the dot product measures relevance, and softmax converts scores into a probability distribution over encoder positions. The output is the expected value under this retrieval distribution.
In a VLM using T5, when the decoder generates the word "red", which encoder representations might receive high cross-attention weight?
Sequence-to-Sequence Formulation
The encoder processes the full input once, producing context vectors . The decoder then generates the output sequence autoregressively, with each token conditioned on both the prefix (via causal self-attention) and the full encoder output (via cross-attention). For VLMs, includes image features and is the text response.
The encoder output is computed once with attention cost, then reused at every decoder step. Generating tokens costs for cross-attention (linear in per step), compared to for a decoder-only model reprocessing the full prefix. The amortized encoder cost makes this architecture more efficient when .
What is the computational advantage of the encoder-decoder split for VLMs?
Theory Exercise
Problem:
Compare the attention patterns in a decoder-only VLM vs an encoder-decoder VLM for the task of image captioning. For a 256-token image and a 50-token caption, calculate the number of attention operations in the self-attention layers of each architecture.
Hints:
- Decoder-only: all 306 tokens in one sequence with causal attention
- Encoder-decoder: encoder processes 256 tokens bidirectionally, decoder processes 50 tokens causally + cross-attends to 256
- Count Q*K^T operations per layer
One of the most critical design decisions in VLMs is how to represent the multimodal input as a single token sequence for the language model. The LLM was pretrained on text tokens; now it must process a mixed sequence of image tokens (continuous embeddings from the vision encoder) and text tokens (discrete vocabulary indices). The tokenization strategy determines the sequence format, the use of special delimiter tokens, and how the model distinguishes between modalities.
The standard format follows: [BOS] [IMG] v_1 v_2 ... v_N [/IMG] text_1 text_2 ... text_T [EOS]
where are projected visual embeddings and are standard text token embeddings.
In this topic
- 1Visual Token Creation
- 2Special Delimiter Tokens
- 3Multi-Image Sequences
Visual Token Creation
Each visual token is created by projecting a vision encoder feature through the bridge module into the LLM's embedding dimension . Unlike text tokens (which are looked up in a discrete embedding table), visual tokens are continuous vectors that occupy the same embedding space as text tokens. The LLM's self-attention treats them identically.
The bridge projection is a learned affine map that aligns the visual feature manifold with the LLM's embedding space. After projection, the Frobenius norm between visual and text token matrices decreases as training progresses, indicating the two modalities converge to a shared representation.
A ViT-L/14 encoder produces 256 patch features of dimension 1024. The LLM uses dimension 4096. What is the projection matrix shape?
Special Delimiter Tokens
Special tokens delineate the boundaries between modalities: [IMG] signals the start of image tokens, [/IMG] signals their end. These tokens are added to the LLM's vocabulary and their embeddings are learned during fine-tuning. They serve as "mode switches" that help the model understand when it is processing visual vs textual information. Some models (e.g., Qwen-VL) add [IMG_PAD] for padding variable-length image sequences.
Delimiter embeddings are learnable vectors that partition the input sequence into modality-specific segments. The attention pattern naturally develops block structure: tokens within the segment attend strongly to each other, creating an implicit modality indicator without explicit type embeddings.
A VLM receives an image and the prompt "Describe this image in detail." Construct the full input token sequence.
Multi-Image Sequences
Models like GPT-4V, Gemini, and LLaVA-NeXT support multiple images interleaved with text in a single conversation. Each image is encoded independently and its tokens are inserted at the appropriate position in the sequence. Image-index tokens (e.g., [IMG_1], [IMG_2]) help the model track which image is being referenced. The total sequence length grows linearly with the number of images.
With images of tokens each and text tokens, the total sequence length is (including delimiters). Self-attention cost scales as , so doubling the number of images approximately quadruples the attention cost. This quadratic scaling motivates token compression methods that reduce each while preserving information.
A user sends two images with the prompt: "Compare these two buildings." Each image produces 144 visual tokens. What is the total sequence length?
Theory Exercise
Problem:
A VLM uses a ViT-L/14 with 14×14 = 196 patches at 224×224 resolution. The user uploads a 1024×1024 image. LLaVA-NeXT uses an "anyres" strategy that tiles the image into 4 sub-images at native resolution plus 1 downscaled global view. Calculate the total number of visual tokens.
Hints:
- Each tile produces 196 tokens from the ViT
- 4 tiles at native resolution + 1 global view = 5 forward passes
- Total visual tokens = patches per tile × number of tiles
In a Vision-Language Model, the attention mechanism must handle a heterogeneous sequence containing both image and text tokens. While the basic scaled dot-product attention is the same, VLMs introduce several specialized attention patterns: full causal self-attention over the mixed sequence (decoder-only models), cross-attention from text to image features (encoder-decoder or adapter-based models), and gated cross-attention (Flamingo-style) that controls the influence of visual information at each layer.
Understanding these patterns is essential for understanding why some VLMs are better at fine-grained visual reasoning (more image-text interaction) vs. coarse-grained understanding (compressed visual representations).
In this topic
- 1Full Causal Self-Attention (Decoder-Only)
- 2Gated Cross-Attention (Flamingo)
- 3Attention Sink and Visual Token Placement
Full Causal Self-Attention (Decoder-Only)
In models like LLaVA, GPT-4V, and Qwen-VL, the image tokens and text tokens are concatenated into a single sequence, and standard causal self-attention is applied. Every text token attends to all preceding image tokens and all preceding text tokens. This is the simplest approach: no architectural changes to the LLM, just a different input. The model learns image-text interactions entirely through the pretrained attention mechanism.
For a mixed sequence of image and text tokens, the causal attention matrix has non-zero entries. Text token attends to all image tokens plus preceding text tokens, so its attention entropy is . As grows large relative to , image tokens dominate each text token's attention budget.
In a decoder-only VLM with 256 image tokens and 50 text tokens, how many attention pairs involve image-to-text interaction?
Gated Cross-Attention (Flamingo)
Flamingo inserts gated cross-attention layers between the frozen LLM layers. A learnable scalar gate (initialized to 0) controls how much visual information flows into each LLM layer. At initialization, , so the model starts as a pure text LLM and gradually learns to incorporate vision. This preserves the LLM's language capabilities during fine-tuning while providing a controlled pathway for visual information.
The gated residual preserves the Jacobian at initialization (when ), ensuring stable gradient flow through the pretrained LLM layers. As is learned, acts as a smooth interpolation coefficient, and peaks at , so the gate is most sensitive to gradient updates early in training.
Why is the gate initialized to rather than ?
Attention Sink and Visual Token Placement
Research has shown that LLMs develop "attention sinks"---early tokens (especially [BOS]) receive disproportionately high attention from later tokens, regardless of semantic relevance. In VLMs, image tokens placed immediately after [BOS] also become attention sinks, which can be beneficial (ensuring the model always considers the image) or harmful (drowning out specific visual details). Some models address this by placing image tokens after the text prompt rather than before it.
Attention sinks arise because softmax normalization forces all weights to be positive and sum to 1. Early tokens accumulate high attention not because they are semantically important, but because the model uses them as a "no-op" sink when no token is strongly relevant — the residual stream's skip connection ensures useful information still propagates even when attention is diffuse.
A VLM places 256 image tokens at the start of the sequence. A user asks about a tiny detail in the image. Why might this detail get lost?
Theory Exercise
Problem:
Design an attention masking strategy for a VLM that needs to process 2 images interleaved with text, where each image should ONLY attend to its own patches (not the other image's patches), but text tokens should attend to both images. Write out the mask matrix structure.
Hints:
- Consider a block-diagonal mask for the image tokens
- Text tokens need full causal access to everything before them
- Image tokens from image 1 should not see image 2's tokens
Related Problems on PixelBank
The choice of LLM backbone is one of the most consequential decisions in VLM design. Different backbone families offer different trade-offs in reasoning quality, instruction following, context length, inference speed, and licensing. The major VLM projects have converged on a small set of preferred backbone families, each chosen for specific strengths.
Understanding why each backbone was chosen reveals important design principles: LLaVA chose Vicuna/LLaMA for its strong instruction-following and open weights; InternVL chose InternLM for its multilingual capabilities; Phi-3-Vision chose Phi for its efficiency at small scale; and Qwen-VL chose Qwen for its long-context support.
In this topic
- 1LLaMA Family (Meta)
- 2Mistral / Mixtral (Mistral AI)
- 3Small Language Models (Phi, Gemma)
- 4Multilingual Backbones (Qwen, InternLM)
LLaMA Family (Meta)
LLaMA (Large Language Model Meta AI) is the most widely used backbone for open VLMs. LLaMA 2 introduced Grouped Query Attention (GQA) for efficient inference and was trained on 2T tokens. LLaMA 3 expanded to 15T tokens with a 128K vocabulary. Vicuna (fine-tuned LLaMA on ShareGPT conversations) was the default backbone for LLaVA. Key architectural features: Rotary Position Embeddings (RoPE), RMSNorm (instead of LayerNorm), SwiGLU activation, no bias terms.
RoPE encodes position by rotating query-key pairs: where is a block-diagonal rotation matrix. The inner product depends only on relative position , providing translation invariance. GQA reduces the KV cache from to with KV heads.
Why did LLaVA-1.5 switch from Vicuna-13B (LLaMA 1) to Vicuna-v1.5-13B (LLaMA 2)?
Mistral / Mixtral (Mistral AI)
Mistral 7B matches LLaMA 2 13B performance at half the size, using Sliding Window Attention (SWA) for efficient long-context processing. Mixtral 8x7B is a Mixture-of-Experts model that activates only 2 of 8 expert FFN layers per token, giving 46.7B total parameters but only 12.9B active per forward pass. VLMs like LLaVA-Mistral leverage Mistral's efficiency for faster inference.
Sliding Window Attention restricts each token to attend within a window of size , reducing per-layer attention cost from to . Over layers, the effective receptive field expands to tokens. Mixtral's top- routing selects experts from , so active parameters per token are of total, achieving the quality of a dense 12.9B model with the memory footprint of 46.7B.
How does Sliding Window Attention benefit a VLM processing a long image token sequence?
Small Language Models (Phi, Gemma)
Microsoft's Phi and Google's Gemma families push the efficiency frontier: Phi-3-mini (3.8B) achieves performance competitive with much larger models through high-quality training data curation. Phi-3-Vision directly extends Phi-3 with a CLIP vision encoder and shows that VLMs do not require 7B+ LLM backbones for practical tasks. These small backbones enable on-device VLMs for mobile phones and edge devices.
Data quality scaling suggests an alternative to Chinchilla: where is the effective dataset size after quality filtering. Phi demonstrates that aggressive data curation () can shift the Pareto frontier, achieving at a fraction of the inference cost.
Phi-3-mini (3.8B) vs LLaMA-2-7B: compare the inference cost for a VLM processing 256 image + 100 text tokens.
Multilingual Backbones (Qwen, InternLM)
Qwen (Alibaba) and InternLM (Shanghai AI Lab) are designed for multilingual capability, with large vocabularies covering Chinese, English, and many other languages. Qwen-VL and InternVL leverage these backbones for multilingual VLMs that can describe images in Chinese, answer questions in Japanese, or read text in Korean from an image. The expanded vocabulary (152K for Qwen vs 32K for LLaMA) enables efficient tokenization across languages.
Vocabulary size determines the embedding table size and the output projection cost per token. CJK languages require ~3.5x more tokens under a 32K BPE vocabulary than under 152K, because characters are split into byte-level fallback tokens. A larger vocabulary reduces sequence length (and hence attention cost) by a factor proportional to the compression ratio gain.
Why does Qwen use a 152K vocabulary vs LLaMA's 32K? What impact does this have on VLMs?
Theory Exercise
Problem:
You are designing a VLM for a mobile health application that needs to: (1) run on a smartphone GPU, (2) process medical images at 512×512 resolution, (3) support English and Spanish, (4) generate structured reports of 200+ tokens. Which LLM backbone would you choose and why?
Hints:
- Mobile GPU = strong memory constraint (4-8GB)
- Medical images need fine-grained detail = many visual tokens
- Bilingual = need adequate vocabulary coverage
- Consider quantized model sizes
Choosing the right LLM backbone size for a VLM is a complex optimization problem. Larger models generally perform better on benchmarks, but they cost more to train, require more memory at inference, and are harder to deploy. Scaling laws provide empirical relationships between model size, dataset size, compute budget, and downstream performance that guide this decision.
For VLMs specifically, the scaling considerations extend beyond the LLM to include the vision encoder size, the bridge architecture complexity, and the total visual token count---each adding to the compute and memory budget.
In this topic
- 1Chinchilla Scaling Law
- 2VLM-Specific Scaling
- 3Quantization for Deployment
Chinchilla Scaling Law
The Chinchilla scaling law (Hoffmann et al., 2022) states that for a fixed compute budget , model parameters and training tokens should be scaled equally: . A compute-optimal 7B model should be trained on ~140B tokens. Many VLM backbones are over-trained relative to Chinchilla (e.g., LLaMA 3 8B trained on 15T tokens), trading compute efficiency for stronger per-parameter performance at inference time.
The empirical loss follows with . Minimizing subject to the compute constraint yields the optimal ratio . Over-training (using ) sacrifices training compute efficiency for better per-parameter quality, which is optimal when inference cost dominates the total deployment budget.
LLaMA 3 8B was trained on 15T tokens. The Chinchilla-optimal data for 8B parameters is ~160B tokens. By what factor is LLaMA 3 over-trained?
VLM-Specific Scaling
VLM inference cost is dominated by the LLM backbone processing the concatenated visual + text tokens. The vision encoder adds a fixed overhead per image. Scaling the LLM backbone from 7B to 70B increases inference cost by ~10x for the same input. Scaling from 256 to 576 visual tokens increases cost by ~2.25x (quadratic in attention, but linear in the FFN which dominates). This creates a two-dimensional scaling problem: model size vs. visual token count.
Total VLM FLOPs decompose as where per token generated. The attention cost within the LLM scales as , creating a quadratic dependence on visual token count. The vision encoder adds a fixed cost per image, making the total cost a sum of two quadratics in .
Compare the approximate LLM inference FLOPs for: (A) 7B model, 256 visual + 100 text tokens vs (B) 13B model, 576 visual + 100 text tokens.
Quantization for Deployment
Quantization reduces the precision of model weights from 16-bit floats to lower bit-widths. A 7B model at FP16 requires ~14GB; at 4-bit (GPTQ/AWQ), only ~3.5GB. This is critical for deploying VLMs on consumer GPUs or edge devices. Modern 4-bit quantization (GPTQ, AWQ, GGUF) loses minimal accuracy on language benchmarks, but the impact on visual understanding tasks is less studied. The KV cache for long visual token sequences also benefits from quantization.
Quantization maps floating-point weights to a discrete grid: where is the scale factor. The quantization error grows as bit-width decreases, but outlier-aware methods (AWQ) weight the error by activation magnitude: , preserving the channels that matter most for the output distribution.
A VLM with a 13B LLM backbone needs to run on an RTX 4090 (24GB VRAM). The ViT encoder uses 430MB. What quantization level is needed?
Theory Exercise
Problem:
You have a 2/GPU-hour). Design the optimal VLM configuration: choose the LLM backbone size, vision encoder, and visual token count. Justify using scaling law reasoning.
Hints:
- 5,000 GPU-hours of A100 available
- A100 achieves ~300 TFLOPS for mixed-precision training
- Consider both training and the resulting inference cost
- Chinchilla-optimal vs over-trained trade-offs