# IDEFICS

## 概述

IDEFICS 模型由 Hugo Laurençon、Lucile Saulnier、Léo Tronchon、Stas Bekman、Amanpreet Singh、Anton Lozhkov、Thomas Wang、Siddharth Karamcheti、Alexander M. Rush、Douwe Kiela、Matthieu Cord 和 Victor Sanh 在 [OBELICS: An Open Web-Scale Filtered Dataset of Interleaved Image-Text Documents](https://huggingface.co/papers/2306.16527) 中提出。

该论文的摘要如下：

*在自然文档上训练的大型多模态模型，这些文档将图像和文本交错排列，在需要针对一张或多张图像进行推理以生成文本的多种多模态基准测试中，表现优于在图像-文本对上进行训练的模型。然而，用于训练这些模型的数据集尚未公开，且数据收集流程也未完全说明。我们介绍了 OBELICS 数据集，这是一个开放的网络规模过滤数据集，包含交错的图像-文本文档，由从 Common Crawl 中提取的 1.41 亿个网页、3.53 亿张相关图像以及 1150 亿个文本 token 组成。我们描述了数据集的创建过程，提供了全面的过滤规则，并对数据集的内容进行了分析。为了展示 OBELICS 的可行性，我们使用该数据集训练了一个 800 亿参数的视觉语言模型，并在多种多模态基准测试中取得了具有竞争力的性能。我们发布了用于复现该数据集的代码以及数据集本身。*

该模型由 [HuggingFaceM4](https://huggingface.co/HuggingFaceM4) 贡献。原始代码仓库未公开。

Transformers 中的 IDEFICS 建模代码用于对预训练的 IDEFICS 模型进行微调（finetuning）和推理（inferencing）。

要从头训练一个新的 IDEFICS 模型，请使用 m4 代码库（待其公开后会提供链接）

## IdeficsConfig[[transformers.IdeficsConfig]]

#### transformers.IdeficsConfig[[transformers.IdeficsConfig]]

```python
transformers.IdeficsConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, vocab_size: int = 32000, additional_vocab_size: int = 0, hidden_size: int = 4096, intermediate_size: int = 11008, num_hidden_layers: int = 32, num_attention_heads: int = 32, dropout: float | int = 0.0, hidden_act: str = 'silu', initializer_range: float = 0.02, alpha_initializer: str = 'zeros', alphas_initializer_range: float = 0.0, alpha_type: str = 'float', rms_norm_eps: float = 1e-06, use_cache: bool = True, pad_token_id: int | None = 0, bos_token_id: int | None = 1, eos_token_id: int | list[int] | None = 2, tie_word_embeddings: bool = False, cross_layer_interval: int = 1, qk_layer_norms: bool = False, freeze_text_layers: bool = True, freeze_text_module_exceptions: list | tuple = (), freeze_lm_head: bool = False, freeze_vision_layers: bool = True, freeze_vision_module_exceptions: list | tuple = (), use_resampler: bool = False, vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, max_position_embeddings: int = 2048, perceiver_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, rope_parameters: dict | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/idefics/configuration_idefics.py#L77)

**参数：**

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

additional_vocab_size (`int`，*可选*，默认为 0)：模型的额外词汇表大小，通常用于特殊的 "" 标记。额外词汇表中的标记始终可训练，而常规词汇表中的标记可以选择冻结或不冻结。

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

intermediate_size (`int`，*可选*，默认为 `11008`)：MLP 表示的维度。

num_hidden_layers (`int`，*可选*，默认为 `32`)：Transformer 解码器中的隐藏层数。

num_attention_heads (`int`，*可选*，默认为 `32`)：Transformer 解码器中每个注意力层的注意力头数量。

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

hidden_act (`str`，*可选*，默认为 `silu`)：解码器中的非线性激活函数（函数或字符串）。例如，`"gelu"`、`"relu"`、`"silu"` 等。

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

alpha_initializer (`str`，*可选*，默认为 `"zeros"`)：alphas 的初始化类型。

alphas_initializer_range (`float`, *可选*，默认为 0.0)：用于初始化门控交叉注意力中 alphas 的 truncated_normal_initializer 的标准差。

alpha_type (`str`，*可选*，默认为 `"float"`)：门控 alpha 应为向量还是单个浮点数。

rms_norm_eps (`float`，*可选*，默认为 `1e-06`)：rms 归一化层使用的 epsilon。

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

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

bos_token_id (`int`，*可选*，默认为 `1`)：词汇表中用于表示流开始的 Token id。

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

tie_word_embeddings (`bool`，*可选*，默认为 `False`)：是否根据模型的 `tied_weights_keys` 映射来绑定权重嵌入。

cross_layer_interval (`int`，*可选*，默认为 1)：交叉注意力（从文本到图像）层的间隔。

qk_layer_norms (`bool`, *可选*, 默认为 `False`) : 是否在 q 和 k 之后添加层归一化

freeze_text_layers (`bool`，*可选*，默认为 `True`)：是否冻结文本层

freeze_text_module_exceptions (`bool`，*可选*，默认为 `[]`)：当 `freeze_text_layers` 为 `True` 时，冻结文本层的例外情况

freeze_lm_head (`bool`，*可选*，默认为 `False`)：是否冻结 lm head

freeze_vision_layers (`bool`，*可选*，默认为 `True`)：是否冻结视觉层

freeze_vision_module_exceptions (`bool`, *可选*, 默认为 `[]`) : 当 `freeze_vision_layers` 为 `True` 时，冻结视觉层的例外情况

use_resampler (`bool`, *可选*, 默认为 `False`) : 是否使用 Resampler

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

max_position_embeddings (`int`，*可选*，默认值为 `2048`)：该模型可能使用的最大序列长度。

perceiver_config (`IdeficsPerceiverConfig`，*可选*)：自定义 perceiver 配置或字典

rope_parameters (`dict`, *可选*) : 包含 RoPE 嵌入配置参数的字典。该字典应包含 `rope_theta` 的值，并且如果您希望使用更长的 `max_position_embeddings` 来使用 RoPE，则可选地包含用于缩放的参数。

这是用于存储 IdeficsModel 配置的类。它根据指定的参数实例化 Idefics 模型，并定义模型架构。使用默认值实例化配置将得到与 [HuggingFaceM4/idefics-9b](https://huggingface.co/HuggingFaceM4/idefics-9b) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

```python
>>> from transformers import IdeficsModel, IdeficsConfig

>>> # Initializing a Idefics idefics-9b style configuration
>>> configuration = IdeficsConfig()

>>> # Initializing a model from the idefics-9b style configuration
>>> model = IdeficsModel(configuration)

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

## IdeficsVisionConfig[[transformers.IdeficsVisionConfig]]

#### transformers.IdeficsVisionConfig[[transformers.IdeficsVisionConfig]]

```python
transformers.IdeficsVisionConfig(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, embed_dim: int = 768, image_size: int | list[int] | tuple[int, int] = 224, intermediate_size: int = 5120, patch_size: int | list[int] | tuple[int, int] = 14, num_hidden_layers: int = 32, num_attention_heads: int = 16, num_channels: int = 3, hidden_act: str = 'gelu', layer_norm_eps: float = 1e-05, attention_dropout: float | int = 0.0, initializer_range: float = 0.02, initializer_factor: float = 1.0)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/idefics/configuration_idefics.py#L29)

**参数：**

embed_dim (`int`，*可选*，默认为 `768`)：嵌入和隐藏状态的维度。

image_size (`Union[int, list[int], tuple[int, int]]`，*可选*，默认为 `224`)：每张图片的尺寸（分辨率）。

intermediate_size (`int`，*可选*，默认值为 `5120`)：MLP 表示的维度。

patch_size (`Union[int, list[int], tuple[int, int]]`，*可选*，默认为 `14`)：每个 patch 的大小（分辨率）。

num_hidden_layers (`int`，*可选*，默认为 `32`)：Transformer 解码器中的隐藏层数。

num_attention_heads (`int`，*可选*，默认为 `16`)：Transformer 解码器中每个注意力层的注意力头数量。

num_channels (`int`，*可选*，默认为 `3`)：输入通道数。

hidden_act (`str`，*可选*，默认为 `gelu`)：解码器中的非线性激活函数（函数或字符串）。例如，`"gelu"`、`"relu"`、`"silu"` 等。

layer_norm_eps (`float`，*可选*，默认为 `1e-05`)：层归一化层所使用的 epsilon。

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

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

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

这是用于存储 IdeficsModel 配置的类。它根据指定的参数实例化 Idefics 模型，并定义模型架构。使用默认值实例化配置将得到与 [HuggingFaceM4/idefics-9b](https://huggingface.co/HuggingFaceM4/idefics-9b) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

## IdeficsPerceiverConfig[[transformers.IdeficsPerceiverConfig]]

#### transformers.IdeficsPerceiverConfig[[transformers.IdeficsPerceiverConfig]]

```python
transformers.IdeficsPerceiverConfig(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, use_resampler: bool = False, resampler_n_latents: int = 64, resampler_depth: int = 6, resampler_n_heads: int = 16, resampler_head_dim: int = 96, qk_layer_norms_perceiver: bool = False)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/idefics/configuration_idefics.py#L49)

**参数：**

use_resampler (`bool`, *可选*, 默认为 `False`) : 是否使用重采样器

resampler_n_latents (`int`，*可选*，默认为 64)：将输入序列重采样（“压缩”）到的潜在嵌入数量（通常 < 128）。

resampler_depth (`int`, *可选*，默认为 6)：Perceiver Resampler（带交叉注意力的 Transformer）的深度。应较浅（< 3）。

resampler_n_heads (`int`，*可选*，默认为 16)：每个 Transformer 块中的注意力头数量（用于多头自注意力）。

resampler_head_dim (`int`，*可选*，默认为 96)：Transformer 块中每个头投影的维度。

qk_layer_norms_perceiver (`bool`，*可选*，默认为 `False`)：是否在 perceiver 中使用 qk 层归一化

这是用于存储 IdeficsModel 配置的类。它根据指定的参数实例化 Idefics 模型，并定义模型架构。使用默认值实例化配置将得到与 [HuggingFaceM4/idefics-9b](https://huggingface.co/HuggingFaceM4/idefics-9b) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

## IdeficsModel[[transformers.IdeficsModel]]

#### transformers.IdeficsModel[[transformers.IdeficsModel]]

```python
transformers.IdeficsModel(config: IdeficsConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/idefics/modeling_idefics.py#L857)

**参数：**

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

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

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/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.IdeficsModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, pixel_values: typing.Optional[torch.Tensor] = None, image_encoder_embeddings: typing.Optional[torch.Tensor] = None, perceiver_embeddings: typing.Optional[torch.Tensor] = None, image_attention_mask: typing.Optional[torch.Tensor] = None, use_cache: bool | None = None, interpolate_pos_encoding: bool | None = False, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/idefics/modeling_idefics.py#L932)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/v5.23.0/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

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

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

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

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

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*) : 与输入图像对应的张量。可以使用 [IdeficsImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/idefics#transformers.IdeficsImageProcessor) 获取像素值。有关详细信息，请参阅 [IdeficsImageProcessor.__call__()](/docs/transformers/v5.23.0/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（[IdeficsProcessor](/docs/transformers/v5.23.0/zh/model_doc/idefics#transformers.IdeficsProcessor) 使用 [IdeficsImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/idefics#transformers.IdeficsImageProcessor) 来处理图像）。

image_encoder_embeddings (`torch.Tensor`, *可选*) : 图像编码器的输出。

perceiver_embeddings (`torch.Tensor`, *可选*) : perceiver resampler 的输出。

image_attention_mask (`torch.LongTensor`, *可选*) : 图像编码器的注意力掩码。

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

interpolate_pos_encoding (`bool`，*可选*，默认为 `False`)：是否对预训练的位置编码进行插值。

**返回：** `IdeficsBaseModelOutputWithPast` 或 `tuple(torch.Tensor)`

`IdeficsBaseModelOutputWithPast` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[IdeficsConfig](/docs/transformers/v5.23.0/zh/model_doc/idefics#transformers.IdeficsConfig)）和输入。

[IdeficsModel](/docs/transformers/v5.23.0/zh/model_doc/idefics#transformers.IdeficsModel) 的 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** (`~cache_utils.Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回) -- 它是一个 [Cache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `past_key_values` 输入）加速顺序解码。
- **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 后的注意力权重，用于在自注意力头中计算加权平均值。
- **image_hidden_states** (`tuple(torch.Tensor)`, *可选*) -- `torch.Tensor` 的元组（一个用于图像嵌入的输出，`(batch_size, num_images, sequence_length, hidden_size)`。

  由视觉编码器生成的模型的 image_hidden_states，以及可选地由 perceiver 生成的

## IdeficsForVisionText2Text[[transformers.IdeficsForVisionText2Text]]

#### transformers.IdeficsForVisionText2Text[[transformers.IdeficsForVisionText2Text]]

```python
transformers.IdeficsForVisionText2Text(config: IdeficsConfig, vision_model = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/idefics/modeling_idefics.py#L1085)

#### forward[[transformers.IdeficsForVisionText2Text.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, pixel_values: typing.Optional[torch.Tensor] = None, image_encoder_embeddings: typing.Optional[torch.Tensor] = None, perceiver_embeddings: typing.Optional[torch.Tensor] = None, image_attention_mask: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = None, interpolate_pos_encoding: bool | None = False, logits_to_keep: typing.Union[int, torch.Tensor] = 0, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/idefics/modeling_idefics.py#L1108)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/v5.23.0/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

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

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

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

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

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*) : 与输入图像对应的张量。可以使用 [IdeficsImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/idefics#transformers.IdeficsImageProcessor) 获取像素值。有关详细信息，请参阅 [IdeficsImageProcessor.__call__()](/docs/transformers/v5.23.0/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（[IdeficsProcessor](/docs/transformers/v5.23.0/zh/model_doc/idefics#transformers.IdeficsProcessor) 使用 [IdeficsImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/idefics#transformers.IdeficsImageProcessor) 来处理图像）。

image_encoder_embeddings (`torch.Tensor`, *可选*) : 图像编码器的输出。

perceiver_embeddings (`torch.Tensor`, *可选*) : perceiver resampler 的输出。

image_attention_mask (`torch.LongTensor`, *可选*) : 图像编码器的注意力掩码。

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

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

interpolate_pos_encoding (`bool`，*可选*，默认为 `False`)：是否对预训练的位置编码进行插值。

logits_to_keep (`Union[int, torch.Tensor]`，*可选*，默认为 `0`)：如果为 `int`，则计算最后 `logits_to_keep` 个 token 的 logits。如果为 `0`，则计算所有 `input_ids` 的 logits（特殊情况）。生成过程只需要最后一个 token 的 logits，仅针对该 token 进行计算可以节省内存，对于长序列或大词汇量而言，这种节省相当可观。如果为 `torch.Tensor`，则必须是一维张量，对应于序列长度维度中需要保留的索引。这在使用打包张量格式（将批次和序列长度合并为单一维度）时非常有用。

**返回：** `IdeficsCausalLMOutputWithPast` 或 `tuple(torch.Tensor)`

`IdeficsCausalLMOutputWithPast` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[IdeficsConfig](/docs/transformers/v5.23.0/zh/model_doc/idefics#transformers.IdeficsConfig)）和输入。

[IdeficsForVisionText2Text](/docs/transformers/v5.23.0/zh/model_doc/idefics#transformers.IdeficsForVisionText2Text) 的 forward 方法重写了 `__call__` 特殊方法。

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

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 语言建模损失（用于下一个 token 预测）。
- **logits**（形状为 `(batch_size, sequence_length, config.vocab_size)` 的 `torch.Tensor`）-- 语言建模头的预测分数（SoftMax 之前每个词汇表 token 的分数）。
- **past_key_values**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）—— 它是一个 [Cache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值），可用于（参见 `past_key_values` 输入）加速顺序解码。
- **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 后的注意力权重，用于在自注意力头中计算加权平均值。
- **image_hidden_states** (`tuple(torch.Tensor)`, *可选*) -- `torch.Tensor` 的元组（一个用于图像嵌入的输出，`(batch_size, num_images, sequence_length, hidden_size)`。

  由视觉编码器生成的模型的 image_hidden_states，以及可选地由 perceiver 生成的

示例：

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

>>> model = IdeficsForVisionText2Text.from_pretrained("HuggingFaceM4/idefics-9b")
>>> processor = AutoProcessor.from_pretrained("HuggingFaceM4/idefics-9b")

>>> dogs_image_url_1 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_nlvr2/raw/main/image1.jpeg"
>>> dogs_image_url_2 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_nlvr2/raw/main/image2.jpeg"

>>> prompts = [
...     [
...         "User:",
...         dogs_image_url_1,
...         "Describe this image.\nAssistant: An image of two dogs.\n",
...         "User:",
...         dogs_image_url_2,
...         "Describe this image.\nAssistant:",
...     ]
... ]
>>> inputs = processor(prompts, return_tensors="pt")
>>> generate_ids = model.generate(**inputs, max_new_tokens=6)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)
```

## IdeficsImageProcessor[[transformers.IdeficsImageProcessor]]

#### transformers.IdeficsImageProcessor[[transformers.IdeficsImageProcessor]]

```python
transformers.IdeficsImageProcessor(**kwargs: *<class 'transformers.models.idefics.image_processing_idefics.IdeficsImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/idefics/image_processing_idefics.py#L52)

**参数：**

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

do_resize (`bool`, *kwargs*, *可选*, 默认为 `True`) : 是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'height' : 224, 'width': 224}`)：描述输入到模型的最大尺寸。

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*，默认值为 `3`) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

do_rescale (`bool`, *kwargs*, *可选*，默认为 `True`)：是否对图像进行重新缩放。

rescale_factor (`float`, *kwargs*, *可选*，默认为 `0.00392156862745098`) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行缩放的缩放因子。

do_normalize (`bool`，*kwargs*，*可选*，默认为 `True`)：是否对图像进行归一化。

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

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.26862954, 0.26130258, 0.27577711]`) : 用于归一化的图像标准差。仅当 `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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

