9 Multimodal 1 / 3
  1. In this chapter
  2. Multimodal LLMs
  3. Diffusion Models and Flow Matching
  4. World models and planning
All chapters →

Chapter 9 · Multimodal 9.1

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.

Intermediate 42 min read Updated Companion code ↓

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_resize rule, 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
  1. The Big Picture: How an Image Enters the Language Model
  2. Patches and the Vision Encoder: Why Resolution Is a Cost
  3. CLIP: Aligning Images and Text with Contrastive Learning
  4. From Alignment to Conversation: LLaVA’s Two Stages
  5. Dynamic Resolution: How Many Tokens Does an Image Take
  6. The Bill for Visual Tokens: Context, KV Cache and Latency
  7. Experiment: Resolution Decides Whether Small Text Can Be Read
  8. Choosing an Approach: OCR, a Vision-Language Model or a Combination
  9. Debugging: Did It See, Is It Aligned, Did It Use It
  10. Evaluation: “Sounds Right” Is Not Enough
  11. From image question answering to native multimodality
  12. Video models can predict images or representations
  13. Summary and Exercises
  14. Quick quiz
  15. Further Reading
  16. 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.

Experiment environment

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

Data flow of a multimodal LLM: image, patches, vision encoder, merge and projection, language model A 1024×768 image is cut into 3072 patches of 16×16 pixels; the vision encoder outputs one 1024-dimensional vector per patch; every 2×2 neighbouring vectors are merged and projected by an MLP into 768 visual tokens of width 2560, which enter the language model together with the text prompt tokens and generate text autoregressively. What happens to an image before the language model sees it Image 1024×768 RGB, 3 channels 1024×768×3 Patchify 16×16 px each 64×48 patches [3072, 1536] ViT encoder self-attention vector per patch [3072, 1024] Merge, project 2×2 neighbours two-layer MLP [768, 2560] Language model visual + text in one sequence [768+n, 2560] Output token by token one at a time Text prompt tokenize + embed [n, 2560] 3072 patches become 768 visual tokens after 2×2 merging. They share the context window and KV cache with the text. 1536 = 2×16×16×3 per patch: Qwen repeats a still image as two frames.
Numbers are from Qwen3-VL-4B: 16-pixel patches, ViT width 1024, language model width 2560; n is the number of text prompt tokens. Schematic: DeepStack and position encodings are omitted.

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:

  1. Patchify: cut the image into small P×PP\times P pixel blocks (patches). An H×WH\times W image gives N=HP⋅WPN=\frac{H}{P}\cdot\frac{W}{P} patches, and each patch is flattened into a vector, like turning a word into a token.
  2. 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 NN vectors.
  3. Merge and projection: every 2×22\times2 group of neighbouring vectors is concatenated into one, then an MLP maps it to the language model’s hidden size. NN vectors become N/4N/4, and these are the visual tokens.
  4. 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, permute and reshape: 8×12=968\times12=96 patch vectors become 24 vectors of width 4096 (4×10244\times1024), so every visual token “sees” a 2×22\times2 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 [29,2560][29, 2560] 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 P×PP\times P pixel “words”. A smaller PP 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 sidePatchesVisual tokens entering the language model
CLIP ViT-B/32 (224×224)3249 (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)14576576 (no merging)
Qwen2-VL-7B (1024×768 resized to 1036×756)143,996999 (2×22\times2 merge)
Qwen3-VL-4B (1024×768)163,072768 (2×22\times2 merge)

Resolution has two bills to pay:

  • Vision encoder: ViT self-attention compares all NN patches pairwise, so its cost grows with N2N^2. Doubling the side length quadruples NN 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 NN images and their NN texts. After normalizing all vectors and computing every pairwise cosine similarity we get an N×NN\times N matrix sijs_{ij}: the diagonal holds the matching pairs and the other N2−NN^2-N 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:

L=12N∑i=1N[−log⁡esii/τ∑jesij/τ−log⁡esii/τ∑jesji/τ]\mathcal{L}=\frac{1}{2N}\sum_{i=1}^{N}\left[-\log\frac{e^{s_{ii}/\tau}}{\sum_{j}e^{s_{ij}/\tau}}-\log\frac{e^{s_{ii}/\tau}}{\sum_{j}e^{s_{ji}/\tau}}\right]

