From pixels to tokens
You already know the text side: a tokenizer cuts a string into tokens, each token becomes an embedding vector, and the language model reads that sequence of vectors. A vision-language model (VLM) works the same way. It just needs a second route that turns an image into vectors of the same kind. Almost every modern VLM builds that route from three parts:
- Vision encoder. Usually a Vision Transformer (ViT). It cuts the image into a grid of small square patches and turns each patch into a vector that describes what is in that square: edges, colour, texture, part of a letter.
- Projector. A small network that maps those vectors into the language model's embedding space, so they are the same width as text-token embeddings and sit in the same "coordinate system". In the original LLaVA paper it was one linear layer sitting on top of a CLIP ViT-L/14 encoder. Qwen3-VL uses an MLP "merger" that also folds each 2×2 block of neighbouring patches into one token.
- Language model. The usual decoder. It gets one sequence of image tokens followed by your text tokens and attends over all of them, so your question can pull detail from the image.
Think of it as a fax machine feeding a reader who speaks only one language. The encoder scans the page in squares, the projector translates each square into the reader's language, and the reader answers. The reader never sees pixels. It sees only the translated squares.
That explains the most important practical fact in this course: image tokens are input tokens, and their number comes from patch size and image dimensions. If a detail is smaller than a patch, such as 6-px text or a hairline crack, it gets blended into one vector with its surroundings. The model may then guess instead of reading.
Worked arithmetic: patch size sets the count
Take one 1000×1000 px photo of a receipt:
| Model (patch per final token) | Calculation | Image tokens |
|---|---|---|
| LLaVA-1 (CLIP ViT-L/14, 224 px input) | resized to 224×224 → (224/14)² | 256 |
| Claude (28×28 px per visual token) | ceil(1000/28) × ceil(1000/28) = 36 × 36 | 1,296 |
| Qwen3-VL (16 px patches, 2×2 merge = 32 px) | resized to 992×992 → 31 × 31 | 961 |
The rule of thumb is that tokens ≈ (width ÷ effective patch) × (height ÷ effective patch). Double both sides of the image and you pay about four times as much. On OpenAI's models that use 32-px patches, the patch count is also multiplied by a factor that depends on the model (1.2 for many current GPT-5.x models) before billing. Every provider has its own rules, so read its vision docs and don't assume another provider's numbers apply.
Walkthrough 1: a hosted model
# pip install anthropic (any hosted vision API follows the same pattern)
import base64, anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
MODEL = "claude-haiku-4-5-20251001" # any vision-capable model
img_b64 = base64.standard_b64encode(open("receipt.jpg", "rb").read()).decode()
question = {"type": "text", "text": "What is the total amount on this receipt?"}
image = {"type": "image",
"source": {"type": "base64", "media_type": "image/jpeg", "data": img_b64}}
resp = client.messages.create(model=MODEL, max_tokens=200,
messages=[{"role": "user", "content": [image, question]}]) # image first, then text
print(resp.content[0].text)
print("input tokens with image:", resp.usage.input_tokens)
# Hosted APIs usually report ONE input total. Find the image's share by
# counting the same request without the image and taking the difference.
text_only = client.messages.count_tokens(model=MODEL,
messages=[{"role": "user", "content": [question]}])
print("image tokens ≈", resp.usage.input_tokens - text_only.input_tokens)
Realistic output:
The total is £23.40.
input tokens with image: 1318
image tokens ≈ 1296
That difference matches the 36 × 36 grid from the table. If you get a smaller number, the provider has probably downscaled your image to fit its size limit. Lesson 2 covers that.
Walkthrough 2: an open model on your own machine
With open weights you can see every image token, because they sit in input_ids as placeholder tokens.
# pip install transformers torch accelerate pillow (a recent transformers)
from transformers import Qwen3VLForConditionalGeneration, AutoProcessor
MID = "Qwen/Qwen3-VL-2B-Instruct" # small enough for one consumer GPU
model = Qwen3VLForConditionalGeneration.from_pretrained(MID, dtype="auto", device_map="auto")
processor = AutoProcessor.from_pretrained(MID)
messages = [{"role": "user", "content": [
{"type": "image", "image": "receipt.jpg"},
{"type": "text", "text": "What is the total amount on this receipt?"}]}]
inputs = processor.apply_chat_template(messages, tokenize=True,
add_generation_prompt=True, return_dict=True, return_tensors="pt").to(model.device)
# 1) Patch grid the encoder saw: [frames, rows, cols] of 16-px patches
print("grid_thw:", inputs["image_grid_thw"].tolist())
# 2) Tokens the LLM actually reads: one <|image_pad|> per merged 2x2 block
pad_id = processor.tokenizer.convert_tokens_to_ids("<|image_pad|>")
print("image tokens:", (inputs["input_ids"] == pad_id).sum().item())
out = model.generate(**inputs, max_new_tokens=64)
print(processor.batch_decode(out[:, inputs["input_ids"].shape[1]:],
skip_special_tokens=True)[0])
grid_thw: [[1, 62, 62]]
image tokens: 961
The total amount is £23.40.
62 × 62 = 3,844 encoder patches. Dividing by 4 for the 2×2 merge gives 961 tokens for the language model. That is the projector's merge step, and you can see it in two numbers.
Gotcha: Results like these are often model-specific. Qwen3-VL's preprocessor resizes images to a multiple of 32 px, within minimum and maximum pixel bounds set in
preprocessor_config.json. A different checkpoint, even a newer one in the same family such as Qwen3.5, may use other settings. Read the config of the model you actually load.
Trade-off: The hosted model is usually more accurate on hard images and costs nothing to set up. The open model shows you exactly what it reads, costs nothing per call and keeps images on your own hardware. When the two disagree on an answer, that tells you which images deserve a closer look.
Hands-on exercise
- Choose three of your own images: a receipt, a dense screenshot and a photo.
- Run both walkthroughs on each one with the same question. Record the hosted answer, the open answer, the hosted image tokens (from the difference) and the open
<|image_pad|>count. - Before each run, predict the token counts using the 28-px and 32-px rules. Explain any mismatch above about 5%.
- Shrink one image to half its width and height and run it again. Check that the tokens drop to about a quarter, and note whether either answer got worse.
Key takeaways
- A VLM is a vision encoder (patches → vectors), a projector (vectors → the LLM's embedding space) and a language model that reads image tokens and text tokens as one sequence.
- Image tokens are ordinary input tokens. They take up context and you pay for them.
- Token count ≈ (width ÷ patch) × (height ÷ patch), so cost grows with pixel area.
- Hosted APIs usually report one input total. Find the image's share by taking a token-count difference. Open models let you count the placeholder tokens directly.
- Details smaller than a patch get averaged away, which is one reason a model misreads tiny text.