# 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) 中提出。

该论文的摘要如下：

> 视觉情境语言无处不在——其来源涵盖带有图表的教科书、包含图像和表格的网页，以及带有按钮和表单的移动应用。或许正是由于这种多样性，以往的工作通常依赖于特定领域的方案，且在底层数据、模型架构和目标方面缺乏共享。我们提出了 Pix2Struct，这是一个用于纯视觉语言理解的预训练图像到文本模型，可以在包含视觉情境语言的任务上进行微调。Pix2Struct 通过学习将网页的掩码截图解析为简化的 HTML 来进行预训练。网络凭借其丰富的视觉元素在 HTML 结构中的清晰映射，提供了大量预训练数据，非常适合下游任务的多样性。直观地说，这一目标涵盖了常见的预训练信号，例如 OCR、语言建模和图像描述。除了新颖的预训练策略外，我们还引入了可变分辨率的输入表示以及更灵活的语言与视觉输入集成方式，其中诸如问题之类的语言提示直接渲染在输入图像之上。我们首次证明，单个预训练模型可以在四个领域（文档、插图、用户界面和自然图像）的九个任务中的六个任务上取得最先进的结果。

提示：

Pix2Struct 已在多种任务和数据集上进行了微调，涵盖图像描述、针对不同输入（书籍、图表、科学示意图）的视觉问答（VQA）、UI 组件描述等。完整列表可在论文的表 1 中找到。因此，我们建议您将这些模型用于其经过微调的任务。例如，如果您想使用 Pix2Struct 进行 UI 描述，应使用在 UI 数据集上微调的模型；如果您想使用 Pix2Struct 进行图像描述，则应使用在自然图像描述数据集上微调的模型，依此类推。

如果您想使用该模型执行条件文本描述，请确保在使用处理器时设置 `add_special_tokens=False`。

