# ColQwen2

[ColQwen2](https://huggingface.co/papers/2407.01449) は、視覚的特徴を分析して文書を検索することを目的に設計された [ColPali](./colpali) モデルのバリアントです。テキスト抽出や OCR に大きく依存する従来のシステムとは異なり、ColQwen2 は各ページを画像として扱います。[Qwen2-VL](./qwen2_vl) バックボーンを使用して、テキストだけでなく、レイアウト、表、チャート、その他の視覚的要素も捉え、ペアワイズなレイトインタラクション類似度スコアを計算して検索に使用できる詳細なマルチベクトル埋め込みを生成します。これにより、文書に対するより包括的な理解が可能になり、より効率的かつ正確な検索を実現します。

このモデルは、[@tonywu71](https://huggingface.co/tonywu71)（ILLUIN Technology）と[@yonigozlan](https://huggingface.co/yonigozlan)（HuggingFace）によって提供されました。

Vidoreの[Hf-native ColVision Models](https://huggingface.co/collections/vidore/hf-native-colvision-models-6755d68fc60a8553acaa96f7)コレクションに、すべてのオリジナルのColPaliチェックポイントを見つけることができます。

> [!TIP]
> ColQwen2の画像検索での使用方法のより多くの例については、右側のサイドバーにあるColQwen2モデルをクリックしてください。

```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)
```

PILでの画像読み込みに問題がある場合は、以下のコードを使用してダミー画像を作成できます。

```python
images = [
    Image.new("RGB", (128, 128), color="white"),
    Image.new("RGB", (64, 32), color="black"),
]
```

Quantization は、重みを低精度で表現することで、大規模モデルのメモリ負荷を軽減します。利用可能な Quantization バックエンドの詳細については、[Quantization](../quantization/overview) の概要を参照してください。

以下の例では、[bitsandbytes](../quantization/bitsandbytes)を使用して重みを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)
```

`ColQwen2.5`のチェックポイントも使用できます。**ColQwen2アーキテクチャと互換性がある**チェックポイントです。このモデルのバージョンでは、バックボーンとして[Qwen2_5_VL](./qwen2_5_vl)を使用しています。

```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)
```

## 注記

- `score_retrieval()` は、第1次元がクエリの数、第2次元が画像の数である2次元テンソルを返します。スコアが高いほど、クエリと画像の類似度が高いことを示します。
- ColPali とは異なり、ColQwen2 は任意の画像解像度とアスペクト比をサポートします。そのため、画像は固定サイズの正方形にリサイズされません。これにより、元の入力シグナルのより多くの情報が保持されます。
- より大きな入力画像は、より長いマルチベクトル埋め込みを生成するため、ユーザーはパフォーマンスとメモリ使用量のバランスを調整するために画像の解像度を調整できます。

## ColQwen2Config[[transformers.ColQwen2Config]]

#### transformers.ColQwen2Config[[transformers.ColQwen2Config]]

```python
transformers.ColQwen2Config(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, vlm_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, embedding_dim: int = 128, initializer_range: float = 0.02)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/colqwen2/configuration_colqwen2.py#L28)

**パラメータ:**

vlm_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *optional*) : ビジョン・言語バックボーンの config オブジェクトまたは辞書。

embedding_dim (`int`、*optional*、デフォルトは`128`) : 埋め込みおよび隠れ状態の次元数。

initializer_range (`float`、*任意*、デフォルトは`0.02`) : すべての重み行列を初期化するためのtruncated_normal_initializerの標準偏差です。

