Multimodal LLMs: How an Image Becomes Tokens
A vision-language model cuts an image into patches, turns them into visual tokens with a vision encoder and a projector, and feeds them to a language model. Measured here are CLIP's contrastive loss, LLaVA's two training stages, token and KV cache costs, and how resolution affects small text.
After this page you will be able to
- Draw the data flow of a multimodal LLM (image, patches, vision encoder, merge and projection, visual tokens, language model) and write down the tensor shape at each step.
- Write CLIP's symmetric contrastive loss, explain the roles of the temperature and the batch size, and check it with zero-shot classification.
- Estimate the number of visual tokens of an image in a dynamic-resolution model with the
smart_resizerule, and convert it into context usage, KV cache and prefill latency. - Explain which parameters each stage of LLaVA's two-stage training updates and what data it uses.
- Choose a resolution and an approach (OCR pipeline, vision-language model or a combination) for a task, and debug along "did it see, is it aligned, did it use it".
On this page
- The Big Picture: How an Image Enters the Language Model
- Patches and the Vision Encoder: Why Resolution Is a Cost
- CLIP: Aligning Images and Text with Contrastive Learning
- From Alignment to Conversation: LLaVA’s Two Stages
- Dynamic Resolution: How Many Tokens Does an Image Take
- The Bill for Visual Tokens: Context, KV Cache and Latency
- Experiment: Resolution Decides Whether Small Text Can Be Read
- Choosing an Approach: OCR, a Vision-Language Model or a Combination
- Debugging: Did It See, Is It Aligned, Did It Use It
- Evaluation: “Sounds Right” Is Not Enough
- From image question answering to native multimodality
- Video models can predict images or representations
- Summary and Exercises
- Quick quiz
- Further Reading
- FAQ
A multimodal large language model (also called a vision-language model, VLM) works in a way that fits in one sentence: it turns the image into a sequence of vectors and puts them into the language model’s input as “visual tokens”. The language model itself barely changes: it still reads a sequence of tokens and predicts the next one, only that some of the tokens come from a picture. So every multimodal question comes down to three things: how an image becomes vectors (the vision encoder), how the vectors become tokens the language model can read (merging and projection), and how many tokens an image takes (resolution and cost). This page first lays out the data flow, then uses CLIP and LLaVA to explain two training ideas, and finally answers with measurements: what an image is worth in tokens, in memory and in latency, and whether small text can be read.
The numbers on this page come from a MacBook Pro (Apple M2 Max, 64 GB unified memory). The CLIP experiments use PyTorch and openai/clip-vit-base-patch32; the vision-language model is mlx-community/Qwen3-VL-4B-Instruct-4bit (a 4-bit quantization of Qwen3-VL-4B-Instruct) run with MLX. Token counts, KV cache sizes and parameter counts are computed from the model configuration files and code; latency and accuracy are measured. Absolute numbers differ on other hardware and models; what to take away are the patterns and the method.
The Big Picture: How an Image Enters the Language Model
Text enters through a tokenizer and an embedding layer: every token is looked up to give a vector. An image has no vocabulary, so it takes another route to vectors of the same shape:
- Patchify: cut the image into small pixel blocks (patches). An image gives patches, and each patch is flattened into a vector, like turning a word into a token.
- Vision encoder: a Vision Transformer (ViT) first maps every patch linearly to the hidden size, then applies many layers of self-attention so that each patch vector carries its surrounding context. The output is still vectors.
- Merge and projection: every group of neighbouring vectors is concatenated into one, then an MLP maps it to the language model’s hidden size. vectors become , and these are the visual tokens.
- Splice: the prompt first reserves placeholder tokens for the image; after the embedding lookup, the vectors at those positions are replaced by the visual tokens, and the whole sequence goes to the language model.
The following runnable code writes steps 3 and 4 in PyTorch, with random numbers:
import torch
import torch.nn as nn
torch.manual_seed(0)
grid_h, grid_w, merge = 8, 12, 2 # an image cut into 8 x 12 patches
d_vit, d_llm = 1024, 2560 # Qwen3-VL-4B: ViT width, LLM width
vit_out = torch.randn(grid_h * grid_w, d_vit) # one vector per patch
# 1. merge: every 2 x 2 block of neighbouring patches becomes one vector
x = vit_out.view(grid_h // merge, merge, grid_w // merge, merge, d_vit)
x = x.permute(0, 2, 1, 3, 4).reshape(-1, merge * merge * d_vit)
# 2. project into the LLM's embedding space (two-layer MLP)
merger = nn.Sequential(nn.Linear(merge * merge * d_vit, merge * merge * d_vit),
nn.GELU(), nn.Linear(merge * merge * d_vit, d_llm))
visual = merger(x)
print("patches", tuple(vit_out.shape), "-> blocks", tuple(x.shape),
"-> visual tokens", tuple(visual.shape))
print("merger parameters:", sum(p.numel() for p in merger.parameters()))
# 3. splice: the prompt has one placeholder id per visual token; after the
# embedding lookup those rows are replaced by the visual tokens
IMAGE = -1
ids = torch.tensor([5, 9] + [IMAGE] * len(visual) + [7, 3, 4])
embed = nn.Embedding(100, d_llm)
inputs_embeds = embed(ids.clamp(min=0)) # dummies for placeholders
inputs_embeds = inputs_embeds.masked_scatter((ids == IMAGE)[:, None], visual)
print("LLM input:", tuple(inputs_embeds.shape),
"= 2 text + 24 visual + 3 text tokens")
patches (96, 1024) -> blocks (24, 4096) -> visual tokens (24, 2560)
merger parameters: 27269632
LLM input: (29, 2560) = 2 text + 24 visual + 3 text tokens
Things worth noticing:
- Merging is only
view,permuteandreshape: patch vectors become 24 vectors of width 4096 (), so every visual token “sees” a block of neighbouring patches. - Merging and projection use a two-layer MLP with 27,269,632 parameters, less than 1% of a 4B language model. The real Qwen3-VL also has three extra merger layers for DeepStack, mentioned below.
- After
masked_scatter, the language model sees a matrix and cannot tell which rows came from the image and which from the embedding table. Position encoding tells it about spatial relations (M-RoPE, below). - In a real prompt an image is written as
<|vision_start|>, followed by as many<|image_pad|>tokens as there are visual tokens, followed by<|vision_end|>(the Qwen convention; the token counts below do not include these two markers, which take one position each).
The models discussed here output text only: the vision part just “translates” the image into vectors the language model can read, and generation is still done by the language model. “Omni” models that generate images or speech directly follow another line of work and are outside this page.
Patches and the Vision Encoder: Why Resolution Is a Cost
The title of the ViT paper (Dosovitskiy et al., 2020), “An Image is Worth 16x16 Words”, sums this step up: see the image as a sentence of pixel “words”. A smaller means more patches, more detail kept and a higher cost. A few common configurations (the patch counts are computed from the configuration files):
| Model (input) | Patch side | Patches | Visual tokens entering the language model |
|---|---|---|---|
| CLIP ViT-B/32 (224×224) | 32 | 49 (plus 1 class token) | Not connected to a language model; one vector represents the whole image |
| LLaVA-1.5-7B (ViT-L/14, 336×336) | 14 | 576 | 576 (no merging) |
| Qwen2-VL-7B (1024×768 resized to 1036×756) | 14 | 3,996 | 999 ( merge) |
| Qwen3-VL-4B (1024×768) | 16 | 3,072 | 768 ( merge) |
Resolution has two bills to pay:
- Vision encoder: ViT self-attention compares all patches pairwise, so its cost grows with . Doubling the side length quadruples and multiplies the attention cost by sixteen.
- Language model: every visual token takes a position in the context, takes part in attention, and takes space in the KV cache. Doubling the side length quadruples the visual tokens, and prefill time and KV cache grow with them.
The section “The Bill for Visual Tokens” below puts numbers on both.
CLIP: Aligning Images and Text with Contrastive Learning
CLIP (Radford et al., OpenAI, 2021) trains an image encoder and a text encoder together with a plain goal: an image and a sentence that describes it should have nearby vectors, and a mismatched image and sentence should have distant ones. The training data are 400 million image-text pairs collected from the web, with a batch size of 32,768.
A batch holds images and their texts. After normalizing all vectors and computing every pairwise cosine similarity we get an matrix : the diagonal holds the matching pairs and the other entries are negatives. Taking a softmax cross-entropy over every row (find the text for an image) and every column (find the image for a text) and averaging gives the symmetric InfoNCE loss:
Here is the temperature. The paper makes it a learnable parameter, initialized to 0.07, and clips at 100, since training was otherwise unstable. In the trained weights sits exactly at this cap, and the code below prints 100.
Zero-shot classification needs no classifier: write every class name into a sentence such as “a photo of a cat.”, encode it into a text vector, and the class whose vector is nearest to the image vector is the prediction. The code below tries this on the 10,000 CIFAR-10 test images (32×32, upscaled to 224×224) and compares several sentence templates:
import torch
import torch.nn.functional as F
from datasets import load_dataset
from transformers import CLIPModel, CLIPProcessor
NAME, DEV = "openai/clip-vit-base-patch32", "mps" # or "cuda" / "cpu"
model = CLIPModel.from_pretrained(NAME).to(DEV).eval()
proc = CLIPProcessor.from_pretrained(NAME)
data = load_dataset("uoft-cs/cifar10", split="test") # 10,000 images
classes = data.features["label"].names
print("temperature scale:", round(model.logit_scale.exp().item()))
def tensor_of(out): # transformers 5 returns an output object
return out if isinstance(out, torch.Tensor) else out.pooler_output
@torch.no_grad()
def embed_images(images):
px = proc(images=images, return_tensors="pt")["pixel_values"].to(DEV)
e = tensor_of(model.get_image_features(pixel_values=px))
return F.normalize(e, dim=-1).cpu()
@torch.no_grad()
def embed_classes(templates):
"""One vector per class: mean over the templates, then normalized."""
rows = []
for c in classes:
tok = proc(text=[t.format(c) for t in templates],
return_tensors="pt", padding=True).to(DEV)
e = F.normalize(tensor_of(model.get_text_features(**tok)), dim=-1)
rows.append(F.normalize(e.mean(0), dim=-1).cpu())
return torch.stack(rows)
images = [r["img"].convert("RGB") for r in data]
labels = torch.tensor(data["label"])
img = torch.cat([embed_images(images[i:i + 250])
for i in range(0, len(images), 250)])
TEMPLATES = {
"bare class name": ["{}"],
"a photo of a {}.": ["a photo of a {}."],
"a drawing of a {}.": ["a drawing of a {}."],
"a low resolution photo of a {}.": ["a low resolution photo of a {}."],
"unrelated sentence": ["the weather is nice today, {}"],
"mean of 7 templates": [
"a photo of a {}.", "a blurry photo of a {}.",
"a low resolution photo of a {}.", "a bad photo of a {}.",
"a good photo of a {}.", "a photo of the {}.",
"a close-up photo of a {}."],
}
for name, templates in TEMPLATES.items():
pred = (img @ embed_classes(templates).T).argmax(-1)
print(f"{name:32s} accuracy {(pred == labels).float().mean():.4f}")
temperature scale: 100
bare class name accuracy 0.8735
a photo of a {}. accuracy 0.8830
a drawing of a {}. accuracy 0.8967
a low resolution photo of a {}. accuracy 0.8903
unrelated sentence accuracy 0.8733
mean of 7 templates accuracy 0.8917
Four things to notice in these results:
- With no classifier trained at all, test accuracy is 87% to 90%. The bare class name gives 87.35%, and “a photo of a {}.” raises it to 88.30%, in line with the CLIP paper’s remark that a sentence is closer to the captions seen in training than a single word.
- The template is a hyperparameter. “a drawing of a {}.” is 1.4 percentage points above “a photo of a {}.”, perhaps because enlarged 32×32 images look more like illustrations; we did not test that. Averaging the text vectors of 7 templates (the paper calls this ensembling in the embedding space) gives 89.17%.
- A sentence unrelated to the image, “the weather is nice today, {}” (87.33%), is almost the same as the bare class name (87.35%), so here the text encoder is mostly reading the class name.
- Picking a template on the test set is only done here to show the sensitivity; in practice choose templates on a validation set. With 10,000 images the standard error of an accuracy around 0.88 is about 0.3 percentage points. The appendix table of the paper gives 91.3% zero-shot accuracy for ViT-B/32 on CIFAR-10; the paper customized the prompts for most datasets and ensembled them, which differs from our 7 generic templates, so the numbers are not directly comparable.
Now the loss itself. Take one image from each of 8 classes and the 8 class texts:
def clip_loss(a, b, scale):
"""Symmetric cross-entropy over the image-text similarity matrix."""
logits = scale * a @ b.T # row i: image i vs. all texts
target = torch.arange(len(logits)) # matches sit on the diagonal
return (F.cross_entropy(logits, target)
+ F.cross_entropy(logits.T, target)) / 2
scale = model.logit_scale.exp().item()
one_each = [(labels == c).nonzero()[0].item() for c in range(8)]
a, b = img[one_each], embed_classes(["a photo of a {}."])[:8]
print("cosine similarities, rows = 8 images, columns = 8 class texts:")
print((a @ b.T).numpy().round(2))
print("loss, correct pairs :", round(clip_loss(a, b, scale).item(), 3))
print("loss, shifted pairs :",
round(clip_loss(a, b.roll(1, dims=0), scale).item(), 3))
print("loss, scale 1 (no temperature):", round(clip_loss(a, b, 1.0).item(), 3))
print("chance level, ln(8) :", round(torch.tensor(8.0).log().item(), 3))
cosine similarities, rows = 8 images, columns = 8 class texts:
[[0.24 0.21 0.23 0.18 0.17 0.18 0.18 0.2 ]
[0.18 0.26 0.19 0.18 0.17 0.19 0.17 0.18]
[0.2 0.21 0.27 0.22 0.22 0.23 0.2 0.23]
[0.17 0.18 0.2 0.21 0.18 0.2 0.18 0.19]
[0.2 0.19 0.22 0.2 0.28 0.22 0.19 0.22]
[0.17 0.19 0.19 0.23 0.19 0.25 0.19 0.2 ]
[0.17 0.21 0.23 0.22 0.2 0.22 0.29 0.19]
[0.18 0.2 0.2 0.21 0.2 0.21 0.16 0.27]]
loss, correct pairs : 0.307
loss, shifted pairs : 6.587
loss, scale 1 (no temperature): 2.027
chance level, ln(8) : 2.079
- The diagonal (matching pairs) is 0.21 to 0.29 and the other entries of a row are 0.16 to 0.23. The gap is small, yet in each of the 8 rows the maximum is on the diagonal.
- Multiplied by , the loss of the correct pairing is 0.307; when every image is paired with the text of the “next class” (shifted) the loss rises to 6.587.
- Without the temperature () the loss is 2.027, almost exactly the random-guess value : the cosine similarities are so close that the softmax is nearly uniform and there is hardly any gradient signal. The temperature’s job is to magnify these small gaps.
- A larger batch means more negatives: with a batch of 32,768, each positive is compared with 32,767 negatives.
CLIP’s boundary is also clear: one vector per image suits retrieval and classification, but it cannot answer “what is the second number in the third row?” and it does not generate text. To let a model converse about images, the image representation has to be connected to a language model.
From Alignment to Conversation: LLaVA’s Two Stages
LLaVA (Liu et al., 2023) has a simple structure: CLIP’s vision encoder (ViT-L/14), one linear projection layer, and the language model Vicuna. Training has two stages:
| Stage 1: feature alignment | Stage 2: visual instruction tuning | |
|---|---|---|
| Trained parameters | Only the projection matrix; vision encoder and language model are frozen | Projection layer and language model; the vision encoder stays frozen |
| Data | Filtered CC3M, 595K image-text pairs (an image and a caption) | 158K instruction samples: 58K conversations, 23K detailed descriptions, 77K complex reasoning |
| Goal | Make the visual tokens line up with the frozen language model’s word embeddings | Learn to answer instructions about images |
| Hyperparameters | 1 epoch, learning rate 2e-3, batch size 128 | 3 epochs, learning rate 2e-5, batch size 32 |
Three further points:
- Stage 1 is “training a tokenizer”: the paper describes it as “training a compatible visual tokenizer for the frozen LLM”. A common explanation is that the randomly initialized projector outputs noise at first, and training it alone keeps that noise from disturbing the language model’s weights.
- The stage 2 data is made up: no image instruction data existed then, so the authors gave the captions and object bounding boxes of images to a text-only GPT-4 and had it write conversations, descriptions and reasoning questions. Stage 2 is essentially instruction tuning with image inputs.
- LLaVA-1.5 (Liu et al., 2023) made two simple changes: the projector became a two-layer MLP and the vision encoder became a CLIP ViT-L/14 with 336×336 input (giving tokens), and it added academic VQA data with a uniform response-format prompt, for 558K plus 665K samples.
The projector is small: for Vicuna-7B (hidden size 4096) and a 1024-wide ViT output, the linear layer has parameters, and the two-layer MLP adds for a total of 20,979,712, which is 0.06% and 0.31% of the 6.74-billion-parameter language model. A tiny module, and in this architecture it decides whether the language model can use the image information at all.
Dynamic Resolution: How Many Tokens Does an Image Take
LLaVA-1.5 turns every picture into 336×336 and always gives 576 tokens: a 12-megapixel phone photo and a screenshot with a few lines of small text get the same number of tokens, and the small text is lost in the resizing.
Qwen2-VL (2024) uses “naive dynamic resolution”: the vision encoder drops absolute position embeddings in favour of 2D RoPE and so accepts any size, and after the encoder an MLP merges every group of neighbouring tokens into one. The image is first resized so that both sides are multiples of ( is the patch side and the merge side; for Qwen2-VL and for Qwen3-VL), so one visual token covers pixels and the token count is:
where and are the height and width after resizing. The total pixels must also stay between min_pixels and max_pixels: an image that is too large is scaled down proportionally and one that is too small is scaled up. Both models’ defaults allow at most 16384 visual tokens per image (Qwen2-VL’s max_pixels is , Qwen3-VL’s is ). The code below writes the rule down and computes the KV cache size on the side:
import math
def smart_resize(h, w, factor, min_pixels, max_pixels):
"""Round both sides to multiples of `factor`; keep pixels in budget."""
hb, wb = round(h / factor) * factor, round(w / factor) * factor
if hb * wb > max_pixels: # too big: shrink
beta = math.sqrt(h * w / max_pixels)
hb = max(factor, math.floor(h / beta / factor) * factor)
wb = max(factor, math.floor(w / beta / factor) * factor)
elif hb * wb < min_pixels: # too small: enlarge
beta = math.sqrt(min_pixels / (h * w))
hb = math.ceil(h * beta / factor) * factor
wb = math.ceil(w * beta / factor) * factor
return hb, wb
# (patch, merge, min_pixels, max_pixels, layers, kv_heads, head_dim)
MODELS = {
"Qwen2-VL-7B": (14, 2, 3136, 12845056, 28, 4, 128),
"Qwen3-VL-4B": (16, 2, 65536, 16777216, 36, 8, 128),
}
for name, (patch, merge, lo, hi, layers, kv, hd) in MODELS.items():
per_token = 2 * layers * kv * hd * 2 # K and V, 2 bytes each (FP16)
print(f"{name}: KV cache {per_token / 1024:.0f} KiB per token")
for h, w in [(224, 224), (768, 1024), (1080, 1920), (3024, 4032)]:
hb, wb = smart_resize(h, w, patch * merge, lo, hi)
n = (hb // patch // merge) * (wb // patch // merge)
print(f" {w}x{h} -> {wb}x{hb}: {n:5d} tokens, "
f"{n * per_token / 2**20:6.0f} MiB of KV cache")
Qwen2-VL-7B: KV cache 56 KiB per token
224x224 -> 224x224: 64 tokens, 4 MiB of KV cache
1024x768 -> 1036x756: 999 tokens, 55 MiB of KV cache
1920x1080 -> 1932x1092: 2691 tokens, 147 MiB of KV cache
4032x3024 -> 4032x3024: 15552 tokens, 850 MiB of KV cache
Qwen3-VL-4B: KV cache 144 KiB per token
224x224 -> 256x256: 64 tokens, 9 MiB of KV cache
1024x768 -> 1024x768: 768 tokens, 108 MiB of KV cache
1920x1080 -> 1920x1088: 2040 tokens, 287 MiB of KV cache
4032x3024 -> 4032x3008: 11844 tokens, 1666 MiB of KV cache
- A 224×224 thumbnail takes only 64 tokens (Qwen3-VL’s lower pixel bound is , so it is first enlarged to 256×256), a 1024×768 image takes 999 and 768, and a 1920×1080 screenshot takes 2691 and 2040.
- A 12-megapixel 4032×3024 photo takes 15,552 and 11,844 tokens in the two models, which is 47% and 36% of a 32K context window. Without a cap, one image could eat most of the window, which is why
max_pixelsexists. - The KV cache takes 56 KiB and 144 KiB per token in the two models; the next section explains where these numbers come from.
The calculator below uses the same rule; you can change the image size, switch the model and cap the tokens per image:
Dynamic resolution raises a new problem: visual tokens have rows and columns in a 2D image, which a 1D position encoding in the language model cannot express. Qwen2-VL’s answer is M-RoPE (multimodal rotary position embedding): the position is split into time, height and width components; a text token has three identical components (which reduces to ordinary RoPE), while an image token’s height and width components follow its row and column. Qwen3-VL interleaves the three components across frequencies and adds DeepStack: it takes three intermediate layers of the vision encoder (layers 5, 11 and 17 counting from 0 in the 4B configuration), passes them through extra merger layers and adds them at the visual positions of the outputs of the language model’s first three layers, so that the language model gets both low-level detail and high-level semantics. Position encoding itself is covered in Positional Encoding.
The Bill for Visual Tokens: Context, KV Cache and Latency
Visual tokens occupy context like text tokens do, and they also need their keys and values cached. The KV cache one token takes across the whole model is:
where is the number of layers, the number of KV heads, the dimension per head and the bytes per number (2 for FP16); the leading 2 is for K and V. Grouped-query attention (GQA) reduces and cuts this bill directly:
| Model | Layers | KV heads | KV per token | Tokens per image | KV per image |
|---|---|---|---|---|---|
| LLaVA-1.5-7B (Vicuna-7B) | 32 | 32 | 512 KiB | 576 (fixed) | 288 MiB |
| Qwen2-VL-7B | 28 | 4 | 56 KiB | 999 (1024×768) | 55 MiB |
| Qwen3-VL-4B | 36 | 8 | 144 KiB | 768 (1024×768) | 108 MiB |
LLaVA-1.5 uses multi-head attention without GQA, 512 KiB per token, so the 576 tokens of one image already take 288 MiB; Qwen2-VL-7B has 1.7 times as many visual tokens and less than a fifth of the KV cache. With several images the bill adds up linearly, and with concurrent requests it is multiplied by the concurrency; for capacity planning see LLM Serving.
Latency has to be measured. With MLX running the 4-bit Qwen3-VL-4B-Instruct and max_tokens set to 1, the measurement is the time to first token (TTFT): image preprocessing, vision encoder and language model prefill. To isolate the vision part, a text-only request with the same prompt length was measured under the same settings as a control.
| Side (tokens) | With image (s) | Text only (s) | Measured share | Estimated share |
|---|---|---|---|---|
| 256×256 (64) | 0.19 | 0.14 | 26% | 26% |
| 512×512 (256) | 0.47 | 0.35 | 25% | 28% |
| 768×768 (576) | 1.2 | 0.82 | 30% | 31% |
| 1024×1024 (1,024) | 2.1 | 1.4 | 33% | 35% |
| 1536×1536 (2,304) | 5.4 | 3.2 | 39% | 43% |
| 2048×2048 (4,096) | 11 | 5.9 | 48% | 51% |
| 3072×3072 (9,216) | 39 | 15 | 60% | 63% |
| 4096×4096 (16,384) | 108 | 32 | 70% | 70% |
The last two columns give the share of the total time taken by the vision part: the second to last is measured (image request minus text control, divided by the image request), the last is the share of compute estimated by the code below (only matrix-multiply FLOPs are counted; normalization and activations are ignored):
# Qwen3-VL-4B shapes (taken from the model's config.json)
VIT = dict(depth=24, d=1024, ff=4096) # vision encoder
LLM = dict(depth=36, d=2560, heads=32, kv=8, hd=128, ff=9728) # language model
def vit_flops(n_tok, merge=2):
"""Vision encoder: merge**2 times more patches than tokens, and they
attend to each other bidirectionally."""
m = merge * merge * n_tok
weights = 4 * VIT["d"] ** 2 + 2 * VIT["d"] * VIT["ff"] # per layer
linear = 2 * m * VIT["depth"] * weights
attn = 4 * m * m * VIT["d"] * VIT["depth"] # QK^T and AV, 2*m^2*d each
return linear + attn
def llm_flops(n_tok):
"""Prefill of n_tok tokens; causal attention counts the lower triangle."""
q, kv = LLM["heads"] * LLM["hd"], LLM["kv"] * LLM["hd"]
d = LLM["d"]
weights = d * (q + 2 * kv) + q * d + 3 * d * LLM["ff"]
linear = 2 * n_tok * LLM["depth"] * weights
attn = 2 * n_tok * n_tok * q * LLM["depth"]
return linear + attn
print(f"{'visual tokens':>13} {'ViT TFLOPs':>11} {'LLM TFLOPs':>11} "
f"{'ViT share':>10}")
for side in (256, 512, 768, 1024, 1536, 2048, 3072, 4096):
n = (side // 32) ** 2 # one visual token covers 32x32 pixels
v, l = vit_flops(n), llm_flops(n)
print(f"{n:>13,} {v / 1e12:>11.2f} {l / 1e12:>11.2f} "
f"{v / (v + l):>10.0%}")
visual tokens ViT TFLOPs LLM TFLOPs ViT share
64 0.16 0.47 26%
256 0.72 1.88 28%
576 1.91 4.28 31%
1,024 4.12 7.75 35%
2,304 13.92 18.31 43%
4,096 36.28 34.71 51%
9,216 155.86 92.02 63%
16,384 461.79 198.22 70%
- Latency grows faster than the token count: going from 1,024 to 4,096 tokens (side ×2, tokens ×4) the time with an image grows 5.4 times (2.1 s to 11 s), and from 4,096 to 16,384 tokens 9.4 times (11 s to 108 s). A text-only request of the same length grows more slowly (4.2 and 5.5 times) but also accelerates: attention compute grows with the square of the length, and the longer the sequence, the larger its share.
- On large images the vision encoder is slower than the language model: the vision encoder attends bidirectionally over times as many patches as there are tokens, and its attention term has a coefficient about 5.3 times that of the language model’s causal attention (compare the
attnline of the two functions with each model’s width and depth plugged in). Its share of the total time rises from 26% to 70%: at a side of 3072 pixels (9,216 tokens) the vision part takes 23 s and the language-model prefill only 15 s. - The formula explains the trend: the estimated share is within 4 percentage points of the measured one, and always a little high. This is a reconciliation, not a prediction formula: a different chip, implementation or quantization changes the shares. It is enough to tell whether the bottleneck is the vision part or the language part.
- This is a single-machine, single-request prefill: the numbers are for batch size 1 on an M2 Max, with no concurrency. On a server GPU the absolute times are much smaller, and the share of the vision part is expected to rise with resolution in the same way, but this page did not verify that.
The bill has three direct uses in practice:
- Treat resolution as a knob for latency and cost: do not send 9,216 tokens to a task that 1,024 tokens can solve; the experiment in the next section shows how to find the smallest resolution that is enough.
- Reuse instead of recompute when the same image is asked about several times: if the inference engine supports caching the image prefix, the fixed cost of vision encoding and prefill is paid once; put the image early in the prompt and the question late so the cache can hit, and see prefix caching in Continuous Batching and PagedAttention.
- Look at the whole picture at low resolution, then crop the details: sending the key region as a separate crop keeps small text at a usable effective size and avoids the quadratic cost of a high-resolution whole image.
Experiment: Resolution Decides Whether Small Text Can Be Read
OCR is the most common requirement in multimodal applications and also where accidents happen most. To quantify how resolution affects reading, here is a synthetic experiment:
- On a 512×512 white image, draw 5 random six-digit numbers (Arial font, font sizes 8, 12, 16 and 24 pixels), 20 images in total with fixed random seeds.
- Each image is first rescaled with bicubic interpolation by ×0.5, ×1, ×2 and ×3, then given to Qwen3-VL-4B-Instruct (4-bit, MLX). The prompt is “Read all the numbers in the image from top to bottom. Answer with the numbers only, separated by commas.” with greedy decoding.
- Two accuracies are recorded: strict match requires the digit groups in the output to equal the truth one by one; ignoring stray punctuation counts “61.6517” as “616517” and only checks whether the digits themselves were read correctly. Each cell has 100 numbers, so a result around 0.7 has roughly a ±9 percentage point 95% error range.
Each cell below is “strict match / ignoring stray punctuation”:
| Font size (px) | ×0.5 (64 tokens) | ×1 (256) | ×2 (1,024) | ×3 (2,304) |
|---|---|---|---|---|
| 8 | 0.01 / 0.04 | 0.69 / 0.90 | 0.94 / 0.99 | 0.97 / 0.97 |
| 12 | 0.75 / 0.75 | 1.00 / 1.00 | 1.00 / 1.00 | 1.00 / 1.00 |
| 16 | 0.92 / 0.92 | 1.00 / 1.00 | 1.00 / 1.00 | 1.00 / 1.00 |
| 24 | 1.00 / 1.00 | 1.00 / 1.00 | 1.00 / 1.00 | 1.00 / 1.00 |
- Accuracy is set by the effective size of the characters, not by the token count: multiply the font size by the scale factor to get the actual size of the characters in the model’s input (the effective font size). All cells fall on nearly one curve: 4% at 4 pixels, 75% at 6, about 91% at 8, and essentially perfect from 12 pixels up. An 8-pixel font enlarged ×1 (256 tokens) and a 16-pixel font shrunk to half (64 tokens) both have an effective size of 8 pixels, and their accuracies are 90% and 92%, with token counts four times apart. One visual token is 32 pixels wide: a font of about 12 pixels (about 0.4 of a token) is read reliably, errors begin at 8 pixels (0.25 of a token), and at 4 pixels (0.125 of a token) nearly everything is wrong.
- Too small, and the model makes things up: for the 8-pixel font shrunk to half (effective size 4 pixels, 64 tokens), only 4 of 100 numbers are read correctly and 8 are off by one digit; the other 88 have the wrong length or more wrong digits. The outputs include repeated “027982,027982,…” and strings that do not look like numbers at all, such as “03 08 17”.
- Errors near the threshold are “off by one digit”: at an effective size of 6 pixels (12-pixel font at half size) there are 25 errors, 22 of them a single digit; at 8 pixels (16-pixel font at half size) there are 8 errors, all a single digit, such as reading “031862” as “031882”. These errors “look right” and are hard to catch by eye.
- Format errors are a separate problem: with the 8-pixel font and 256 tokens, strict match is 0.69 and ignoring stray punctuation gives 0.90. In the 21 numbers that make up the difference all digits were read correctly, but the model added a decimal point inside the number, such as “61.6517” or “76.86.94”, which then count as two or three numbers. An output-format constraint and a check catch this: ask for exactly six digits per line and validate with a regular expression; see Structured Output and Function Calling.
- Enlarging helps, but cannot recover lost information: enlarging the 8-pixel image ×2 raises the accuracy from 0.90 to 0.99 and ×3 gives 0.97, no further gain. Enlarging adds no information; it only gives each character more tokens, and strokes that were blurred in the original stay blurred. For fonts of 12 pixels and up, 256 tokens (512×512) are already perfect, and enlarging more only adds cost.
This is a result on synthetic data: only Arial digits, one 4-bit 4B model and one prompt. What to take away is the method, not the thresholds: run your own real samples at several resolutions, plot accuracy against token count and pick the knee.
When small text is misread, try the cheap fixes first: render PDFs at a higher DPI, enlarge screenshots, crop only the key region and send it separately. Raising the resolution of the whole image costs tokens in proportion to the square of the side length.
Choosing an Approach: OCR, a Vision-Language Model or a Combination
The table below is general advice as of November 2026; the final choice still needs an evaluation on your own samples:
| Task | Better approach | Why |
|---|---|---|
| Image search, image-text retrieval, zero-shot classification | An image-text embedding model such as CLIP or SigLIP plus vector search | Each image is encoded once and then only vectors are compared, which is cheap; see RAG for retrieval |
| Extracting fixed fields from invoices and forms | OCR or layout parsing plus rule checks; if a vision-language model extracts, add validation | Auditable and checkable; a vision-language model that misreads a digit usually looks right |
| Answering questions about screenshots, charts and interfaces | A vision-language model with a high enough input resolution | Needs layout and semantics, not only text |
| Multi-page PDFs, contracts, strictly regulated Q&A | Layout parsing plus retrieval, and only key pages go to the vision-language model | Tokens and cost grow linearly with the page count, and answers need traceable sources |
| Agents that operate interfaces | A vision-language model reading the screen, plus tool calls | Agents and Tool Calling in Practice |
Debugging: Did It See, Is It Aligned, Did It Use It
When a multimodal system answers wrongly, looking only at the final answer mixes up the causes. A more reliable order of checks:
| Layer | Question | Typical symptom | Check and fix |
|---|---|---|---|
| Did it see | Did the target information reach the visual tokens | Small text, thin lines and dense tables go wrong, and changing the prompt does not help | Estimate the effective font size and token count; enlarge, crop the region, raise max_pixels (see the experiment above) |
| Is it aligned | Are the visual tokens bound to the instruction correctly | Off-topic answers; mixing up images when there are several | Check the chat template and placeholders: does every image have start and end markers, does the number of placeholder tokens equal the number of visual tokens, the order of images and question |
| Did it use it | Is the model really answering from the image | Inventing content that is not in the image; answering from common sense without looking | Run controls: swap the image, mask the key region, use a blank image; if the answer does not change, the image is not being used; ask for evidence from the image |
Evaluation: “Sounds Right” Is Not Enough
A minimal useful multimodal evaluation records errors by type, which is more useful than one overall score:
- Prepare 20 to 50 real samples covering your real input types (screenshots, scans, photos).
- Write the reference answer for each image and label the failure type: perception errors (objects, colours, counts), OCR errors (especially digits and proper nouns), spatial relation errors, instruction and format errors, hallucinations (information that is not in the image).
- Run at several resolutions and prompts, and record the number of errors of each type, the latency and the cost per call.
- Add control samples (swapped image, blank image) to confirm that the model really uses the image.
For general evaluation methods see LLM Evaluation.
From image question answering to native multimodality
The Stanford CS25 lecture on native multimodality examines representations, sequence modeling, and modality-specific computation. When reading a model description, ask which modalities share the backbone, which are trained together, and which the model can emit directly. Adding a vision encoder can enable image question answering. Real-time audio and video interaction also involves different sampling rates, temporal alignment, and streaming output.
As a diagnostic, create a second version of a video that changes only the frame order, then ask which event happened first. If both inputs consistently yield the same answer, check whether sampling preserved the events, whether temporal information reaches the model, and whether the question gives away the order. This comparison tests a property that matters for video tasks.
Video models can predict images or representations
Stanford CS25’s Joint Embedding Predictive World Models lecture uses V-JEPA 2 to illustrate a predictive learning objective. An encoder maps video to features, and a predictor learns to estimate target features from the visible context when part of the input is masked. Feature prediction can train a representation. The action-conditioned V-JEPA 2-AC also takes an action as input and predicts a representation of the resulting state.
For robot planning, evaluate candidate actions from the same observed state and compare the predicted representations with the goal representation. Track prediction error and actual task success separately. A model may represent object position accurately while losing information about contact, occlusion, or small shape differences that change grasp outcomes. Slicing by action and occlusion can reveal failures rarely covered by visual question answering.
Summary and Exercises
Key points:
- A multimodal LLM cuts an image into patches, turns them into visual tokens through a vision encoder, merging and projection, replaces the placeholder positions in the prompt with them, and lets the language model process them like text; the output is still text.
- CLIP aligns images and text with a symmetric InfoNCE loss, and the temperature magnifies the small gaps between cosine similarities; one vector per image suits retrieval and zero-shot classification but not conversation.
- LLaVA has two steps: first train only the projector to align, then fine-tune the projector and the language model on image instruction data.
- With dynamic resolution the visual token count is ( is the patch side times the merge side, 28 or 32 pixels); the token count determines context usage, KV cache and prefill latency, and GQA lowers the KV cache.
- Latency grows faster than the token count: the time to first token of Qwen3-VL-4B on an M2 Max is about 2 s for 1,024 visual tokens and about 108 s for 16,384; the vision encoder’s share rises from 26% to 70% and at a side of 3072 pixels it is slower than the language model.
- Whether small text is read correctly is mainly set by the effective size of the characters in the input: in this page’s experiment fonts of about 12 pixels and up are essentially perfect (a visual token is 32 pixels wide), errors start at 8 pixels and nearly everything is wrong at 4. The errors are often “off by one digit”, plus format errors such as an added decimal point. Enlarge or crop first, only then consider another model, and catch format problems with an output constraint.
Quick quiz
1. Which parameters does LLaVA’s stage 1 (feature alignment) train?
- All parameters of the vision encoder, projector and language model
- Only the projector
- Only the language model
- The vision encoder and language model, with the projector frozen
Stage 1 freezes the vision encoder and the language model and trains only the projection matrix; only stage 2 updates the projector and the language model together.
2. Qwen2-VL (patch 14, merge) processes a 448×448 image. How many visual tokens does it produce (not counting the start and end markers)?
- 1024
- 64
- 256
- 1568
and , so there are tokens.
3. Why does CLIP need a very large batch (32,768)?
- To fill the GPU memory
- Each positive is contrasted with the other samples in the batch, so a larger batch gives more negatives
- Because the text encoder needs many images
- To avoid using a temperature parameter
The diagonal holds the positives and the other pairs are negatives; a larger batch makes the contrast richer.
4. In this page’s experiment, CLIP’s loss without a temperature () is 2.027, close to the random-guess value . Why?
- The model is broken
- Cosine similarity can only be 0 or 1
- The cosine similarities differ by only a few hundredths, so without scaling the softmax is nearly uniform
- 8 classes are too few
The temperature magnifies gaps of 0.01 to 0.1 by 100 times so that the softmax can tell the entries apart and the gradient has a signal.
5. With about 1000 visual tokens, why is Qwen2-VL-7B’s KV cache far smaller than that of LLaVA-1.5-7B’s 576 tokens?
- Because Qwen2-VL’s tokens are shorter
- Because Qwen2-VL compresses the KV cache to 8 bits
- Because Qwen2-VL uses GQA with only 4 KV heads: its KV cache is 56 KiB per token, against 512 KiB for LLaVA-1.5
- Because visual tokens need no KV cache
The KV cache per token is proportional to the number of KV heads: bytes.
6. A model cannot read small text in a screenshot. What is the cheapest first step?
- Switch to a larger model
- Enlarge the input or crop out only the key region so that the characters get more visual tokens
- Set the temperature to 0
- Add more examples to the prompt
When the characters are too small, the information is already lost in patchifying and merging, and neither a bigger model nor a different prompt can recover it.
Exercises:
- Compute by hand with
smart_resize: for Qwen2-VL processing a 1920×1080 screenshot, what are the resized size, the number of visual tokens and the FP16 KV cache? - For a batch of , what is the expected CLIP loss of random guessing? Compare it with the 2.027 obtained without the temperature in this page’s experiment: what does it tell you?
- LLaVA-1.5’s ViT outputs 1024 dimensions and Vicuna-7B’s hidden size is 4096. Compute the parameter counts of the linear projection and the two-layer MLP projection, and verify them with code.
- Reproduce the “resolution and reading” experiment on one of your own screenshots: enlarge ×1, ×2 and ×3, let the model read each, and record the type of the errors.
- A customer-service system must read user-uploaded invoices and fill in the amount. Design an approach: which step uses OCR, which uses a vision-language model, and how do you prevent errors that “look right”?
- Using this page’s
vit_flopsandllm_flops, compare a 2048×2048 image with a 1024×1024 one: by what factor do the vision encoder’s and the language model’s prefill compute grow, and why are the two factors different?
Reference answers
- : rounds to 39 and ; rounds to 69 and . The resized image is 1932×1092, both below the pixel cap, so no further adjustment. The number of visual tokens is . Each token takes bytes (56 KiB) of KV cache, in total .
- For random guessing the softmax of each sample is roughly uniform and the cross-entropy is ; the average of the two directions is also 2.079. The 2.027 without the temperature is almost equal to it: the cosine similarities are too close for the model to discriminate, which is also why CLIP uses a close to 100.
- Linear projection: ; two-layer MLP: add for in total. Counting
numel()ofnn.Linear(1024, 4096)andnn.Linear(4096, 4096)verifies it. - There is no fixed answer. A typical pattern is “off by one digit” errors at ×1 that disappear after enlarging, which means the information was there and only the tokens were too few; if errors remain after enlarging, the information in the original is already lost (compression, blur) and you need a sharper source.
- A reference approach: use OCR or layout parsing to locate the “amount” region and read its text; then let the vision-language model read the same region and send to a human when the two readings disagree; apply rule checks such as the sum of the line items against the total, the invoice-number format and the date range; keep the original image and the recognition result for auditing. The key is not to trust one reading: let a second path or a rule catch the errors that “look right”.
- The vision encoder goes from 4.12 TFLOPs to 36.28 TFLOPs, a factor of 8.8; the language model goes from 7.75 to 34.71 TFLOPs, a factor of 4.5. The token count grows 4 times, and the linear parts (projections and MLP) of both grow 4 times, while the attention part grows 16 times, so the total lands between 4 and 16 times and moves toward 16 as attention takes a larger share. The vision encoder’s attention coefficient is much larger, so its factor is higher; for an even larger image its share of the time keeps rising.
Further Reading
-
Radford et al., Learning Transferable Visual Models From Natural Language Supervision (CLIP); explainer: CLIP.
-
Dosovitskiy et al., An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale (ViT; paper breakdown).
-
Liu et al., Visual Instruction Tuning (LLaVA; explainer: LLaVA) and Improved Baselines with Visual Instruction Tuning (LLaVA-1.5).
-
Zhai et al., Sigmoid Loss for Language Image Pre-Training (SigLIP, replacing the softmax with a sigmoid loss).
-
Wang et al., Qwen2-VL: Enhancing Vision-Language Model’s Perception of the World at Any Resolution; Qwen Team, Qwen3-VL Technical Report.
-
Related pages: Diffusion Models and Flow Matching (the other direction: drawing images instead of reading them; the action heads of π0 and GR00T N1 are flow-matching models), Attention Basics, Positional Encoding, KV Cache, LLM Serving, RAG.
-
Brohan et al., RT-2: Vision-Language-Action Models Transfer Web Knowledge to Robotic Control: robot actions written as tokens and a vision-language model co-fine-tuned with web data; paper breakdown.
-
Kim et al., OpenVLA: An Open-Source Vision-Language-Action Model: an open VLA built on Llama 2 7B with fused DINOv2 and SigLIP vision encoders; paper breakdown.
-
Black et al., π0: A Vision-Language-Action Flow Model for General Robot Control: a roughly 300M flow-matching action expert next to PaliGemma that generates 50-step continuous action chunks at once; paper breakdown.
-
NVIDIA, GR00T N1: An Open Foundation Model for Generalist Humanoid Robots: an Eagle-2 vision-language model plus a flow-matching DiT action head joined by cross-attention, with a “data pyramid” that unifies real robots, simulation, neural videos and human video; paper breakdown.
FAQ
- What is the basic structure of a multimodal LLM?
- Three components and one convention. A vision encoder (usually a ViT) cuts the image into patches and encodes them as vectors; a merge-and-projection layer merges neighbouring patch vectors and maps them with a linear layer or MLP to the language model's hidden size, producing visual tokens; the language model backbone reads these visual tokens and the text tokens like ordinary text and generates text. The convention is that the prompt reserves one placeholder token per visual token, and after the embedding lookup the vectors at those positions are replaced by the visual tokens.
- What is the difference between CLIP and LLaVA?
- CLIP trains an image encoder and a text encoder with contrastive learning so that matching image-text pairs land close together in one vector space. Each image gets a single vector, which is good for retrieval and zero-shot classification, but CLIP does not generate text. LLaVA connects CLIP's vision encoder to a language model through a projection layer: it first trains only the projector to align the features, then fine-tunes the projector and the language model on image instruction data, so the model can converse about images.
- How many tokens does an image take in a multimodal model?
- It depends on the model. LLaVA-1.5 always resizes to 336×336 and always uses 576 tokens. Qwen2-VL and Qwen3-VL use dynamic resolution: both sides are rounded to a multiple of the patch size times the merge factor (28 or 32 pixels), and each token covers 784 or 1024 pixels. A 1920×1080 screenshot takes about 2040 to 2691 tokens, a 4032×3024 phone photo about 12 to 16 thousand, and the default pixel cap corresponds to at most 16384 tokens per image.
- Is a higher image resolution always better for multimodal models?
- No. Doubling the resolution quadruples the token count and with it the prefill latency and the KV cache, and it only pays off when the task needs the detail. In this page's experiment Qwen3-VL-4B reads digits with a font of 12 pixels or more perfectly on a 512×512 input (256 tokens); digits with an 8-pixel font are almost always wrong at 256×256 (64 tokens), about 90% right at 512×512 and 99% right at 1024×1024 (1024 tokens). Choose the resolution from the smallest detail the task needs, and crop and enlarge the relevant region instead of raising the resolution of the whole image.
- When should I use OCR and when a vision-language model directly?
- To extract fixed fields such as amounts, dates and numbers with an auditable record, prefer OCR or layout parsing plus rule checks, because a vision-language model that misreads a digit usually looks right. To answer questions that depend on layout, charts and image semantics, a vision-language model is the better fit. Multi-page PDFs and strictly regulated settings usually call for a combination: parse and retrieve first, and send only the key pages to the vision-language model.