Here τ\tau is the temperature. The paper makes it a learnable parameter, initialized to 0.07, and clips 1/τ1/\tau at 100, since training was otherwise unstable. In the trained weights 1/τ1/\tau 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 1/τ=1001/\tau=100, 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 (1/τ=11/\tau=1) the loss is 2.027, almost exactly the random-guess value ln⁡8=2.079\ln 8=2.079: 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 alignmentStage 2: visual instruction tuning
Trained parametersOnly the projection matrix; vision encoder and language model are frozenProjection layer and language model; the vision encoder stays frozen
DataFiltered CC3M, 595K image-text pairs (an image and a caption)158K instruction samples: 58K conversations, 23K detailed descriptions, 77K complex reasoning
GoalMake the visual tokens line up with the frozen language model’s word embeddingsLearn to answer instructions about images
Hyperparameters1 epoch, learning rate 2e-3, batch size 1283 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 24×24=57624\times24=576 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 1024×4096+4096=4,198,4001024\times4096+4096=4{,}198{,}400 parameters, and the two-layer MLP adds 4096×4096+40964096\times4096+4096 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 2×22\times2 group of neighbouring tokens into one. The image is first resized so that both sides are multiples of f=p⋅mf=p\cdot m (pp is the patch side and mm the merge side; f=14×2=28f=14\times2=28 for Qwen2-VL and f=16×2=32f=16\times2=32 for Qwen3-VL), so one visual token covers f×ff\times f pixels and the token count is:

ntok=H′f⋅W′fn_{\text{tok}}=\frac{H'}{f}\cdot\frac{W'}{f}

where H′H' and W′W' 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 282×1638428^2\times16384, Qwen3-VL’s is 322×1638432^2\times16384). 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 2562256^2, 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_pixels exists.
  • 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:

bytes per token=2×L×nkv×dhead×b\text{bytes per token}=2\times L\times n_{\text{kv}}\times d_{\text{head}}\times b

where LL is the number of layers, nkvn_{\text{kv}} the number of KV heads, dheadd_{\text{head}} the dimension per head and bb the bytes per number (2 for FP16); the leading 2 is for K and V. Grouped-query attention (GQA) reduces nkvn_{\text{kv}} and cuts this bill directly:

ModelLayersKV headsKV per tokenTokens per imageKV per image
LLaVA-1.5-7B (Vicuna-7B)3232512 KiB576 (fixed)288 MiB
Qwen2-VL-7B28456 KiB999 (1024×768)55 MiB
Qwen3-VL-4B368144 KiB768 (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.

How the time to first token splits between the vision part and the language-model prefill Eight input sizes, from 256 pixels (64 visual tokens) to 4096 pixels (16,384). The vision encoder and projector take 26%, 25%, 30%, 33%, 39%, 48%, 60% and 70% of the time, and from 3072 pixels on they take longer than the language-model prefill. The total time with an image is 0.19, 0.47, 1.2, 2.1, 5.4, 11, 39 and 108 seconds. Bigger images shift time to the vision encoder: it passes the LLM at 3072 px Number above a bar: total time with the image; numbers inside: share of each part 0% 25% 50% 75% 100% 26% 74% 0.19 s 64 tokens 256×256 px 25% 75% 0.47 s 256 tokens 512×512 px 30% 70% 1.2 s 576 tokens 768×768 px 33% 67% 2.1 s 1,024 tokens 1024×1024 px 39% 61% 5.4 s 2,304 tokens 1536×1536 px 48% 52% 11 s 4,096 tokens 2048×2048 px 60% 40% 39 s 9,216 tokens 3072×3072 px 70% 30% 108 s 16,384 tokens 4096×4096 px Vision encoder and projector (image minus text) Language-model prefill (text control) Dashed: 50%
Time for Qwen3-VL-4B-Instruct (4-bit, MLX) on an M2 Max to produce one token: median of 3 runs per size (2 for the largest) after one warm-up call. The image is a white canvas with 60 random color blocks; the text control is a prompt of the same length, so the difference is the vision part, including image preprocessing.
Side (tokens)With image (s)Text only (s)Measured shareEstimated share
256×256 (64)0.190.1426%26%
512×512 (256)0.470.3525%28%
768×768 (576)1.20.8230%31%
1024×1024 (1,024)2.11.433%35%
1536×1536 (2,304)5.43.239%43%
2048×2048 (4,096)115.948%51%
3072×3072 (9,216)391560%63%
4096×4096 (16,384)1083270%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 2×22\times2 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 attn line 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:

  1. 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.
  2. 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.
  3. 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.
Digit recognition accuracy against effective font size The horizontal axis is the effective font size, the original font size times the scale factor, in pixels on a log scale; the vertical axis is the share of six-digit numbers Qwen3-VL-4B reads correctly, ignoring stray punctuation. It is 4% at 4 pixels, 75% at 6 pixels, about 91% at 8 pixels and essentially 100% from 12 pixels up. One visual token is 32 pixels wide. Smaller characters are harder to read: accuracy falls below 8 pixels Share of numbers read correctly (stray punctuation ignored) 0% 25% 50% 75% 100% 4 6 8 12 16 24 36 48 72 Effective font size = font size × scale factor (pixels, log scale) Side of one visual token: 32 pixels 8 px font 12 px font 16 px font 24 px font
Qwen3-VL-4B-Instruct (4-bit) reading six-digit numbers on a 512×512 white canvas, 100 numbers per point. The image is rescaled by ×0.5, ×1, ×2 or ×3 before it is fed in, so one effective size can come from different fonts and scales; points at the same x are nudged slightly sideways.

Each cell below is “strict match / ignoring stray punctuation”:

Font size (px)×0.5 (64 tokens)×1 (256)×2 (1,024)×3 (2,304)
80.01 / 0.040.69 / 0.900.94 / 0.990.97 / 0.97
120.75 / 0.751.00 / 1.001.00 / 1.001.00 / 1.00
160.92 / 0.921.00 / 1.001.00 / 1.001.00 / 1.00
241.00 / 1.001.00 / 1.001.00 / 1.001.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:

TaskBetter approachWhy
Image search, image-text retrieval, zero-shot classificationAn image-text embedding model such as CLIP or SigLIP plus vector searchEach image is encoded once and then only vectors are compared, which is cheap; see RAG for retrieval
Extracting fixed fields from invoices and formsOCR or layout parsing plus rule checks; if a vision-language model extracts, add validationAuditable and checkable; a vision-language model that misreads a digit usually looks right
Answering questions about screenshots, charts and interfacesA vision-language model with a high enough input resolutionNeeds layout and semantics, not only text
Multi-page PDFs, contracts, strictly regulated Q&ALayout parsing plus retrieval, and only key pages go to the vision-language modelTokens and cost grow linearly with the page count, and answers need traceable sources
Agents that operate interfacesA vision-language model reading the screen, plus tool callsAgents 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:

LayerQuestionTypical symptomCheck and fix
Did it seeDid the target information reach the visual tokensSmall text, thin lines and dense tables go wrong, and changing the prompt does not helpEstimate the effective font size and token count; enlarge, crop the region, raise max_pixels (see the experiment above)
Is it alignedAre the visual tokens bound to the instruction correctlyOff-topic answers; mixing up images when there are severalCheck 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 itIs the model really answering from the imageInventing content that is not in the image; answering from common sense without lookingRun 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:

  1. Prepare 20 to 50 real samples covering your real input types (screenshots, scans, photos).
  2. 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).
  3. Run at several resolutions and prompts, and record the number of errors of each type, the latency and the cost per call.
  4. 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:

  1. 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.
  2. 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.
  3. LLaVA has two steps: first train only the projector to align, then fine-tune the projector and the language model on image instruction data.
  4. With dynamic resolution the visual token count is H′f⋅W′f\frac{H'}{f}\cdot\frac{W'}{f} (ff 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.
  5. 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.
  6. 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, 2×22\times2 merge) processes a 448×448 image. How many visual tokens does it produce (not counting the start and end markers)?

  • 1024
  • 64
  • 256
  • 1568