该模型由 [ybelkada](https://huggingface.co/ybelkada) 贡献。原始代码可在[此处](https://github.com/google-research/pix2struct)找到。

## 资源

- [微调 Notebook](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/main/src/transformers/models/pix2struct/configuration_pix2struct.py#L142)

**参数：**

is_encoder_decoder (`bool`，*可选*，默认为 `True`)：模型是否用作编码器/解码器。

text_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：文本骨干网络的配置对象或字典。

vision_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：视觉骨干网络的配置对象或字典。

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/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/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/main/src/transformers/models/pix2struct/configuration_pix2struct.py#L27)

**参数：**

vocab_size (`int`，*可选*，默认为 `50244`)：模型的词汇表大小。定义了 `input_ids` 可以表示的不同 token 数量。

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`，*可选*，默认为 32)：每个注意力层使用的桶数。

relative_attention_max_distance (`int`，*可选*，默认为 128)：用于分桶分离的较长序列的最大距离。

dropout_rate (`Union[float, int]`，*可选*，默认为 `0.1`)：所有 dropout 层的比率。

layer_norm_epsilon (`float`, *可选*, 默认为 `1e-06`) : 层归一化层使用的 epsilon。

initializer_factor (`float`, *可选*，默认为 `1.0`)：用于初始化所有权重矩阵的系数（应保持为 1，内部用于初始化测试）。

dense_act_fn (`Union[Callable, str]`，*可选*，默认为 `"gelu_new"`)：非线性激活函数（函数或字符串）。

decoder_start_token_id (`int`，*可选*，默认为 `0`)：如果编码器-解码器模型以不同于 `bos` 的 token 开始解码，则该 token 的 id。

use_cache (`bool`，*可选*，默认为 `False`)：模型是否应返回最后的键/值注意力（并非所有模型都使用）。仅当 `config.is_decoder=True` 或模型为仅解码器生成模型时相关。

pad_token_id (`int`，*可选*，默认为 `0`)：词表中用于填充的 Token ID。

eos_token_id (`Union[int, list[int]]`，*可选*，默认为 `1`)：词汇表中用于表示流结束（end-of-stream）的 Token ID。

bos_token_id (`int`, *可选*) : 词表中用于表示流开始的 Token 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/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/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/main/src/transformers/models/pix2struct/configuration_pix2struct.py#L87)

**参数：**

hidden_size (`int`，*可选*，默认为 `768`)：隐藏表示的维度。

patch_embed_hidden_size (`int`，*可选*，默认值为 768)：Transformer 编码器中输入 patch_embedding 层的维度。

d_ff (`int`，*可选*，默认为 2048)：Transformer 编码器中“中间”（即前馈）层的维度。

d_kv (`int`，*可选*，默认为 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`) : 层归一化层使用的 epsilon。

dropout_rate (`Union[float, int]`，*可选*，默认值为 `0.0`)：所有 dropout 层的比率。

attention_dropout (`Union[float, int]`，*可选*，默认值为 `0.0`)：注意力概率的 dropout 比率。

initializer_range (`float`, *可选*, 默认为 `1e-10`) : 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

initializer_factor (`float`, *可选*，默认为 `1.0`)：用于初始化所有权重矩阵的系数（应保持为 1，内部用于初始化测试）。

seq_len (`int`，*可选*，默认值为 4096)：模型支持的最大序列长度（即 patch 数量）。

relative_attention_num_buckets (`int`，*可选*，默认为 32)：每个注意力层使用的桶数。

relative_attention_max_distance (`int`，*可选*，默认为 128)：每个注意力层使用的最大距离（以 token 计）。

这是用于存储 Pix2StructModel 配置的类。它根据指定的参数实例化 Pix2Struct 模型，并定义模型架构。使用默认值实例化配置将生成与 [google/pix2struct-base](https://huggingface.co/google/pix2struct-base) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/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/main/src/transformers/models/pix2struct/processing_pix2struct.py#L47)

**参数：**

image_processor (`Pix2StructImageProcessor`)：图像处理器是必需的输入。

tokenizer (`TokenizersBackend`)：分词器是必需的输入。

构建一个 Pix2StructProcessor，它将图像处理器和分词器封装为单一处理器。

[Pix2StructProcessor](/docs/transformers/main/zh/model_doc/pix2struct#transformers.Pix2StructProcessor) 提供了 [Pix2StructImageProcessor](/docs/transformers/main/zh/model_doc/pix2struct#transformers.Pix2StructImageProcessor) 和 [TokenizersBackend](/docs/transformers/main/zh/main_classes/tokenizer#transformers.TokenizersBackend) 的所有功能。有关更多信息，请参阅 [~Pix2StructImageProcessor](/docs/transformers/main/zh/model_doc/pix2struct#transformers.Pix2StructImageProcessor) 和 [~TokenizersBackend](/docs/transformers/main/zh/main_classes/tokenizer#transformers.TokenizersBackend)。

#### __调用__[[transformers.Pix2StructProcessor.__call__]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pix2struct/processing_pix2struct.py#L52)

**参数：**

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_tensors (`str` 或 [TensorType](/docs/transformers/main/zh/internal/file_utils#transformers.TensorType)，*可选*)：如果设置，将返回特定框架的张量。可接受的值为： - `'pt'`：返回 PyTorch `torch.Tensor` 对象。 - `'np'`：返回 NumPy `np.ndarray` 对象。

- ****kwargs** ([ProcessingKwargs](/docs/transformers/main/zh/main_classes/processors#transformers.ProcessingKwargs), *可选*) : 针对每种模态（文本、图像、视频、音频）的额外处理选项。模型特定参数已在上方列出；有关支持参数的完整列表，请参阅 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/main/src/transformers/models/pix2struct/image_processing_pix2struct.py#L151)

**参数：**

do_convert_rgb (`bool`，*kwargs*，*可选*，默认为 `True`)：是否将图像转换为 RGB。

do_resize (`bool`，*kwargs*，*可选*)：是否调整图像大小。

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*，*可选*，默认为 `True`)：是否对图像进行归一化。

image_mean (`Union[float, list[float], tuple[float, ...]]`，*kwargs*，*可选*)：用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*) : 用于归一化的图像标准差。仅当 `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*, *可选*) : 是否对图像进行居中裁剪。

data_format (`Union[str, ~image_utils.ChannelDimension]`，*kwargs*，*可选*)：仅支持 `ChannelDimension.FIRST`。为兼容旧版处理器而添加。

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*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

如果设置为 `'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/main/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*, *可选*) : 是否将图像转换为 RGB。

do_resize (`bool`，*kwargs*，*可选*)：是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*)：描述模型的最大输入维度。

default_to_square (`bool`, *kwargs*, *可选*) : 当 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*, *可选*) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行缩放的缩放因子。

do_normalize (`bool`, *kwargs*, *可选*) : 是否对图像进行归一化。

image_mean (`Union[float, list[float], tuple[float, ...]]`，*kwargs*，*可选*)：用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*) : 用于归一化的图像标准差。仅当 `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*, *可选*) : 是否对图像进行居中裁剪。

data_format (`Union[str, ~image_utils.ChannelDimension]`，*kwargs*，*可选*)：仅支持 `ChannelDimension.FIRST`。为兼容旧版处理器而添加。

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*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

max_patches (`int`, *kwargs*, *可选*) : 要提取的最大 patch 数量。

patch_size (`dict[str, *kwargs*, int]`，*可选*，默认为 `{"height" : 16, "width": 16}`)：用于图像的 patch size。根据 Pix2Struct 论文和代码，patch size 为 16x16。

is_vqa (`bool`, *kwargs*, *可选*，默认为 `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]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

## Pix2StructImageProcessorPil[[transformers.Pix2StructImageProcessorPil]]

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

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pix2struct/image_processing_pil_pix2struct.py#L163)

**参数：**

do_convert_rgb (`bool`，*kwargs*，*可选*，默认为 `True`)：是否将图像转换为 RGB。

do_resize (`bool`，*kwargs*，*可选*)：是否调整图像大小。

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*，*可选*，默认为 `True`)：是否对图像进行归一化。

