ColPali

repository·main·Indexed 25 days ago

https://github.com/illuin-tech/colpali

A framework for efficient document retrieval using Vision Language Models (VLMs). ColPali creates multi-vector embeddings from visual document patches, enabling retrieval that considers both text and visual layout (such as charts and tables) without requiring separate OCR or layout recognition pipelines. The colpali-engine package supports models like ColQwen2, ColQwen2.5, and ColSmol, and provides tools for similarity map visualization, hierarchical token pooling, and integration with various vector databases.

Tokens
5.3K
Snippets
12
Records
17
Agent score
34%

What's inside ColPali

  1. Explore ColPali community libraries and integrations

    main

    ColPali is supported by various community-developed libraries and integrations for vector databases and deployment frameworks.

    Key Libraries

    • Byaldi: A high-level library (equivalent to RAGatouille for ColPali) that leverages colpali-engine to facilitate indexing and storing embeddings.
    • PyVespa: Enables interaction with the Vespa vector database with detailed ColPali support.
    • EmbedAnything: Provides end-to-end ColPali inference using Candle and ONNX backends.
    • BentoML: Facilitates easy deployment of ColPali with features like adaptive batching and zero-copy I/O.
    • ColiVara: A web-first retrieval API for storing and searching documents based on visual embeddings.
    • Astra-multivector: Provides enterprise-grade integration with AstraDB, implementing token pooling and embedding caching.
    • Mixpeek: A production platform for multimodal late-interaction retrieval supporting ColBERT, ColPaLI, and ColQwen2.
    • NoOCR: An open-source end-to-end solution for complex PDFs powered by ColPali.

    Supported Vector Databases

    • Vespa (via PyVespa)
    • Qdrant
    • Elastic Search
    • Weaviate
    • Milvus
    • AstraDB (via Astra-multivector)
    • LanceDB
  2. Visualize similarity maps for interpretability

    main

    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")
  3. Accelerate matching with fast-plaid

    main

    For larger corpus sizes, you can use fast-plaid experimentally. This involves installing fast-plaid and fastkmeans, creating a plaid_index using processor.create_plaid_index, and retrieving top-k results via processor.get_topk_plaid.

    # !pip install --no-deps fast-plaid fastkmeans
    
    # Process the inputs by batches of 4
    dataloader = DataLoader(
        dataset=images,
        batch_size=4,
        shuffle=False,
        collate_fn=lambda x: processor.process_images(x),
    )
    
    ds  = []
    for batch_doc in tqdm(dataloader):
        with torch.no_grad():
            batch_doc = {k: v.to(model.device) for k, v in batch_doc.items()}
            embeddings_doc = model(**batch_doc)
        ds.extend(list(torch.unbind(embeddings_doc.to("cpu"))))
    
    plaid_index = processor.create_plaid_index(ds)
    
    scores = processor.get_topk_plaid(query_embeddings, plaid_index, k=10)
  4. Find ColPali tutorials and notebooks

    main

    A variety of notebooks and cookbooks are available for learning how to use ColPali in different RAG (Retrieval-Augmented Generation) scenarios:

  5. Install colpali-engine

    main

    Install the colpali-engine package via PyPI or directly from the source repository. The codebase requires Python >=3.10, <3.15 and recent PyTorch versions.

    Note for ColPali versions above v1.0: Ensure you install colpali-engine from source or use a version above v0.2.0.

    Note for Mac users: If using MPS with ColQwen models and encountering errors with torch 2.6.0, downgrade to torch 2.5.1.

    pip install colpali-engine # from PyPI
    pip install git+https://github.com/illuin-tech/colpali # from source
  6. Quick start with ColQwen2

    main

    To perform document retrieval using ColQwen2, load the model and processor, process your images and queries, and perform a forward pass to obtain embeddings. Use processor.score_multi_vector to calculate similarity scores between query and image embeddings.

    import torch
    from PIL import Image
    from transformers.utils.import_utils import is_flash_attn_2_available
    
    from colpali_engine.models import ColQwen2, ColQwen2Processor
    
    model_name = "vidore/colqwen2-v1.0"
    
    model = ColQwen2.from_pretrained(
        model_name,
        torch_dtype=torch.bfloat16,
        device_map="cuda:0",  # or "mps" if on Apple Silicon
        attn_implementation="flash_attention_2" if is_flash_attn_2_available() else None,
    ).eval()
    
    processor = ColQwen2Processor.from_pretrained(model_name)
    
    # Your inputs
    images = [
        Image.new("RGB", (128, 128), color="white"),
        Image.new("RGB", (64, 32), color="black"),
    ]
    queries = [
        "What is the organizational structure for our R&D department?",
        "Can you provide a breakdown of last year’s financial performance?",
    ]
    
    # Process the inputs
    batch_images = processor.process_images(images).to(model.device)
    batch_queries = processor.process_queries(queries).to(model.device)
    
    # Forward pass
    with torch.no_grad():
        image_embeddings = model(**batch_images)
        query_embeddings = model(**batch_queries)
    
    scores = processor.score_multi_vector(query_embeddings, image_embeddings)
  7. Test a new model family

    main

    When adding a new model family, run targeted tests and linting to ensure correctness.

    Testing Commands:

    # Run model family tests
    pytest tests/models/<family>
    
    # Run checkpoint mapping tests
    pytest tests/models/test_checkpoint_key_mappings.py
    
    # Run linter
    ruff check .

    Test Requirements:

    • Processor Tests: Verify from_pretrained returns the custom class, process_images returns correct batch dimensions, and process_texts returns correct batch sizes.
    • Model Tests: Verify from_pretrained returns the custom class, and the image/query forward passes return tensors with the expected dimensions ((batch_size, sequence_length, model.dim) for Col* models).
    • Use @pytest.mark.slow for tests involving large checkpoint downloads.
    pytest tests/models/<family>
    pytest tests/models/test_checkpoint_key_mappings.py
    ruff check .
  8. Reproduce paper results with specific version

    main

    To reproduce the exact results presented in the ColPali paper, you must use the v0.1.1 tag or install the specific colpali-engine package release via pip.

    pip install colpali-engine==0.1.1
  9. Install Fused MaxSim kernels (optional)

    main

    To improve performance and reduce memory usage during scoring and ColBERT losses, you can install the [lik] extra. This installs late-interaction-kernels, a fused Triton MaxSim kernel that is automatically used on CUDA Ampere+ or Apple Silicon. This avoids the quadratic memory cost of materializing the [B, B, Lq, Ld] score tensor.

    You can control the backend using the COLPALI_SCORES_BACKEND environment variable:

    • auto (default): Uses the kernel when eligible, otherwise falls back to torch.
    • torch: Forces the pure-torch reference implementation.
    • lik: Requires the kernel and raises an error if it cannot run.
    pip install "colpali-engine[lik]"
  10. Implement a Col* processor

    main

    Processors must inherit from both BaseVisualRetrieverProcessor and the matching Transformers processor. They are responsible for image/text formatting and scoring.

    Required Methods:

    • process_images(self, images): Converts PIL images to model-ready batches.
    • process_texts(self, texts): Converts text inputs to model-ready batches.
    • score(self, qs, ps, device=None, **kwargs): For Col* models, this should delegate to score_multi_vector.
    • get_n_patches(...): Returns (n_patches_x, n_patches_y) for interpretability.

    Configuration: Set attributes like visual_prompt_prefix, query_prefix, query_augmentation_token, and image_token as required by the backbone. Ensure self.tokenizer.padding_side is set correctly in __init__.

    class ColNewFamilyProcessor(BaseVisualRetrieverProcessor, NewFamilyProcessor):
        ...