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.
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.
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:
A vision encoder (the Module 2 ViT, with the [CLS] token and classification head removed) turns an image into a sequence of patch embeddings.
A visual projector (a 2-layer MLP) maps those embeddings from the ViT's hidden dim into the LLM's hidden dim.
An LLM decoder consumes image tokens and text tokens as one concatenated sequence and generates the next token autoregressively.
image datatext prompt / bookkeepinglearned weightsmixing 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.
Shapes with batch B: image [B, 3, H, W] (C×H×W, NCHW) → ViT patch embed + blocks, no [CLS], no head → [B, N_v, d_v] → projector (2-layer MLP) → [B, N_v, d_t]. Text "What is this?" → [B, N_t] token IDs → lookup in the LLM's embedding table → [B, N_t, d_t]. The LLM (causal attention × L) sees [B, N_v + N_t, d_t]; the LM head on the last position gives the next-token logits.
Decode loop (dashed): append the sampled token, run the LLM on just that token (the KV cache holds the rest), repeat.
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].
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):
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.
Where 576 comes from: N_v = (336/14)² = 24² = 576 (a Conv2d with kernel = stride = 14 inside the ViT). Batch = 1 is dropped from the labels.
Attention: bidirectional inside the ViT, causal inside the LLM. The text embedding table is [32K, 2048]. Generation only needs the logits of the last position, [:, -1].
Like any autoregressive LLM, a VLM's forward pass splits into stages with very different cost profiles:
Phase
What happens
Runs
Compute profile
Vision encode
Image → patch features → projected image tokens
Once per image
Dense batched GEMMs; compute-bound with Tensor Cores (Module 2)
Prefill
Full forward pass on [image tokens + prompt], fills the KV cache
Once per request
Hundreds of tokens in one pass: big GEMMs, compute-bound
Decode
One token at a time, attending to the cached K,V
N_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:
TTFT (time-to-first-token) = vision encode + prefill. This is the wait the user feels before any output appears.
TPOT (time-per-output-token) = decode time per token. This is the steady-state streaming speed. End-to-end latency ≈ TTFT + (N_out − 1) × TPOT, because TTFT already ends with the first output token.
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.
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].
Once concatenated, the sequence passes through causal self-attention. Two things to notice:
Image tokens are causally masked too. With a plain causal mask (LLaVA, Qwen-VL, and is_causal=True in vlm.py), image token i sees only image tokens 0..i: the first patch "reads" none of the others inside the LLM. This costs little because the ViT already mixed all patches bidirectionally before projection. Prefix-LM models such as PaliGemma instead use a bidirectional block over the whole image + prompt prefix. (vlm.py's demo_causal_image_tokens() perturbs the last image token: earlier image positions change by exactly 0.)
Text tokens see all image tokens plus all earlier text tokens. Text token at position N_v + i attends to positions 0 through N_v + i, so it has full access to the image and the conversation history up to that point.
🎭 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):
Strategy
Used by
Idea
1D flat
LLaVA
Positions 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-RoPE
Qwen2-VL, Qwen2.5-VL
Rotary 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-RoPE
Qwen3-VL (so Cosmos-Reason2), Qwen3.5
Same 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: one parallel pass over the promptdecode: 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).
Row A: the VLM prefill is 576 image tokens + ~24 prompt tokens. Row B uses the vLLM numbers from §8: TTFT 75 ms (ending with token 1), then 99 tokens × 17 ms.
Why this matters for optimization: in a text chat, decode dominates, so GQA/MQA, KV-cache quantization and INT4 weights matter most. In a VLM, image tokens dominate TTFT, so FlashAttention, chunked prefill and token reduction matter too. For answers of 100+ tokens decode still dominates total time: both matter.
My Orin Nano Super benchmark (Cosmos-Reason2-2B): TTFT text-only 29–61 ms across three runtimes; with an image 75–420 ms (1.2–14.5× the text TTFT). The gap is the vision encode plus the prefill of the visual tokens.
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.
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.
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.
stack 4 neighbouring patches into 4·d_v channels, then an MLP → d_t
256
nothing dropped, keeps the 2D grid; current mainstream
Perceiver resampler (Flamingo, Idefics2)
K learned queries cross-attend to all patches
64–256 (fixed)
decouples N_v from resolution; extra parameters (~200M in Flamingo)
Q-Former (BLIP-2)
a small transformer (~188M) with 32 learned queries
32 (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)
Recipe
Arithmetic
LLM 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-VL
P = 14, native resolution, 2×2 merge
32² / 4 (+2 marker tokens)
256
InternVL3
448² tiles, P = 14, pixel shuffle 0.5
32² / 4 per tile (bigger images get more tiles)
256
Qwen3-VL-2B / Cosmos-Reason2-2B / Qwen3.5
P = 16, 2×2 merge (one token per 32×32 px)
(448/16)² / 4 = 28² / 4
196
Idefics2
Perceiver resampler (then concatenated)
64 learned queries
64
BLIP-2
Q-Former
32 learned queries
32
Flamingo
Perceiver → cross-attention
64 latents, outside the LLM sequence
0
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.
VisionEncoder — stripped-down ViT▼
Purpose: Turn an image into a sequence of patch features for the projector. Same architecture as the Module 2 classification ViT but with two parts removed: no [CLS] token (we want all patch tokens, not a single global vector) and no classification head (we're not predicting classes — we're producing features for the LLM).
classVisionEncoder(nn.Module):
def__init__(self, img_size=448, patch_size=14, embed_dim=1024,
depth=24, num_heads=16):
super().__init__()
self.embed_dim = embed_dim
self.patch_embed = PatchEmbed(img_size, patch_size, 3, embed_dim)
num_patches = self.patch_embed.num_patches # 1024 for 448/14# Pos embed has one slot per patch — no extra slot for CLS
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim))
self.blocks = nn.ModuleList([
VisionBlock(embed_dim, num_heads) for _ inrange(depth)
])
self.norm = nn.LayerNorm(embed_dim)
nn.init.trunc_normal_(self.pos_embed, std=0.02)
defforward(self, images):
x = self.patch_embed(images) # [B, N_v, d_v]
x = x + self.pos_embed
for block in self.blocks:
x = block(x) # bidirectional attn
x = self.norm(x)
return x # [B, N_v, d_v] — features
Real towers: LLaVA's CLIP ViT-L/14-336 does have a [CLS] token; LLaVA drops it after encoding and takes features from the second-to-last block (vision_feature_layer=-2), before any final norm. SigLIP-style towers have no [CLS] at all.
Deployment note: This module has a fixed output shape given a fixed input image size — no autoregression, no KV cache. It compiles cleanly to a static TensorRT engine and captures well with CUDA graphs. Models with native-resolution input (Qwen-VL family) need an engine with dynamic shapes or a few fixed resolution buckets.
VisualProjector — the bridge MLP▼
Purpose: Map vision features [B, N_v, d_v] into the LLM's embedding space [B, N_v, d_t]. This is the only module trained from scratch in LLaVA-style training — in stage 1 the ViT and LLM stay frozen while the projector learns to align the two spaces.
Why it's so small: Two linear layers and a GELU: 1024·2048 + 2048 + 2048·2048 + 2048 = 6.3M params for d_v=1024, d_t=2048, about 0.5% of VLM-Small. Inference cost is small next to the ViT and the LLM; deployments usually build it into the vision engine.
Variants: The original LLaVA used a single Linear; LLaVA-1.5 switched to this 2-layer MLP and improved. PaliGemma deliberately uses a single Linear. Qwen-VL models use the 2×2 merger MLP (§4). Flamingo uses a Perceiver resampler; BLIP-2 uses a Q-Former followed by a Linear into the LLM's width.
LLMDecoder — causal transformer▼
Purpose: Consume a sequence of embeddings (image tokens + text embeddings, pre-fused) and produce next-token logits. This is a standard decoder-only LLM — the multimodal magic already happened in the fusion step.
Note on the interface: This takes embeddings, not token IDs. The token-ID lookup happens outside, in the VLM wrapper, because we need to concatenate with image tokens before feeding the LLM.
classLLMDecoder(nn.Module):
def__init__(self, vocab_size=32000, hidden_dim=2048,
depth=24, num_heads=16, max_seq_len=4096, tie_embeddings=False):
super().__init__()
self.hidden_dim = hidden_dim
self.vocab_size = vocab_size
# Token embedding table — used by outer VLM for text lookup
self.embed_tokens = nn.Embedding(vocab_size, hidden_dim)
self.pos_embed = nn.Parameter(torch.zeros(1, max_seq_len, hidden_dim))
self.blocks = nn.ModuleList([
LLMBlock(hidden_dim, num_heads) for _ inrange(depth)
])
self.norm = nn.LayerNorm(hidden_dim)
self.lm_head = nn.Linear(hidden_dim, vocab_size, bias=False)
if tie_embeddings: # Qwen3-VL-2B ties; LLaVA-1.5 doesn't
self.lm_head.weight = self.embed_tokens.weight
nn.init.trunc_normal_(self.pos_embed, std=0.02)
defforward(self, embeds):
# embeds: [B, N, hidden_dim] — already-fused image + text
B, N, _ = embeds.shape
x = embeds + self.pos_embed[:, :N]
for block in self.blocks:
x = block(x) # causal self-attention
x = self.norm(x)
return self.lm_head(x) # [B, N, vocab]
Real-world differences from this code: Modern LLMs use RoPE instead of learned position embeddings (better length generalization), RMSNorm instead of LayerNorm, SwiGLU instead of GELU in the MLP, and GQA (fewer K,V heads than Q heads: Qwen3-1.7B uses 16 Q / 8 KV heads, a 2× smaller KV cache; Llama 3.1 8B (same shape as Llama 3 8B) uses 32 / 8, 4×). Some tie the LM head to the embedding table. All substitutable without changing the VLM structure.
CausalAttention — where the mask lives▼
Purpose: The one line that makes the LLM a decoder. The mask covers the whole concatenated sequence, image tokens included (§2.1).
classCausalAttention(nn.Module):
def__init__(self, dim, num_heads):
super().__init__()
self.num_heads = num_heads
self.head_dim = dim // num_heads
self.qkv = nn.Linear(dim, dim * 3, bias=False) # Llama/Qwen3: no QKV bias
self.proj = nn.Linear(dim, dim, bias=False)
defforward(self, x):
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim)
q, k, v = qkv.permute(2, 0, 3, 1, 4).unbind(0)
# position i attends to 0..i — image tokens included
x = F.scaled_dot_product_attention(q, k, v, is_causal=True)
return self.proj(x.transpose(1, 2).reshape(B, N, C))
KV-cache trap: when you add a cache and run one new query against N cached keys, is_causal=True uses a top-left-aligned mask, so the single query row would see only key 0. For a 1-token decode step, pass no mask (the new token may see every cached key) — see exercise E5.
VLM — the full model, the fusion step▼
Purpose: Tie everything together. This class is the one that actually answers the question "what is a VLM?" — it shows exactly how image tokens get stitched into the text sequence before the LLM runs.
classVLM(nn.Module):
def__init__(self, vision_encoder, llm):
super().__init__()
self.vision_encoder = vision_encoder
self.projector = VisualProjector(
vision_dim=vision_encoder.embed_dim,
text_dim=llm.hidden_dim,
)
self.llm = llm
defencode_image(self, images):
# The step that gets CACHED in production —# deterministic, runs once per image.
vision_feats = self.vision_encoder(images) # [B, N_v, d_v]
image_tokens = self.projector(vision_feats) # [B, N_v, d_t]return image_tokens
defforward(self, images, text_token_ids):
# Vision path (once per image)
image_tokens = self.encode_image(images) # [B, N_v, d_t]# Text path: token IDs → embeddings via LLM's table
text_embeds = self.llm.embed_tokens(text_token_ids) # [B, N_t, d_t]# *** THE FUSION STEP ***# Both tensors are in the LLM's embedding space now —# concatenating them is well-defined.
combined = torch.cat([image_tokens, text_embeds], dim=1)
# LLM sees one sequence, doesn't distinguish modalitiesreturn self.llm(combined) # [B, N_v+N_t, vocab]
What's NOT shown here: The autoregressive generation loop (KV cache, sampling) and the real chat template that surrounds image tokens with control markers like <|vision_start|> / <|vision_end|>. Those live in the inference stack (vLLM, TensorRT Edge-LLM, llama.cpp), not in the model architecture itself. Exercise E5 adds the loop.
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.
7.1 FlashAttention — mandatory for long prefill▼
Vanilla attention materializes the [B, h, N, N] score matrix in DRAM (h = heads). For a VLM with N=1024 visual tokens and 16 heads at batch 1, FP16, that's 16 × 1024 × 1024 × 2 B = 32 MiB per layer — written, then read back. Across 28 LLM layers: ~0.9 GB written plus ~0.9 GB read just for the attention matrix.
FlashAttention tiles the computation in on-chip SRAM and never materializes the full score matrix. On a Jetson Orin Nano Super with 102 GB/s of LPDDR5 shared by CPU and GPU, avoiding ~1.8 GB of traffic is worth ~18 ms of TTFT on its own. It is on by default in modern frameworks (PyTorch 2.x SDPA on Ampere-class GPUs such as Orin, vLLM, TensorRT).
import torch.nn.functional as F
# PyTorch picks a fused (Flash / memory-efficient) kernel automatically when it can
x = F.scaled_dot_product_attention(q, k, v, is_causal=True)
7.2 Vision encoder caching▼
The vision encoder is deterministic: same preprocessed image, same token sequence. In multi-turn chat, or when the same image appears across many queries, cache the post-projector tokens. On VLM-Base each cache hit saves one ViT-L/14 forward at 448² (~0.72 TFLOPs, the calculator's "Vision encoder FLOPs") plus the projector. Note that new frames from a camera are new images: caching helps repeated images, not video streams.
import hashlib
import torch
CACHE = {}
defencode_image_cached(model, image): # image: [3, H, W] preprocessed tensor# Key on the preprocessed pixels AND shape, so the same file resized differently misses
key = (hashlib.sha256(image.cpu().numpy().tobytes()).hexdigest(), tuple(image.shape))
if key not in CACHE:
with torch.no_grad():
CACHE[key] = model.encode_image(image.unsqueeze(0)) # [1, N_v, d_t]return CACHE[key]
vLLM's V1 engine does this for you: its encoder cache shares the vision-encoder outputs of the same multimodal item (identified by its content hash) across requests. In other runtimes you may have to wire it up yourself.
7.3 Separate vision and LLM engines▼
Edge deployments typically split the vision encoder and LLM decoder into two independent inference engines. TensorRT Edge-LLM, for example, builds a visual.engine and a separate LLM engine. Why:
Vision runs once per image; the LLM runs once per output token. Different cost profiles want different batch strategies.
Vision has a static (or bucketed) shape; the LLM needs a KV cache and, in servers, continuous batching.
Engines can live on different devices in multi-GPU deployments.
Quantization differs — the ViT tolerates INT8 well, while the LLM decoder usually wants INT4 weights + FP16 activations.
What to notice: the two engines run at different rates, so they are optimized separately. Vision engine (e.g. TensorRT Edge-LLM's visual.engine): static shape, CUDA graph, FP16 or INT8. LLM engine: prefill once, then one decode step per token; KV cache (paged in servers); INT4 weights + FP16 activations. TTFT = vision + prefill; TPOT = one decode step; output streams to the user.
vLLM, by contrast, runs the vision encoder and the LLM inside one model runner, but schedules encoder work separately and caches its outputs (7.2).
Standard prefill processes the full [N_v + N_t] input in one pass, blocking any other request. Chunked prefill breaks it into smaller pieces (say, 256 tokens at a time) and interleaves them with decode steps from other requests.
For a serving system with 10 concurrent requests, this prevents any single VLM request with a big image from monopolizing the GPU for 200+ ms. Instead, the GPU alternates between "prefill chunk for request A" and "decode step for requests B-J."
vLLM's V1 engine enables chunked prefill by default and splits any prefill that exceeds its per-step token budget (max_num_batched_tokens). In TensorRT-LLM's LLM API it is enable_chunked_prefill=True (off by default). Directly relevant if you're serving multiple users; on a single-user Jetson it mostly matters for very long multi-image prompts.
7.5 Quantization — different for each component▼
Different VLM components have different quantization tolerances:
Component
Typical quantization
Why
Vision encoder
INT8 or FP16
ViT tolerates INT8 well; static shape makes PTQ easy
Projector
FP16
Tiny, not worth quantizing; accuracy-sensitive
LLM decoder weights
INT4 (AWQ or GPTQ)
Biggest component; decode is bandwidth-bound, so 4× fewer bytes ≈ faster tokens
LLM decoder activations
FP16
W4A16 is the sweet spot for edge deployment
KV cache
FP16 or INT8/FP8
8-bit KV halves cache memory, usually with small quality loss
On my Orin Nano runs, W4A16 AWQ + FP16 vision + FP16 KV fit the 2B model in 4.3 GB peak with room to spare.
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):
Runtime
Quantization
TTFT (text)
TTFT (image)
TPOT
TPS
Peak memory
llama.cpp
Q4_K_M
33 ms
114 ms
26 ms
38
—
vLLM
W4A16 AWQ
61 ms
75 ms
17 ms
56
6.9 GB
TRT Edge-LLM
W4A16 AWQ
29 ms
420 ms
17 ms
60
4.3 GB
Three observations that came out of the data:
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.
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).
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).
W4A16: 1.41B × 0.5 B ≈ 0.70 GB (4 bits per weight, group scales ignored; AWQ's g = 128 scales make it 4.25 bits, about 6% more), plus the LM head: 0.62 GB if kept in FP16 (common for AWQ checkpoints) or 0.16 GB if 4-bit → 0.86–1.33 GB per token.
Divide by 102 GB/s → 8.4–13.0 ms per token as a hard floor (ignoring KV reads, ~0.1 MB per context token).
Measured 17 ms → the runtimes reach ~50–78% of peak bandwidth, which is typical. Arithmetic intensity is ~2 FLOPs per weight per 0.5 B ≈ 4 FLOP/byte, far below the Orin Nano Super's ridge of ≈ 167 FLOP/byte (17 FP16 TFLOPS ÷ 102 GB/s): adding TOPS would not help, fewer bytes would.
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:
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).
Concatenation
Cross-attention
Used by
LLaVA, Qwen-VL, Cosmos, Idefics2
Flamingo, IDEFICS-1, Llama 3.2-Vision
How the image enters
as extra tokens in the sequence; standard causal self-attention, all tokens through the same weights
through gated cross-attention layers inserted into the LLM
Strengths
simpler, reuses a vanilla LLM; won the mainstream
image tokens don't grow the LLM sequence
Costs
N_v tokens inflate prefill cost and the KV cache
architecturally 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
A VLM = the Module 2 ViT (no [CLS], no head) → a small projector → a decoder LLM that sees image tokens as a prefix.
Fusion is a torch.cat along the sequence dimension; the causal mask then applies to image tokens too, unless the model uses a prefix-LM mask.
Visual tokens dominate the prefill: N_v = (H/P)², reduced 4× by a 2×2 merge (Qwen3-VL: one token per 32×32 px → 196 tokens at 448²).
Each prefix token costs KV memory: 2 × L × n_kv × head_dim × bytes (112 KiB for Cosmos-Reason2-2B at FP16).
TTFT = vision + prefill (image-dominated); TPOT = one decode step, bounded by bytes of weights ÷ DRAM bandwidth.
On an Orin Nano Super, W4A16 decode of a 2B VLM has a floor of ~8–13 ms/token; measured 17 ms.
Deploy the vision encoder and the LLM as separately optimized engines; cache encoder outputs for repeated images.
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?
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.