transform (`Callable`, *kwargs*, *optional*, 默认为 `None`) : 可以传入一个接受单张图像的自定义转换函数用于训练。例如，可以使用 `torchvision.Compose` 来组合多个转换。如果为 `None` - 则假定处于推理模式 - 此时将对图像应用一组针对推理的预设转换。

image_size (`int`, *kwargs*, *可选*，默认为 `self.image_size`) : 调整至图像尺寸。这是 `size` 的向后兼容别名。如果提供，它将覆盖 `size` 并将其设置为 `{"height": image_size, "width": image_size}`。

image_num_channels (`int`, *kwargs*, *可选*，默认为 `3`)：图像的通道数。

构造一个 IdeficsImageProcessor 图像处理器。

#### preprocess[[transformers.IdeficsImageProcessor.preprocess]]

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

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/idefics/image_processing_idefics.py#L71)

**参数：**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`) : 要预处理的图像。期望输入单张或一批像素值在 0 到 255 之间的图像。如果传入的图像像素值在 0 到 1 之间，请设置 `do_rescale=False`。

do_convert_rgb (`bool`, *kwargs*, *可选*) : 是否将图像转换为 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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

transform (`Callable`, *kwargs*, *optional*, 默认为 `None`) : 可以传入一个接受单张图像的自定义转换函数用于训练。例如，可以使用 `torchvision.Compose` 来组合多个转换。如果为 `None` - 则假定处于推理模式 - 此时将对图像应用一组针对推理的预设转换。

image_size (`int`, *kwargs*, *可选*，默认为 `self.image_size`) : 调整至图像尺寸。这是 `size` 的向后兼容别名。如果提供，它将覆盖 `size` 并将其设置为 `{"height": image_size, "width": image_size}`。

image_num_channels (`int`, *kwargs*, *可选*，默认为 `3`)：图像的通道数。

**返回值：**

`TensorType | BatchFeature`

## IdeficsImageProcessorPil[[transformers.IdeficsImageProcessorPil]]

#### transformers.IdeficsImageProcessorPil[[transformers.IdeficsImageProcessorPil]]

```python
transformers.IdeficsImageProcessorPil(**kwargs: *<class 'transformers.models.idefics.image_processing_pil_idefics.IdeficsImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/idefics/image_processing_pil_idefics.py#L51)

**参数：**

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

do_resize (`bool`, *kwargs*, *可选*, 默认为 `True`) : 是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'height' : 224, 'width': 224}`)：描述输入到模型的最大尺寸。

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*，默认值为 `3`) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

do_rescale (`bool`, *kwargs*, *可选*，默认为 `True`)：是否对图像进行重新缩放。

rescale_factor (`float`, *kwargs*, *可选*，默认为 `0.00392156862745098`) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行缩放的缩放因子。

do_normalize (`bool`，*kwargs*，*可选*，默认为 `True`)：是否对图像进行归一化。

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

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.26862954, 0.26130258, 0.27577711]`) : 用于归一化的图像标准差。仅当 `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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

transform (`Callable`, *kwargs*, *optional*, 默认为 `None`) : 可以传入一个接受单张图像的自定义转换函数用于训练。例如，可以使用 `torchvision.Compose` 来组合多个转换。如果为 `None` - 则假定处于推理模式 - 此时将对图像应用一组针对推理的预设转换。

image_size (`int`, *kwargs*, *可选*，默认为 `self.image_size`) : 调整至图像尺寸。这是 `size` 的向后兼容别名。如果提供，它将覆盖 `size` 并将其设置为 `{"height": image_size, "width": image_size}`。

image_num_channels (`int`, *kwargs*, *可选*，默认为 `3`)：图像的通道数。

构造一个 IdeficsImageProcessor 图像处理器。

#### preprocess[[transformers.IdeficsImageProcessorPil.preprocess]]

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

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/idefics/image_processing_pil_idefics.py#L70)

**参数：**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`) : 要预处理的图像。期望输入单张或一批像素值在 0 到 255 之间的图像。如果传入的图像像素值在 0 到 1 之间，请设置 `do_rescale=False`。

