Cheat sheets

Multimodal and Vision-Native RAG

Embed page images, score with MaxSim, fuse modalities, cite evidence regions. Python and TypeScript from the lessons.

  • Concepts and terms
  • Tasks and commands
  • Annotated code
  • Diagrams
  • Comparisons
  • Defaults and numbers
  • Troubleshooting
  • Questions and tips

Source

Run the lessons and the project#

CommandWhat it does
python main.pyCapstone MaxSim scaffold plus a pruning ablation
npm startViewer self-check pass with --demo. Exits 0
npm run serveHTTP viewer on 127.0.0.1. Free port when PORT is unset
npm testFixture, HTML escape and route tests
python3 scripts/project_test.py visual-evidence-library --init my-visual-evidence-libraryCreates the incomplete workspace
python3 scripts/project_test.py visual-evidence-library --stage 1 --path my-visual-evidence-libraryGrades stage 1
python3 main.py --manifest ./fixtures/manifest.json --query "return dry seeds" --out ./visual-outputWrites index.html and evidence.json
python3 demo.pyRuns the search on the original fixtures

From 19.04 code/main.py, 19.04 code/ts/README.md, 19.04 code/ts/package.json, visual-evidence-library/README.md

MaxSim late interaction#

def max_sim_score(query_tokens, doc_patches):
total = 0.0
for q in query_tokens:one vector per query token
best = -1e9
for p in doc_patches:every patch on the page
s = dot(q, p)
if s > best:
best = s
total += bestsum of the best match per token
return total
idx = build_index(prune=True)DocPruner keeps 50% of patches
hits = idx.retrieve(q, k=3)list of (Page, score)

From 19.04 code/main.py

Options side by side#

FactorColPaliVisRAGText-RAG
Page vectorsN_p patch vectorsOne pooled vectorOne vector per chunk
ScoringMaxSimBi-encoderCosine on chunks
OCR stepNoneNoneOCR / pdftotext
Storage~30x text-RAGSmaller~150 kB per 50 chunks
RecallStrongWeakerLoses charts and tables
Use forQualityScalePure-text documents

From Lesson 12.23

Manifest and proposal errors#

SymptomCauseFix
Asset IDs must be nonempty and uniqueEmpty or repeated idGive each asset a unique id
Image dimensions must be positive integers at most 20000Bad width or heightDeclare integer pixel sizes
Asset must be an image inside the manifest directoryPath escapes root or wrong suffixUse .svg, .png, .jpg or .jpeg under root
Asset exceeds 5 MBLarge fileShrink the image
Bounding box lies outside the declared image dimensionsx + w or y + h too largeFix the bbox
Model-proposed text needs explicit review before indexingreviewed is not trueCheck the image, then set reviewed=true
Vision extraction requires --provider-url, --width and --heightMissing flagsPass all three
Image bytes do not match the extensionPNG or JPEG magic bytes differUse the correct extension

From solution/main.py, visual-evidence-library/README.md

Vision-first document QA pipeline#

page imagespatchesMaxSimtop-k pagescited pages + regionsclientPDFspage renderer,180 DPImodelColQwen2.5-v0.2~2048 patchesper pageprocessDocPruner50% compressionstoreMulti-vectorindexVespa or QdrantclientQuerytoken embeddingsprocessRetrievetop-kMaxSimmodelVLM answererquery + pageimagesclientViewerboxes on sourcepagepage imagespatchesMaxSimtop-k pagescited pages + regionsclientPDFspage renderer, 180 DPImodelColQwen2.5-v0.2~2048 patches per pageprocessDocPruner50% compressionstoreMulti-vector indexVespa or QdrantclientQuerytoken embeddingsprocessRetrieve top-kMaxSimmodelVLM answererquery + page imagesclientViewerboxes on source page

From Lesson 19.04

Tasks in code#