f=14×2=28f=14\times2=28 and 448/28=16448/28=16, so there are 16×16=25616\times16=256 tokens.

3. Why does CLIP need a very large batch (32,768)?

  • To fill the GPU memory
  • Each positive is contrasted with the other N−1N-1 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 N2−NN^2-N pairs are negatives; a larger batch makes the contrast richer.

4. In this page’s experiment, CLIP’s loss without a temperature (1/τ=11/\tau=1) is 2.027, close to the random-guess value ln⁡8=2.079\ln 8=2.079. 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: 2×28×4×128×2=573442\times28\times4\times128\times2=57344 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:

  1. 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?
  2. For a batch of N=8N=8, 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?
  3. 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.
  4. 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.
  5. 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”?
  6. Using this page’s vit_flops and llm_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
  1. f=28f=28: 1080/28=38.571080/28=38.57 rounds to 39 and 39×28=109239\times28=1092; 1920/28=68.571920/28=68.57 rounds to 69 and 69×28=193269\times28=1932. The resized image is 1932×1092, both below the pixel cap, so no further adjustment. The number of visual tokens is 39×69=269139\times69=2691. Each token takes 2×28×4×128×2=573442\times28\times4\times128\times2=57344 bytes (56 KiB) of KV cache, in total 2691×56 KiB≈147 MiB2691\times56\text{ KiB}\approx147\text{ MiB}.
  2. For random guessing the softmax of each sample is roughly uniform and the cross-entropy is ln⁡8≈2.079\ln 8\approx2.079; 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 1/τ1/\tau close to 100.
  3. Linear projection: 1024×4096+4096=4,198,4001024\times4096+4096=4{,}198{,}400; two-layer MLP: add 4096×4096+4096=16,781,3124096\times4096+4096=16{,}781{,}312 for 20,979,71220{,}979{,}712 in total. Counting numel() of nn.Linear(1024, 4096) and nn.Linear(4096, 4096) verifies it.
  4. 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.
  5. 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”.
  6. 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

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.