do_convert_rgb (`bool`, *kwargs*, *可选*) : 是否将图像转换为 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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

transform (`Callable`, *kwargs*, *optional*, 默认为 `None`) : 可以传入一个接受单张图像的自定义转换函数用于训练。例如，可以使用 `torchvision.Compose` 来组合多个转换。如果为 `None` - 则假定处于推理模式 - 此时将对图像应用一组针对推理的预设转换。

image_size (`int`, *kwargs*, *可选*，默认为 `self.image_size`) : 调整至图像尺寸。这是 `size` 的向后兼容别名。如果提供，它将覆盖 `size` 并将其设置为 `{"height": image_size, "width": image_size}`。

image_num_channels (`int`, *kwargs*, *可选*，默认为 `3`)：图像的通道数。

## IdeficsProcessor[[transformers.IdeficsProcessor]]

#### transformers.IdeficsProcessor[[transformers.IdeficsProcessor]]

```python
transformers.IdeficsProcessor(image_processor, tokenizer = None, image_size = 224, add_end_of_utterance_token = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/idefics/processing_idefics.py#L157)

**参数：**

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

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

image_size (`int`，*可选*，默认为 224)：要处理的图像尺寸。

add_end_of_utterance_token (`bool`，*可选*，默认为 None)：是否向文本添加话语结束标记。

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

[IdeficsProcessor](/docs/transformers/v5.23.0/zh/model_doc/idefics#transformers.IdeficsProcessor) 提供了 [IdeficsImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/idefics#transformers.IdeficsImageProcessor) 和 [LlamaTokenizer](/docs/transformers/v5.23.0/zh/model_doc/llama2#transformers.LlamaTokenizer) 的所有功能。有关更多信息，请参阅 [~IdeficsImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/idefics#transformers.IdeficsImageProcessor) 和 [~LlamaTokenizer](/docs/transformers/v5.23.0/zh/model_doc/llama2#transformers.LlamaTokenizer)。

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

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

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/idefics/processing_idefics.py#L195)

**参数：**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], list[Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]], str, list[str], list[list[str]]]`, *可选*) : 要预处理的图像。期望输入单张或一批像素值在 0 到 255 之间的图像。如果传入的图像像素值在 0 到 1 之间，请设置 `do_rescale=False`。