TaskCode
Score one pagemaxsim(query_tokens, patches)
Rank toy pagesretrieve(query, pages, k=3)
Prune patchesdoc_prune(patches, keep_fraction=0.5)
Index with pruningbuild_index(prune=True)
Fuse three modalitiesfuse([t, i, a], [0.3, 0.4, 0.3])
Retry on low confidenceagentic_loop(query, confidence_floor=0.8)
Check a manifestvalidate_manifest(manifest, root)
Search text regionssearch(assets, query, limit=20)

From 12.23 code/main.py, 19.04 code/main.py, 12.24 code/main.py, solution/main.py

Score fusion and agentic retry#

1Decompose"quiet" goes to audio, "vegan brunch" to text,"natural light" to images.2text_retrievekeyword counts in review text, divided by thenumber of keywords.3image_retrievequery hints map to tags such as natural_lightand airy.4audio_retrieve"quiet" gives 1.0 - r.ambient_db / 80.0. Else0.5.5fuseweighted sum with weights 0.3, 0.4, 0.3. top_kkeeps 3.6Checktop score below confidence_floor adds " brightwindows low noise".7Round 2fuse again with weights 0.3, 0.5, 0.2.8grounded_generateeach hit cites review, image tags and ambientdB.

From 12.24 code/main.py, Lesson 12.24

Use X when#

  • Use ColPali or ColQwen2 for financial reports, papers, contracts and medical records.
  • Use VisRAG when indexing speed and storage matter more than recall.
  • Use text-RAG for wiki articles, chat logs and multi-million-page archives.
  • Use text-RAG when regulation demands extractable OCR text.
  • Use CLIP or SigLIP 2 for text and image. Use CLAP for text and audio.
  • Use score fusion first. Upgrade to MoE fusion when A/B shows clear wins.

From Lesson 12.23, Lesson 12.24

Formulas and numbers#

MaxSim
\sum_i \max_j \cos(q_i, p_j) over query tokens and page patches.
ColPali storage
50 729 128 * 4 bytes = ~18 MB raw, ~4 MB after PQ.
Text-RAG storage
50 chunks 768-dim 4 bytes = ~150 kB.
PQ
shrinks storage ~8x and keeps vector similarity.
ViDoRe
ColPali-v1 ~80% nDCG@5. Text-RAG ~50-60%.
ColQwen page
~2048 patch embeddings of dim 128.
DocPruner
50% compression at < 0.5% accuracy loss.
Capstone targets
10k pages, top-5 pages to the VLM, answers under 2s.

From Lesson 12.23, Lesson 19.04

Defaults#

SettingDefaultNote
EMB_DIM16Fake patch vectors in the capstone
keep_fraction0.5doc_prune keeps at least 1 patch
Retrieve k5Top pages by MaxSim
confidence_floor0.8main passes 0.7
search limit20Must be between 1 and 100
--queryseed returnEvidence library CLI
--modellocal-vision-modelUsed with --vision-image
--outvisual-outputHolds index.html and evidence.json

From 19.04 code/main.py, 12.24 code/main.py, solution/main.py

Abbreviations#

MaxSim
max similarity per query token, summed across the query.
ViDoRe
Visual Document Retrieval Evaluation. Metric nDCG@5.
PQ / OPQ
product quantization. Compresses patch vectors.
VisRAG
pools each page into one vector with a VLM.
M3DocRAG
retrieves pages across documents for multi-page reasoning.
MoE fusion
a gating network routes to modality experts.
MuRAG
the 2022 paper that started multimodal RAG.
Evidence region
a bbox on the source page for the answer span.

From Lesson 12.23, Lesson 12.24, Lesson 19.04

Questions#

Why MaxSim, not mean similarity?
Irrelevant patches wash out the mean.
How do you cite mixed sources?
Text [1], image [img 3], audio [audio 2 at 0:34].
How do you grade cross-modal RAG?
Recall@k per modality and fused top-k accuracy.
Does the evidence library do OCR?
No. It indexes supplied text rectangles.
What is query coverage?
Matched terms divided by query terms. It is not confidence.

From 12.23 code/main.py, Lesson 12.23, Lesson 12.24, visual-evidence-library/README.md