Level 3 In-Depth AI · Vision, Audio and Multimodal
Multimodal LLMs
Language models that can also look and listen. A vision encoder turns an image into a few hundred "image tokens", a small projector translates them into the language model's embedding space, and the LLM reads them alongside the text. This chapter explains that recipe, how such models are trained, and where they still fail.
- Level
- ●●●●● Intermediate
- Reading
- 12 min
- To learn it well
- 1 hour to read, an hour to practise
- Builds on
- 41 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 41 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- Python for AI
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Tokenization
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Tensors and Shapes
- Language Modeling and Next-Token Prediction
- Supervised Learning
- Images as Data
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Convolutional Neural Networks
- Word Embeddings
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- Image Classification
- LSTMs and GRUs
- Residual Connections
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- BERT and Encoder Models
- GPT and Decoder-Only Models
- Vision Transformers
- Sentence Embeddings
- CLIP and Contrastive Learning
- Multimodal LLMs
Read them roughly in this order. See it on the concept map →
Why it matters
Since 2023, chat assistants have learned to see. You can photograph a broken appliance and ask how to fix it, paste a chart and ask what it shows, hand over a screenshot of an error, a scanned invoice, a whiteboard sketch, or a page of handwritten maths. Many assistants also take audio directly and talk back. Models that read more than one kind of input (text, images, audio, video) are called multimodal LLMs. Those that combine images and text are also called vision-language models (VLMs).
They matter because so much of the world's information is visual: documents, interfaces, diagrams, photos and video. A multimodal model can answer questions about them ("visual question answering"), extract structured data from them (OCR and Document AI), describe images for blind and low-vision users, operate computer interfaces by looking at the screen (AI Agents), and reason about charts and figures. Many of these tasks used to need a separate specialised model each. Remarkably, the core recipe is simple, and it reuses parts you already know: a ViT from CLIP and a GPT-style language model.
The intuition
A language model reads a sequence of token embeddings: vectors, one per piece of text. It does not care where those vectors came from. So the trick is to turn an image into vectors that look to the LLM like a few hundred extra "words", and put them in the sequence next to the question.
- A vision encoder, usually a CLIP or SigLIP vision Transformer, cuts the image into patches and produces one feature vector per patch. These vectors already carry meaning that lines up with language, because CLIP was trained to match images with captions.
- A small projector (often a two-layer MLP) translates each patch vector into the LLM's embedding space, like an interpreter who translates from "vision-speak" into the LLM's own language. Each translated vector is an image token.
- The image tokens and the text tokens form one sequence. The LLM reads it and generates the answer one token at a time, exactly as it would for text alone.
Key idea Most open multimodal LLMs are three parts glued together: a pretrained vision encoder (a CLIP-style ViT), a small trained projector, and a pretrained LLM. The image becomes a few hundred tokens in the LLM's input, and everything else is ordinary next-token prediction.
How it works
From pixels to image tokens
Take LLaVA-1.5, an influential open model from 2023. Its vision encoder is CLIP ViT-L/14 at 336 × 336 pixels. With 14-pixel patches that is a grid, so 576 patch features, each a 1,024-dimensional vector. The projector is an MLP mapping each one to the LLM's width (4,096 for a 7-billion-parameter LLM), giving 576 image tokens:
Here is the vision feature of patch , and are the projector's weight matrices, and is the resulting image token. The LLM then sees
where is the LLM's own embedding of a text token. The model is trained with the usual next-token cross-entropy, but only on the answer tokens. You don't train it to predict the image tokens or the question.
Worked example of token cost. One image at 576 tokens costs as much context as about 430 English words (at roughly 0.75 words per token). A 10-page document scanned at that resolution is about 5,800 tokens. Higher resolution helps with small text but costs more: one popular technique, image tiling, cuts a large image into several 336-pixel tiles plus a downscaled overview and encodes each, so a single detailed screenshot can take several thousand tokens. Commercial APIs bill images by size. As of late 2026, Anthropic's documentation, for example, counts one token per 28 × 28-pixel patch, , so a 1,000 × 1,000 pixel image is tokens (larger images are first scaled down to a per-model limit).
Training in two stages
LLaVA's recipe, followed in spirit by many open models:
- Alignment pretraining. Freeze the vision encoder and the LLM. Train only the projector on image–caption pairs (LLaVA used about 600,000), so the LLM learns to "read" image tokens: given an image, predict its caption. It is cheap, because only a few million parameters change.
- Visual instruction tuning. Unfreeze the LLM (or add LoRA adapters) and train on image–instruction–answer conversations: "What is unusual about this image?", "Read the table and compute the total", step-by-step reasoning about charts. LLaVA generated its first 158,000 such conversations by giving a text-only GPT-4 the captions and object boxes of COCO images and asking it to write questions and answers. This is Instruction Tuning and Chat Models for images.
Larger production models add more stages: training on huge collections of interleaved web documents (text with images in between), OCR-heavy data such as documents, charts and screenshots, video, and finally preference tuning to reduce errors and improve helpfulness.
Three ways to connect vision and language
- Projector / input fusion (LLaVA, and many open models such as Qwen-VL and InternVL): simple and cheap, and it works well. The cost is many tokens per image. Variants compress them: BLIP-2's "Q-Former" squeezes an image into 32 learned query tokens.
- Cross-attention (DeepMind's Flamingo, 2022): the LLM stays frozen and its input stays text. New gated cross-attention layers inserted between its layers let text positions look at image features. The context stays short however many images there are, and the LLM's text skills are untouched.
- Native or early fusion: one Transformer is trained from the start on sequences that mix image, text and sometimes audio tokens. Images are often turned into discrete tokens by a learned image tokenizer, so the model can also generate images. Meta's Chameleon (2024) is a published example. Frontier assistants such as GPT-4o and Gemini are described by their makers as natively multimodal, but their exact architectures are not published.
Beyond images
- Audio: a speech encoder (such as the encoder half of Whisper) turns a log-mel spectrogram (Audio as Data) into audio tokens, and a projector feeds them to the LLM. Voice assistants that hear tone and respond in speech work this way or natively.
- Video: sample frames (say one per second), encode each like an image, and often pool or merge tokens over time to stay within context (Video Understanding).
- Documents and screens: high-resolution tiling and OCR-heavy training let models read dense pages and user interfaces, which powers "computer use" agents.
What they are good and bad at
As of late 2026, frontier multimodal models are strong at describing scenes, reading printed text, answering questions about charts and documents, and explaining diagrams and screenshots. They are noticeably weaker at:
- Counting and precise spatial relations ("how many chairs?", "is the cup left of the plate?").
- Fine detail in low-resolution inputs, such as small text, distant objects and dense tables.
- Object hallucination: confidently describing objects that aren't in the image, often ones that usually appear in similar scenes, like a fork next to a plate. It is the visual form of Hallucinations.
- Measuring and exact geometry: reading values off a chart axis precisely, or judging lengths and angles.
Benchmarks track these abilities. MMMU tests college-level questions with images, DocVQA and ChartQA test documents and charts, and MathVista tests visual maths.
In code
A miniature LLaVA in PyTorch, untrained, to make every shape concrete: patch features, projector, joined sequence, causal Transformer, and a loss only on the answer tokens.
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(0)
VOCAB, D_TXT, D_IMG = 1000, 128, 96 # tiny sizes; real: ~150k vocab, 4096, 1024
# 1. Vision encoder (stand-in for a frozen CLIP/SigLIP ViT): image -> patch features
patchify = nn.Conv2d(3, D_IMG, kernel_size=16, stride=16)
image = torch.rand(1, 3, 224, 224)
patches = patchify(image).flatten(2).transpose(1, 2) # (1, 196, 96)
# 2. Projector: map patch features into the LLM's token-embedding space
projector = nn.Sequential(nn.Linear(D_IMG, D_TXT), nn.GELU(), nn.Linear(D_TXT, D_TXT))
image_tokens = projector(patches) # (1, 196, 128)
# 3. Text tokens -> embeddings, using the LLM's own embedding table
embed = nn.Embedding(VOCAB, D_TXT)
prompt_ids = torch.tensor([[11, 42, 7]]) # "What is in the image?"
answer_ids = torch.tensor([[95, 3, 250, 2]]) # "A cat on a sofa." + end
text_ids = torch.cat([prompt_ids, answer_ids], dim=1)
# 4. One sequence: [image tokens][prompt][answer], fed to a causal Transformer
seq = torch.cat([image_tokens, embed(text_ids)], dim=1) # (1, 196 + 7, 128)
layer = nn.TransformerEncoderLayer(D_TXT, nhead=4, batch_first=True, norm_first=True)
llm = nn.TransformerEncoder(layer, num_layers=2, enable_nested_tensor=False)
causal = nn.Transformer.generate_square_subsequent_mask(seq.shape[1])
hidden = llm(seq, mask=causal, is_causal=True)
logits = nn.Linear(D_TXT, VOCAB)(hidden) # next-token scores at every position
print("sequence length:", seq.shape[1], "| logits:", tuple(logits.shape))
# sequence length: 203 | logits: (1, 203, 1000)
# 5. Loss only on the answer tokens: position t predicts token t+1
n_img, n_prompt = image_tokens.shape[1], prompt_ids.shape[1]
start = n_img + n_prompt - 1 # last prompt position predicts answer[0]
pred = logits[:, start:start + answer_ids.shape[1]]
loss = F.cross_entropy(pred.reshape(-1, VOCAB), answer_ids.reshape(-1))
print(f"loss on 4 answer tokens: {loss.item():.2f} (random guessing: ln 1000 = 6.91)")
# loss on 4 answer tokens: 7.36 (random guessing: ln 1000 = 6.91)
In stage 1 of training only projector would receive gradients. In stage 2 the LLM would too.
Running a small open VLM locally with Hugging Face Transformers (photo.jpg is any image, and the model downloads on first use):
from transformers import pipeline
pipe = pipeline("image-text-to-text", model="llava-hf/llava-onevision-qwen2-0.5b-ov-hf")
messages = [{"role": "user", "content": [
{"type": "image", "url": "photo.jpg"},
{"type": "text", "text": "Describe this image in one sentence."},
]}]
out = pipe(text=messages, max_new_tokens=60, return_full_text=False)
print(out[0]["generated_text"])
And through a hosted API. Here is Anthropic's Python SDK, which reads the key from the ANTHROPIC_API_KEY environment variable (see Using LLM APIs):
import base64
import anthropic
client = anthropic.Anthropic()
with open("chart.png", "rb") as f:
data = base64.standard_b64encode(f.read()).decode()
message = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
messages=[{"role": "user", "content": [
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": data}},
{"type": "text", "text": "What does this chart show? Answer in two sentences."},
]}],
)
print(next(block.text for block in message.content if block.type == "text"))
Put the image before the question, as above. Most providers recommend that order.
Common pitfalls
- Trusting counts, numbers read off charts, and small text. Check them. For exact numbers, ask the model to read the values aloud first, or give it the underlying data instead of a picture.
- Images too small or too large. Downscaled images lose small text, and huge images cost many tokens or are resized by the provider anyway. Crop to the region that matters and send it at a sensible resolution.
- Hallucinated objects and details. Ask for "only what is visible" and for uncertainty to be stated, and verify anything that matters (Checking AI Output).
- Prompt injection through images. Text inside an image ("ignore previous instructions…") is read like any other text. Treat images from untrusted sources as untrusted input (Prompt Injection and LLM Security).
- Privacy. Photos carry faces, documents, location metadata and things in the background. Know what you are sending to a hosted API, and strip EXIF metadata when needed.
- Evaluating on famous images. Public benchmark images may have been in the training data. Test on your own images.
Watch out Multimodal models describe images fluently whether or not they are right, and the fluency makes errors easy to miss. For medical images, safety inspections, identity decisions or anything legally significant, treat the output as a draft for a qualified human to check, never as the decision.
Where it leads
- OCR and Document AI covers document understanding, where multimodal LLMs now compete with specialised OCR pipelines.
- Video Understanding extends the same ideas through time.
- Speech Recognition explains the audio encoders that give models ears.
- Computer-use agents read screenshots with multimodal models and act on them.
- Text-to-Image in Practice and Diffusion Models go the other way, from words to pictures. Early-fusion models aim to do both in one network.
A bit of history
Image captioning with neural networks took off around 2014–2015 ("Show and Tell" paired a CNN with an LSTM), and visual question answering datasets followed. CLIP (2021) supplied image features already aligned with language. DeepMind's Flamingo (April 2022) showed that a frozen LLM with added cross-attention could handle interleaved images and text and learn new visual tasks from a few examples. Salesforce's BLIP-2 (January 2023) bridged frozen encoders and LLMs cheaply with its Q-Former.
GPT-4, announced in March 2023 with image input and released with vision in September 2023, brought image understanding to a mass audience. LLaVA (April 2023) showed that a simple projector plus GPT-generated instruction data produced a capable open model, and spawned a large family of open VLMs. Google's Gemini (December 2023) and OpenAI's GPT-4o (May 2024) were presented as natively multimodal, the latter including speech in and out. Since then, image input has become a standard feature of chat assistants and APIs, and the research frontier has moved to video, high-resolution documents, computer use and image generation within one model.
Try it
- How many image tokens does a ViT with 14-pixel patches produce at 448 × 448? How does the attention cost change compared with 336 × 336?
- In the code, freeze everything except
projector(setrequires_grad = Falseon the other parameters) and confirm withloss.backward()that only the projector gets gradients.- Try it: give a multimodal assistant a photo of a messy desk and ask how many pens there are, then count yourself. Next, ask for a list of every object and check for hallucinated ones.
Hint for 1: , so there are 1,024 tokens, against 576. Attention cost grows with the square, so it is about 3.2 times larger.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Visual Instruction Tuning
LLaVA. Connects a CLIP image encoder to an open language model with a simple projection and trains it on GPT-4-generated visual instruction data. The template for many open multimodal models.
Vision Language Models Explained
An accessible overview of open vision-language models, how they are built and trained, how they are evaluated, and how to run and fine-tune them with Transformers.
Flamingo: a Visual Language Model for Few-Shot Learning
Inserts gated cross-attention layers into a frozen language model so it can read interleaved images and text, and learn new visual tasks from a few examples in the prompt.
BLIP-2: Bootstrapping Language-Image Pre-training with Frozen Image Encoders and Large Language Models
Bridges a frozen image encoder and a frozen LLM with a small "Q-Former" that compresses the image into 32 query tokens.
Chameleon: Mixed-Modal Early-Fusion Foundation Models
A single Transformer trained from scratch on interleaved image and text tokens, able to read and generate both, and an open example of early-fusion multimodality.
Learning Transferable Visual Models From Natural Language Supervision
CLIP: images and text in one embedding space, trained on 400M image–caption pairs.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/vision/multimodal-llms.md