text (`Union[str, list[str], list[list[str]], list[list[list[str]]]]`，*可选*)：要编码的序列或序列批次。每个序列可以是字符串或字符串列表（预分词字符串）。如果传入预分词输入，请设置 `is_split_into_words=True` 以避免与批量输入产生歧义。

add_eos_token (`bool`, *kwargs*, *可选*) : 已弃用，请改用 `IdeficsProcessorKwargs.add_eos_token`。是否在文本输入的末尾添加序列结束（end-of-sequence）标记。启用后，会在文本序列末尾追加一个 EOS 标记以指示序列结束，这在生成任务中非常有用。

add_end_of_utterance_token (`bool`, *kwargs*, *可选*) : 已弃用，请改用 `IdeficsProcessorKwargs.add_end_of_utterance_token`。是否添加话语结束标记，以在对话场景中指示用户消息的结尾。该标记有助于模型在多轮对话中区分不同的话语，对于基于聊天的模型尤为重要。

return_mm_token_type_ids (`bool`, *kwargs*) : 是否返回多模态 token 类型 ID，以指示多模态占位符 token 的位置。

return_text_replacement_offsets (`bool`, *kwargs*) : 是否返回每个多模态占位符及其替换项的字符偏移量。

add_eos_token (`bool`, *kwargs*, *可选*，默认为 `False`) : 是否在文本输入的末尾添加序列结束（end-of-sequence）标记。启用后，会在文本序列末尾追加一个 EOS 标记以指示序列结束，这在生成任务中非常有用。

