Multimodal RAG
After this lesson, you will be able to:
- Explain why text-only RAG fails on visually rich documents, and why OCR-then-embed loses layout, chart and table information in slides, scanned PDFs, and scientific figures
- Use ColPali-style late-interaction vision-language retrievers to embed each document patch and retrieve by max-similarity — a leading approach since 2024
- Pick between OCR-then-retrieve, CLIP-style joint embedding, and ColPali late-interaction based on document complexity and latency budget
- Build a multimodal RAG pipeline that retrieves document images and feeds them directly into a multimodal LLM (any vision-capable model) — the modern visual-RAG architecture
Before you start
Don't worry if "multimodal retrieval" sounds intimidating — the core idea is simple: stop converting documents to text and back, just embed the document images directly and let a vision-language model do the retrieval and the answering.
Open the /play/embedding-distance playground and compare the embedding distance between a page rendered as image vs the same page after OCR. For tables, charts, and laid-out PDFs, the OCR'd version is typically further from the query, which is the layout and figure signal that ColPali's page-image approach keeps.
#The Visually Rich Document Problem
#Three Generations of Multimodal Retrieval
#Generation 1: OCR + Text RAG (The Legacy)
PDF → OCR → text chunks → text embeddings → vector DB
↓
Query → text embedding → top-k → text-LLM answer
Works for clean text documents. Fails on slides, scanned forms, anything with layout. The default until ~2024.
#Generation 2: CLIP-Style Joint Embedding
CLIP (Radford 2021) was trained with InfoNCE on 400M (image, caption) pairs:
The formula above is only the image-to-text half. CLIP also trains the text-to-image half and averages the two. InfoNCE itself is derived in Loss Functions: Teaching the Network What 'Wrong' Means, so the next derivation covers only what the symmetric sum adds.
#Generation 3: ColPali Late Interaction (2024+)
Before the storage math, let's anchor the late-interaction trick with a quick check.
Two retrievers index 10,000 PDF pages. System A: one 768-d CLIP embedding per page. System B: ColPali, 1024 patches × 128-d per page. A query is 'show the row in the revenue table where Q3 2025 exceeded forecast.' Which is more likely to surface the correct page, and why?
Two things decide whether late interaction is affordable: how many vectors a page produces, and how many comparisons MaxSim makes. The first is plain arithmetic.
You have a 50-page PDF report with mostly text but several embedded charts, tables, and a few diagrams. Which retrieval approach gives the best query-time recall on the chart/table content?
#The Modern Multimodal RAG Pipeline
PDF / image corpus
↓
ColPali / ColQwen encoder → patch embeddings (1024 per page)
↓
Vespa / Weaviate / Qdrant with late-interaction support
↓
Query → query encoder → MaxSim retrieval → top-k pages (as IMAGES)
↓
Vision-capable multimodal LLM given query + retrieved images
↓
Grounded answer with image citations
The shift from text-RAG: retrieved context is images, not text strings. The multimodal LLM reads the images directly. This preserves layout, figures, tables, equations, signatures — everything that OCR loses.
The code below needs a GPU, several large packages and a model download, so it cannot run on this page and is read-only. Copy it to Google Colab (use a GPU runtime and run the pip line first). Its scoring step, MaxSim, is the same operation as in the numpy playground further down, which does run here.
# Copy to Colab: needs a GPU, torch, colpali-engine, pdf2image and Pillow, so it cannot run on this page.
# Multimodal RAG: ColPali retrieval + multimodal LLM answer
# !pip install colpali-engine pdf2image Pillow
from pdf2image import convert_from_path
from PIL import Image
import torch
# 1. Convert PDF pages to images
pdf_path = "report.pdf"
page_images = convert_from_path(pdf_path)
print(f"Loaded {len(page_images)} pages")
# 2. Load ColPali (or ColQwen2 for smaller/faster)
from colpali_engine.models import ColQwen2, ColQwen2Processor
model = ColQwen2.from_pretrained(
"vidore/colqwen2-v1.0",
torch_dtype=torch.bfloat16,
device_map="auto",
)
processor = ColQwen2Processor.from_pretrained("vidore/colqwen2-v1.0")
# 3. Encode all pages once
with torch.no_grad():
page_inputs = processor.process_images(page_images).to(model.device)
page_embeddings = model(**page_inputs) # shape: (n_pages, n_patches, dim)
# 4. Encode query and score
query = "What was the Q4 2025 revenue forecast?"
with torch.no_grad():
q_inputs = processor.process_queries([query]).to(model.device)
q_embedding = model(**q_inputs) # shape: (1, n_query_tokens, dim)
# 5. MaxSim scoring
def maxsim(q, p): # q: (n_q, d), p: (n_p, d)
return torch.einsum("nd,md->nm", q, p).max(dim=-1).values.sum()
scores = torch.stack([
maxsim(q_embedding[0], page_embeddings[i])
for i in range(len(page_images))
])
# 6. Top-3 pages
top_k = scores.topk(3).indices.tolist()
print(f"Top-3 relevant pages: {top_k}")
# 7. Feed top pages to a vision-capable LLM
# import anthropic
# client = anthropic.Anthropic()
# response = client.messages.create(
# model="claude-sonnet-5-5", # model names change, check the docs
# max_tokens=1024,
# messages=[{
# "role": "user",
# "content": [
# {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": img_b64}}
# for img_b64 in [encode_image(page_images[i]) for i in top_k]
# ] + [{"type": "text", "text": f"Based on these document pages, answer: {query}"}]
# }],
# )
# print(response.content[0].text)
print("\nCHALLENGE: Add a CLIP-only baseline that encodes each page as ONE")
print("vector and retrieves with cosine similarity. Measure NDCG@3 vs ColQwen2.")
# --- CHALLENGE solution (CLIP baseline) ---
# CLIP baseline:
# from transformers import CLIPModel, CLIPProcessor
# clip = CLIPModel.from_pretrained('openai/clip-vit-large-patch14')
# clip_proc = CLIPProcessor.from_pretrained('openai/clip-vit-large-patch14')
#
# # One embedding per page (vs ColPali's 1024)
# page_clip = []
# for p in page_images:
# inp = clip_proc(images=[p], return_tensors='pt')
# page_clip.append(clip.get_image_features(**inp).squeeze(0))
# page_clip = torch.stack(page_clip)
#
# q_clip = clip.get_text_features(**clip_proc(text=[query], return_tensors='pt', padding=True)).squeeze(0)
# clip_scores = torch.cosine_similarity(q_clip.unsqueeze(0), page_clip)
# Compare the top-3 indices of the two retrievers on table- and chart-heavy queries.#Decision Rubric
| Document type | Best retrieval approach |
|---|---|
| Clean text PDFs (papers, books) | OCR + dense text embeddings (cheaper, sufficient) |
| Slides, infographics, dashboards | ColPali / ColQwen2 (visual layout matters) |
| Scanned forms, contracts, medical records | ColPali / ColQwen2 (handwriting + layout) |
| Photo collections, product catalogs | CLIP / OpenCLIP / SigLIP (image-only, no text emphasis) |
| Mixed text + images | ColPali + text fallback (best of both) |
| Mostly tabular data | Specialized table parsers (Camelot, tablular-transformer) + RAG |
#The Math of MaxSim and the Storage Curve
score(q, d) = Σ_i max_j ⟨E_qi, E_dj⟩. The playground below builds patch embeddings, runs MaxSim by hand, and plots storage cost vs corpus size so you can pick the right encoder for your fleet.#Key Takeaways
- OCR-then-text-RAG loses much of the layout and figure information on visually rich documents. Slides, scanned forms, scientific papers, contracts all carry layout/figure/table signal that OCR throws away
- ColPali late interaction is a leading approach since 2024. Encode each page as ~1024 patch embeddings, retrieve by MaxSim over query tokens; beats the paper's OCR text pipelines by about 15 nDCG@5 points on average on ViDoRe
- The pipeline shift: retrieved context is images, not text. Vision-capable LLMs can take retrieved page images directly, preserving layout end-to-end
- Storage cost ~100× higher than single-vector retrieval but quality jump justifies it for visually rich corpora; vector DBs (Vespa, Weaviate, Qdrant) now support late interaction natively
- Decision rule: clean text → text RAG; visually rich content → ColPali; image-only → CLIP/SigLIP; mixed → ColPali with text fallback
#Quick Check
Why does ColPali store ~1024 embeddings per page instead of one pooled embedding?