Some checks failed
Self-hosted runner (nightly-past-ci-caller) / Get number (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.11 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.10 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.9 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.8 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.7 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.6 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.5 (push) Has been cancelled
Self-hosted runner (benchmark) / Benchmark (aws-g5-4xlarge-cache) (push) Has been cancelled
Build documentation / build (push) Has been cancelled
Build documentation / build_other_lang (push) Has been cancelled
CodeQL Security Analysis / CodeQL Analysis (push) Has been cancelled
New model PR merged notification / Notify new model (push) Has been cancelled
PR CI / pr-ci (push) Has been cancelled
Slow tests on important models (on Push - A10) / Get all modified files (push) Has been cancelled
Secret Leaks / trufflehog (push) Has been cancelled
Update Transformers metadata / build_and_package (push) Has been cancelled
Slow tests on important models (on Push - A10) / Model CI (push) Has been cancelled
Check Tiny Models / Check tiny models (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / Model CI (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / Pipeline CI (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / Example CI (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / DeepSpeed CI (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / Trainer/FSDP CI (push) Has been cancelled
Nvidia CI - Flash Attn / Setup (push) Has been cancelled
Nvidia CI - Flash Attn / Model CI (push) Has been cancelled
Nvidia CI / Setup (push) Has been cancelled
Nvidia CI / Model CI (push) Has been cancelled
Nvidia CI / Torch pipeline CI (push) Has been cancelled
Nvidia CI / Example CI (push) Has been cancelled
Nvidia CI / Trainer/FSDP CI (push) Has been cancelled
Nvidia CI / DeepSpeed CI (push) Has been cancelled
Nvidia CI / Quantization CI (push) Has been cancelled
Nvidia CI / Kernels CI (push) Has been cancelled
Doctests / Setup (push) Has been cancelled
Doctests / Call doctest jobs (push) Has been cancelled
Doctests / Send results to webhook (push) Has been cancelled
Extras Smoke Test / Get supported Python versions (push) Has been cancelled
Extras Smoke Test / Test extras on Python ${{ matrix.python-version }} (push) Has been cancelled
Extras Smoke Test / Check Slack token availability (push) Has been cancelled
Extras Smoke Test / Notify failures to Slack (push) Has been cancelled
Self-hosted runner (AMD scheduled CI caller) / Trigger Scheduled AMD CI (push) Has been cancelled
Stale Bot / Close Stale Issues (push) Has been cancelled
190 lines
7.0 KiB
Markdown
190 lines
7.0 KiB
Markdown
<!--Copyright 2025 The HuggingFace Team. All rights reserved.
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
|
the License. You may obtain a copy of the License at
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
|
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
|
specific language governing permissions and limitations under the License.
|
|
|
|
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
|
rendered properly in your Markdown viewer.
|
|
|
|
-->
|
|
*This model was published in HF papers on 2024-06-27 and contributed to Hugging Face Transformers on 2025-06-02.*
|
|
|
|
|
|
# ColQwen2
|
|
|
|
[ColQwen2](https://huggingface.co/papers/2407.01449) is a variant of the [ColPali](./colpali) model designed to retrieve documents by analyzing their visual features. Unlike traditional systems that rely heavily on text extraction and OCR, ColQwen2 treats each page as an image. It uses the [Qwen2-VL](./qwen2_vl) backbone to capture not only text, but also the layout, tables, charts, and other visual elements to create detailed multi-vector embeddings that can be used for retrieval by computing pairwise late interaction similarity scores. This offers a more comprehensive understanding of documents and enables more efficient and accurate retrieval.
|
|
|
|
This model was contributed by [@tonywu71](https://huggingface.co/tonywu71) (ILLUIN Technology) and [@yonigozlan](https://huggingface.co/yonigozlan) (HuggingFace).
|
|
|
|
You can find all the original ColPali checkpoints under Vidore's [Hf-native ColVision Models](https://huggingface.co/collections/vidore/hf-native-colvision-models-6755d68fc60a8553acaa96f7) collection.
|
|
|
|
> [!TIP]
|
|
> Click on the ColQwen2 models in the right sidebar for more examples of how to use ColQwen2 for image retrieval.
|
|
|
|
<hfoptions id="usage">
|
|
<hfoption id="image retrieval">
|
|
|
|
```python
|
|
import requests
|
|
import torch
|
|
from PIL import Image
|
|
|
|
from transformers import ColQwen2ForRetrieval, ColQwen2Processor
|
|
from transformers.utils.import_utils import is_flash_attn_2_available
|
|
|
|
|
|
# Load the model and the processor
|
|
model_name = "vidore/colqwen2-v1.0-hf"
|
|
|
|
model = ColQwen2ForRetrieval.from_pretrained(
|
|
model_name,
|
|
device_map="auto", # "cpu", "cuda", "xpu" or "mps" for Apple Silicon
|
|
attn_implementation="flash_attention_2" if is_flash_attn_2_available() else "sdpa",
|
|
)
|
|
processor = ColQwen2Processor.from_pretrained(model_name)
|
|
|
|
# The document page screenshots from your corpus
|
|
url1 = "https://upload.wikimedia.org/wikipedia/commons/8/89/US-original-Declaration-1776.jpg"
|
|
url2 = "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4c/Romeoandjuliet1597.jpg/500px-Romeoandjuliet1597.jpg"
|
|
|
|
images = [
|
|
Image.open(requests.get(url1, stream=True).raw),
|
|
Image.open(requests.get(url2, stream=True).raw),
|
|
]
|
|
|
|
# The queries you want to retrieve documents for
|
|
queries = [
|
|
"When was the United States Declaration of Independence proclaimed?",
|
|
"Who printed the edition of Romeo and Juliet?",
|
|
]
|
|
|
|
# Process the inputs
|
|
inputs_images = processor(images=images).to(model.device)
|
|
inputs_text = processor(text=queries).to(model.device)
|
|
|
|
# Forward pass
|
|
with torch.no_grad():
|
|
image_embeddings = model(**inputs_images).embeddings
|
|
query_embeddings = model(**inputs_text).embeddings
|
|
|
|
# Score the queries against the images
|
|
scores = processor.score_retrieval(query_embeddings, image_embeddings)
|
|
|
|
print("Retrieval scores (query x image):")
|
|
print(scores)
|
|
```
|
|
|
|
If you have issue with loading the images with PIL, you can use the following code to create dummy images:
|
|
|
|
```python
|
|
images = [
|
|
Image.new("RGB", (128, 128), color="white"),
|
|
Image.new("RGB", (64, 32), color="black"),
|
|
]
|
|
```
|
|
|
|
</hfoption>
|
|
</hfoptions>
|
|
|
|
Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to the [Quantization](../quantization/overview) overview for more available quantization backends.
|
|
|
|
The example below uses [bitsandbytes](../quantization/bitsandbytes) to quantize the weights to int4.
|
|
|
|
```python
|
|
import requests
|
|
import torch
|
|
from PIL import Image
|
|
|
|
from transformers import BitsAndBytesConfig, ColQwen2ForRetrieval, ColQwen2Processor
|
|
|
|
|
|
model_name = "vidore/colqwen2-v1.0-hf"
|
|
|
|
# 4-bit quantization configuration
|
|
bnb_config = BitsAndBytesConfig(
|
|
load_in_4bit=True,
|
|
bnb_4bit_use_double_quant=True,
|
|
bnb_4bit_quant_type="nf4",
|
|
bnb_4bit_compute_dtype=torch.float16,
|
|
)
|
|
|
|
model = ColQwen2ForRetrieval.from_pretrained(
|
|
model_name,
|
|
quantization_config=bnb_config,
|
|
device_map="auto",
|
|
).eval()
|
|
|
|
processor = ColQwen2Processor.from_pretrained(model_name)
|
|
|
|
url1 = "https://upload.wikimedia.org/wikipedia/commons/8/89/US-original-Declaration-1776.jpg"
|
|
url2 = "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4c/Romeoandjuliet1597.jpg/500px-Romeoandjuliet1597.jpg"
|
|
|
|
images = [
|
|
Image.open(requests.get(url1, stream=True).raw),
|
|
Image.open(requests.get(url2, stream=True).raw),
|
|
]
|
|
|
|
queries = [
|
|
"When was the United States Declaration of Independence proclaimed?",
|
|
"Who printed the edition of Romeo and Juliet?",
|
|
]
|
|
|
|
# Process the inputs
|
|
inputs_images = processor(images=images, return_tensors="pt").to(model.device)
|
|
inputs_text = processor(text=queries, return_tensors="pt").to(model.device)
|
|
|
|
# Forward pass
|
|
with torch.no_grad():
|
|
image_embeddings = model(**inputs_images).embeddings
|
|
query_embeddings = model(**inputs_text).embeddings
|
|
|
|
# Score the queries against the images
|
|
scores = processor.score_retrieval(query_embeddings, image_embeddings)
|
|
|
|
print("Retrieval scores (query x image):")
|
|
print(scores)
|
|
```
|
|
|
|
You can also use checkpoints for `ColQwen2.5` that are **compatible with the ColQwen2 architecture**. This version of the model uses [Qwen2_5_VL](./qwen2_5_vl) as the backbone.
|
|
|
|
```python
|
|
from transformers import ColQwen2ForRetrieval, ColQwen2Processor
|
|
from transformers.utils.import_utils import is_flash_attn_2_available
|
|
|
|
|
|
model_name = "Sahil-Kabir/colqwen2.5-v0.2-hf" # An existing compatible checkpoint
|
|
|
|
model = ColQwen2ForRetrieval.from_pretrained(
|
|
model_name,
|
|
device_map="auto",
|
|
attn_implementation="flash_attention_2" if is_flash_attn_2_available() else "sdpa"
|
|
)
|
|
processor = ColQwen2Processor.from_pretrained(model_name)
|
|
```
|
|
|
|
## Notes
|
|
|
|
- [`~ColQwen2Processor.score_retrieval`] returns a 2D tensor where the first dimension is the number of queries and the second dimension is the number of images. A higher score indicates more similarity between the query and image.
|
|
- Unlike ColPali, ColQwen2 supports arbitrary image resolutions and aspect ratios, which means images are not resized into fixed-size squares. This preserves more of the original input signal.
|
|
- Larger input images generate longer multi-vector embeddings, allowing users to adjust image resolution to balance performance and memory usage.
|
|
|
|
## ColQwen2Config
|
|
|
|
[[autodoc]] ColQwen2Config
|
|
|
|
## ColQwen2Processor
|
|
|
|
[[autodoc]] ColQwen2Processor
|
|
- __call__
|
|
|
|
## ColQwen2ForRetrieval
|
|
|
|
[[autodoc]] ColQwen2ForRetrieval
|
|
- forward
|