Vision-Language Model (VLM)

LLaVA / Qwen-VL / Cosmos-Reason2 style: a ViT encoder wired to an LLM decoder through a tiny MLP projector. GPU inference study guide with shape traces, fusion mechanics, and edge deployment notes.

Before you start

Prerequisites

  • Module 1: Transformer: causal attention, KV cache, prefill vs decode.
  • Module 2: ViT: patches → tokens, N = (H/P)² patches (a VLM drops [CLS], so N_v = (H/P)²), why ViT is compute-bound.

What you'll learn

  • How image tokens become an LLM "prefix": ViT → projector → concatenation.
  • What the causal mask does to image tokens (and what prefix-LM changes).
  • Why images dominate time-to-first-token, and how token reduction (2×2 merge, resamplers) helps.
  • How to estimate token counts, KV-cache bytes and decode speed on a Jetson from first principles.

Time

  • ~60 min reading + widgets.
  • ~20 min running vlm.py (CPU, ~6 GB RAM) and the exercises.
🎬 Learn it visually
  1. What Are Vision Language Models? How AI Sees & Understands Images, IBM Technology, presented by Martin Keen (video, 10 min). A no-maths first look at what VLMs do and how an image is turned into tokens a language model can read.
  2. Understanding Multimodal LLMs, Sebastian Raschka. Clear diagrams of the two designs compared in §9 (image tokens in the sequence vs cross-attention) and a tour of recent models built each way.
  3. Coding a Multimodal (Vision) Language Model from scratch in PyTorch with full explanation, Umar Jamil (video, 5 h 46 min). Code-along that builds PaliGemma: the SigLIP vision encoder, the projector, the Gemma decoder and a KV cache.
  4. nanoVLM: The simplest repository to train your VLM in pure PyTorch, Hugging Face. A small, readable code base (vision encoder, modality projection, language model) you can train yourself.

Notation on this page

