To visualize which image patches are most salient to specific query terms, install the interpretability extension and use the interpretability module. You will need to generate image and query embeddings, calculate the number of patches with processor.get_n_patches, and create an image_mask with processor.get_image_mask before calling get_similarity_maps_from_embeddings and plot_all_similarity_maps.
pip install colpali-engine[interpretability]
import torch
from PIL import Image
from colpali_engine.interpretability import (
get_similarity_maps_from_embeddings,
plot_all_similarity_maps,
)
from colpali_engine.models import ColPali, ColPaliProcessor
from colpali_engine.utils.torch_utils import get_torch_device
model_name = "vidore/colpali-v1.3"
device = get_torch_device("auto")
# Load the model
model = ColPali.from_pretrained(
model_name,
torch_dtype=torch.bfloat16,
device_map=device,
).eval()
# Load the processor
processor = ColPaliProcessor.from_pretrained(model_name)
# Load the image and query
image = Image.open("shift_kazakhstan.jpg")
query = "Quelle partie de la production pétrolière du Kazakhstan provient de champs en mer ?"
# Preprocess inputs
batch_images = processor.process_images([image]).to(device)
batch_queries = processor.process_queries([query]).to(device)
# Forward passes
with torch.no_grad():
image_embeddings = model.forward(**batch_images)
query_embeddings = model.forward(**batch_queries)
# Get the number of image patches
n_patches = processor.get_n_patches(image_size=image.size, patch_size=model.patch_size)
# Get the tensor mask to filter out the embeddings that are not related to the image
image_mask = processor.get_image_mask(batch_images)
# Generate the similarity maps
batched_similarity_maps = get_similarity_maps_from_embeddings(
image_embeddings=image_embeddings,
query_embeddings=query_embeddings,
n_patches=n_patches,
image_mask=image_mask,
)
# Get the similarity map for our (only) input image
similarity_maps = batched_similarity_maps[0] # (query_length, n_patches_x, n_patches_y)
# Tokenize the query
query_tokens = processor.tokenizer.tokenize(query)
# Plot and save the similarity maps for each query token
plots = plot_all_similarity_maps(
image=image,
query_tokens=query_tokens,
similarity_maps=similarity_maps,
)
for idx, (fig, ax) in enumerate(plots):
fig.savefig(f"similarity_map_{idx}.png")