# SigLIP2

## 概要

[SigLIP2](https://huggingface.co/papers/2502.14786) は、[SigLIP](./siglip) の学習レシピを基盤とする、多言語対応のビジョン・言語エンコーダーのファミリーです。デコーダーベースの事前学習、自己蒸留、マスク予測を含み、密な予測タスク（セグメンテーション、深度推定など）の性能を向上させます。このモデルは、2つのバリアントで利用可能です。

- NaFlex は異なる解像度をサポートし、元の画像のアスペクト比を維持します。
- FixRes は固定解像度をサポートしており、[SigLIP](./siglip) と後方互換性があります。

すべてのオリジナルのSigLIP2チェックポイントは、[SigLIP2](https://huggingface.co/collections/google/siglip2-67b5dcef38c175486e240107)コレクション内で確認できます。

> [!TIP]
> SigLIP2を異なる画像およびテキストタスクに適用する方法のより多くの例については、右側のサイドバーにあるSigLIP2モデルをクリックしてください。

以下の例では、[Pipeline](/docs/transformers/main/ja/main_classes/pipelines#transformers.Pipeline)または[AutoModel](/docs/transformers/main/ja/model_doc/auto#transformers.AutoModel)クラスを用いたゼロショット分類を示しています。

```python
from transformers import pipeline

image = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
candidate_labels = ["a Pallas cat", "a lion", "a Siberian tiger"]

pipeline = pipeline(task="zero-shot-image-classification", model="google/siglip2-base-patch16-224", device=0)
pipeline(image, candidate_labels=candidate_labels)
```

```python
import requests
import torch
from PIL import Image

from transformers import AutoModel, AutoProcessor

model = AutoModel.from_pretrained("google/siglip2-base-patch16-224", device_map="auto", attn_implementation="sdpa")
processor = AutoProcessor.from_pretrained("google/siglip2-base-patch16-224")

url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
image = Image.open(requests.get(url, stream=True).raw)
candidate_labels = ["a Pallas cat", "a lion", "a Siberian tiger"]

# follows the pipeline prompt template to get same results
texts = [f'This is a photo of {label}.' for label in candidate_labels]

# IMPORTANT: we pass `padding=max_length` and `max_length=64` since the model was trained with this
inputs = processor(text=texts, images=image, padding="max_length", max_length=64, return_tensors="pt").to(model.device)

with torch.no_grad():
    outputs = model(**inputs)

logits_per_image = outputs.logits_per_image
probs = torch.sigmoid(logits_per_image)
print(f"{probs[0][0]:.1%} that image 0 is '{candidate_labels[0]}'")
```

```python
import requests
import torch
from PIL import Image

from transformers import AutoModel, AutoProcessor

model = AutoModel.from_pretrained("google/siglip2-base-patch16-naflex", device_map="auto", attn_implementation="sdpa")
processor = AutoProcessor.from_pretrained("google/siglip2-base-patch16-naflex")

url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
image = Image.open(requests.get(url, stream=True).raw)
candidate_labels = ["a Pallas cat", "a lion", "a Siberian tiger"]
texts = [f'This is a photo of {label}.' for label in candidate_labels]

# default value for `max_num_patches` is 256, but you can increase resulted image resolution providing higher values e.g. `max_num_patches=512`
inputs = processor(text=texts, images=image, padding="max_length", max_num_patches=256, return_tensors="pt").to(model.device)

with torch.no_grad():
    outputs = model(**inputs)

logits_per_image = outputs.logits_per_image
probs = torch.sigmoid(logits_per_image)
print(f"{probs[0][0]:.1%} that image 0 is '{candidate_labels[0]}'")
```

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

以下の例では、[bitsandbytes](../quantization/bitsandbytes)を使用して、重みを int4 にのみ量子化します。

```python
import requests
import torch
from PIL import Image

from transformers import AutoModel, AutoProcessor, BitsAndBytesConfig

bnb_config = BitsAndBytesConfig(load_in_4bit=True)
model = AutoModel.from_pretrained("google/siglip2-base-patch16-224", quantization_config=bnb_config, device_map="auto", attn_implementation="sdpa")
processor = AutoProcessor.from_pretrained("google/siglip2-base-patch16-224")

url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
image = Image.open(requests.get(url, stream=True).raw)
candidate_labels = ["a Pallas cat", "a lion", "a Siberian tiger"]

# follows the pipeline prompt template to get same results
texts = [f'This is a photo of {label}.' for label in candidate_labels]

# IMPORTANT: we pass `padding=max_length` and `max_length=64` since the model was trained with this
inputs = processor(text=texts, images=image, padding="max_length", max_length=64, return_tensors="pt").to(model.device)

with torch.no_grad():
    outputs = model(**inputs)

logits_per_image = outputs.logits_per_image
probs = torch.sigmoid(logits_per_image)
print(f"{probs[0][0]:.1%} that image 0 is '{candidate_labels[0]}'")
```
## テキスト埋め込みと検索

SigLIP2は、検索や類似性ベースのタスク（プロダクトやキャプションの検索など）において、テキスト埋め込みを生成するために使用できます。

最適な結果を得るためには、トレーニング時に使用したテキスト前処理を適用する必要があります。[AutoProcessor]経由でSigLIP2のチェックポイントをロードする場合、この前処理はプロセッサによって自動的に処理されます。

### デフォルトのテキスト前処理（自動で処理されます）

SigLIP2モデルの場合、プロセッサはテキスト入力に対して以下のデフォルトを適用します。
- **小文字化**するすべての入力テキスト
- **パディングと切り詰めを固定**: `padding="max_length"`、`max_length=64`、`truncation=True`

これらのデフォルト値により、一貫性があり正確なテキスト埋め込みが保証されます。これらをオーバーライドすると、検索品質が低下する可能性があります。

### 例: テキスト埋め込みの計算

```python
import torch

from transformers import AutoModel, AutoProcessor

model_id = "google/siglip2-so400m-patch14-384"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModel.from_pretrained(model_id, device_map="auto").eval()

texts = [
    "HOME084 Timbangan Badan Digital Kaca Transparan 28CM Body Scale Personal Scale",
    "26cm Timbangan Badan digital personal scale weight",
    "33cm Timbangan Badan digital personal scale weight",
]

# NOTE: lowercasing and padding/truncation to length 64 are applied automatically by the processor pipeline.
inputs = processor(text=texts, return_tensors="pt").to(model.device)

with torch.no_grad():
    text_features = model.get_text_features(**inputs)

# Normalize embeddings for cosine similarity
text_features = text_features / text_features.norm(p=2, dim=-1, keepdim=True)
```
### テキストのみの使用: Siglip2Tokenizer

プロセッサなしでテキストをエンコードする場合（[AutoTokenizer]経由など）、[Siglip2Tokenizer]を使用してください。

- Siglip2Tokenizerは、トークナイザーのバックエンドレベルで小文字化を適用します（SigLIP2の学習時の正規化に一致）。これにより、元のトークナイザーと同じトークン化を維持します。

- トークナイザーを直接使用する場合、トレーニング時に使用したのと同じパディング/切り詰め設定（例: max_length=64）を明示的に適用する必要があります。

```python
from transformers import Siglip2Tokenizer

model_id = "google/siglip2-so400m-patch14-384"
tokenizer = Siglip2Tokenizer.from_pretrained(model_id)

inputs = tokenizer(
    ["HELLO WORLD"],
    padding="max_length",
    truncation=True,
    max_length=64,
    return_tensors="pt",
)
```
## 注記

- 単一ノード・マルチアクセラレータ環境でのDDPおよびFSDPによるトレーニングがサポートされています。ただし、[torch.distributed](https://pytorch.org/tutorials/beginner/dist_overview.html)のユーティリティを使用しないため、バッチサイズのスケーラビリティが制限される可能性があります。
- スタンドアロンの[GemmaTokenizerFast](/docs/transformers/main/ja/model_doc/gemma#transformers.GemmaTokenizer)を使用する際は、モデルがそのように学習されているため、`padding="max_length"`と`max_length=64`を渡すようにしてください。
- モデルは*小文字化*されたテキストで学習されているため、テキストラベルも同様に前処理されていることを確認してください。
- [Pipeline](/docs/transformers/main/ja/main_classes/pipelines#transformers.Pipeline) と同じ結果を得るには、プロンプトテンプレートとして `"This is a photo of {label}."` をプロセッサに渡す必要があります。
- NaFlexバリアントは、適切な解像度で異なるタイプの画像を処理します（例えば、文書画像にはより高い解像度を使用します）。また、OCRなどの特定の推論タスクにおけるアスペクト比の歪みの影響を最小限に抑えます。

   NaFlex は、リサイズ後の高さと幅がパッチサイズの倍数になるように入力画像をリサイズします。アスペクト比の歪みを可能な限り低く保ち、最大で希望するターゲットシーケンス長（`max_num_patches`）までのシーケンス長を生成します。リサイズ後、画像はパッチのシーケンスに分割され、パディング情報を含むマスクが追加されます。
- よりメモリ効率の高いアテンションを使用するには、`attn_implementation` パラメータを `"sdpa"` または `"flash_attention_2"` に切り替えてください。

    ```py
    # pip install -U flash-attn --no-build-isolation

    from transformers import Siglip2Model

    model = Siglip2Model.from_pretrained(
        "google/siglip2-so400m-patch14-384",
        attn_implementation="flash_attention_2",
        device_map="auto",
    )
    ```

## Siglip2Config[[transformers.Siglip2Config]]

#### transformers.Siglip2Config[[transformers.Siglip2Config]]

```python
transformers.Siglip2Config(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, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, initializer_factor: float = 1.0)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip2/configuration_siglip2.py#L114)

**パラメータ:**

text_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *任意*) : テキストバックボーンの config オブジェクトまたは辞書。

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

initializer_factor (`float`、*任意*、デフォルトは`1.0`) : すべての重み行列を初期化する係数です（1に保つ必要があります。初期化テスト用に内部で使用されます）。

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

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

例:

```python
>>> from transformers import Siglip2Config, Siglip2Model

>>> # Initializing a Siglip2Config with google/siglip2-base-patch16-224 style configuration
>>> configuration = Siglip2Config()

>>> # Initializing a Siglip2Model (with random weights) from the google/siglip2-base-patch16-224 style configuration
>>> model = Siglip2Model(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

>>> # We can also initialize a Siglip2Config from a Siglip2TextConfig and a Siglip2VisionConfig
>>> from transformers import Siglip2TextConfig, Siglip2VisionConfig

>>> # Initializing a Siglip2Text and Siglip2Vision configuration
>>> config_text = Siglip2TextConfig()
>>> config_vision = Siglip2VisionConfig()

>>> config = Siglip2Config(text_config=config_text, vision_config=config_vision)
```

## Siglip2TextConfig[[transformers.Siglip2TextConfig]]

#### transformers.Siglip2TextConfig[[transformers.Siglip2TextConfig]]

```python
transformers.Siglip2TextConfig(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, vocab_size: int = 32000, hidden_size: int = 768, intermediate_size: int = 3072, num_hidden_layers: int = 12, num_attention_heads: int = 12, max_position_embeddings: int = 64, hidden_act: str = 'gelu_pytorch_tanh', layer_norm_eps: float = 1e-06, attention_dropout: float | int = 0.0, pad_token_id: int | None = 1, bos_token_id: int | None = 49406, eos_token_id: int | list[int] | None = 49407, projection_size: int | None = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip2/configuration_siglip2.py#L30)

**パラメータ:**

vocab_size (`int`、*任意*、デフォルトは `32000`) : モデルの語彙サイズ。`input_ids` で表現できるトークンの種類数を定義します。

hidden_size (`int`、*任意*、デフォルトは`768`) : 隠れ表現の次元数。

intermediate_size (`int`、*任意*、デフォルトは `3072`) : MLP 表現の次元数。

num_hidden_layers (`int`, *任意*, デフォルトは `12`) : Transformer デコーダーの隠れ層の数。

num_attention_heads (`int`、*任意*、デフォルトは `12`) : Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。

max_position_embeddings (`int`、*optional*、デフォルトは`64`) : このモデルが使用される可能性のある最大シーケンス長。

hidden_act (`str`、*任意*、デフォルトは `gelu_pytorch_tanh`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"` など。

layer_norm_eps (`float`、*任意*、デフォルトは`1e-06`) : Layer Normalization 層で使用する epsilon です。

attention_dropout (`Union[float, int]`、*任意*、デフォルトは`0.0`) : 注意確率のドロップアウト率。

pad_token_id (`int`, *任意*, デフォルトは `1`) : 語彙内でパディングに使用されるトークン ID。

bos_token_id (`int`、*任意*、デフォルトは `49406`) : 語彙内でストリームの開始に使用されるトークン ID。

eos_token_id (`Union[int, list[int]]`、*任意*、デフォルトは `49407`) : 語彙内でストリーム終了に使用されるトークン ID。

projection_size (`int`, *任意*) : テキストおよびビジョンの投影層の次元数。

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

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

例:

```python
>>> from transformers import Siglip2TextConfig, Siglip2TextModel

>>> # Initializing a Siglip2TextConfig with google/siglip2-base-patch16-224 style configuration
>>> configuration = Siglip2TextConfig()

>>> # Initializing a Siglip2TextModel (with random weights) from the google/siglip2-base-patch16-224 style configuration
>>> model = Siglip2TextModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```

## Siglip2VisionConfig[[transformers.Siglip2VisionConfig]]

#### transformers.Siglip2VisionConfig[[transformers.Siglip2VisionConfig]]

```python
transformers.Siglip2VisionConfig(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, hidden_size: int = 768, intermediate_size: int = 3072, num_hidden_layers: int = 12, num_attention_heads: int = 12, num_channels: int = 3, patch_size: int | list[int] | tuple[int, int] = 16, hidden_act: str = 'gelu_pytorch_tanh', layer_norm_eps: float = 1e-06, attention_dropout: float | int = 0.0, num_patches: int = 256)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip2/configuration_siglip2.py#L73)

**パラメータ:**

hidden_size (`int`、*任意*、デフォルトは`768`) : 隠れ表現の次元数。

intermediate_size (`int`、*任意*、デフォルトは `3072`) : MLP 表現の次元数。

num_hidden_layers (`int`, *任意*, デフォルトは `12`) : Transformer デコーダーの隠れ層の数。

num_attention_heads (`int`、*任意*、デフォルトは `12`) : Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。

num_channels (`int`、*任意*、デフォルトは`3`) : 入力チャネル数。

patch_size (`Union[int, list[int], tuple[int, int]]`、*任意*、デフォルトは`16`) : 各パッチのサイズ（解像度）。

hidden_act (`str`、*任意*、デフォルトは `gelu_pytorch_tanh`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"` など。

layer_norm_eps (`float`、*任意*、デフォルトは`1e-06`) : Layer Normalization 層で使用する epsilon です。

attention_dropout (`Union[float, int]`、*任意*、デフォルトは`0.0`) : 注意確率のドロップアウト率。

num_patches (`int`, *optional*, デフォルト値は 256) : サイズが (`patch_size`, `patch_size`) のパッチにおける、画像内のパッチ数です。画像は、このパッチ数の上限を満たすようにリサイズされ、アスペクト比が保持されます。結果として得られるパッチ数がこの数値を下回る場合は、画像は "patch" 次元でパディングされます。

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

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

例:

```python
>>> from transformers import Siglip2VisionConfig, Siglip2VisionModel

>>> # Initializing a Siglip2VisionConfig with google/siglip2-base-patch16-naflex style configuration
>>> configuration = Siglip2VisionConfig()

>>> # Initializing a Siglip2VisionModel (with random weights) from the google/siglip2-base-patch16-naflex style configuration
>>> model = Siglip2VisionModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```

## Siglip2ImageProcessor[[transformers.Siglip2ImageProcessor]]

#### transformers.Siglip2ImageProcessor[[transformers.Siglip2ImageProcessor]]

```python
transformers.Siglip2ImageProcessor(**kwargs: *<class 'transformers.models.siglip2.image_processing_siglip2.Siglip2ImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip2/image_processing_siglip2.py#L121)

**パラメータ:**

do_convert_rgb (`bool`, *kwargs*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *任意*, デフォルトは `True`) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *任意*、デフォルトは `True`) : size が整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*、デフォルト値は`2`) : 画像のリサイズ時に使用するリサンプリングフィルタです。これは列挙型`PILImageResampling`のいずれかになります。`do_resize`が`True`に設定されている場合のみ、効果が現れます。

do_rescale (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*, デフォルトは `0.00392156862745098`) : `do_rescale` が `True` に設定されている場合、画像をリスケールするための係数。

do_normalize (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.5, 0.5, 0.5]`) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.5, 0.5, 0.5]`) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

patch_size (`int`, *kwargs*, *optional*, デフォルトは `self.patch_size`) : 画像を分割する各パッチのサイズ（解像度）。

max_num_patches (`int`, *kwargs*, *optional*, デフォルトは `self.max_num_patches`) : 画像は、パッチ数がこの数以下になるようにリサイズされ、その後「patch」次元がパディングされて、ちょうどこの数に一致します。

Siglip2ImageProcessor の画像プロセッサを構築します。

#### preprocess[[transformers.Siglip2ImageProcessor.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], **kwargs: *<class 'transformers.models.siglip2.image_processing_siglip2.Siglip2ImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip2/image_processing_siglip2.py#L136)

**パラメータ:**

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` を設定してください。

do_convert_rgb (`bool`, *kwargs*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *optional*) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*) : size が int の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 画像をリサイズする場合に使用するリサンプリングフィルタ。`PILImageResampling` の列挙型のいずれかです。`do_resize` が `True` に設定されている場合のみ有効です。

do_rescale (`bool`, *kwargs*, *任意*) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*) : `do_rescale` が `True` に設定されている場合、画像をリサイズするためのリスケール係数。

do_normalize (`bool`, *kwargs*, *optional*) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

patch_size (`int`, *kwargs*, *optional*, デフォルトは `self.patch_size`) : 画像を分割する各パッチのサイズ（解像度）。

max_num_patches (`int`, *kwargs*, *optional*, デフォルトは `self.max_num_patches`) : 画像は、パッチ数がこの数以下になるようにリサイズされ、その後「patch」次元がパディングされて、ちょうどこの数に一致します。

**戻り値:** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- __call__ メソッドによって返されるリスト/配列/テンソルの辞書（'pixel_values' など）。
- **tensor_type** (`Union[None, str, TensorType]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。

## Siglip2ImageProcessorPil[[transformers.Siglip2ImageProcessorPil]]

#### transformers.Siglip2ImageProcessorPil[[transformers.Siglip2ImageProcessorPil]]

```python
transformers.Siglip2ImageProcessorPil(**kwargs: *<class 'transformers.models.siglip2.image_processing_pil_siglip2.Siglip2ImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip2/image_processing_pil_siglip2.py#L120)

**パラメータ:**

do_convert_rgb (`bool`, *kwargs*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *任意*, デフォルトは `True`) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *任意*、デフォルトは `True`) : size が整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*、デフォルト値は`2`) : 画像のリサイズ時に使用するリサンプリングフィルタです。これは列挙型`PILImageResampling`のいずれかになります。`do_resize`が`True`に設定されている場合のみ、効果が現れます。

do_rescale (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*, デフォルトは `0.00392156862745098`) : `do_rescale` が `True` に設定されている場合、画像をリスケールするための係数。

do_normalize (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.5, 0.5, 0.5]`) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.5, 0.5, 0.5]`) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

patch_size (`int`, *kwargs*, *optional*, デフォルトは `self.patch_size`) : 画像を分割する各パッチのサイズ（解像度）。

max_num_patches (`int`, *kwargs*, *optional*, デフォルトは `self.max_num_patches`) : 画像は、パッチ数がこの数以下になるようにリサイズされ、その後「patch」次元がパディングされて、ちょうどこの数に一致します。

Siglip2ImageProcessor の画像プロセッサを構築します。

#### preprocess[[transformers.Siglip2ImageProcessorPil.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], **kwargs: *<class 'transformers.models.siglip2.image_processing_pil_siglip2.Siglip2ImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip2/image_processing_pil_siglip2.py#L135)

**パラメータ:**

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` を設定してください。

do_convert_rgb (`bool`, *kwargs*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *optional*) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*) : size が int の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 画像をリサイズする場合に使用するリサンプリングフィルタ。`PILImageResampling` の列挙型のいずれかです。`do_resize` が `True` に設定されている場合のみ有効です。

do_rescale (`bool`, *kwargs*, *任意*) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*) : `do_rescale` が `True` に設定されている場合、画像をリサイズするためのリスケール係数。

do_normalize (`bool`, *kwargs*, *optional*) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

patch_size (`int`, *kwargs*, *optional*, デフォルトは `self.patch_size`) : 画像を分割する各パッチのサイズ（解像度）。

max_num_patches (`int`, *kwargs*, *optional*, デフォルトは `self.max_num_patches`) : 画像は、パッチ数がこの数以下になるようにリサイズされ、その後「patch」次元がパディングされて、ちょうどこの数に一致します。

**戻り値:** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- __call__ メソッドによって返されるリスト/配列/テンソルの辞書（'pixel_values' など）。
- **tensor_type** (`Union[None, str, TensorType]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。

## Siglip2Processor[[transformers.Siglip2Processor]]

#### transformers.Siglip2Processor[[transformers.Siglip2Processor]]

```python
transformers.Siglip2Processor(image_processor, tokenizer)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip2/processing_siglip2.py#L37)

**パラメータ:**

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

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

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

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

#### __call__[[transformers.Siglip2Processor.__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 = None, videos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = None, audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None, **kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/processing_utils.py#L657)

**パラメータ:**

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` を設定してください。

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

audio (`Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]]`, *任意*) : 準備対象のオーディオまたはオーディオのバッチです。各オーディオは NumPy 配列または PyTorch テンソルであることができます。NumPy 配列/PyTorch テンソルの場合、各オーディオの形状は (C, T) である必要があります。ここで C はチャネル数、T はオーディオのサンプル長を表します。

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 クラスを参照してください。

## Siglip2Model[[transformers.Siglip2Model]]

#### transformers.Siglip2Model[[transformers.Siglip2Model]]

```python
transformers.Siglip2Model(config: Siglip2Config)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip2/modeling_siglip2.py#L712)

**パラメータ:**

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

特定のヘッドを付加せず、生のhidden-statesを出力する素のSiglip2 Model。

このモデルは [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.Siglip2Model.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, pixel_values: typing.Optional[torch.FloatTensor] = None, pixel_attention_mask: typing.Optional[torch.Tensor] = None, spatial_shapes: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, return_loss: bool | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip2/modeling_siglip2.py#L810)

**パラメータ:**

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)

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

pixel_attention_mask (`torch.Tensor`、形状 `(batch_size, image_size, image_size)`、*任意*) : パディングピクセルのインデックスに対してアテンションを実行しないためのマスク。

spatial_shapes (`torch.LongTensor`、形状 `(batch_size, 2)`) : 入力画像の空間次元（高さ、幅）を含むテンソル。

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)

return_loss (`bool`, *任意*) : 対比損失を返すかどうか。

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

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

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

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

- **loss** (`torch.FloatTensor`、shape `(1,)`、*optional*、`return_loss` が `True` の場合のみ返されます) -- 画像とテキストの類似度に対する対比損失。
- **logits_per_image** (`torch.FloatTensor`、shape `(image_batch_size, text_batch_size)`) -- `image_embeds` と `text_embeds` 間のスケーリング済みドット積スコアです。これは画像とテキストの類似度スコアを表します。
- **logits_per_text** (`torch.FloatTensor`、shape `(text_batch_size, image_batch_size)`) -- `text_embeds` と `image_embeds` 間のスケーリング済みドット積スコアです。これはテキストと画像の類似度スコアを表します。
- **text_embeds** (`torch.FloatTensor`、shape `(batch_size, output_dim`) -- [Siglip2TextModel](/docs/transformers/main/ja/model_doc/siglip2#transformers.Siglip2TextModel)のプーリング済み出力に投影層を適用して得られたテキスト埋め込み。
- **image_embeds** (`torch.FloatTensor`、shape `(batch_size, output_dim`) -- [Siglip2VisionModel](/docs/transformers/main/ja/model_doc/siglip2#transformers.Siglip2VisionModel)のプーリング済み出力に投影層を適用して得られた画像埋め込み。
- **text_model_output** (`~modeling_outputs.BaseModelOutputWithPooling`、*任意*) -- [Siglip2TextModel](/docs/transformers/main/ja/model_doc/siglip2#transformers.Siglip2TextModel)の出力です。
- **vision_model_output** (`~modeling_outputs.BaseModelOutputWithPooling`、*任意*) -- [Siglip2VisionModel](/docs/transformers/main/ja/model_doc/siglip2#transformers.Siglip2VisionModel)の出力です。

例:

```python
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import AutoProcessor, AutoModel
>>> import torch

>>> model = AutoModel.from_pretrained("google/siglip2-base-patch16-224")
>>> processor = AutoProcessor.from_pretrained("google/siglip2-base-patch16-224")

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> texts = ["a photo of 2 cats", "a photo of 2 dogs"]
>>> # important: we pass `padding=max_length` since the model was trained with this
>>> inputs = processor(text=texts, images=image, padding="max_length", return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> logits_per_image = outputs.logits_per_image
>>> probs = torch.sigmoid(logits_per_image) # these are the probabilities
>>> print(f"{probs[0][0]:.1%} that image 0 is '{texts[0]}'")
31.9% that image 0 is 'a photo of 2 cats'
```

#### get_text_features[[transformers.Siglip2Model.get_text_features]]

```python
get_text_features(input_ids: Tensor, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip2/modeling_siglip2.py#L737)

**パラメータ:**

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

**戻り値:** [BaseModelOutputWithPooling](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) または `tuple(torch.FloatTensor)`

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

- **last_hidden_state** (`torch.FloatTensor`、shape `(batch_size, sequence_length, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **pooler_output** (`torch.FloatTensor`、shape `(batch_size, hidden_size)`) -- 補助事前学習タスクに使用される層をさらに通して処理された後、シーケンスの最初のトークン（分類トークン）の最終層の隠れ状態です。例えば、BERT 系のモデルでは、線形層と tanh 活性化関数を経て処理された後の分類トークンを返します。この線形層の重みは、事前学習中の次文予測（分類）目的から学習されます。
- **hidden_states** (`tuple(torch.FloatTensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.FloatTensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各層の出力用が 1 つずつ）で、形状は `(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
>>> from transformers import AutoTokenizer, AutoModel
>>> import torch

>>> model = AutoModel.from_pretrained("google/siglip2-base-patch16-224")
>>> tokenizer = AutoTokenizer.from_pretrained("google/siglip2-base-patch16-224")

>>> # important: make sure to set padding="max_length" as that's how the model was trained
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt")
>>> with torch.no_grad():
...     text_features = model.get_text_features(**inputs)
```

#### get_image_features[[transformers.Siglip2Model.get_image_features]]

```python
get_image_features(pixel_values: typing.Optional[torch.FloatTensor] = None, pixel_attention_mask: typing.Optional[torch.Tensor] = None, spatial_shapes: typing.Optional[torch.LongTensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip2/modeling_siglip2.py#L768)

**パラメータ:**

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

pixel_attention_mask (`torch.Tensor`、形状 `(batch_size, image_size, image_size)`、*任意*) : パディングピクセルのインデックスに対してアテンションを実行しないためのマスク。

spatial_shapes (`torch.LongTensor`、形状 `(batch_size, 2)`) : 入力画像の空間次元（高さ、幅）を含むテンソル。

**戻り値:** [BaseModelOutputWithPooling](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) または `tuple(torch.FloatTensor)`

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

- **last_hidden_state** (`torch.FloatTensor`、shape `(batch_size, sequence_length, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **pooler_output** (`torch.FloatTensor`、shape `(batch_size, hidden_size)`) -- 補助事前学習タスクに使用される層をさらに通して処理された後、シーケンスの最初のトークン（分類トークン）の最終層の隠れ状態です。例えば、BERT 系のモデルでは、線形層と tanh 活性化関数を経て処理された後の分類トークンを返します。この線形層の重みは、事前学習中の次文予測（分類）目的から学習されます。
- **hidden_states** (`tuple(torch.FloatTensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.FloatTensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各層の出力用が 1 つずつ）で、形状は `(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
>>> import torch
>>> from transformers import AutoProcessor, AutoModel
>>> from transformers.image_utils import load_image

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = load_image(url)

>>> model = AutoModel.from_pretrained("google/siglip2-base-patch16-224")
>>> processor = AutoProcessor.from_pretrained("google/siglip2-base-patch16-224")

>>> inputs = processor(images=image, return_tensors="pt")

>>> with torch.no_grad():
...     image_features = model.get_image_features(**inputs)
```

## Siglip2TextModel[[transformers.Siglip2TextModel]]

#### transformers.Siglip2TextModel[[transformers.Siglip2TextModel]]

```python
transformers.Siglip2TextModel(config: Siglip2TextConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip2/modeling_siglip2.py#L587)

**パラメータ:**

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

ヘッドや投影が上に乗せられていないSiglip2のテキストモデル。

このモデルは [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.Siglip2TextModel.forward]]

```python
forward(input_ids: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip2/modeling_siglip2.py#L604)

**パラメータ:**

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

**戻り値:** [BaseModelOutputWithPooling](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) または `tuple(torch.FloatTensor)`

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

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

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

- **last_hidden_state** (`torch.FloatTensor`、shape `(batch_size, sequence_length, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **pooler_output** (`torch.FloatTensor`、shape `(batch_size, hidden_size)`) -- 補助事前学習タスクに使用される層をさらに通して処理された後、シーケンスの最初のトークン（分類トークン）の最終層の隠れ状態です。例えば、BERT 系のモデルでは、線形層と tanh 活性化関数を経て処理された後の分類トークンを返します。この線形層の重みは、事前学習中の次文予測（分類）目的から学習されます。
- **hidden_states** (`tuple(torch.FloatTensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.FloatTensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各層の出力用が 1 つずつ）で、形状は `(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
>>> from transformers import AutoTokenizer, Siglip2TextModel

>>> model = Siglip2TextModel.from_pretrained("google/siglip2-base-patch16-224")
>>> tokenizer = AutoTokenizer.from_pretrained("google/siglip2-base-patch16-224")

>>> # important: make sure to set padding="max_length" as that's how the model was trained
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt")

>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output  # pooled (EOS token) states
```

## Siglip2VisionModel[[transformers.Siglip2VisionModel]]

#### transformers.Siglip2VisionModel[[transformers.Siglip2VisionModel]]

```python
transformers.Siglip2VisionModel(config: Siglip2VisionConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip2/modeling_siglip2.py#L499)

**パラメータ:**

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

ヘッドや投影が一切付加されていないSiglip2のビジョンモデルです。

このモデルは [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.Siglip2VisionModel.forward]]

```python
forward(pixel_values: FloatTensor, pixel_attention_mask: Tensor, spatial_shapes: LongTensor, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip2/modeling_siglip2.py#L519)

**パラメータ:**

pixel_values (`torch.FloatTensor`、shape `(batch_size, num_channels, image_size, image_size)`) : 入力画像に対応するテンソルです。ピクセル値は [Siglip2ImageProcessor](/docs/transformers/main/ja/model_doc/siglip2#transformers.Siglip2ImageProcessor) を使用して取得できます。詳細は [Siglip2ImageProcessor.__call__()](/docs/transformers/main/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（[Siglip2Processor](/docs/transformers/main/ja/model_doc/siglip2#transformers.Siglip2Processor) は画像の処理に [Siglip2ImageProcessor](/docs/transformers/main/ja/model_doc/siglip2#transformers.Siglip2ImageProcessor) を使用します）。

pixel_attention_mask (`torch.Tensor`、形状 `(batch_size, image_size, image_size)`、*任意*) : パディングピクセルのインデックスに対してアテンションを実行しないためのマスク。

spatial_shapes (`torch.LongTensor`、形状 `(batch_size, 2)`) : 入力画像の空間次元（高さ、幅）を含むテンソル。

**戻り値:** [BaseModelOutputWithPooling](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) または `tuple(torch.FloatTensor)`

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

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

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

- **last_hidden_state** (`torch.FloatTensor`、shape `(batch_size, sequence_length, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **pooler_output** (`torch.FloatTensor`、shape `(batch_size, hidden_size)`) -- 補助事前学習タスクに使用される層をさらに通して処理された後、シーケンスの最初のトークン（分類トークン）の最終層の隠れ状態です。例えば、BERT 系のモデルでは、線形層と tanh 活性化関数を経て処理された後の分類トークンを返します。この線形層の重みは、事前学習中の次文予測（分類）目的から学習されます。
- **hidden_states** (`tuple(torch.FloatTensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.FloatTensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各層の出力用が 1 つずつ）で、形状は `(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
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from PIL import Image
>>> from transformers import AutoProcessor, Siglip2VisionModel

>>> model = Siglip2VisionModel.from_pretrained("google/siglip2-base-patch16-224")
>>> processor = AutoProcessor.from_pretrained("google/siglip2-base-patch16-224")

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> inputs = processor(images=image, return_tensors="pt")

>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output  # pooled features
```

## Siglip2ForImageClassification[[transformers.Siglip2ForImageClassification]]

#### transformers.Siglip2ForImageClassification[[transformers.Siglip2ForImageClassification]]

```python
transformers.Siglip2ForImageClassification(config: Siglip2Config)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip2/modeling_siglip2.py#L915)

**パラメータ:**

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

Siglip2のビジョンエンコーダーの上に画像分類ヘッド（パッチトークンのプーリングされた最終隠れ状態の上に配置された線形層）を備えたモデル。ImageNetなどでの使用例。

このモデルは [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.Siglip2ForImageClassification.forward]]

```python
forward(pixel_values: typing.Optional[torch.Tensor] = None, pixel_attention_mask: typing.Optional[torch.Tensor] = None, spatial_shapes: typing.Optional[torch.LongTensor] = None, labels: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip2/modeling_siglip2.py#L939)

**パラメータ:**

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

pixel_attention_mask (`torch.Tensor`、形状 `(batch_size, image_size, image_size)`、*任意*) : パディングピクセルのインデックスに対してアテンションを実行しないためのマスク。

spatial_shapes (`torch.LongTensor`、形状 `(batch_size, 2)`) : 入力画像の空間次元（高さ、幅）を含むテンソル。

labels (`torch.LongTensor`、shape `(batch_size,)`、*任意*) : 画像分類/回帰の損失を計算するためのラベル。インデックスは `[0, ..., config.num_labels - 1]` の範囲である必要があります。`config.num_labels == 1` の場合は回帰損失（Mean-Square loss）が計算され、`config.num_labels > 1` の場合は分類損失（Cross-Entropy）が計算されます。

**戻り値:** [ImageClassifierOutput](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.ImageClassifierOutput) または `tuple(torch.FloatTensor)`

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

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

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

- **loss** (`torch.FloatTensor`、shape `(1,)`、*optional*、`labels` が指定された場合に返されます) -- 分類（または config.num_labels==1 の場合は回帰）の損失。
- **logits** (`torch.FloatTensor`、shape `(batch_size, config.num_labels)`) -- SoftMax 適用前の分類（または config.num_labels==1 の場合は回帰）スコア。
- **hidden_states** (`tuple(torch.FloatTensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返される) -- `torch.FloatTensor` のタプル（モデルに埋め込み層がある場合はその出力用 1 つ、各ステージの出力用 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。各ステージの出力におけるモデルの隠れ状態（特徴マップとも呼ばれる）です。
- **attentions** (`tuple(torch.FloatTensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.FloatTensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, patch_size, sequence_length)`。

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

例:

```python
>>> from transformers import AutoImageProcessor, Siglip2ForImageClassification
>>> import torch
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> torch.manual_seed(3)
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> # note: we are loading a `Siglip2Model` from the hub here,
>>> # so the head will be randomly initialized, hence the predictions will be random if seed is not set above.
>>> image_processor = AutoImageProcessor.from_pretrained("google/siglip2-base-patch16-224")
>>> model = Siglip2ForImageClassification.from_pretrained("google/siglip2-base-patch16-224")

>>> inputs = image_processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> logits = outputs.logits
>>> # model predicts one of the two classes
>>> predicted_class_idx = logits.argmax(-1).item()
>>> print("Predicted class:", model.config.id2label[predicted_class_idx])
Predicted class: LABEL_1
```

## Siglip2Tokenizer[[transformers.Siglip2Tokenizer]]

#### transformers.Siglip2Tokenizer[[transformers.Siglip2Tokenizer]]

```python
transformers.Siglip2Tokenizer(vocab: str | dict[str, int] | None = None, merges: str | list[str] | None = None, unk_token: str = '<unk>', bos_token: str = '<bos>', eos_token: str = '<eos>', pad_token: str = '<pad>', mask_token: str = '<mask>', **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip2/tokenization_siglip2.py#L31)

Gemma トークナイザー + SigLIP2 トレーニングのデフォルト: 小文字正規化。

#### __call__[[transformers.Siglip2Tokenizer.__call__]]

```python
__call__(text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None, text_pair: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None, text_target: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None, text_pair_target: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None, add_special_tokens: bool = True, padding: bool | str | PaddingStrategy = False, truncation: bool | str | TruncationStrategy | None = None, max_length: int | None = None, stride: int = 0, is_split_into_words: bool = False, pad_to_multiple_of: int | None = None, padding_side: str | None = None, return_tensors: str | TensorType | None = None, return_token_type_ids: bool | None = None, return_attention_mask: bool | None = None, return_overflowing_tokens: bool = False, return_special_tokens_mask: bool = False, return_offsets_mapping: bool = False, return_length: bool = False, verbose: bool = True, tokenizer_kwargs: dict[str, Any] | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_utils_base.py#L2449)

**パラメータ:**

text (`str`、`list[str]`、`list[list[str]]`、*任意*) : エンコード対象のシーケンスまたはシーケンスのバッチです。各シーケンスは文字列、または文字列のリスト（プレトークナイズ済み文字列）であることができます。シーケンスが文字列のリスト（プレトークナイズ済み）として提供される場合、`is_split_into_words=True` を設定する必要があります（シーケンスのバッチとの曖昧さを解消するため）。

text_pair (`str`、`list[str]`、`list[list[str]]`、*任意*) : エンコード対象のシーケンスまたはシーケンスのバッチです。各シーケンスは文字列、または文字列のリスト（プレトークナイズ済み文字列）であることができます。シーケンスが文字列のリスト（プレトークナイズ済み）として提供される場合、`is_split_into_words=True` を設定する必要があります（シーケンスのバッチとの曖昧さを解消するため）。

text_target (`str`、`list[str]`、`list[list[str]]`、*任意*) : ターゲットテキストとしてエンコードするシーケンスまたはシーケンスのバッチです。各シーケンスは文字列または文字列のリスト（プレトークナイズされた文字列）であることができます。シーケンスが文字列のリスト（プレトークナイズ）として提供される場合、`is_split_into_words=True` を設定する必要があります（シーケンスのバッチとの曖昧さを解消するため）。

text_pair_target (`str`、`list[str]`、`list[list[str]]`、*任意*) : ターゲットテキストとしてエンコードするシーケンスまたはシーケンスのバッチです。各シーケンスは文字列または文字列のリスト（プレトークナイズされた文字列）であることができます。シーケンスが文字列のリスト（プレトークナイズ）として提供される場合、`is_split_into_words=True` を設定する必要があります（シーケンスのバッチとの曖昧さを解消するため）。

tokenizer_kwargs (`dict[str, Any]`、*省略可*) : トークナイザーに渡す追加の kwargs です。これらは明示的なパラメータやその他の kwargs とマージされますが、明示的なパラメータが優先されます。

add_special_tokens (`bool`、*任意*、デフォルトは`True`) : シーケンスをエンコードする際に特殊トークンを追加するかどうか。これは、入力 ID に自動的に追加されるトークンを定義する基盤となる`PretrainedTokenizerBase.build_inputs_with_special_tokens`関数を使用します。`bos`または`eos`トークンを自動的に追加したい場合に便利です。

padding (`bool`、`str` または [PaddingStrategy](/docs/transformers/main/ja/internal/file_utils#transformers.utils.PaddingStrategy)、*optional*、デフォルトは `False`) : パディングの有効化と制御を行います。以下の値を受け取ります:  - `True` または `'longest'`: バッチ内の最長のシーケンスの長さにパディングします（単一のシーケンスのみが提供された場合は、パディングを行いません）。 - `'max_length'`: 引数 `max_length` で指定された最大長、またはその引数が提供されていない場合はモデルが受け入れ可能な最大入力長までパディングします。 - `False` または `'do_not_pad'`（デフォルト）: パディングを行いません（つまり、長さが異なるシーケンスのバッチを出力できます）。

truncation (`bool`、`str` または [TruncationStrategy](/docs/transformers/main/ja/internal/tokenization_utils#transformers.tokenization_utils_base.TruncationStrategy)、*optional*、デフォルトは `False`) : トランケーションを有効化し、制御します。以下の値を受け取ります: - `True` または `'longest_first'`: 引数 `max_length` で指定された最大長、またはその引数が指定されていない場合はモデルが許容する最大入力長まで切り詰めます。ペアのシーケンス（またはペアのバッチ）が提供されている場合、ペアの中で最も長いシーケンスからトークン単位で1トークンずつ削除します。 - `'only_first'`: 引数 `max_length` で指定された最大長、またはその引数が指定されていない場合はモデルが許容する最大入力長まで切り詰めます。ペアのシーケンス（またはペアのバッチ）が提供されている場合、ペアの最初のシーケンスのみを切り詰めます。 - `'only_second'`: 引数 `max_length` で指定された最大長、またはその引数が指定されていない場合はモデルが許容する最大入力長まで切り詰めます。ペアのシーケンス（またはペアのバッチ）が提供されている場合、ペアの2番目のシーケンスのみを切り詰めます。 - `False` または `'do_not_truncate'`（デフォルト）: トランケーションを行いません（つまり、モデルが許容する最大入力サイズを超えるシーケンス長を持つバッチを出力する可能性があります）。

max_length (`int`, *optional*) : 切り詰め/パディングパラメータのいずれかによって使用される最大長を制御します。 未設定のまま、または `None` に設定されている場合、切り詰め/パディングパラメータのいずれかが最大長を必要とする場合、事前に定義されたモデルの最大長が使用されます。 モデルに特定の最大入力長がない場合（XLNet など）、最大長への切り詰め/パディングは無効になります。

stride (`int`、*optional*、デフォルト値は 0) : `max_length` とともに数値が設定されている場合、`return_overflowing_tokens=True` のときに返されるオーバーフローしたトークンは、切り詰められたシーケンスの末尾の一部のトークンを含み、切り詰められたシーケンスとオーバーフローしたシーケンスの間に重複部分を持たせます。この引数の値は、重複するトークンの数を定義します。

is_split_into_words (`bool`、*任意*、デフォルトは `False`) : 入力がすでに事前トークン化済み（例：単語に分割済み）かどうかを示します。`True` に設定すると、トークナイザーは入力がすでに単語に分割済み（たとえば空白で分割済み）であると仮定し、それをトークン化します。これは NER やトークン分類に有用です。

pad_to_multiple_of (`int`, *optional*) : 設定すると、シーケンスを指定された値の倍数にパディングします。`padding` が有効になっている必要があります。これは、計算能力が `>= 7.5` (Volta) の NVIDIA ハードウェア上で Tensor Cores を使用可能にするために特に有用です。

padding_side (`str`, *任意*) : モデルにパディングを適用する側です。['right', 'left'] から選択する必要があります。デフォルト値は、同名のクラス属性から取得されます。

return_tensors (`str` または [TensorType](/docs/transformers/main/ja/internal/file_utils#transformers.TensorType)、*optional*) : 設定されている場合、Python の整数のリストではなくテンソルを返します。指定可能な値は以下の通りです。 - `'pt'`: PyTorch の `torch.Tensor` オブジェクトを返します。 - `'np'`: Numpy の `np.ndarray` オブジェクトを返します。

return_token_type_ids (`bool`、*省略可*) : トークンタイプIDを返すかどうか。デフォルトのままにすると、`return_outputs` 属性で定義される特定のトークナイザーのデフォルトに従って、トークンタイプIDを返します。  [トークンタイプIDとは?](../glossary#token-type-ids)

return_attention_mask (`bool`、*省略可*) : アテンションマスクを返すかどうか。デフォルトのままにすると、`return_outputs` 属性で定義される特定のトークナイザーのデフォルトに従って、アテンションマスクを返します。  [アテンションマスクとは?](../glossary#attention-mask)

return_overflowing_tokens (`bool`, *任意*, デフォルトは `False`) : 溢れたトークンシーケンスを返すかどうかを指定します。入力 ID のシーケンスのペア（またはペアのバッチ）が `truncation_strategy = longest_first` または `True` とともに提供された場合、溢れたトークンを返す代わりにエラーが発生します。

return_special_tokens_mask (`bool`, *任意*, デフォルトは `False`) : 特殊トークンのマスク情報を返すかどうか。

return_offsets_mapping (`bool`、*任意*、デフォルトは`False`) : 各トークンについて`(char_start, char_end)`を返すかどうか。これは[PreTrainedTokenizerFast](/docs/transformers/main/ja/main_classes/tokenizer#transformers.TokenizersBackend)を継承する fast tokenizer のみで利用可能であり、Python の tokenizer を使用している場合、このメソッドは`NotImplementedError`を送出します。

return_length (`bool`、*任意*、デフォルトは`False`) : エンコードされた入力の長さを返すかどうか。

verbose (`bool`、*任意*、デフォルトは `True`) : 詳細な情報や警告を表示するかどうか。

- ****kwargs** : `self.tokenize()` メソッドに渡されます

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

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

- **input_ids** -- モデルに渡すトークンIDのリスト。

  [入力IDとは何ですか？](../glossary#input-ids)

- **token_type_ids** -- モデルに渡すトークンタイプIDのリスト（`return_token_type_ids=True`の場合、または`self.model_input_names`に*"token_type_ids"*が含まれる場合）。

  [トークンタイプIDとは?](../glossary#token-type-ids)

- **attention_mask** -- モデルがどのトークンに注意すべきかを指定するインデックスのリスト（`return_attention_mask=True` の場合、または `self.model_input_names` に *"attention_mask"* が含まれている場合）。

  [アテンションマスクとは?](../glossary#attention-mask)

- **overflowing_tokens** -- 溢れ出したトークンシーケンスのリスト（`max_length`が指定され、`return_overflowing_tokens=True`の場合）。
- **num_truncated_tokens** -- トークンが切り詰められた数（`max_length`が指定され、`return_overflowing_tokens=True`の場合）。
- **special_tokens_mask** -- 0 と 1 のリスト。1 は追加された特殊トークンを、0 は通常のシーケンストークンを示します（`add_special_tokens=True` かつ `return_special_tokens_mask=True` の場合）。
- **length** -- 入力データの長さ（`return_length=True`の場合）

1 つ以上のシーケンス、または 1 つ以上のシーケンスのペアをトークナイズし、モデル用に準備するための主要なメソッドです。

