Scanned reports and chart-heavy PDFs can lose context when reduced to extracted text. Sentence Transformers supports visual document search that matches a text query directly to page images, preserving the layout, tables, and figures that help identify the relevant page.
ColQwen2 represents each page with multiple image-patch vectors rather than one pooled vector. Its MaxSim score sums the best page-vector match for each query token, allowing pages to be ranked without an OCR stage. The scores compare pages for one query and are not probabilities or generated answers.
A small collection can be searched exhaustively in memory with a pretrained checkpoint. The Linux CPU path needs 16 GiB of available RAM and several gigabytes of download space; encoding one page at a time limits batch memory. Larger collections need a separate indexing and capacity plan because every query is compared with every page's vectors.
Steps to build visual document search with Sentence Transformers:
- Create a fresh Python virtual environment in your project directory.
$ python3 -m venv .venv
Python 3.14, python3-venv, and HTTPS certificates are required for the Ubuntu 26.04 path. The distribution packages are python3, python3-venv, and ca-certificates.
Related: Install Python on Ubuntu or Debian
Related: Create a Python virtual environment - Activate the project virtual environment.
$ source .venv/bin/activate
Package installation and program execution use this environment.
Related: Activate a Python virtual environment - Install matching CPU builds of PyTorch and Torchvision.
$ python -m pip install torch==2.15.0 torchvision==0.29.2 \ --index-url https://download.pytorch.org/whl/cpuBoth packages come from the CPU index so Torchvision's compiled operators match the PyTorch runtime. A PyPI Torchvision wheel mixed with CPU PyTorch can fail during import with operator torchvision::nms does not exist.
Related: Install Sentence Transformers with pip - Install Sentence Transformers with its image dependencies.
The pinned packages use Sentence Transformers 6 and Transformers 5. A fresh environment keeps these major versions separate from an existing application's dependencies.
Related: Migrate Sentence Transformers code to v6$ python -m pip install "sentence-transformers[image]==6.3.0" \ "transformers==5.22.2" - Create visual_search.py in your text editor with the input definitions.
- visual_search.py
import torch from sentence_transformers import MultiVectorEncoder corpus_revision = "49f05727417edee37938141fd1dd6ad70cbcc559" base_url = ( "https://huggingface.co/datasets/" "sentence-transformers/example-documents/resolve/" f"{corpus_revision}/" ) page_ids = ["doc1", "doc2", "doc3", "doc4"] page_images = [f"{base_url}{page_id}.jpg" for page_id in page_ids] query = "Total outlay is maximum in which year?" expected_top_page = "doc2"
The four public document-page images have a fixed revision. doc1 is a scientific contour plot, doc2 contains natural-resources outlays by fiscal year, doc3 is a research-paper appendix, and doc4 covers traffic safety. The outlays question should retrieve doc2; the other three pages are distractors. The dataset credits these images to the vidore/colpali_train_set test split.
- Append the pretrained model loading and page encoding section at the end of visual_search.py.
torch.set_num_threads(4) model = MultiVectorEncoder( "vidore/colqwen2-v1.0-hf", revision="ddc07d2317c80f75fc742b7362ee9ad1912908f9", device="cpu", model_kwargs={"dtype": torch.float32}, ) page_embeddings = model.encode_document( page_images, batch_size=1, show_progress_bar=False, ) print(f"Encoded {len(page_embeddings)} page images.")
The ColQwen2 checkpoint includes its trained retrieval projection and loads through the native Transformers implementation. No training, remote model code, or API key is required. Four CPU threads and one image per batch bound the work; float32 avoids depending on CPU support for reduced-precision arithmetic. The first execution downloads the model and public images, then keeps the page vectors in memory.
- Append the text-query encoding and MaxSim ranking section at the end of visual_search.py.
query_embeddings = model.encode_query( [query], show_progress_bar=False, ) scores = model.similarity(query_embeddings, page_embeddings)[0] ranking = scores.argsort(descending=True).tolist() print(f"Query: {query}") for rank, index in enumerate(ranking, start=1): print(f"{rank}. {page_ids[index]} MaxSim={scores[index].item():.4f}")
encode_query accepts text, while encode_document accepts the image URLs. Each encoded input is a matrix with 128 columns and a variable number of token or patch rows. model.similarity uses MaxSim by default and returns queries by pages; [0] selects the only query's row. Sorting the scores from largest to smallest maps the ranking back to page_ids.
Related: Sentence Transformers multi-vector inference - Append the expected-top-page assertion at the end of visual_search.py.
top_page = page_ids[ranking[0]] assert top_page == expected_top_page, ( f"Expected {expected_top_page}, got {top_page}" ) print(f"Top-page check passed: {top_page}")
A different winning page raises AssertionError. Normal Python execution keeps assertions enabled; python -O disables them. For your own collection, page_images can contain local page-image paths, page_ids must follow the same order, and the query and expected identifier must refer to a known matching page.
- Save visual_search.py in your editor.
- Run visual_search.py to confirm that doc2 ranks first. Example output:
$ python visual_search.py ##### snipped ##### Encoded 4 page images. Query: Total outlay is maximum in which year? 1. doc2 MaxSim=16.3066 2. doc1 MaxSim=8.2268 3. doc3 MaxSim=7.8384 4. doc4 MaxSim=7.2634 Top-page check passed: doc2
The omitted lines contain downloads, weight-loading progress, and RoPE configuration notices from the pinned checkpoint. These notices do not stop encoding. An unauthenticated Hub warning concerns download rate limits. Small score differences can occur across runtimes, but doc2 should remain the top page and the assertion must pass.