image_mean (`Union[float, list[float], tuple[float, ...]]`，*kwargs*，*可选*)：用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*) : 用于归一化的图像标准差。仅当 `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*, *可选*) : 是否对图像进行居中裁剪。

data_format (`Union[str, ~image_utils.ChannelDimension]`，*kwargs*，*可选*)：仅支持 `ChannelDimension.FIRST`。为兼容旧版处理器而添加。

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*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

构建一个 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/main/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*, *可选*) : 是否将图像转换为 RGB。

do_resize (`bool`，*kwargs*，*可选*)：是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*)：描述模型的最大输入维度。

default_to_square (`bool`, *kwargs*, *可选*) : 当 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*, *可选*) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行缩放的缩放因子。

do_normalize (`bool`, *kwargs*, *可选*) : 是否对图像进行归一化。

image_mean (`Union[float, list[float], tuple[float, ...]]`，*kwargs*，*可选*)：用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*) : 用于归一化的图像标准差。仅当 `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*, *可选*) : 是否对图像进行居中裁剪。

data_format (`Union[str, ~image_utils.ChannelDimension]`，*kwargs*，*可选*)：仅支持 `ChannelDimension.FIRST`。为兼容旧版处理器而添加。

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*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

max_patches (`int`, *kwargs*, *可选*) : 要提取的最大 patch 数量。

patch_size (`dict[str, *kwargs*, int]`，*可选*，默认为 `{"height" : 16, "width": 16}`)：用于图像的 patch size。根据 Pix2Struct 论文和代码，patch size 为 16x16。