add_end_of_utterance_token (`bool`, *kwargs*, *可选*) : 是否添加一个话语结束标记，以在对话场景中指示用户消息的结束。该标记有助于模型在多轮对话中区分不同的话语，对于基于聊天的模型尤为重要。如果为 `None`，则仅当分词器在训练时使用了该标记时才会添加。

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

- ****kwargs** ([ProcessingKwargs](/docs/transformers/v5.23.0/zh/main_classes/processors#transformers.ProcessingKwargs), *可选*) : 针对每种模态（文本、图像、视频、音频）的额外处理选项。模型特定参数已在上方列出；有关支持参数的完整列表，请参阅 TypedDict 类。

**返回：** `a dict with entries`

`input_ids`、`attention_mask`、`pixel_values`、`image_attention_mask`，可直接传入 `model.generate`

详细说明：

`text` 中的每个条目要么是原样传递的文本，要么是将被处理的图像。

图像可以是图像对象（`PIL.Image`），也可以是用于获取图像的 URL。

当处理器遇到图像时，它会在提示中注入`<fake_token_around_image><image><fake_token_around_image>`条目。

示例：

```python
checkpoint = "HuggingFaceM4/idefics-9b"
processor = AutoProcessor.from_pretrained(checkpoint)
url = "https://hips.hearstapps.com/hmg-prod/images/cute-photos-of-cats-in-grass-1593184777.jpg"
img = processor.image_processor.fetch_images([url])[0]

prompts = [
    "User:",
    img,
    "Describe this image.\nAssistant: An image of two kittens in grass.\n",
    "User:",
    "https://hips.hearstapps.com/hmg-prod/images/dog-puns-1581708208.jpg",
    "Describe this image.\nAssistant:",
]

inputs = processor(text=prompts, return_tensors="pt")
generated_ids = model.generate(**inputs, max_length=100)
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
```

在此示例中，`prompts` 将被转换为：

```
<s>User:<fake_token_around_image><image><fake_token_around_image>Describe this image.
Assistant: An image of two kittens in grass.
User:<fake_token_around_image><image><fake_token_around_image>Describe this image.
Assistant:'
```

这两张图片将通过 [IdeficsImageProcessor.__call__()](/docs/transformers/v5.23.0/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) 方法进行处理，并放置在返回值的 `pixel_values` 字典项中。

此示例还说明了图像可以以对象或文本 URL 的形式传入。可以看到，第一张图像以对象形式传入，第二张则以 URL 形式传入。

要进行训练，请执行以下操作：

```python
image_transform = transforms.Compose(
    [
        transforms.RandomResizedCrop(
            (w, h), scale=(0.9, 1.0), interpolation=transforms.InterpolationMode.BICUBIC
        ),
        transforms.ToTensor(),
        transforms.Normalize(mean=self.image_mean, std=self.image_std),
    ]
)
inputs = processor(text=prompts, transform=image_transform, return_tensors="pt")
```

为了帮助调试提示词生成，请启用 `debug=True`，这将显示正在发生的事情。