H, W, P
image height and width, patch size (as in Module 2)
N_v, N_t, N
image tokens, text tokens, N = N_v + N_t in the LLM's sequence (Module 1's N)
d_v, d_t
widths of the vision encoder and of the LLM (Module 1's d)
h, d_k, n_kv
query heads, head dimension, K/V heads (as in Module 1; never H)
L, L_v, L_t
layers: of the LLM, or of the vision encoder / LLM when both appear
N_out
output tokens of one answer; m = merge factor (m × m patches → 1 token)

The Key Idea: VLM = ViT + Projector + LLM

In plain words: a VLM gives a language model eyes through a translator. The ViT describes the picture as a few hundred vectors in its own "vector language"; the projector translates them into the LLM's embedding space; the LLM then reads them like a few hundred extra words placed before your question.

A VLM is not a new architecture — it's three existing components wired together:

  1. A vision encoder (the Module 2 ViT, with the [CLS] token and classification head removed) turns an image into a sequence of patch embeddings.
  2. A visual projector (a 2-layer MLP) maps those embeddings from the ViT's hidden dim into the LLM's hidden dim.
  3. An LLM decoder consumes image tokens and text tokens as one concatenated sequence and generates the next token autoregressively.
VLM = ViT + projector + LLM Image Vision encoder (ViT) [N_v, d_v] Projector the translator [N_v, d_t] Text prompt Embedding lookup [N_t, d_t] concat LLM decoder [N_v+N_t, d_t] Next token decode loop
image data text prompt / bookkeeping learned weights mixing across tokens (attention) output

What to notice: image and text meet only at the concat node. After the projector, image tokens have the same width d_t as word embeddings, so the LLM processes them with the same weights and the same attention as words.

Image tokens form a prefix that the LLM attends to while generating text. In practice a chat template wraps them in special tokens; Qwen-VL style, schematically: <|im_start|>user <|vision_start|>[IMAGE TOKENS]<|vision_end|>What is this?<|im_end|><|im_start|>assistant. LLaVA instead puts an <image> placeholder in the prompt and swaps in the 576 projected vectors.

Why this works. You reuse battle-tested ViT and LLM checkpoints. LLaVA's recipe: stage 1 freezes the ViT and the LLM and trains only the projector on image-caption pairs (feature alignment); stage 2 keeps the ViT frozen and fine-tunes the projector + LLM on visual instruction data. Far cheaper than training a multimodal model from scratch.
The projector: a translator into the LLM's embedding space
Intuition
Every image token goes through the same small two-layer network, which re-expresses it in the coordinates the LLM uses for words.
Z = GELU(V·W1 + b1)·W2 + b2
V : [N_v, d_v] → Z : [N_v, d_t],  W1 : [d_v, d_t],  W2 : [d_t, d_t]
Read it aloud
Take the N_v image features V, each d_v wide. Multiply by W1 to get d_t numbers, apply GELU, multiply by W2. Out come N_v vectors, each d_t wide: the LLM's embedding width. For VLM-Small, d_v = 1024 (ViT-L) and d_t = 2048.
Why it exists
Two reasons. The widths differ (1024 vs 2048), so ViT features could not even be concatenated with word embeddings. And even with equal widths the two spaces mean different things: dimension 17 of a ViT feature has nothing to do with dimension 17 of a word embedding. LLaVA's stage 1 trains only this mapping, on image-caption pairs. LLaVA-1.5 replaced LLaVA's single Linear with this 2-layer MLP and improved; PaliGemma deliberately keeps a single Linear.
Tiny example
d_v = 2 → d_t = 3, biases 0. Feature v = [1, −2]; W1 = [[1, 0, 1], [0, 1, 1]] gives v·W1 = [1, −2, −1]; GELU gives [0.8413, −0.0455, −0.1587]; W2 = [[1, 1, 0], [0, 1, 1], [1, 0, 1]] gives the token [0.6827, 0.7958, −0.2042]. Without the GELU, the two layers would collapse into one matrix: v·W1·W2 = [0, −1, −3].
Code
projector = nn.Sequential(nn.Linear(d_v, d_t), nn.GELU(), nn.Linear(d_t, d_t))
image_tokens = projector(vit_features)   # [B, N_v, d_v] → [B, N_v, d_t]
Size
1024·2048 + 2048 + 2048·2048 + 2048 = 6,295,552 ≈ 6.3M parameters (0.5% of VLM-Small) and ≈ 7.2 GFLOPs for 576 image tokens.

1. End-to-End Inference Pipeline

1.1 Shape flow through the full model

Tracing a single image + text query through VLM-Small (ViT-L/14 at 336×336 + 16-layer LLM with d=2048):

Shapes: one 336² image + a 20-token prompt Image [3, 336, 336] ViT-L/14 × 24 [576, 1024] Projector [576, 2048] Text IDs [20] Embed lookup [20, 2048] LLM × 16 [596, 2048] LM head [596, 32000]

What to notice: the image becomes 576 tokens, 29× more than the 20-token prompt, so the LLM's sequence is 576 + 20 = 596 tokens long.

1.2 Two phases of inference

Like any autoregressive LLM, a VLM's forward pass splits into stages with very different cost profiles:

PhaseWhat happensRunsCompute profile
Vision encodeImage → patch features → projected image tokensOnce per imageDense batched GEMMs; compute-bound with Tensor Cores (Module 2)
PrefillFull forward pass on [image tokens + prompt], fills the KV cacheOnce per requestHundreds of tokens in one pass: big GEMMs, compute-bound
DecodeOne token at a time, attending to the cached K,VN_out − 1 times per request (prefill already made token 1)Tiny compute per step; memory-bound at batch 1 (every weight is read once per token)

Two metrics come directly from this split:

2. The Fusion Step

In plain words: paste the translated image tokens in front of the word tokens, like a picture "sentence" placed before the question. Nothing else happens at this step.

The non-obvious part of a VLM is how image and text modalities merge. Once you see it, it's trivially simple — which is why this pattern won.

Fusion = concatenation along the sequence Image tokens [N_v, d_t] v₀ vNv−1 Text tokens [N_t, d_t] t₀ tNt−1 torch.cat(dim=1) LLM input [N_v + N_t, d_t]

What to notice: nothing is added, mixed or cross-attended here. The LLM simply receives a longer sequence, and its own attention does the mixing. In vlm.py nothing marks the boundary (dashed line); real chat templates wrap the image in tokens such as <|vision_start|> … <|vision_end|>.

Fusion as a formula
Intuition
Stack the image tokens and the word tokens into one list; the LLM cannot tell (and does not need to know) where one kind ends.
X = concat( Zimg, Etxt ) along the sequence axis
[N_v, d_t] ⊕ [N_t, d_t] → [N_v + N_t, d_t]
Read it aloud
X stacks the N_v projected image tokens on top of the N_t text embeddings. Both are d_t wide, so the result is one matrix with N_v + N_t rows; row i gets position i.
Why it exists
One sequence lets you reuse an unmodified LLM: its self-attention does the cross-modal mixing. The cost: every image token lengthens the prefill and gets a KV-cache entry in every layer (§3).
Tiny example
N_v = 2 image tokens and N_t = 3 text tokens, d_t = 3: X is [5, 3], positions 0–4. Under a causal mask 15 of the 25 query–key pairs are allowed (5 + 4 + 3 + 2 + 1); the first text token (position 2) sees both image tokens and itself. VLM-Small: 576 + 20 = 596, so X is [1, 596, 2048].
Code
text_embeds = llm.embed_tokens(text_ids)                  # [B, N_t, d_t]
combined = torch.cat([image_tokens, text_embeds], dim=1)  # [B, N_v + N_t, d_t]
logits = llm(combined)                                    # [B, N_v + N_t, vocab]

2.1 Causal attention across modalities

Once concatenated, the sequence passes through causal self-attention. Two things to notice:

🎭 Try it: who can see whom?

A toy sequence of 4 image tokens (blue), 3 prompt tokens (grey) and 3 answer tokens (green). Row = query, column = key; a filled cell means the row can attend to that column. Click a row to inspect it.

What to notice: both masks give answer tokens exactly the same view (everything before them), so generation and the KV cache work the same way. They differ only inside the prefix: causal gives image token i a view of i+1 image tokens (on average about half of them), prefix-LM lets every image and prompt token see the whole prefix. In PyTorch, causal is is_causal=True; prefix-LM needs an explicit boolean attn_mask.

The LLM doesn't have a separate mechanism for "paying attention to the image." Image tokens just happen to be early in the sequence, so every text-generation step naturally attends to them through the same causal self-attention that handles the text.

2.2 Position handling

Each token needs a position. Three common strategies (all built on the LLM's rotary embedding, RoPE):

StrategyUsed byIdea
1D flatLLaVAPositions 0..N_v+N_t−1 assigned in order. Image tokens look like a long run of word tokens; the 2D layout must be inferred.
M-RoPEQwen2-VL, Qwen2.5-VLRotary dimensions are split into temporal / height / width sections; image tokens get (t, row, col) ids. Text tokens use the same id on all three axes, which reduces to plain 1D RoPE.
Interleaved M-RoPEQwen3-VL (so Cosmos-Reason2), Qwen3.5Same idea, but t/h/w are interleaved across the full frequency range instead of contiguous chunks, which helps long videos.

3. Prefill vs Decode Asymmetry

In plain words: the image is read all at once, the answer is written one word at a time. Reading (prefill) is one big parallel job; writing (decode) is many small steps, each limited by how fast the weights can be read from memory.

The critical difference between a VLM and a text-only LLM at inference time is the prefill/decode ratio. Both rows below are drawn to scale:

Prefill vs decode, drawn to scale A · tokens (0.45 px per token) Text chat 50 + 500 tokens VLM, 1 image ~600 + 100 tokens B · time on Orin Nano Super, vLLM (0.25 px per ms) VLM, 1 image 75 ms + 1.68 s
prefill: one parallel pass over the prompt decode: one token per step, memory-bound

What to notice: the image makes the prefill 12× longer than a text chat's (≈600 vs 50 tokens), so it dominates the wait before the first token. For a 100-token answer, decode still takes most of the total time (1.68 s vs 75 ms).

What one token costs in memory: KV-cache bytes per token
Intuition
Every token in the context leaves one K vector and one V vector in every layer, and they stay in memory until the answer is finished. Image tokens are context too.
bytes per token = 2 × L × nkv × dk × bytes per value
Read it aloud
Two tensors (K and V), times the number of layers L, times the number of KV heads, times the head width, times the bytes per number (2 for FP16).
Why it exists
It turns token counts into memory. Multiply by the context length to get the cache size, and remember that each decode step reads the whole cache.
Examples

Cosmos-Reason2-2B (Qwen3-VL-2B text model: 28 layers, 8 KV heads × 128, FP16): 2 × 28 × 8 × 128 × 2 B = 114,688 B = 112 KiB per token. One 448×448 image = 196 tokens → 21.4 MiB; a 1024-token context → 112 MiB.

vlm.py's VLM-Base (same width, but plain MHA: 16 KV heads × 128): 224 KiB per token — GQA halves it.

Qwen3.5-2B (Feb 2026; only 6 of its 24 layers use full attention with 2 KV heads × 256, the other 18 are Gated DeltaNet linear-attention layers): 2 × 6 × 2 × 256 × 2 B = 12 KiB per token, plus a fixed-size recurrent state (18 layers × 16 heads × 128×128 values) that does not grow with context. Linear-recurrent layers of the kind covered in the Mamba module are already in shipping VLMs.

Code
kv_bytes_per_token = 2 * n_layers * n_kv_heads * head_dim * 2   # FP16; = 114,688 for Cosmos-Reason2-2B

4. Image Token Reduction

In plain words: image tokens grow with the area of the picture, so they are the first thing to shrink. Either merge neighbouring patches, or let a few learned "summary" queries read the image.

A 448×448 image at patch size 14 gives 1024 visual tokens. That's before the user types a single word. With 3 images per prompt, you're at 3000 tokens before the conversation starts — and every token inflates the KV cache and prefill compute.

How many image tokens?
Intuition
Count the tiles, then divide by the merge: double the image side and you get four times the tokens.
N_v = (H / P)² / m²
Read it aloud
Image side H divided by patch size P gives the grid side; square it to count patches; divide by m² when an m×m merge follows (m = 2 in Qwen-VL and InternVL, m = 1 in plain LLaVA).
Why it exists
N_v sets the prefill length, the KV-cache size and the N² attention cost (N = N_v + N_t) of every LLM layer, so it is the first number to check for any VLM.
Tiny example
448 / 14 = 32 → 32² = 1024 tokens (vlm.py, no merge). Qwen3-VL: 448 / 16 = 28 → 784 patches → ÷ 4 = 196. LLaVA-1.5: 336 / 14 = 24 → 576.
Code
n_v = (H // P) ** 2 // m ** 2   # 1024 for (448, 14, 1); 196 for (448, 16, 2)

Four common reduction strategies:

Four ways to cut the image-token count (448² image) Raw patches LLaVA, vlm.py 1024 tokens 2×2 merge Qwen-VL, InternVL 256 tokens Perceiver resampler Flamingo, Idefics2 64–256 tokens Q-Former BLIP-2 32 tokens
image patches / tokens one merged token (per-token MLP) learned queries / module cross-attention token count (cost)

What to notice: the merge keeps every patch's information and the 2D grid (it moves 4 patches into one token's channels); the two query-based methods fix the count regardless of resolution but add a learned module.

StrategyHow it worksTokens (448², P = 14)Trade-off
Raw patches (plain LLaVA, vlm.py)one token per patch, N_v = (H/P)²1024simple, no compression; baseline, too many tokens
2×2 merge, "pixel shuffle" (Qwen2/3-VL, Cosmos-Reason2, InternVL)stack 4 neighbouring patches into 4·d_v channels, then an MLP → d_t256nothing dropped, keeps the 2D grid; current mainstream
Perceiver resampler (Flamingo, Idefics2)K learned queries cross-attend to all patches64–256 (fixed)decouples N_v from resolution; extra parameters (~200M in Flamingo)
Q-Former (BLIP-2)a small transformer (~188M) with 32 learned queries32 (fixed)most aggressive, loses spatial detail; its output is concatenated as an LLM prefix

The 2×2 merge has won mainstream. Qwen2-VL, Qwen2.5-VL, Qwen3-VL (hence Cosmos-Reason2) and InternVL all use it. Qwen-VL calls it a patch merger, InternVL calls it pixel shuffle; it is the same space-to-depth reshape followed by an MLP:

# Input: patch features from ViT, [B, H/P, W/P, d_v]
# H/P = W/P = 32 for 448/14 → 1024 patches in a 32×32 grid

# 2×2 merge: stack each 2×2 block of neighbouring patches into one token
B, Gh, Gw, C = x.shape                           # [B, 32, 32, 1024]
x = x.reshape(B, Gh//2, 2, Gw//2, 2, C)          # [B, 16, 2, 16, 2, 1024]
x = x.permute(0, 1, 3, 2, 4, 5)                    # [B, 16, 16, 2, 2, 1024]
x = x.reshape(B, (Gh//2)*(Gw//2), 4*C)           # [B, 256, 4096]
x = merger_mlp(x)                                # [B, 256, d_t]: Linear(4C,4C) → GELU → Linear(4C, d_t)
                                                 # (this MLP replaces the plain projector)

# 4× fewer tokens, same information (moved into the channel dim)

Why "almost free": the merger MLP runs on 256 tokens of width 4096, so its FLOPs (≈ 12.9 GFLOPs for d_t = 2048) are about the same as the plain projector on 1024 tokens, but every LLM layer after it now sees 4× fewer image tokens: prefill FLOPs, KV cache and attention all shrink.

Worked example: tokens for one 448×448 image, as of Oct 2026

Model (vision tower)RecipeArithmeticLLM tokens
vlm.py VLM-Base (ViT-L/14 @448)raw patches(448/14)² = 32²1024
LLaVA-1.5 (CLIP ViT-L/14-336)resize to 336², raw patches(336/14)² = 24²576
Qwen2-VL / Qwen2.5-VLP = 14, native resolution, 2×2 merge32² / 4 (+2 marker tokens)256
InternVL3448² tiles, P = 14, pixel shuffle 0.532² / 4 per tile (bigger images get more tiles)256
Qwen3-VL-2B / Cosmos-Reason2-2B / Qwen3.5P = 16, 2×2 merge (one token per 32×32 px)(448/16)² / 4 = 28² / 4196
Idefics2Perceiver resampler (then concatenated)64 learned queries64
BLIP-2Q-Former32 learned queries32
FlamingoPerceiver → cross-attention64 latents, outside the LLM sequence0

At Cosmos-Reason2's 112 KiB per token (§3), the 1024 → 196 difference is 112 MiB vs 21 MiB of KV cache per image. Other levers you will meet: windowed attention inside the ViT (Qwen2.5-VL keeps full attention in only 4 of its ViT blocks), and training-free pruning of low-attention visual tokens at inference (FastV, VisionZip), which trades some accuracy for speed.

5. Code Walkthrough

The core classes from vlm.py. Click any header to expand.

6. Complexity Calculator

The three vlm.py presets reproduce count_parameters() and compute_flops() exactly (default: VLM-Base, the last row of python vlm.py's comparison table). The Cosmos-Reason2-2B preset is an approximation: right token count and KV layout, simplified MLP and no DeepStack mergers.

Presets:

FLOPs count matmuls only (1 MAC = 2 FLOPs) and assume MHA-sized projections and a 4× GELU MLP, as in vlm.py. "2×2 merge" uses a Qwen-style merger MLP (Linear(4d_v, 4d_v) → GELU → Linear(4d_v, d_t)) in place of the projector; a 16-query-head / 8-KV-head model is "1/2". With a resampler, the projector row counts the MLP only (its cross-attention is not modelled). The LM head is applied to the last prefill position and to each decoded token. Weight memory applies one precision to everything; real W4A16 deployments usually keep the vision tower and the LM head in FP16.

7. Critical Optimizations for Inference

In plain words: make the GPU read and compute less. For a VLM that means fewer image tokens, fewer weight bytes per decode step, and never encoding the same image twice.

The general techniques below (FlashAttention, quantization, KV-cache sizing, chunked prefill) are explained step by step in the Memory & inference efficiency cookbook; this section covers what is specific to VLMs.

8. Deployment on Orin Nano — What Actually Mattered

From my three-runtime benchmark of Cosmos-Reason2-2B on the 8 GB Orin Nano Super (JetPack 6.2.2, MAXN_SUPER power mode):

RuntimeQuantizationTTFT (text)TTFT (image)TPOTTPSPeak memory
llama.cppQ4_K_M33 ms114 ms26 ms38—
vLLMW4A16 AWQ61 ms75 ms17 ms566.9 GB
TRT Edge-LLMW4A16 AWQ29 ms420 ms17 ms604.3 GB

Three observations that came out of the data:

  1. The image TTFT gap is the vision + visual-token prefill cost. Every runtime's image TTFT is 1.2–14.5× its text TTFT (gaps of 81, 14 and 391 ms). The gap is time spent on the vision encode plus prefill over the visual tokens, and how well each runtime handles that path (engine warm-up, CUDA graphs, caching) varies a lot. This is the prefill-dominated TTFT story from §3, visible in real numbers.
  2. Decode TPS tracks LPDDR5 bandwidth, not compute. 38–60 TPS across three very different runtimes, all on the same 102 GB/s memory subsystem. Decode is memory-bound at batch 1; bandwidth is the real bottleneck, not TOPS (worked example below).
  3. TRT Edge-LLM wins peak memory by a lot. 4.3 GB vs 6.9 GB — 37% less than vLLM. Why: fully-fused engine with predictable static allocations, no Python overhead, INT4 weights pre-packed. Cost: 10-minute engine build + two workarounds (CMA kernel param + ONNX graph rewrite).

Worked example: why TPOT is ≈ 17 ms (a bandwidth lower bound)

At batch 1, each decode step must stream every LLM weight from DRAM once. Cosmos-Reason2-2B's text model (Qwen3-VL-2B dims: 28 layers, d = 2048, GQA 16q/8kv × 128, SwiGLU 6144) has 50.3M weights per layer → 1.41B non-embedding weights, plus a 151,936 × 2048 = 311M-weight LM head (the embedding table itself is only gathered, one row per token).

Production trade-off made concrete. llama.cpp: portable generic CUDA kernels, small-chunk memory allocation — no build step, works everywhere, middling speed. TRT Edge-LLM: device-specific tactic selection, large contiguous scratch buffers — fastest when built, failed the first time because Myelin's 1 GiB allocation hit NvMap fragmentation on JetPack 6.2.2. The portability/optimality trade-off is not just a talking point at the edge.

9. Two Fusion Patterns

In plain words: either put the image into the conversation (concatenation), or let the text look at the image through a side window (cross-attention).

This guide has focused on the concatenation pattern (LLaVA, Qwen-VL, Cosmos). There's a second family worth knowing:

Two fusion patterns Concatenation LLaVA, Qwen-VL, Cosmos image text one sequence → LLM self-attention Cross-attention Flamingo, Llama 3.2-Vision image text K, V Q gated x-attn

What to notice: on the left the image tokens become part of the LLM's own sequence; on the right they stay outside it and are read only through extra cross-attention layers (Q from text, K/V from the image).

ConcatenationCross-attention
Used byLLaVA, Qwen-VL, Cosmos, Idefics2Flamingo, IDEFICS-1, Llama 3.2-Vision
How the image entersas extra tokens in the sequence; standard causal self-attention, all tokens through the same weightsthrough gated cross-attention layers inserted into the LLM
Strengthssimpler, reuses a vanilla LLM; won the mainstreamimage tokens don't grow the LLM sequence
CostsN_v tokens inflate prefill cost and the KV cachearchitecturally invasive; more parameters

When someone says "VLM" today, assume concatenation. The cross-attention pattern is rarer but shows up where N_v would otherwise explode (many images, video) and in Meta's Llama 3.2-Vision. BLIP-2's Q-Former uses cross-attention inside the adapter, but its 32 outputs are then concatenated as an LLM prefix, so at the LLM it is the concatenation pattern. Idefics2's authors compared the two directly: cross-attention did better while the pretrained backbones stayed frozen, but once the backbones were trained too (with LoRA for stability), the fully autoregressive (concatenation) design won despite having fewer parameters.

10. Recap, Self-Check and Exercises

Key takeaways

Self-check

1. How many LLM tokens does Qwen3-VL-2B (or Cosmos-Reason2-2B) produce for a 448×448 image? And vlm.py's VLM-Base?

Answer
Qwen3-VL: patch 16 → (448/16)² = 784 patches, 2×2 merge → 196 tokens (plus vision start/end markers). VLM-Base: patch 14, no merge → (448/14)² = 1024 tokens.

2. In vlm.py, can image token 3 attend to image token 7? In PaliGemma?

Answer
vlm.py: no — is_causal=True covers the whole sequence, so token 3 sees tokens 0..3. PaliGemma: yes — its prefix-LM mask makes the image + prompt block bidirectional.

3. What is the FP16 KV cache per token for Cosmos-Reason2-2B, and for a 1024-token context? What would full MHA cost?

Answer
2 × 28 layers × 8 KV heads × 128 × 2 B = 114,688 B = 112 KiB/token; 1024 tokens → 112 MiB. With 16 KV heads (MHA, as in vlm.py's VLM-Base): 224 KiB/token, 224 MiB.

4. With vLLM on the Orin Nano Super, image TTFT is 75 ms and TPOT is 17 ms. For a 100-token answer, which phase dominates end-to-end latency?

Answer
Decode: 99 × 17 ms = 1.68 s vs 75 ms TTFT (TTFT already produced token 1), so decode is ~96% of the 1.76 s total. Images dominate TTFT; long answers are still decode-dominated.

5. Estimate a lower bound for TPOT of a W4A16 2B VLM on a 102 GB/s device.

Answer
Bytes per token ≈ 1.41B × 0.5 B + LM head (0.62 GB FP16 or 0.16 GB INT4) ≈ 0.86–1.33 GB → ÷ 102 GB/s ≈ 8.4–13 ms. The measured 17 ms is ~50–78% of peak bandwidth.

6. A 2×2 merge turns [1024, 1024] ViT features into what shape before the merger MLP, and why is it "almost free"?

Answer
[256, 4096]: each token stacks a 2×2 block of patches in its channels. The merger MLP on 256 × 4096 costs about as much as the plain projector on 1024 × 1024 (≈ 12.9 GFLOPs for d_t = 2048), but every LLM layer afterwards sees 4× fewer image tokens.

7. In LLaVA's two-stage training, what is trained in each stage?

Answer
Stage 1 (feature alignment): only the projector; ViT and LLM frozen. Stage 2 (visual instruction tuning): projector + LLM; the ViT stays frozen.

8. Which fusion pattern grows the LLM's KV cache with image tokens, and which does not?

Answer
Concatenation puts image tokens into the LLM sequence, so they get KV entries in every layer and lengthen every attention. Cross-attention (Flamingo, Llama 3.2-Vision) keeps them outside the self-attention sequence: the image K/V for the inserted cross-attention layers are computed once per image, but the self-attention KV cache and causal sequence only hold text tokens.

9. You cache encoder outputs keyed by the image file's bytes. What can go wrong?

Answer
The same file preprocessed to a different resolution (or with different normalization) produces different tokens but hits the same key. Key on the preprocessed tensor (and its shape), as in the 7.2 snippet.

Hands-on exercises (with vlm.py)

🔧 Build it yourself

labs/lab05.html is a guided lab: build the projector, the image+text concatenation, the joint attention mask and image-token counting of a tiny VLM from scratch and check the shapes as you go. Setup is in labs/index.html. The exercises below then extend vlm.py.

E1 (easy) — count and tie. Add tie_embeddings=True to the LLM in vlm_base() and recount (build it under with torch.device("meta"):).

Self-verify: count_parameters drops from 2,358,885,376 to 2,047,720,448, a difference of exactly 151,936 × 2048 = 311,164,928, and m.llm.lm_head.weight is m.llm.embed_tokens.weight.

E2 (easy) — check the FLOP counter. For vlm_tiny(), run model.vision_encoder(img) under torch.utils.flop_counter.FlopCounterMode.

Self-verify: the measured total equals compute_flops(model)["vision_gflops"] * 1e9 (9.147 GFLOPs). Then repeat for the projector.

E3 (medium) — a Qwen-style 2×2 merger. Write PatchMerger(d_v, d_t): LayerNorm(d_v) → reshape the 32×32 grid as in §4 → Linear(4d_v, 4d_v) → GELU → Linear(4d_v, d_t). Use it in place of VisualProjector.

Self-verify: output shape [B, N_v/4, d_t]; merged token 0 (before the MLP) equals torch.cat of patches (0,0), (0,1), (1,0), (1,1); the calculator with "2×2 merge" shows the same projector FLOPs as FlopCounterMode.

E4 (medium) — prefix-LM mask. Give CausalAttention an optional boolean attn_mask and build a PaliGemma-style mask: full attention inside the first N_v + N_t positions, causal after.

Self-verify: rerun demo_causal_image_tokens() with the mask: earlier image positions now do change when the last image token changes; positions after the prefix still never depend on later positions.

E5 (hard) — KV-cache generation. Implement generate(model, image, ids, n_new) with greedy decoding: one prefill pass that stores K and V per layer, then one-token steps that append to the cache.

Self-verify: the generated tokens equal those from re-running the full forward pass at every step. Watch the trap: for the 1-token steps, do not pass is_causal=True (top-left alignment would hide all keys but the first). Then time both versions to see why the cache exists.

References