is_vqa (`bool`, *kwargs*, *可选*，默认为 `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]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

## Pix2StructTextModel[[transformers.Pix2StructTextModel]]

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

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pix2struct/modeling_pix2struct.py#L926)

**参数：**

config ([Pix2StructTextConfig](/docs/transformers/main/zh/model_doc/pix2struct#transformers.Pix2StructTextConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

Pix2Struct 的独立文本解码器

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/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/main/src/transformers/models/pix2struct/modeling_pix2struct.py#L955)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`)：输入序列词元在词汇表中的索引。Pix2StructText 是一个具有相对位置嵌入的模型，因此您可以在右侧和左侧对输入进行填充。 可以使用 [AutoTokenizer](/docs/transformers/main/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids) 要了解如何为预训练准备 `input_ids`，请查看 [Pix2StructText Training](./t5#training)。

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

encoder_hidden_states (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：编码器最后一层输出的隐藏状态序列。如果模型被配置为解码器，则用于交叉注意力。

encoder_attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对编码器输入中填充标记索引执行注意力机制的掩码。如果模型被配置为解码器，此掩码将用于交叉注意力。在 `[0, 1]` 中选择的掩码值： - 对于**未掩码**的标记，值为 1； - 对于**已掩码**的标记，值为 0。

inputs_embeds (`torch.LongTensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，您可以选择直接传入嵌入表示，而不是传入 `input_ids`。如果您希望对将 `input_ids` 索引转换为相应向量的方式拥有比模型内部嵌入查找矩阵更多的控制权，这将非常有用。

past_key_values (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常由模型在解码的先前阶段返回的 `past_key_values` 组成，前提是 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `past_key_values`，则默认初始化 [DynamicCache](/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入相同的缓存格式。 如果使用 `past_key_values`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

use_cache (`bool`，*可选*)：如果设置为 `True`，则会返回 `past_key_values` 键值状态，可用于加速解码（参见 `past_key_values`）。

output_attentions (`bool`, *可选*) : 是否返回所有注意力层的注意力张量。有关更多详细信息，请参阅返回张量中的 `attentions`。

output_hidden_states (`bool`, *可选*) : 是否返回所有层的隐藏状态。有关更多详细信息，请参阅返回张量中的 `hidden_states`。

labels (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于计算掩码语言建模损失的标签。索引值应在 `[0, ..., config.vocab_size]` 范围内，或为 -100（参见 `input_ids` 的文档字符串）。索引值设为 `-100` 的 token 将被忽略（即被掩码），损失仅针对标签在 `[0, ..., config.vocab_size]` 范围内的 token 进行计算。

return_dict (`bool`, *可选*) : 是否返回 [ModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.utils.ModelOutput) 而不是普通元组。

**返回：** [CausalLMOutputWithCrossAttentions](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.CausalLMOutputWithCrossAttentions) 或 `tuple(torch.Tensor)`

一个 [CausalLMOutputWithCrossAttentions](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.CausalLMOutputWithCrossAttentions) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Pix2StructConfig](/docs/transformers/main/zh/model_doc/pix2struct#transformers.Pix2StructConfig)）和输入。

[Pix2StructTextModel](/docs/transformers/main/zh/model_doc/pix2struct#transformers.Pix2StructTextModel) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 语言建模损失（用于下一个 token 预测）。
- **logits**（形状为 `(batch_size, sequence_length, config.vocab_size)` 的 `torch.Tensor`）-- 语言建模头的预测分数（SoftMax 之前每个词汇表 token 的分数）。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。
- **cross_attentions** (`tuple(torch.Tensor)`，*可选*，在传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  在注意力 softmax 之后的交叉注意力权重，用于在交叉注意力头中计算加权平均值。
- **past_key_values**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）—— 它是一个 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（注意力块中的键和值），可用于（参见 `past_key_values` 输入）加速顺序解码。

示例：

```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/main/src/transformers/models/pix2struct/modeling_pix2struct.py#L393)

**参数：**

config ([Pix2StructVisionConfig](/docs/transformers/main/zh/model_doc/pix2struct#transformers.Pix2StructVisionConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化并不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

未添加任何特定头部的裸 Pix2Struct 模型，直接输出原始隐藏状态。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/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/main/src/transformers/models/pix2struct/modeling_pix2struct.py#L415)

**参数：**

flattened_patches （形状为 `(batch_size, sequence_length, num_channels x patch_height x patch_width)` 的 `torch.Tensor`）：展平并填充后的像素值。这些值可以通过 [AutoImageProcessor](/docs/transformers/main/zh/model_doc/auto#transformers.AutoImageProcessor) 获取。有关详细信息，请参阅 `Pix2StructVisionImageProcessor.__call__`。更多细节请参见[原始论文](https://huggingface.co/papers/2210.03347)（图 5）。

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

output_attentions (`bool`, *可选*) : 是否返回所有注意力层的注意力张量。有关更多详细信息，请参阅返回张量中的 `attentions`。

output_hidden_states (`bool`, *可选*) : 是否返回所有层的隐藏状态。有关更多详细信息，请参阅返回张量中的 `hidden_states`。

return_dict (`bool`, *可选*) : 是否返回 [ModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.utils.ModelOutput) 而不是普通元组。

**返回：** [BaseModelOutputWithPooling](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `tuple(torch.Tensor)`

一个 [BaseModelOutputWithPooling](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Pix2StructConfig](/docs/transformers/main/zh/model_doc/pix2struct#transformers.Pix2StructConfig)）和输入。

[Pix2StructVisionModel](/docs/transformers/main/zh/model_doc/pix2struct#transformers.Pix2StructVisionModel) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.Tensor`）-- 序列中第一个 token（分类 token）的最后一层隐藏状态，经过用于辅助预训练任务的层进一步处理后的结果。例如，对于 BERT 系列模型，这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重是在预训练期间通过下一句预测（分类）目标训练得到的。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(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/main/src/transformers/models/pix2struct/modeling_pix2struct.py#L1147)

**参数：**

config ([Pix2StructConfig](/docs/transformers/main/zh/model_doc/pix2struct#transformers.Pix2StructConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

带有语言建模头的条件生成模型。可用于序列生成任务。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/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/main/src/transformers/models/pix2struct/modeling_pix2struct.py#L1174)

**参数：**

flattened_patches (`torch.Tensor`，形状为 `(batch_size, seq_length, hidden_size)`)：展平的像素块。`hidden_size` 由以下公式得出：`hidden_size` = `num_channels` * `patch_size` * `patch_size` 展平像素块的过程由 `Pix2StructProcessor` 完成。

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

decoder_input_ids (`torch.LongTensor`，形状为 `(batch_size, target_sequence_length)`，*可选*) : 解码器输入序列中词元在词汇表中的索引。 可以使用 [AutoTokenizer](/docs/transformers/main/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。 有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。  [什么是解码器输入 ID？](../glossary#decoder-input-ids)  Pix2StructText 使用 `pad_token_id` 作为 `decoder_input_ids` 生成的起始词元。 如果使用 `past_key_values`，则只需输入最后几个 `decoder_input_ids`（参见 `past_key_values`）。  有关如何为预训练准备 `decoder_input_ids` 的更多信息，请参阅 [Pix2StructText 训练](./t5#training)。

decoder_attention_mask (`torch.BoolTensor`，形状为 `(batch_size, target_sequence_length)`，*可选*) : 默认行为：生成一个忽略 `decoder_input_ids` 中填充标记的张量。默认情况下也会使用因果掩码。

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`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常由模型在解码的先前阶段返回的 `past_key_values` 组成，前提是 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `past_key_values`，则默认初始化 [DynamicCache](/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入相同的缓存格式。 如果使用 `past_key_values`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

labels (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于计算解码器掩码语言建模损失的标签。

decoder_inputs_embeds (`torch.Tensor`，形状为 `(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`。

return_dict (`bool`, *可选*) : 是否返回 [ModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.utils.ModelOutput) 而不是普通元组。

**返回：** [Seq2SeqModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.Seq2SeqModelOutput) 或 `tuple(torch.Tensor)`

一个 [Seq2SeqModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.Seq2SeqModelOutput) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Pix2StructConfig](/docs/transformers/main/zh/model_doc/pix2struct#transformers.Pix2StructConfig)）和输入。

[Pix2StructForConditionalGeneration](/docs/transformers/main/zh/model_doc/pix2struct#transformers.Pix2StructForConditionalGeneration) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型解码器最后一层输出的隐藏状态序列。

  如果使用了 `past_key_values`，则仅输出形状为 `(batch_size, 1, hidden_size)` 的序列的最后一个隐藏状态。
- **past_key_values**（`EncoderDecoderCache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）-- 它是一个 [EncoderDecoderCache](/docs/transformers/main/zh/internal/generation_utils#transformers.EncoderDecoderCache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于（参见 `past_key_values` 输入）加速顺序解码。
- **decoder_hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层输出的一个张量，以及每个层输出的一个张量），形状为 `(batch_size, sequence_length, hidden_size)`。

  解码器在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **decoder_attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  解码器在注意力 softmax 之后的注意力权重，用于在自注意力头中计算加权平均值。
- **cross_attentions** (`tuple(torch.Tensor)`，*可选*，在传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  解码器交叉注意力层在注意力 softmax 之后的注意力权重，用于在交叉注意力头中计算加权平均值。
- **encoder_last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`，*可选*）-- 模型编码器最后一层输出的隐藏状态序列。
- **encoder_hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  编码器每层输出处的隐藏状态，以及可选的初始嵌入输出。
- **encoder_attentions** (`tuple(torch.Tensor)`，*可选*，在传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `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
```

