- Derive and compute the CLIP contrastive (InfoNCE) loss and use CLIP for zero-shot classification.
- Explain the image encoder, projector and LLM architecture of adapter-style vision-language models and their two-stage training.
- Compare continuous, discrete and hybrid image tokenization and explain early-fusion native multimodal models.
- Estimate image and video token budgets and choose resolution and frame-sampling settings.
- Design a document-understanding pipeline that combines OCR, a VLM and validation.
- Identify multimodal failure modes and select appropriate benchmarks and private evaluations.
Before this: Transformers: A Deep Dive, Computer Vision: Tasks, Metrics, Models and Deployment, Generative Models: The Big Picture
Most frontier AI assistants now accept images, screenshots, PDFs, audio and video alongside text, and some generate images and speech as well. This is what makes it possible to ask questions about a chart, extract fields from a scanned invoice, debug a UI from a screenshot or summarize a recorded meeting. This lesson explains how multimodal foundation models are built, from contrastive pretraining to vision-language adapters to natively multimodal and any-to-any designs, and how to judge their limits.
Intuition: a shared language for different senses
Imagine a library where every book, photograph and recording has a catalog card written in one shared code. Books about dogs and photos of dogs get similar cards. Once everything is cataloged in the same code, you can search photos with words, describe photos in words, or reason about both together. Multimodal models build that shared code: an embedding space, or a shared token stream, in which an image of a dog and the word "dog" end up near each other.
There are three broad designs, in roughly historical order:
- Dual encoders (CLIP-style): separate image and text encoders trained to agree. Good for retrieval and zero-shot classification; cannot generate text.
- Adapter-style vision-language models (VLMs): a pretrained image encoder connected to a pretrained LLM through a small projector. The LLM reads image features as if they were tokens.
- Native multimodal models: one model trained from the start (or early) on interleaved sequences of text, image, audio and video tokens, sometimes generating several modalities.
CLIP: contrastive language-image pretraining
CLIP (Radford et al., 2021) trained an image encoder and a text encoder on about 400 million image-caption pairs collected from the web. The task: in a batch of pairs, identify which caption goes with which image.
Let and be the image and text encoders, each followed by L2 normalization, producing unit vectors and . The similarity matrix is , where is a learned temperature. The loss is a symmetric cross-entropy (an InfoNCE loss) over rows and columns:
The first term asks each image to pick its caption among all captions in the batch; the second asks each caption to pick its image. The other items in the batch act as negatives, so larger batches give harder, more informative training (CLIP used a batch size of 32,768).
Worked example. A batch of with cosine similarities , , , and . Logits: .
- Image 1 (row 1): ; loss .
- Image 2 (row 2): ; loss .
- Text 1 (column 1): ; loss .
- Text 2 (column 2): ; loss .
- Total: .
Lowering sharpens the softmax and would make this already-correct batch's loss smaller.
Zero-shot classification follows directly: embed prompts such as "a photo of a {class}" for every class, embed the image, and pick the class whose text embedding has the highest cosine similarity. CLIP-style encoders (and successors such as SigLIP, which replaces the softmax with a pairwise sigmoid loss that does not need the whole batch for normalization) are the standard vision towers inside VLMs, and they are used for retrieval, filtering training data and evaluation (CLIP score).
Adapter-style vision-language models
The adapter recipe connects strong unimodal parts:
- Image encoder, usually a Vision Transformer (ViT) from CLIP or SigLIP. A ViT splits an image into patches (for example pixels) and outputs one feature vector per patch. At resolution with 14-pixel patches you get patch features.
- Projector that maps image features into the LLM's embedding space. LLaVA (Liu et al., 2023) used a single linear layer; LLaVA-1.5 used a two-layer MLP. Flamingo (Alayrac et al., 2022) instead used a Perceiver Resampler to compress features into a fixed small number of tokens and inserted gated cross-attention layers into a frozen LLM. BLIP-2 (Li et al., 2023) used a Q-Former, a small transformer with learned queries.
- LLM that receives the projected image tokens interleaved with text tokens and generates the answer.
Training typically has two stages. Alignment pretraining: freeze encoder and LLM, train only the projector on image-caption pairs so image tokens land in a region the LLM understands. Visual instruction tuning: train the projector and the LLM (fully or with LoRA) on instruction-response data about images; LLaVA generated much of this data by prompting a text-only LLM with captions and bounding boxes. The approach is cheap because it reuses expensive pretrained parts, which is why it became the standard open-model recipe.
Resolution and token budget. High resolution matters for documents and small text, but tokens grow quadratically with side length. A common solution ("any-resolution" tiling) splits a large image into tiles at the encoder's native resolution plus a downscaled global view. For a screenshot with -pixel tiles: tiles plus 1 global view, image tokens before any compression. Many models then merge neighboring patches (for example pooling, giving tokens) to save context.
Native multimodal and any-to-any models
Adapter models bolt vision onto a language model after the fact. Native multimodal models train on mixed-modality data from early in pretraining so all modalities share one representation. Several frontier developers describe their flagship models this way, though most do not publish architectural details.
A published example of the early-fusion approach is Chameleon (Meta, 2024): images are converted into discrete tokens by a learned image tokenizer and mixed with text tokens in one sequence, and a single transformer is trained with next-token prediction over everything. Because images are just tokens, the same model can both read and generate interleaved text and images.
Image tokenization choices:
- Continuous patch embeddings (ViT features): best for understanding, cannot be generated by next-token prediction directly.
- Discrete tokens from a VQ-VAE or VQGAN-style tokenizer: an image becomes, for example, a grid of codebook indices. These can be generated autoregressively, but quantization loses fine detail such as small text.
- Hybrid designs: understanding through continuous features, generation through a diffusion or flow head attached to the LLM, or a decoder that maps LLM outputs into a diffusion model's conditioning.
Any-to-any models accept and produce several modalities (text, image, audio, sometimes video), typically by giving each output modality its own tokenizer or decoder. Speech-native assistants that hear and speak in one model are the most widely deployed instance as of November 2026. Design trade-offs: shared models transfer knowledge across modalities and handle interleaved content naturally, but training is harder to balance, one modality can degrade another, and serving costs rise.
Document understanding
Documents combine text, layout, tables, charts and handwriting. Two approaches:
- OCR pipeline: run OCR (and layout detection), then feed recognized text with coordinates to a language model. Precise for clean scans, auditable, and cheap; fragile on complex layouts, charts and handwriting.
- OCR-free VLMs: feed page images directly (Donut and Pix2Struct were early research examples; general VLMs now do this). They capture layout and visual cues but can hallucinate plausible text, misread digits and lose accuracy on dense small print unless resolution is high.
Production systems often combine them: OCR provides exact strings, the VLM interprets layout and semantics, and validation rules (totals add up, dates parse, IDs match checksums) catch errors. For extraction, ask for structured output with a schema and ask the model to cite where each value appears.
Video understanding
A video is a stream of frames plus audio. Models sample frames (for example 1 frame per second), encode each, often pool or merge tokens across neighboring frames, and add timestamps. Token arithmetic dominates: one hour at 1 fps with 256 tokens per frame is tokens, which is why long-video models compress aggressively, sample adaptively (more frames when scenes change) or use retrieval over clip embeddings. Brief events between sampled frames are simply invisible to the model, a frequent cause of wrong answers about fast actions. Audio transcripts often carry more information than frames for talks and meetings.
Code: zero-shot classification with CLIP
import torch
from PIL import Image
from transformers import CLIPModel, CLIPProcessor
model_id = "openai/clip-vit-base-patch32"
model = CLIPModel.from_pretrained(model_id).eval()
processor = CLIPProcessor.from_pretrained(model_id)
labels = ["cat", "dog", "invoice", "bar chart"]
prompts = [f"a photo of a {c}" if c in ("cat", "dog") else f"an image of a {c}"
for c in labels]
image = Image.open("example.jpg").convert("RGB") # any local image
inputs = processor(text=prompts, images=image, return_tensors="pt", padding=True)
with torch.no_grad():
out = model(**inputs)
probs = out.logits_per_image.softmax(dim=-1)[0] # logits are scaled cosine similarities
for label, p in sorted(zip(labels, probs.tolist()), key=lambda x: -x[1]):
print(f"{label:10s} {p:.3f}")
logits_per_image already includes the learned temperature (CLIP stores as logit_scale). Prompt wording measurably changes zero-shot accuracy; averaging embeddings over several templates ("a photo of a {}", "a picture of a {}") is a standard improvement.
The contrastive loss itself is a few lines of PyTorch:
import torch.nn.functional as F
def clip_loss(img_emb, txt_emb, temperature=0.07):
img = F.normalize(img_emb, dim=-1)
txt = F.normalize(txt_emb, dim=-1)
logits = img @ txt.T / temperature # (N, N)
targets = torch.arange(len(img), device=img.device)
return 0.5 * (F.cross_entropy(logits, targets) +
F.cross_entropy(logits.T, targets))
Applying the same two cross-entropies to the worked example's logit matrix (cosine similarities divided by 0.5) reproduces the 0.222 computed above.
Limitations
- Hallucination: describing objects, text or details that are not in the image, often driven by language priors ("a kitchen usually has a refrigerator"). Benchmarks such as POPE probe this with yes/no questions about object presence.
- Counting, spatial relations and fine detail: patch features and token compression lose small objects and exact positions; models often miscount beyond a handful of objects.
- Text in images: reading small, rotated or low-contrast text depends heavily on input resolution.
- Charts and diagrams: models may read values approximately or infer them from titles rather than the plotted data.
- Prompt injection through images: text embedded in an image or document can carry instructions the model may follow. Treat image content from untrusted sources as untrusted input in agent systems.
- Bias and privacy: models can infer sensitive attributes or identify people; many providers restrict face identification.
Evaluation
Benchmarks probe different skills, so look at several. Representative examples (verify current versions and known contamination issues before relying on scores):
| Benchmark | What it measures |
|---|---|
| MMMU | College-level questions across many disciplines requiring images (diagrams, charts, chemical structures) |
| MathVista | Mathematical reasoning in visual contexts |
| DocVQA | Question answering over scanned document images |
| ChartQA | Questions about charts requiring visual and logical reasoning |
| Video-MME | Video understanding across short, medium and long videos |
| POPE | Object hallucination via yes/no presence questions |
Public scores saturate and leak into training data, and multiple-choice formats can be partly answered from text alone (always check a text-only baseline). For your application, build a private evaluation set from real inputs with ground truth: your invoices, your screenshots, your camera conditions. Report accuracy per field or per question type, not only overall.
Common pitfalls
- Downscaling inputs so small text becomes unreadable, then blaming the model. Check the effective resolution the API or model actually uses.
- Trusting extracted numbers without validation. Add arithmetic checks, cross-field consistency checks and human review for high-stakes fields.
- Assuming video means every frame. Know the sampling rate; ask about events that last longer than the sampling interval or use higher frame rates for short clips.
- Using CLIP similarity as ground truth for fine-grained correctness. It is a coarse, bag-of-concepts signal.
- Ignoring image-borne prompt injection in agents that browse or read documents.
In practice
For classification, search and deduplication, CLIP-style embeddings are cheap and strong. For question answering, extraction and reasoning over images, use a VLM, choosing between an API model and an open adapter-style model based on privacy, cost and accuracy on your own evaluation set. Combine VLMs with OCR and rule-based validation for documents, constrain outputs with schemas, log inputs and outputs for audit, and re-run your evaluation whenever the model version changes. Fine-tuning an open VLM with LoRA on a few thousand domain examples is a common, affordable way to close gaps on specialized forms or imagery.
Key takeaways
- CLIP learns a shared image-text embedding space with a symmetric contrastive loss in which other batch items serve as negatives, enabling zero-shot classification and retrieval.
- Adapter-style VLMs connect a pretrained vision encoder to an LLM through a small projector, trained first for alignment and then with visual instruction tuning.
- Native multimodal models train on mixed-modality sequences from early on; early-fusion designs tokenize images into discrete codes so one transformer can read and generate them.
- Image and video token counts grow quickly with resolution, tiles and frame rate, so resolution and sampling are central design choices.
- VLMs hallucinate, miscount, misread small text and can follow instructions embedded in images; validate outputs and treat image content as untrusted input.
- Public benchmarks such as MMMU, DocVQA and Video-MME are useful signals, but private evaluation on your own data decides deployment.
Terms in this lesson
- Contrastive learning
- Training representations by pulling matched pairs together and pushing mismatched pairs apart in embedding space.
- InfoNCE loss
- A cross-entropy loss that asks a model to identify the positive pair among a set of negatives using softmax-normalized similarities.
- Vision-language model (VLM)
- A model that takes images and text as input and generates text, typically by feeding image features into a language model.
- Projector
- A small network, such as a linear layer or MLP, that maps image-encoder features into a language model's token embedding space.
- Visual instruction tuning
- Fine-tuning a vision-language model on instruction-and-response examples grounded in images.
- Early fusion
- A multimodal design in which all modalities are converted to tokens and processed together by one model from the first layer.
- Image tokenizer
- A model, often a VQ-VAE or VQGAN, that converts an image into a grid of discrete codebook indices and back.
- Any-to-any model
- A multimodal model that can accept and generate several modalities, such as text, images and audio.
Check your understanding
- 1.
In CLIP training with batch size N, what serves as the negatives for each image?
- 2.
A ViT with 14-pixel patches processes a 448 x 448 image. How many patch tokens does it produce?
- 3.
You must extract invoice totals with near-zero tolerance for wrong digits. Which design is most appropriate?
- 4.
Why can an early-fusion model like Chameleon generate images with next-token prediction while a LLaVA-style model cannot?
- 5.
A model samples video at 2 fps with 196 tokens per frame. How many visual tokens are in a 10-minute video?
Exercises
Work each problem before opening the solution.
- Exercise 1Core
Compute the CLIP loss for with cosine similarities (rows images, columns texts) and .
Show solution
Logits .
- Row 1: , loss .
- Row 2: , loss .
- Column 1: , loss .
- Column 2: , loss .
Total .
- Exercise 2Core
A VLM uses 336-pixel tiles with 14-pixel patches plus one global thumbnail, followed by 2×2 token merging. How many image tokens does a 1344×1008 page image use? How many would a 4-page document use?
Show solution
Tiles: across, down, so 12 tiles plus 1 global = 13 views. Each view has patches; after 2×2 merging, tokens. Per page: tokens. Four pages: tokens (plus any separator or text tokens).
- Exercise 3Core
Extend the lesson's CLIP code to use prompt ensembling: for each class, average the normalized text embeddings of three templates, then classify an image by cosine similarity.
Show solution
import torch, torch.nn.functional as F from PIL import Image from transformers import CLIPModel, CLIPProcessor mid = "openai/clip-vit-base-patch32" model = CLIPModel.from_pretrained(mid).eval() proc = CLIPProcessor.from_pretrained(mid) labels = ["cat", "dog", "horse"] templates = ["a photo of a {}.", "a blurry photo of a {}.", "a close-up photo of a {}."] texts = [t.format(c) for c in labels for t in templates] # class-major order image = Image.open("example.jpg").convert("RGB") inputs = proc(text=texts, images=image, return_tensors="pt", padding=True) with torch.no_grad(): out = model(**inputs) txt = out.text_embeds.view(len(labels), len(templates), -1) # unit vectors (C, K, D) class_embs = F.normalize(txt.mean(dim=1), dim=-1) # (C, D) v = out.image_embeds # unit vector (1, D) sims = (v @ class_embs.T)[0] print(labels[int(sims.argmax())], sims.tolist())text_embedsandimage_embedsreturned byCLIPModelare already L2-normalized projections. Averaging the normalized template embeddings for each class and then renormalizing the mean keeps every class on the unit sphere, so the dot products are cosine similarities and are comparable across classes. - Exercise 4Challenge
Design an evaluation for a VLM that will read photos of utility meters (digits on a display) taken by field workers. Specify the dataset, metrics, slices, a text-only or trivial baseline, and acceptance criteria.
Show solution
Dataset: 1,000+ real photos sampled across meter models, lighting (day, night, flash), angles, glare, dirt and phone models, labelled by two annotators with adjudication; hold out a set never used for prompt tuning. Include unreadable images labelled as such.
Metrics: exact-match accuracy of the full reading (primary); per-digit accuracy; abstention rate and accuracy when not abstaining; rate of confident wrong answers (most important for billing); latency and cost per image.
Slices: by meter model, lighting, blur level, digit count, and whether the reading changed from last month.
Baselines: last month's reading (a trivial prior a hallucinating model might mimic); a classical OCR engine; a smaller VLM.
Acceptance: for example, at least 99% exact match on readable images, 0.5% or fewer confident wrong answers, correct abstention on at least 90% of unreadable images, with no slice below 97%. Add runtime checks: reading must be at least last month's and within a plausible consumption range, otherwise route to human review.
- Exercise 5Challenge
Explain why adapter-style VLMs are often trained in two stages (projector-only alignment, then instruction tuning). What would go wrong if you unfroze the LLM from step one with a randomly initialized projector?
Show solution
At initialization the projector outputs essentially random vectors in the LLM's embedding space. If the LLM is trainable at that point, large, noisy gradients from the misaligned image tokens flow into its weights and can damage its language abilities (catastrophic forgetting), while the model may learn to ignore the image tokens entirely and answer from text priors. Stage 1 freezes the LLM and trains only the projector on simple caption data, so image features are mapped into a region of embedding space the LLM already interprets meaningfully, at low cost. Stage 2 then fine-tunes the LLM (and projector) on instruction data with small learning rates, teaching it to follow instructions grounded in images without destroying its general skills. Mixing in text-only instruction data during stage 2 further protects language ability.
Further reading
- paperRadford et al., Learning Transferable Visual Models From Natural Language Supervision (CLIP) (2021)
- paperLiu et al., Visual Instruction Tuning (LLaVA) (2023)
- paperAlayrac et al., Flamingo: a Visual Language Model for Few-Shot Learning (2022)
- paperLi et al., BLIP-2: Bootstrapping Language-Image Pre-training with Frozen Image Encoders and Large Language Models (2023)
- paperChameleon Team, Chameleon: Mixed-Modal Early-Fusion Foundation Models (2024)
- paperYue et al., MMMU: A Massive Multi-discipline Multimodal Understanding and Reasoning Benchmark (2023)
Go further
Sources
- Zhai et al., Sigmoid Loss for Language Image Pre-Training (SigLIP)
- Liu et al., Improved Baselines with Visual Instruction Tuning (LLaVA-1.5)
- Dosovitskiy et al., An Image is Worth 16x16 Words (ViT)
- Kim et al., OCR-free Document Understanding Transformer (Donut)
- Lee et al., Pix2Struct
- Mathew et al., DocVQA
- Lu et al., MathVista
- Masry et al., ChartQA
- Fu et al., Video-MME
- Li et al., Evaluating Object Hallucination in Large Vision-Language Models (POPE)
Fact-checked and last reviewed 2026-11-05