Visual document retrieval depends on both trained weights and the way page images and queries are prepared. A colpali-engine workflow can move to Sentence Transformers MultiVectorEncoder while preserving its query-to-page scores and keeping the original environment available for rollback.
The original ColQwen2 checkpoint is supported by both libraries. Its converted -hf variant is intended for Transformers rather than colpali-engine, so switching between those variants would combine an API migration with a checkpoint change.
Recent colpali-engine releases omit a query prefix retained by the checkpoint's Sentence Transformers configuration. Preserving the existing input format is necessary for score agreement; matching only the winning page can conceal a change in retrieval behavior.
Steps to migrate colpali-engine models to Sentence Transformers MultiVectorEncoder:
- Record the dependencies of your working colpali-engine environment.
$ .venv-colpali/bin/python -m pip freeze > colpali-requirements.txt
The POSIX commands assume your existing interpreter is .venv-colpali/bin/python; substitute its actual path if different. The ColQwen2 CPU path uses Python 3.14 on Ubuntu 26.04, colpali-engine 0.3.18, Transformers 5.22.2, PEFT 0.20.0, PyTorch 2.13.0+cpu, and Torchvision 0.28.0+cpu. It needs 16 GiB of available RAM and several gigabytes for checkpoint downloads. The original environment, application code, and checkpoint stay in place.
Related: Install Python on Ubuntu or Debian - Create legacy_baseline.py in your editor with the checkpoint and retrieval inputs.
- legacy_baseline.py
import json from pathlib import Path import torch from PIL import Image from huggingface_hub import hf_hub_download, snapshot_download from colpali_engine.models import ColQwen2, ColQwen2Processor adapter_revision = "2b6ac8fb37f46a49e4841e599583d00ae8a20117" base_revision = "9fe8a713422a7cb4ef79ca77a09b381ee2243101" corpus_revision = "49f05727417edee37938141fd1dd6ad70cbcc559" checkpoint = snapshot_download("vidore/colqwen2-v1.0", revision=adapter_revision) page_ids = ["doc1", "doc2", "doc3", "doc4"] page_paths = [hf_hub_download( "sentence-transformers/example-documents", f"{name}.jpg", repo_type="dataset", revision=corpus_revision, ) for name in page_ids] queries = [ "What is the variable represented on the y-axis of the graph?", "Total outlay is maximum in which year?", ] expected_top_indices = [0, 1]
The adapter and corpus use immutable Hub commits. Loading the adapter from its downloaded local snapshot lets revision=base_revision pin its separate vidore/colqwen2-base weights. The public document pages contain a contour plot in doc1, outlays by fiscal year in doc2, a research appendix in doc3, and traffic-safety material in doc4. The two queries should retrieve doc1 and doc2 respectively; all four pages participate in both rankings. For your own collection, the checkpoint, revisions, image list, queries, and expected winners must describe the original working inputs.
Related: Build visual document search - Append the colpali-engine encoding calls at the end of legacy_baseline.py.
torch.set_num_threads(4) processor = ColQwen2Processor.from_pretrained(checkpoint) model = ColQwen2.from_pretrained( checkpoint, revision=base_revision, dtype=torch.float32, attn_implementation="eager", ).eval() with torch.inference_mode(): query_embeddings = [model(**processor.process_queries([q]))[0] for q in queries] page_embeddings = [model(**processor.process_images( [Image.open(p).convert("RGB")] ))[0] for p in page_paths]
A batch contains one query or page image, keeping padding and batch memory comparable. Both environments use float32 and eager attention. The original processor supplies its actual query prefix and ten query-augmentation tokens; the baseline is captured before changing this behavior.
- Append the score calculation and baseline export at the end of legacy_baseline.py.
scores = processor.score_multi_vector(query_embeddings, page_embeddings) ranking = scores.argsort(dim=1, descending=True, stable=True) assert ranking[:, 0].tolist() == expected_top_indices, "A known relevant page did not win" baseline = { "checkpoint": checkpoint, "adapter_revision": adapter_revision, "base_revision": base_revision, "corpus_revision": corpus_revision, "page_ids": page_ids, "page_paths": page_paths, "queries": queries, "query_prefix": processor.query_prefix, "expected_top_indices": expected_top_indices, "scores": scores.tolist(), "ranking": ranking.tolist(), } Path("colpali-baseline.json").write_text(json.dumps(baseline, indent=2)) print("ColPali scores:") for row in scores.tolist(): print([round(value, 4) for value in row]) print("ColPali rankings:", ranking.tolist()) print("Query prefix:", repr(processor.query_prefix))
Rows follow query order and columns follow doc1 through doc4. The full matrix and rankings are saved alongside the exact inputs in colpali-baseline.json. The expected_top_indices list names the known relevant page for each query and must describe your own collection when you replace the inputs. Normal Python execution keeps assertions enabled; python -O disables them.
- Save legacy_baseline.py in your editor.
- Run the baseline with the unchanged colpali-engine interpreter. Example output:
$ .venv-colpali/bin/python legacy_baseline.py ##### snipped ##### ColPali scores: [12.2599, 9.8574, 9.9941, 8.845] [5.4906, 13.5026, 5.8183, 4.6121] ColPali rankings: [[0, 2, 1, 3], [1, 2, 0, 3]] Query prefix: ''
The first load downloads the public checkpoint and images. An unauthenticated Hub warning concerns download rate limits; no sign-in is required. The empty prefix is the current colpali-engine behavior. A nonempty prefix needs its own matching query template rather than removal from the baseline. This interpreter and script remain the rollback path after the migration.
- Create a separate virtual environment for Sentence Transformers.
Sentence Transformers 6 requires Transformers 5. Installing into an existing application environment can change its dependency set; the separate environment leaves the working colpali-engine installation intact.
$ python3 -m venv .venv-mve
On Ubuntu, python3-venv supplies virtual-environment support.
Related: Create a Python virtual environment - Install the same CPU PyTorch and Torchvision pair in the new environment.
$ .venv-mve/bin/python -m pip install torch==2.13.0 torchvision==0.28.0 \ --index-url https://download.pytorch.org/whl/cpuBoth wheels come from the CPU index so Torchvision's compiled operators match PyTorch. Matching the baseline runtime avoids combining an encoder migration with a PyTorch upgrade.
- Install Sentence Transformers and the matching Transformers and PEFT versions.
$ .venv-mve/bin/python -m pip install "sentence-transformers[image]==6.3.0" \ transformers==5.22.2 peft==0.20.0The image extra supplies visual-input dependencies; PEFT loads the original checkpoint's trained LoRA adapters. This checkpoint requires Transformers 5.15 or newer because earlier releases can ignore its adapter-key mapping.
Related: Install Sentence Transformers with pip
Related: Migrate Sentence Transformers code to v6 - Check the new environment for dependency conflicts.
$ .venv-mve/bin/python -m pip check No broken requirements found.
- Create migrate_colpali.py in your editor with the MultiVectorEncoder initialization.
- migrate_colpali.py
import json from pathlib import Path import torch from sentence_transformers import MultiVectorEncoder baseline = json.loads(Path("colpali-baseline.json").read_text()) torch.set_num_threads(4) model = MultiVectorEncoder( baseline["checkpoint"], revision=baseline["base_revision"], device="cpu", model_kwargs={"dtype": torch.float32, "attn_implementation": "eager"}, )
MultiVectorEncoder reads the same local adapter snapshot and pinned base revision as the original API. The checkpoint supplies the trained projection and normalization; no retraining or converted -hf checkpoint is involved.
Related: Sentence Transformers migration guide - Append the query-format compatibility section at the end of migrate_colpali.py.
query_template = ( "{{ messages[0]['content'][0]['text'] }}" "{{ '<|endoftext|>' * 10 }}" ) assert baseline["query_prefix"] == "", "This path preserves an unprefixed baseline" query_embeddings = model.encode_query( baseline["queries"], batch_size=1, show_progress_bar=False, processing_kwargs={"chat_template": {"chat_template": query_template}}, )
The checkpoint's default query template adds Query: before the query text. The explicit template retains the current baseline's unprefixed text plus ten <|endoftext|> tokens; it changes query formatting only. The guard stops the program if the recorded baseline used another prefix. An unchanged query format matters even when both variants rank the same page first.
Related: ColQwen2 model card - Append the page encoding and score comparison at the end of migrate_colpali.py.
page_embeddings = model.encode_document( baseline["page_paths"], batch_size=1, show_progress_bar=False, ) scores = model.similarity(query_embeddings, page_embeddings) old_scores = torch.tensor(baseline["scores"]) ranking = scores.argsort(dim=1, descending=True, stable=True) torch.testing.assert_close(scores, old_scores, rtol=1e-5, atol=1e-4) assert ranking.tolist() == baseline["ranking"], "Document rankings changed" assert ranking[:, 0].tolist() == baseline["expected_top_indices"], ( "A known relevant page did not win" ) print("MultiVectorEncoder scores:") for row in scores.tolist(): print([round(value, 4) for value in row]) print("Original rankings:", baseline["ranking"]) print("Migrated rankings:", ranking.tolist()) print(f"Maximum score difference: {(scores - old_scores).abs().max().item():.8f}") print("Score and ranking checks passed.")
encode_query() and encode_document() replace the processor-plus-model calls, while similarity() replaces score_multi_vector() with the same MaxSim operation. The tolerance is set before comparing the two APIs and permits only small float32 differences, at most 0.0001 + 0.00001 * abs(baseline_score) per score. It does not permit changed preprocessing. Full rankings must also match, and the known relevant pages must still win. A traceback stops the migration when any condition fails.
- Save migrate_colpali.py in your editor.
- Confirm that MultiVectorEncoder reproduces the baseline scores and page rankings. Example output:
$ .venv-mve/bin/python migrate_colpali.py ##### snipped ##### MultiVectorEncoder scores: [12.2599, 9.8574, 9.9941, 8.845] [5.4906, 13.5026, 5.8183, 4.6121] Original rankings: [[0, 2, 1, 3], [1, 2, 0, 3]] Migrated rankings: [[0, 2, 1, 3], [1, 2, 0, 3]] Maximum score difference: 0.00000191 Score and ranking checks passed.
The model-load report can list the old custom_text_proj keys as unexpected because Sentence Transformers loads that trained projection through its separate Dense module. The processor-keyword notices do not stop encoding. The two ranking rows use zero-based page indices. The migrated program is usable only after both numerical and ranking checks pass. The old environment, legacy_baseline.py, and original checkpoint remain available if the application needs to return to colpali-engine.