これはColqwen2Modelの設定を保存するための設定クラスです。指定された引数に基づいてColqwen2モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[vidore/colqwen2-v1.0-hf](https://huggingface.co/vidore/colqwen2-v1.0-hf)と類似した設定が得られます。

設定オブジェクトは [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

例:

```python
from transformers.models.colqwen2 import ColQwen2Config, ColQwen2ForRetrieval

config = ColQwen2Config()
model = ColQwen2ForRetrieval(config)
```

## ColQwen2Processor[[transformers.ColQwen2Processor]]

#### transformers.ColQwen2Processor[[transformers.ColQwen2Processor]]

```python
transformers.ColQwen2Processor(image_processor = None, tokenizer = None, chat_template = None, visual_prompt_prefix: str | None = None, query_prefix: str | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/colqwen2/processing_colqwen2.py#L51)

**パラメータ:**

image_processor (`Qwen2VLImageProcessor`) : 画像プロセッサは必須の入力です。

tokenizer (`Qwen2Tokenizer`) : トークナイザーは必須の入力です。

chat_template (`str`) : チャット内のメッセージのリストをトークン化可能な文字列に変換するための Jinja テンプレート。

visual_prompt_prefix (`str`、*任意*、デフォルトは `"<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Describe the image.<|im_end|><|endoftext|>"`) : トークン化されて画像トークンの前に付加される文字列。

query_prefix (`str`、*任意*、デフォルトは`"Query : "`): クエリに使用するプレフィックス。

画像プロセッサとトークナイザーを単一のプロセッサにラップするColQwen2Processorを構築します。

[ColQwen2Processor](/docs/transformers/main/ja/model_doc/colqwen2#transformers.ColQwen2Processor) は、[Qwen2VLImageProcessor](/docs/transformers/main/ja/model_doc/qwen2_vl#transformers.Qwen2VLImageProcessor) と [Qwen2Tokenizer](/docs/transformers/main/ja/model_doc/qwen2#transformers.Qwen2Tokenizer) のすべての機能を提供します。詳細については、[~Qwen2VLImageProcessor](/docs/transformers/main/ja/model_doc/qwen2_vl#transformers.Qwen2VLImageProcessor) および [~Qwen2Tokenizer](/docs/transformers/main/ja/model_doc/qwen2#transformers.Qwen2Tokenizer) を参照してください。

#### __call__[[transformers.ColQwen2Processor.__call__]]

```python
__call__(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, text: str | list[str] | list[list[str]] = None, **kwargs: *<class 'transformers.models.colqwen2.processing_colqwen2.ColQwen2ProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/colqwen2/processing_colqwen2.py#L77)

**パラメータ:**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`, *任意*) : 前処理を行う画像。ピクセル値が 0 から 255 の範囲にある単一の画像またはバッチの画像を想定しています。ピクセル値が 0 から 1 の範囲にある画像を渡す場合は、`do_rescale=False` を設定してください。

text (`Union[str, list[str], list[list[str]]]`、*任意*) : エンコード対象のシーケンスまたはシーケンスのバッチです。各シーケンスは文字列、または文字列のリスト（プレトークナイズ済み文字列）であることができます。プレトークナイズ済み入力を渡す場合は、バッチ入力との曖昧さを避けるために `is_split_into_words=True` を設定してください。

return_tensors (`str` または [TensorType](/docs/transformers/main/ja/internal/file_utils#transformers.TensorType)、*optional*) : 設定されている場合、特定のフレームワークのテンソルを返します。受け入れ可能な値は以下の通りです:  - `'pt'`: PyTorch の `torch.Tensor` オブジェクトを返します。 - `'np'`: NumPy の `np.ndarray` オブジェクトを返します。

- ****kwargs** ([ProcessingKwargs](/docs/transformers/main/ja/main_classes/processors#transformers.ProcessingKwargs), *optional*) : 各モダリティ（テキスト、画像、動画、音声）の追加処理オプション。モデル固有のパラメータは上記にリストされています。サポートされている引数の完全なリストについては、TypedDict クラスを参照してください。

**戻り値:** [BatchFeature](/docs/transformers/main/ja/main_classes/feature_extractor#transformers.BatchFeature)

以下のフィールドを持つ[BatchFeature](/docs/transformers/main/ja/main_classes/feature_extractor#transformers.BatchFeature):

- **input_ids** -- モデルに与えるトークンIDのリスト。`text`が`None`でない場合に返されます。`suffix`が指定されている場合、`input_ids`にはサフィックスのinput idsも含まれます。
- **attention_mask** -- モデルが注意すべきトークンを指定するインデックスのリスト（`return_attention_mask=True`の場合、または`self.model_input_names`に*"attention_mask"*が含まれており`text`が`None`でない場合）。
- **pixel_values** -- モデルに渡すピクセル値。`images` が `None` でない場合に返されます。
- **labels** -- `suffix`がNoneでない場合に、トレーニングと互換性のあるラベル

## ColQwen2ForRetrieval[[transformers.ColQwen2ForRetrieval]]

#### transformers.ColQwen2ForRetrieval[[transformers.ColQwen2ForRetrieval]]

```python
transformers.ColQwen2ForRetrieval(config: ColQwen2Config)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/colqwen2/modeling_colqwen2.py#L92)

**パラメータ:**

config ([ColQwen2Config](/docs/transformers/main/ja/model_doc/colqwen2#transformers.ColQwen2Config)) : モデルのすべてのパラメータを含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを確認してください。

ColPaliのアプローチに従い、ColQwen2はVLM（視覚言語モデル）を活用して、文書検索のために文書画像（「スクリーンショット」）から直接効率的なマルチベクトル埋め込みを構築します。このモデルは、ColBERTで導入された遅延相互作用（late interaction）手法を用いて、これらの文書埋め込みと対応するクエリ埋め込みの類似度を最大化するように学習されます。

ColQwen2を使用することで、文書のテキストと視覚的な内容（レイアウト、チャートなど）の両方を考慮できる単一のモデルにより、複雑で脆弱になりがちなレイアウト認識やOCRパイプラインの必要性を排除できます。

ColQwen2はColVisionモデルファミリーの一部であり、ColPaliとともに以下の論文で紹介されました: [*ColPali: Efficient Document Retrieval with Vision Language Models*](https://huggingface.co/papers/2407.01449)。

このモデルは [PreTrainedModel](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.ColQwen2ForRetrieval.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, labels: typing.Optional[torch.LongTensor] = None, inputs_embeds: typing.Optional[torch.FloatTensor] = None, use_cache: bool | None = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, pixel_values: typing.Optional[torch.Tensor] = None, image_grid_thw: typing.Optional[torch.LongTensor] = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/colqwen2/modeling_colqwen2.py#L106)

**パラメータ:**

input_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 語彙における入力シーケンスのトークンインデックスです。デフォルトでは、パディングは無視されます。インデックスは [AutoTokenizer](/docs/transformers/main/ja/model_doc/auto#transformers.AutoTokenizer) を使用して取得できます。詳細については、[PreTrainedTokenizer.encode()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) および [PreTrainedTokenizer.__call__()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) を参照してください。 [入力IDとは何ですか？](../glossary#input-ids)

attention_mask (`torch.Tensor`、shape `(batch_size, sequence_length)`、*任意*) : padding トークンのインデックスに対する attention を回避するためのマスクです。マスクの値は `[0, 1]` から選択されます:  - **マスクされない**トークンは 1、- **マスクされる**トークンは 0。  [attention マスクとは?](../glossary#attention-mask)

position_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 各入力シーケンスのトークンが位置埋め込み内で占める位置のインデックスです。`[0, config.n_positions - 1]` の範囲から選択されます。 [位置 ID とは何か？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`, *任意*) : 逐次デコードを高速化するために使用できる、事前計算された hidden-states（self-attention ブロックおよび cross-attention ブロック内の key と value）です。通常、`use_cache=True` または `config.use_cache=True` の場合、モデルがデコードの以前の段階で返した `past_key_values` で構成されます。入力として許可されるのは [Cache](/docs/transformers/main/ja/internal/generation_utils#transformers.Cache) インスタンスのみです。[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。`past_key_values` が渡されない場合、デフォルトで [DynamicCache](/docs/transformers/main/ja/internal/generation_utils#transformers.DynamicCache) が初期化されます。モデルは、入力として与えられたのと同じキャッシュ形式を出力します。`past_key_values` を使用する場合は、すべての `input_ids`（形状 `(batch_size, sequence_length)`）の代わりに、このモデルに過去の key value 状態が与えられていない未処理の `input_ids`（形状 `(batch_size, unprocessed_length)`）のみを入力する必要があります。

labels (`torch.LongTensor`、形状 `(batch_size, sequence_length)`、*任意*) : マスク言語モデリング損失を計算するためのラベル。インデックスは `[0, ..., config.vocab_size]` の範囲内であるか、-100 である必要があります（`input_ids` のドキュメント文字列を参照）。インデックスが `-100` に設定されたトークンは無視（マスク）され、損失は `[0, ..., config.vocab_size]` の範囲内のラベルを持つトークンに対してのみ計算されます。

inputs_embeds (`torch.FloatTensor`、shape `(batch_size, sequence_length, hidden_size)`、*任意*) : `input_ids` を渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込み参照行列よりも、`input_ids` のインデックスを対応するベクトルに変換する方法をより細かく制御したい場合に有用です。

use_cache (`bool`, *任意*) : `True`に設定すると、`past_key_values`のキーバリュー状態が返され、デコーディングの高速化に利用できます（`past_key_values`を参照）。

output_attentions (`bool`, *任意*) : すべてのアテンション層のアテンションテンソルを返すかどうか。詳細は、返されるテンソルの `attentions` を参照してください。

output_hidden_states (`bool`, *任意*) : 全レイヤーの hidden states を返すかどうかを指定します。詳細は、返されるテンソルの `hidden_states` を参照してください。

return_dict (`bool`, *任意*) : プレーンなタプルではなく [ModelOutput](/docs/transformers/main/ja/main_classes/output#transformers.utils.ModelOutput) を返すかどうか。

pixel_values (`torch.Tensor`、形状 `(batch_size, num_channels, image_size, image_size)`、*任意*) : 入力画像に対応するテンソルです。ピクセル値は [Qwen2VLImageProcessor](/docs/transformers/main/ja/model_doc/qwen2_vl#transformers.Qwen2VLImageProcessor) を使用して取得できます。詳細については [Qwen2VLImageProcessor.__call__()](/docs/transformers/main/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（[ColQwen2Processor](/docs/transformers/main/ja/model_doc/colqwen2#transformers.ColQwen2Processor) は画像処理に [Qwen2VLImageProcessor](/docs/transformers/main/ja/model_doc/qwen2_vl#transformers.Qwen2VLImageProcessor) を使用します）。

image_grid_thw (`torch.LongTensor`、形状 `(num_images, 3)`、*任意*) : LLM における各画像のフィーチャー形状の時間軸、高さ、幅。

**戻り値:** `ColQwen2ForRetrievalOutput` または `tuple(torch.FloatTensor)`

`ColQwen2ForRetrievalOutput`、または `torch.FloatTensor` のタプル（`return_dict=False` が渡された場合、または `config.return_dict=False` の場合）。設定（[ColQwen2Config](/docs/transformers/main/ja/model_doc/colqwen2#transformers.ColQwen2Config)）や入力に応じて、さまざまな要素で構成されます。

[ColQwen2ForRetrieval](/docs/transformers/main/ja/model_doc/colqwen2#transformers.ColQwen2ForRetrieval) の forward メソッドは、`__call__` という特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **loss** (`torch.FloatTensor`、shape `(1,)`、*optional*、`labels` が指定された場合に返されます) -- 言語モデリングの損失(次のトークンの予測用)。
- **embeddings** (`torch.FloatTensor`、形状 `(batch_size, sequence_length, hidden_size)`) -- モデルの埋め込み。
- **past_key_values** (`Cache`、*任意*、`use_cache=True` が渡された場合または `config.use_cache=True` の場合に返されます) -- [Cache](/docs/transformers/main/ja/internal/generation_utils#transformers.Cache) のインスタンスです。詳細については、[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。

  逐次デコーディングを高速化するために使用できる（`past_key_values` 入力参照）、事前計算済みの隠れ状態（自己注意ブロックのキーとバリュー）が含まれます。
- **hidden_states** (`tuple[torch.FloatTensor]`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.FloatTensor` のタプル（モデルに埋め込み層がある場合はその出力用 + 各層の出力用）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple[torch.FloatTensor]`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.FloatTensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

例:

```python
```

