# Pix2Struct

## 概要

Pix2Structモデルは、Kenton Lee、Mandar Joshi、Iulia Turc、Hexiang Hu、Fangyu Liu、Julian Eisenschlos、Urvashi Khandelwal、Peter Shaw、Ming-Wei Chang、Kristina Toutanova による [Pix2Struct: Screenshot Parsing as Pretraining for Visual Language Understanding](https://huggingface.co/papers/2210.03347) で提案されました。

論文の抄録は以下の通りです。

> 視覚的に位置づけられた言語は至る所に存在します。その出典は、図解付きの教科書から、画像や表付きのWebページ、ボタンやフォーム付きのモバイルアプリまで多岐にわたります。おそらくこの多様性のため、従来の研究は、基盤となるデータ、モデルアーキテクチャ、目的関数の共有が限定的な、ドメイン固有の手法に依存してきました。私たちは、純粋な視覚的言語理解のための事前学習済み画像からテキストへの変換モデルであるPix2Structを提案します。Pix2Structは、視覚的に位置づけられた言語を含むタスクでファインチューニングできます。Pix2Structは、Webページのマスクされたスクリーンショットを簡略化されたHTMLにパースすることを学習することで事前学習されます。Webは、その視覚的要素の豊富さがHTML構造にきれいに反映されているため、下流タスクの多様性に適した事前学習データの大きなソースを提供します。直感的に、この目的関数は、OCR、言語モデリング、画像キャプション付けといった一般的な事前学習シグナルを包含します。新しい事前学習戦略に加えて、可変解像度の入力表現と、言語と視覚の入力のより柔軟な統合を導入します。この統合では、質問などの言語プロンプトが入力画像の上に直接レンダリングされます。私たちは初めて、単一の事前学習済みモデルが、ドキュメント、イラスト、ユーザーインターフェース、自然画像という4つのドメインにまたがる9つのタスクのうち6つで、最先端の結果を達成できることを示しました。

ヒント:

Pix2Structは、画像キャプション生成、異なる入力（書籍、チャート、科学図表）に対する視覚的質問応答（VQA）、UIコンポーネントのキャプション生成など、多様なタスクとデータセットでファインチューニングされています。完全なリストは、論文のTable 1に記載されています。そのため、これらのモデルは、ファインチューニングされたタスクでの使用を推奨します。例えば、Pix2StructをUIキャプション生成に使用したい場合は、UIデータセットでファインチューニングされたモデルを使用してください。同様に、画像キャプション生成にPix2Structを使用したい場合は、自然画像のキャプション生成データセットでファインチューニングされたモデルを使用してください。

モデルを使用して条件付きテキストキャプショニングを実行する場合は、`add_special_tokens=False` を指定してプロセッサーを使用してください。

このモデルは[ybelkada](https://huggingface.co/ybelkada)によって提供されました。元のコードは[こちら](https://github.com/google-research/pix2struct)で確認できます。

## リソース

- [ファインチューニングノートブック](https://github.com/huggingface/notebooks/blob/main/examples/image_captioning_pix2struct.ipynb)
- [すべてのモデル](https://huggingface.co/models?search=pix2struct)

## Pix2StructConfig[[transformers.Pix2StructConfig]]

#### transformers.Pix2StructConfig[[transformers.Pix2StructConfig]]

```python
transformers.Pix2StructConfig(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, 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, is_encoder_decoder: bool = True, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, initializer_factor: float = 1.0, initializer_range: float = 0.02, is_vqa: bool = False, tie_word_embeddings: bool = False)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/pix2struct/configuration_pix2struct.py#L142)

**パラメータ:**

is_encoder_decoder (`bool`、*任意*、デフォルトは`True`) : モデルがエンコーダー/デコーダーとして使用されるかどうかを示します。

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

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

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

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

is_vqa (`bool`、*任意*、デフォルトは`False`) : モデルがVQAのためにファインチューニングされているかどうか。

tie_word_embeddings (`bool`, *任意*, デフォルトは `False`) : モデルの `tied_weights_keys` マッピングに従って重み埋め込みを共有するかどうか。

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

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

例:

```python
>>> from transformers import Pix2StructConfig, Pix2StructForConditionalGeneration

>>> # Initializing a Pix2StructConfig with google/pix2struct-base style configuration
>>> configuration = Pix2StructConfig()

>>> # Initializing a Pix2StructForConditionalGeneration (with random weights) from the google/pix2struct-base style configuration
>>> model = Pix2StructForConditionalGeneration(configuration)

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

>>> # We can also initialize a Pix2StructConfig from a Pix2StructTextConfig and a Pix2StructVisionConfig

>>> # Initializing a Pix2Struct text and Pix2Struct vision configuration
>>> config_text = Pix2StructTextConfig()
>>> config_vision = Pix2StructVisionConfig()

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

## Pix2StructTextConfig[[transformers.Pix2StructTextConfig]]

#### transformers.Pix2StructTextConfig[[transformers.Pix2StructTextConfig]]

```python
transformers.Pix2StructTextConfig(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 = 50244, hidden_size: int = 768, d_kv: int = 64, d_ff: int = 2048, num_layers: int = 12, num_heads: int = 12, relative_attention_num_buckets: int = 32, relative_attention_max_distance: int = 128, dropout_rate: float | int = 0.1, layer_norm_epsilon: float = 1e-06, initializer_factor: float = 1.0, dense_act_fn: str = 'gelu_new', decoder_start_token_id: int = 0, use_cache: bool = False, pad_token_id: int | None = 0, eos_token_id: int | list[int] | None = 1, bos_token_id: int | None = None, tie_word_embeddings: bool = False, is_decoder: bool = True, add_cross_attention: bool = False)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/pix2struct/configuration_pix2struct.py#L27)

**パラメータ:**

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

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

d_kv (`int`、*任意*、デフォルトは`64`) : アテンションヘッドごとのキー、クエリ、バリューの射影サイズ。射影層の`inner_dim`は`num_heads * d_kv`として定義されます。

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

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

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

relative_attention_num_buckets (`int`、*optional*、デフォルトは 32) : 各アテンション層で使用するバケット数。

relative_attention_max_distance (`int`、*optional*、デフォルトは 128) : バケット分離における、長いシーケンスの最大距離。

dropout_rate (`Union[float, int]`、*任意*、デフォルトは`0.1`) : すべての dropout 層の比率。

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

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

dense_act_fn (`Union[Callable, str]`、*任意*、デフォルトは`"gelu_new"`) : 非線形活性化関数（関数または文字列）。

decoder_start_token_id (`int`、*optional*、デフォルトは`0`) : エンコーダーデコーダーモデルが`bos`以外のトークンでデコーディングを開始する場合、そのトークンのID。

use_cache (`bool`, *任意*, デフォルトは `False`) : モデルが最後のキー/バリューアテンションを返すかどうかを指定します（すべてのモデルでサポートされているわけではありません）。`config.is_decoder=True` の場合、またはモデルがデコーダー専用の生成モデルである場合にのみ関連します。

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

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

bos_token_id (`int`, *任意*) : 語彙内でストリームの開始に使用されるトークン ID。

tie_word_embeddings (`bool`, *任意*, デフォルトは `False`) : モデルの `tied_weights_keys` マッピングに従って重み埋め込みを共有するかどうか。

is_decoder (`bool`、*任意*、デフォルトは`True`) : モデルがデコーダーとして使用されるかどうかを示します。`False`の場合、モデルはエンコーダーとして使用されます。

add_cross_attention (`bool`、*任意*、デフォルトは`False`) : モデルにクロスアテンション層を追加するかどうか。

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

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

例:

```python
>>> from transformers import Pix2StructTextConfig, Pix2StructTextModel

>>> # Initializing a Pix2StructTextConfig with google/pix2struct-base style configuration
>>> configuration = Pix2StructTextConfig()

>>> # Initializing a Pix2StructTextModel (with random weights) from the google/pix2struct-base style configuration
>>> model = Pix2StructTextModel(configuration)

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

## Pix2StructVisionConfig[[transformers.Pix2StructVisionConfig]]

#### transformers.Pix2StructVisionConfig[[transformers.Pix2StructVisionConfig]]

```python
transformers.Pix2StructVisionConfig(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, patch_embed_hidden_size: int = 768, d_ff: int = 2048, d_kv: int = 64, num_hidden_layers: int = 12, num_attention_heads: int = 12, dense_act_fn: str = 'gelu_new', layer_norm_eps: float = 1e-06, dropout_rate: float | int = 0.0, attention_dropout: float | int = 0.0, initializer_range: float = 1e-10, initializer_factor: float = 1.0, seq_len: int = 4096, relative_attention_num_buckets: int = 32, relative_attention_max_distance: int = 128)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/pix2struct/configuration_pix2struct.py#L87)

**パラメータ:**

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

patch_embed_hidden_size (`int`、*任意*、デフォルトは 768) : Transformer エンコーダーの input patch_embedding レイヤーの入力次元数。

d_ff (`int`、*optional*、デフォルトは 2048) : Transformer エンコーダーにおける「intermediate」（すなわち、feed-forward）層の次元数。

d_kv (`int`, *optional*, デフォルトは 64) : 各アテンションヘッドにおけるキー、クエリ、バリューの射影の次元数。

エンコーダーとプーラーで使用する非線形活性化関数（関数または文字列）。文字列の場合、`"gelu"`、: `"relu"`、`"selu"`、`"gelu_new"`、`"gelu"` がサポートされています。

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

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

dense_act_fn (`Union[Callable, str]`、*任意*、デフォルトは`"gelu_new"`) : 非線形活性化関数（関数または文字列）。

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

dropout_rate (`Union[float, int]`、*任意*、デフォルトは`0.0`) : すべての dropout レイヤーの比率。

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

initializer_range (`float`、*任意*、デフォルトは `1e-10`) : 全重み行列の初期化に使用される truncated_normal_initializer の標準偏差です。

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

seq_len (`int`、*optional*、デフォルトは 4096) : モデルがサポートする最大シーケンス長（ここではパッチ数）。

relative_attention_num_buckets (`int`、*optional*、デフォルトは 32) : 各アテンション層で使用するバケット数。

relative_attention_max_distance (`int`、*optional*、デフォルトは 128) : 各アテンション層で使用する最大距離（トークン数）。

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

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

例:

```python
>>> from transformers import Pix2StructVisionConfig, Pix2StructVisionModel

>>> # Initializing a Pix2StructVisionConfig with google/pix2struct-base style configuration
>>> configuration = Pix2StructVisionConfig()

>>> # Initializing a Pix2StructVisionModel (with random weights) from the google/pix2struct-base style configuration
>>> model = Pix2StructVisionModel(configuration)

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

## Pix2StructProcessor[[transformers.Pix2StructProcessor]]

#### transformers.Pix2StructProcessor[[transformers.Pix2StructProcessor]]

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

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/pix2struct/processing_pix2struct.py#L29)

**パラメータ:**

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

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

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

[Pix2StructProcessor](/docs/transformers/v5.23.0/ja/model_doc/pix2struct#transformers.Pix2StructProcessor) は、[Pix2StructImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/pix2struct#transformers.Pix2StructImageProcessor) と [TokenizersBackend](/docs/transformers/v5.23.0/ja/main_classes/tokenizer#transformers.TokenizersBackend) のすべての機能を提供します。詳細については、[~Pix2StructImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/pix2struct#transformers.Pix2StructImageProcessor) および [~TokenizersBackend](/docs/transformers/v5.23.0/ja/main_classes/tokenizer#transformers.TokenizersBackend) を参照してください。

#### __call__[[transformers.Pix2StructProcessor.__call__]]

```python
__call__(images = None, text: str | list[str] | list[list[str]] = None, **kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/pix2struct/processing_pix2struct.py#L42)

**パラメータ:**

images (``) : Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`.

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

return_mm_token_type_ids (`bool`, *kwargs*) : マルチモーダルプレースホルダトークンの位置を示すマルチモーダルトークンタイプIDを返すかどうか。

return_text_replacement_offsets (`bool`, *kwargs*) : 各マルチモーダルプレースホルダーとその置換文字列の文字オフセットを返すかどうか。

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

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

**戻り値:**

`Union[~tokenization_utils_base.BatchEncoding, ~feature_extraction_utils.BatchFeature]`

## Pix2StructImageProcessor[[transformers.Pix2StructImageProcessor]]

#### transformers.Pix2StructImageProcessor[[transformers.Pix2StructImageProcessor]]

```python
transformers.Pix2StructImageProcessor(**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/pix2struct/image_processing_pix2struct.py#L151)

**パラメータ:**

do_convert_rgb (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を RGB に変換するかどうか。

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

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*) : 画像をリサイズする場合に使用するリサンプリングフィルタ。`PILImageResampling` の列挙型のいずれかです。`do_resize` が `True` に設定されている場合のみ有効です。

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

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

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

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

`'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。 --

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

disable_grouping (`bool`, *kwargs*, *任意*): 画像をサイズごとにグループ化してバッチ処理する機能を無効にし、個別に処理するかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、ここ https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。 image_seq_length (`int`, *kwargs*, *任意*): 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

#### preprocess[[transformers.Pix2StructImageProcessor.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']], header_text: str | list[str] | None = None, **kwargs: *<class 'transformers.models.pix2struct.image_processing_pix2struct.Pix2StructImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/pix2struct/image_processing_pix2struct.py#L331)

**パラメータ:**

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

header_text (`Union[str, list[str]]`、*任意*) : ヘッダーとしてレンダリングするテキスト。`image_processor.is_vqa` が `True` の場合のみ有効です。

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

max_patches (`int`, *kwargs*, *optional*) : 抽出するパッチの最大数。

patch_size (`dict[str, *kwargs*, int]`, *任意*, デフォルトは `{"height" : 16, "width": 16}`): 画像に使用するパッチサイズです。Pix2Structの論文およびコードによると、パッチサイズは16x16です。

is_vqa (`bool`, *kwargs*, *optional*, デフォルトは `False`) : 画像プロセッサが VQA タスク用かどうかを示します。`True` かつ `header_text` が渡された場合、テキストが入力画像にレンダリングされます。

header_text (`Union[list[str], *kwargs*, str]`、*任意*) : ヘッダーとしてレンダリングするテキスト。`image_processor.is_vqa` が `True` の場合のみ有効です。

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

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

## Pix2StructImageProcessorPil[[transformers.Pix2StructImageProcessorPil]]

#### transformers.Pix2StructImageProcessorPil[[transformers.Pix2StructImageProcessorPil]]

```python
transformers.Pix2StructImageProcessorPil(**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/pix2struct/image_processing_pil_pix2struct.py#L163)

**パラメータ:**

do_convert_rgb (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を RGB に変換するかどうか。

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

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*) : 画像をリサイズする場合に使用するリサンプリングフィルタ。`PILImageResampling` の列挙型のいずれかです。`do_resize` が `True` に設定されている場合のみ有効です。

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

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

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

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

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

#### preprocess[[transformers.Pix2StructImageProcessorPil.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']], header_text: str | list[str] | None = None, **kwargs: *<class 'transformers.models.pix2struct.image_processing_pil_pix2struct.Pix2StructImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/pix2struct/image_processing_pil_pix2struct.py#L320)

**パラメータ:**

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

header_text (`Union[str, list[str]]`、*任意*) : ヘッダーとしてレンダリングするテキスト。`image_processor.is_vqa` が `True` の場合のみ有効です。

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

max_patches (`int`, *kwargs*, *optional*) : 抽出するパッチの最大数。

patch_size (`dict[str, *kwargs*, int]`, *任意*, デフォルトは `{"height" : 16, "width": 16}`): 画像に使用するパッチサイズです。Pix2Structの論文およびコードによると、パッチサイズは16x16です。

is_vqa (`bool`, *kwargs*, *optional*, デフォルトは `False`) : 画像プロセッサが VQA タスク用かどうかを示します。`True` かつ `header_text` が渡された場合、テキストが入力画像にレンダリングされます。

header_text (`Union[list[str], *kwargs*, str]`、*任意*) : ヘッダーとしてレンダリングするテキスト。`image_processor.is_vqa` が `True` の場合のみ有効です。

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

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

## Pix2StructTextModel[[transformers.Pix2StructTextModel]]

#### transformers.Pix2StructTextModel[[transformers.Pix2StructTextModel]]

```python
transformers.Pix2StructTextModel(config: Pix2StructTextConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/pix2struct/modeling_pix2struct.py#L926)

**パラメータ:**

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

Pix2Structのスタンドアロンテキストデコーダー

このモデルは [PreTrainedModel](/docs/transformers/v5.23.0/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.Pix2StructTextModel.forward]]

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

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/pix2struct/modeling_pix2struct.py#L955)

**パラメータ:**

input_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`) : 語彙における入力シーケンスのトークンインデックス。Pix2StructText は相対位置埋め込みを持つモデルであるため、入力の右側と左側の両方にパディングを適用できます。インデックスは [AutoTokenizer](/docs/transformers/v5.23.0/ja/model_doc/auto#transformers.AutoTokenizer) を使用して取得できます。詳細については、[PreTrainedTokenizer.encode()](/docs/transformers/v5.23.0/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) および [PreTrainedTokenizer.__call__()](/docs/transformers/v5.23.0/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) を参照してください。[入力 ID とは何か？](../glossary#input-ids) 事前学習のために `input_ids` を準備する方法について詳しく知るには、[Pix2StructText Training](./t5#training) をご覧ください。

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

encoder_hidden_states (`torch.Tensor`、形状 `(batch_size, sequence_length, hidden_size)`、*任意*) : エンコーダーの最終層の出力における隠れ状態のシーケンス。モデルがデコーダーとして設定されている場合、クロスアテンションで使用されます。

encoder_attention_mask (`torch.Tensor`、形状 `(batch_size, sequence_length)`、*任意*) : エンコーダー入力のpaddingトークンインデックスに対するattentionの実行を回避するためのマスクです。モデルがデコーダーとして設定されている場合、このマスクはcross-attentionで使用されます。`[0, 1]`から選択されるマスクの値:  - **マスクされない**トークンは1、 - **マスクされる**トークンは0。

inputs_embeds (`torch.LongTensor`、shape `(batch_size, sequence_length, hidden_size)`、*任意*) : `input_ids` を渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込みルックアップ行列よりも、`input_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/v5.23.0/ja/internal/generation_utils#transformers.Cache) インスタンスのみです。[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。`past_key_values` が渡されない場合、デフォルトで [DynamicCache](/docs/transformers/v5.23.0/ja/internal/generation_utils#transformers.DynamicCache) が初期化されます。モデルは、入力として与えられたのと同じキャッシュ形式を出力します。`past_key_values` を使用する場合は、すべての `input_ids`（形状 `(batch_size, sequence_length)`）の代わりに、このモデルに過去の key value 状態が与えられていない未処理の `input_ids`（形状 `(batch_size, unprocessed_length)`）のみを入力する必要があります。

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

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

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

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

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

**戻り値:** [CausalLMOutputWithCrossAttentions](/docs/transformers/v5.23.0/ja/main_classes/output#transformers.modeling_outputs.CausalLMOutputWithCrossAttentions) または `tuple(torch.Tensor)`

config（[Pix2StructConfig](/docs/transformers/v5.23.0/ja/model_doc/pix2struct#transformers.Pix2StructConfig)）および入力に応じて、さまざまな要素で構成される、[CausalLMOutputWithCrossAttentions](/docs/transformers/v5.23.0/ja/main_classes/output#transformers.modeling_outputs.CausalLMOutputWithCrossAttentions) または `torch.Tensor` のタプル（`return_dict=False` が渡された場合、または `config.return_dict=False` の場合）。

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

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

- **loss** (`torch.Tensor`、形状 `(1,)`、*任意*、`labels` が指定された場合に返されます) -- 言語モデリングの損失(次のトークンの予測用)。
- **logits** (`torch.Tensor`、形状 `(batch_size, sequence_length, config.vocab_size)`) -- 言語モデリングヘッドの予測スコア（SoftMax 適用前の各語彙トークンのスコア）。
- **hidden_states** (`tuple(torch.Tensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（モデルに埋め込み層がある場合はその出力用 1 つ、各層の出力用 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

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

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
- **cross_attentions** (`tuple(torch.Tensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  クロスアテンションのsoftmax後の重み。クロスアテンションヘッドにおける加重平均の計算に使用されます。
- **past_key_values** (`Cache`、*任意*、`use_cache=True` が渡された場合または `config.use_cache=True` の場合に返されます) -- [Cache](/docs/transformers/v5.23.0/ja/internal/generation_utils#transformers.Cache) のインスタンスです。詳細については、[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。

  シーケンシャルなデコーディングを高速化するために使用できる（`past_key_values` 入力参照）、事前計算済みの hidden-states（アテンションブロック内のキーとバリュー）が含まれます。

例:

```python
>>> from transformers import AutoProcessor, Pix2StructTextModel

>>> processor = AutoProcessor.from_pretrained("google/pix2struct-textcaps-base")
>>> model = Pix2StructTextModel.from_pretrained("google/pix2struct-textcaps-base")

>>> inputs = processor(text="Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)
>>> loss = outputs.loss
```

## Pix2StructVisionModel[[transformers.Pix2StructVisionModel]]

#### transformers.Pix2StructVisionModel[[transformers.Pix2StructVisionModel]]

```python
transformers.Pix2StructVisionModel(config: Pix2StructVisionConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/pix2struct/modeling_pix2struct.py#L393)

**パラメータ:**

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

…

このモデルは [PreTrainedModel](/docs/transformers/v5.23.0/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.Pix2StructVisionModel.forward]]

```python
forward(flattened_patches: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/pix2struct/modeling_pix2struct.py#L415)

**パラメータ:**

flattened_patches (`torch.Tensor`、形状 `(batch_size, sequence_length, num_channels x patch_height x patch_width)`) : フラット化およびパディングされたピクセル値。これらの値は [AutoImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/auto#transformers.AutoImageProcessor) を使用して取得できます。詳細については `Pix2StructVisionImageProcessor.__call__` を参照してください。さらに詳細については、[元の論文](https://huggingface.co/papers/2210.03347)（図5）を参照してください。

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

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

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

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

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

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

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

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

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

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple(torch.Tensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに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, Pix2StructVisionModel

>>> image_processor = AutoProcessor.from_pretrained("google/pix2struct-textcaps-base")
>>> model = Pix2StructVisionModel.from_pretrained("google/pix2struct-textcaps-base")

>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> inputs = image_processor(images=image, return_tensors="pt")
>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 2048, 768]
```

## Pix2StructForConditionalGeneration[[transformers.Pix2StructForConditionalGeneration]]

#### transformers.Pix2StructForConditionalGeneration[[transformers.Pix2StructForConditionalGeneration]]

```python
transformers.Pix2StructForConditionalGeneration(config: Pix2StructConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/pix2struct/modeling_pix2struct.py#L1147)

**パラメータ:**

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

言語モデリングヘッドを備えた条件付き生成モデルです。シーケンス生成タスクに使用できます。

このモデルは [PreTrainedModel](/docs/transformers/v5.23.0/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.Pix2StructForConditionalGeneration.forward]]

```python
forward(flattened_patches: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, decoder_input_ids: typing.Optional[torch.LongTensor] = None, decoder_attention_mask: typing.Optional[torch.BoolTensor] = None, encoder_outputs: tuple[tuple[torch.Tensor]] | None = None, past_key_values: transformers.cache_utils.Cache | None = None, labels: typing.Optional[torch.LongTensor] = None, decoder_inputs_embeds: typing.Optional[torch.Tensor] = None, use_cache: bool | None = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/pix2struct/modeling_pix2struct.py#L1174)

**パラメータ:**

flattened_patches (`torch.Tensor`、shape `(batch_size, seq_length, hidden_size)`) : フラット化されたピクセルパッチ。`hidden_size` は以下の式で得られます: `hidden_size` = `num_channels` * `patch_size` * `patch_size`  ピクセルパッチのフラット化は `Pix2StructProcessor` によって行われます。

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

decoder_input_ids (`torch.LongTensor`、shape `(batch_size, target_sequence_length)`、*任意*) : 語彙におけるデコーダー入力シーケンスのトークンインデックス。[AutoTokenizer](/docs/transformers/v5.23.0/ja/model_doc/auto#transformers.AutoTokenizer) を使用してインデックスを取得できます。詳細については、[PreTrainedTokenizer.encode()](/docs/transformers/v5.23.0/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) および [PreTrainedTokenizer.__call__()](/docs/transformers/v5.23.0/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) を参照してください。[デコーダー入力 ID とは何か？](../glossary#decoder-input-ids) Pix2StructText は、`decoder_input_ids` の生成の開始トークンとして `pad_token_id` を使用します。`past_key_values` を使用する場合、オプションとして最後の `decoder_input_ids` だけを入力すれば十分です（`past_key_values` を参照）。`decoder_input_ids` を事前学習のために準備する方法の詳細については、[Pix2StructText Training](./t5#training) をご覧ください。

decoder_attention_mask (`torch.BoolTensor`、shape `(batch_size, target_sequence_length)`、*任意*) : デフォルトの動作: `decoder_input_ids`内のpadトークンを無視するテンソルを生成します。デフォルトでは、causal maskも使用されます。

encoder_outputs (`tuple[tuple[torch.Tensor]]`, *任意*) : (`last_hidden_state`, *任意*: `hidden_states`, *任意*: `attentions`) のタプルです。`last_hidden_state` は形状 `(batch_size, sequence_length, hidden_size)` を持ち、*任意* です。エンコーダーの最終層の出力における隠れ状態のシーケンスです。デコーダーのクロスアテンションで使用されます。

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/v5.23.0/ja/internal/generation_utils#transformers.Cache) インスタンスのみです。[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。`past_key_values` が渡されない場合、デフォルトで [DynamicCache](/docs/transformers/v5.23.0/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)`、*任意*) : デコーダーのマスク言語モデリング損失を計算するためのラベル。

decoder_inputs_embeds (`torch.Tensor`、shape `(batch_size, target_sequence_length, hidden_size)`、*任意*) : `decoder_input_ids` を渡す代わりに、埋め込み表現を直接渡すこともできます。`past_key_values` を使用する場合、`decoder_inputs_embeds` の最後の部分のみを入力すればよい場合があります（`past_key_values` を参照）。`decoder_input_ids` のインデックスを関連するベクトルに変換する方法を、モデル内部の埋め込みルックアップ行列よりも細かく制御したい場合に便利です。 `decoder_input_ids` と `decoder_inputs_embeds` の両方が設定されていない場合、`decoder_inputs_embeds` は `inputs_embeds` の値を採ります。

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/v5.23.0/ja/main_classes/output#transformers.utils.ModelOutput) を返すかどうか。

**戻り値:** [Seq2SeqModelOutput](/docs/transformers/v5.23.0/ja/main_classes/output#transformers.modeling_outputs.Seq2SeqModelOutput) または `tuple(torch.Tensor)`

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

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

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

- **last_hidden_state** (`torch.Tensor`、形状 `(batch_size, sequence_length, hidden_size)`) -- モデルのデコーダーの最終層の出力における、隠れ状態のシーケンスです。

  `past_key_values`が使用されている場合、出力されるのは、形状`(batch_size, 1, hidden_size)`のシーケンスの最後の隠れ状態のみです。
- **past_key_values** (`EncoderDecoderCache`、*任意*、`use_cache=True` が渡された場合または `config.use_cache=True` の場合に返されます) -- [EncoderDecoderCache](/docs/transformers/v5.23.0/ja/internal/generation_utils#transformers.EncoderDecoderCache) のインスタンスです。詳細については、[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。

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

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

  自己アテンションヘッドにおける加重平均を計算するために使用される、アテンションのsoftmax後のデコーダーのアテンション重み。
- **cross_attentions** (`tuple(torch.Tensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  クロスアテンション層のアテンション重みは、アテンションのsoftmax適用後に計算され、クロスアテンションヘッドにおける加重平均の計算に使用されます。
- **encoder_last_hidden_state** (`torch.Tensor`、形状 `(batch_size, sequence_length, hidden_size)`、*任意*) -- モデルのエンコーダーの最終層の出力における隠れ状態のシーケンス。
- **encoder_hidden_states** (`tuple(torch.Tensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用 1 つ + 各層の出力用 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるエンコーダーのHidden-states、および任意の初期埋め込み出力。
- **encoder_attentions** (`tuple(torch.Tensor)`、*任意*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- 各レイヤーごとに 1 つの `torch.Tensor` からなるタプルで、形状は `(batch_size, num_heads, sequence_length, sequence_length)` です。

  アテンションのsoftmaxを適用した後のエンコーダーのアテンション重み。自己アテンションヘッドにおける加重平均の計算に使用されます。

例:

推論:

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

>>> processor = AutoProcessor.from_pretrained("google/pix2struct-textcaps-base")
>>> model = Pix2StructForConditionalGeneration.from_pretrained("google/pix2struct-textcaps-base")

>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

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

>>> # autoregressive generation
>>> generated_ids = model.generate(**inputs, max_new_tokens=50)
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
>>> print(generated_text)
A stop sign is on a street corner.

>>> # conditional generation
>>> text = "A picture of"
>>> inputs = processor(text=text, images=image, return_tensors="pt", add_special_tokens=False)

>>> generated_ids = model.generate(**inputs, max_new_tokens=50)
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
>>> print(generated_text)
A picture of a stop sign with a red stop sign
```

トレーニング:

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

>>> processor = AutoProcessor.from_pretrained("google/pix2struct-base")
>>> model = Pix2StructForConditionalGeneration.from_pretrained("google/pix2struct-base")

>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))
>>> text = "A stop sign is on the street corner."

>>> inputs = processor(images=image, return_tensors="pt")
>>> labels = processor(text=text, return_tensors="pt").input_ids

>>> # forward pass
>>> outputs = model(**inputs, labels=labels)
>>> loss = outputs.loss
>>> print(f"{loss.item():.5f}")
5.94282
```

