Transformers 文档

Idefics2

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

Idefics2

PyTorch FlashAttention SDPA

概述

Idefics2 模型由 Léo Tronchon、Hugo Laurencon、Victor Sanh 在 构建视觉语言模型时什么最重要? 中提出。随附的博客文章可以在这里找到。

Idefics2 是一个开放的多模态模型,它接受任意图像和文本输入序列,并生成文本输出。该模型可以回答有关图像的问题、描述视觉内容、创建基于多张图像的故事,或者仅充当没有视觉输入的纯语言模型。它改进了 IDEFICS-1,特别是在文档理解、OCR 或视觉推理方面。Idefics2 是轻量级的(80 亿参数),并以其原始纵横比和分辨率处理图像,这允许不同的推理效率。

论文的摘要如下

对视觉语言模型 (VLM) 日益增长的兴趣是由大型语言模型和视觉 Transformer 的改进所驱动的。尽管关于该主题的文献数量很多,但我们观察到,关于 VLM 设计的关键决策通常没有得到合理的解释。我们认为,这些未经支持的决策阻碍了该领域的进步,因为它们使得难以确定哪些选择可以提高模型性能。为了解决这个问题,我们围绕预训练模型、架构选择、数据和训练方法进行了广泛的实验。我们对发现的总结包括开发了 Idefics2,这是一个高效的基础 VLM,具有 80 亿个参数。Idefics2 在各种多模态基准测试中,在其规模类别内实现了最先进的性能,并且通常与规模是其四倍的模型相当。我们发布了该模型(基础模型、指令模型和聊天模型)以及为其训练创建的数据集。

drawing Idefics2 架构。取自原始论文。

此模型由 amyeroberts 贡献。原始代码可以在这里找到。

使用技巧

  • 每个样本可以包含多个图像,并且图像的数量在样本之间可能有所不同。处理器将输入填充到批次中图像的最大数量,以便输入到模型。
  • 处理器有一个 do_image_splitting 选项。如果为 True,则每个输入图像将被拆分为 4 个子图像,并与原始图像连接以形成 5 个图像。这对于提高模型性能很有用。如果模型未使用此选项进行训练,请确保将 processor.image_processor.do_image_splitting 设置为 False
  • 传递给处理器的 text 应该在图像应插入的位置具有 <image> 标记。并且如果文本是聊天消息,则在每个话语的末尾使用 <end_of_utterance>
  • 处理器有自己的 apply_chat_template 方法,用于将聊天消息转换为文本,然后可以作为 text 传递给处理器。

如何在聊天消息上使用处理器的示例

import requests
from PIL import Image
from transformers import Idefics2Processor, Idefics2ForConditionalGeneration
import torch

device = "cuda" if torch.cuda.is_available() else "cpu"

url_1 = "http://images.cocodataset.org/val2017/000000039769.jpg"
url_2 = "http://images.cocodataset.org/val2017/000000219578.jpg"

image_1 = Image.open(requests.get(url_1, stream=True).raw)
image_2 = Image.open(requests.get(url_2, stream=True).raw)
images = [image_1, image_2]

messages = [{
    "role": "user",
    "content": [
        {"type": "text", "text": "What’s the difference between these two images?"},
        {"type": "image"},
        {"type": "image"},
    ],
}]

processor = Idefics2Processor.from_pretrained("HuggingFaceM4/idefics2-8b")
model = Idefics2ForConditionalGeneration.from_pretrained("HuggingFaceM4/idefics2-8b")
model.to(device)

# at inference time, one needs to pass `add_generation_prompt=True` in order to make sure the model completes the prompt
text = processor.apply_chat_template(messages, add_generation_prompt=True)
print(text)
# 'User: What’s the difference between these two images?<image><image><end_of_utterance>\nAssistant:'

inputs = processor(images=images, text=text, return_tensors="pt").to(device)

generated_text = model.generate(**inputs, max_new_tokens=500)
generated_text = processor.batch_decode(generated_text, skip_special_tokens=True)[0]
print("Generated text:", generated_text)
  • 在训练期间,确定模型不应学习哪些标记非常重要。对于 Idefics2,这通常归结为图像和填充标记。这意味着可以按如下方式创建标签
import requests
from PIL import Image
from transformers import Idefics2Processor, Idefics2ForConditionalGeneration
import torch

url_1 = "http://images.cocodataset.org/val2017/000000039769.jpg"
url_2 = "http://images.cocodataset.org/val2017/000000219578.jpg"

image_1 = Image.open(requests.get(url_1, stream=True).raw)
image_2 = Image.open(requests.get(url_2, stream=True).raw)
images = [image_1, image_2]

messages = [{
    "role": "user",
    "content": [
        {"type": "text", "text": "What’s the difference between these two images?"},
        {"type": "image"},
        {"type": "image"},
    ],
},
{
    "role": "assistant",
    "content": [
        {"type": "text", "text": "The difference is that one image is about dogs and the other one about cats."},
    ],
}]

device = "cuda" if torch.cuda.is_available() else "cpu"

processor = Idefics2Processor.from_pretrained("HuggingFaceM4/idefics2-8b")
model = Idefics2ForConditionalGeneration.from_pretrained("HuggingFaceM4/idefics2-8b")
model.to(device)

text = processor.apply_chat_template(messages, add_generation_prompt=False)
inputs = processor(images=images, text=text, return_tensors="pt").to(device)

labels = inputs.input_ids.clone()
labels[labels == processor.tokenizer.pad_token_id] = -100
labels[labels == model.config.image_token_id] = -100

inputs["labels"] = labels

outputs = model(**inputs)
loss = outputs.loss
loss.backward()

请注意,当在用户和助手之间的多轮对话中训练 Idefics2 时,通常还会将与用户消息对应的所有标记设置为 -100。

模型优化:Flash Attention

上面的代码片段展示了没有任何优化技巧的推理。但是,可以通过利用 Flash Attention 来大幅加速模型,Flash Attention 是模型内部使用的注意力机制的更快实现。

首先,请确保安装最新版本的 Flash Attention 2,以包含滑动窗口注意力功能。

pip install -U flash-attn --no-build-isolation

还要确保您拥有与 Flash-Attention 2 兼容的硬件。请阅读 flash attention 存储库 的官方文档,了解更多信息。还要确保以半精度(例如 torch.float16)加载模型

要使用 Flash Attention-2 加载和运行模型,只需使用以下更改修改上面的代码片段

model = Idefics2ForConditionalGeneration.from_pretrained(
    "HuggingFaceM4/idefics2-8b",
+    torch_dtype=torch.float16,    
+    attn_implementation="flash_attention_2",
).to(device)

使用量化缩小 Idefics2

由于 Idefics2 模型有 80 亿个参数,因此在半精度 (float16) 下将需要大约 16GB 的 GPU RAM,因为每个参数存储在 2 个字节中。但是,可以使用量化来缩小模型的大小。如果模型量化为 4 位(或每个参数半个字节),则只需要大约 3.5GB 的 RAM。

量化模型就像将 quantization_config 传递给模型一样简单。可以使用下面的更改来修改上面的代码片段。我们将利用 BitsAndyBytes 量化(但请参阅 此页面 了解其他量化方法)

+ from transformers import BitsAndBytesConfig

+ quantization_config = BitsAndBytesConfig(
+    load_in_4bit=True,
+    bnb_4bit_quant_type="nf4",
+    bnb_4bit_use_double_quant=True,
+    bnb_4bit_compute_dtype=torch.float16
+ )
model = Idefics2ForConditionalGeneration.from_pretrained(
    "HuggingFaceM4/idefics2-8b",
+    torch_dtype=torch.float16,    
+    quantization_config=quantization_config,
).to(device)

资源

官方 Hugging Face 和社区 (🌎 表示) 资源列表,可帮助您开始使用 Idefics2。如果您有兴趣提交资源以包含在此处,请随时打开 Pull Request,我们将对其进行审核!该资源最好展示一些新的内容,而不是重复现有资源。

  • 关于如何使用 Trainer 在自定义数据集上微调 Idefics2 的笔记本可以在这里找到。它支持完全微调以及(量化的)LoRa。
  • 关于如何使用 TRL 库微调 Idefics2 的脚本可以在这里找到。
  • 关于为 JSON 提取用例微调 Idefics2 的演示笔记本可以在这里找到。 🌎

Idefics2Config

class transformers.Idefics2Config

< >

( use_cache = True image_token_id = 32001 tie_word_embeddings = False vision_config = None perceiver_config = None text_config = None **kwargs )

参数

  • use_cache (bool, 可选, 默认为 True) — 模型是否应缓存注意力机制的键/值对。
  • image_token_id (int, 可选, 默认为 32001) — “image” 标记的 ID。
  • tie_word_embeddings (bool, 可选, 默认为 False) — 是否将词嵌入与标记嵌入绑定。
  • vision_config (IdeficsVisionConfigdict, 可选) — 自定义 vision config 或 dict
  • perceiver_config (IdeficsPerceiverConfigdict, 可选) — 自定义 perceiver config 或 dict
  • text_config (MistralConfigdict, 可选) — 文本模型的自定义 text config 或 dict

这是用于存储 Idefics2Model 配置的配置类。它用于根据指定的参数实例化 Idefics2 模型,定义模型架构。使用默认值实例化配置将产生与 Idefics2 HuggingFaceM4/idefics2-8b 架构模型相似的配置。

配置对象继承自 PretrainedConfig,可用于控制模型输出。阅读 PretrainedConfig 的文档以获取更多信息。

示例

>>> from transformers import Idefics2Model, Idefics2Config
>>> # Initializing configuration
>>> configuration = Idefics2Config()
>>> # Initializing a model from the configuration
>>> model = Idefics2Model(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config

Idefics2Model

class transformers.Idefics2Model

< >

( config: Idefics2Config )

参数

  • config (Idefics2ConfigIdefics2VisionConfig) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。

Idefics2 模型由 SIGLIP 视觉编码器和 Mistral 语言解码器组成。此模型继承自 PreTrainedModel。查看超类文档,了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

此模型也是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档,了解所有与常规用法和行为相关的事项。

forward

< >

( input_ids: LongTensor = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None pixel_values: typing.Optional[torch.FloatTensor] = None pixel_attention_mask: typing.Optional[torch.BoolTensor] = None image_hidden_states: typing.Optional[torch.FloatTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None return_dict: typing.Optional[bool] = None )

参数

  • input_ids (torch.LongTensor,形状为 (batch_size, sequence_length)) — 词汇表中输入序列标记的索引。如果您提供填充,默认情况下将忽略填充。

    索引可以使用 AutoTokenizer 获取。 有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入 ID?

  • attention_mask (torch.Tensor,形状为 (batch_size, sequence_length), 可选) — 掩码,用于避免对填充标记索引执行注意力机制。掩码值在 [0, 1] 中选择:

    • 1 表示标记未被掩盖
    • 0 表示标记被掩盖

    什么是注意力掩码?

    索引可以使用 AutoTokenizer 获取。 有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    如果使用 past_key_values,则可以选择仅输入最后一个 decoder_input_ids(请参阅 past_key_values)。

    如果您想更改填充行为,则应阅读 modeling_opt._prepare_decoder_attention_mask 并根据您的需要进行修改。有关默认策略的更多信息,请参阅 论文 中的图 1。

    • 1 表示头未被掩盖
    • 0 表示头被掩盖
  • position_ids (torch.LongTensor,形状为 (batch_size, sequence_length), 可选) — 每个输入序列标记在位置嵌入中的位置索引。在范围 [0, config.n_positions - 1] 中选择。 什么是位置 ID?
  • past_key_values (tuple(tuple(torch.FloatTensor)), 可选, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstuple(torch.FloatTensor) 元组,每个元组具有 2 个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量和 2 个形状为 (batch_size, num_heads, encoder_sequence_length, embed_size_per_head) 的附加张量。

    包含预先计算的隐藏状态(自注意力模块和交叉注意力模块中的键和值),这些状态可以用于(请参阅 past_key_values 输入)加速顺序解码。

    如果使用 past_key_values,则用户可以选择仅输入最后一个 decoder_input_ids(那些没有为其提供过去键值状态的模型),形状为 (batch_size, 1) 而不是所有形状为 (batch_size, sequence_length)decoder_input_ids

  • inputs_embeds (torch.FloatTensor,形状为 (batch_size, sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望比模型的内部嵌入查找矩阵更好地控制如何将 input_ids 索引转换为关联向量,这将非常有用。
  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, image_size, image_size)) -- 与输入图像对应的张量。像素值可以使用 [AutoImageProcessor](/docs/transformers/v4.50.0/en/model_doc/auto#transformers.AutoImageProcessor) 获取。 有关详细信息,请参阅 [CLIPImageProcessor.__call__()](/docs/transformers/v4.50.0/en/model_doc/vilt#transformers.ViltFeatureExtractor.__call__) ([`LlavaProcessor`] 使用 CLIPImageProcessor 处理图像)。
  • pixel_attention_mask (torch.Tensor,形状为 (batch_size, image_size, image_size), 可选) — 掩码,用于避免对填充像素索引执行注意力机制。
  • image_hidden_states (torch.FloatTensor,形状为 (batch_size, num_channels, image_size, image_size)) — 模态投影和 perceiver 重采样后图像编码器的隐藏状态。
  • use_cache (bool, 可选) — 如果设置为 True,则返回 past_key_values 键值状态,并且可以用于加速解码(请参阅 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
  • cache_position (torch.LongTensor,形状为 (sequence_length), 可选) — 索引,描述输入序列标记在序列中的位置。与 position_ids 相反,此张量不受填充的影响。它用于在正确的位置更新缓存,并推断完整的序列长度。

Idefics2Model forward 方法,覆盖了 __call__ 特殊方法。

尽管 forward 传递的配方需要在该函数中定义,但之后应该调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

馈送到模型的输入可以具有任意数量的图像。为了解决这个问题,馈送到模型的 pixel_values 具有图像填充 -> (batch_size, max_num_images, 3, max_heights, max_widths),其中 max_num_images 是批次大小样本中图像的最大数量。

除了在模型入口处填充 pixel_values 之外,不需要填充图像。为了提高效率,我们仅通过 vision_model 的 forward 传递真实图像,方法是丢弃填充图像,即大小为 (image_batch_size, 3, height, width) 的 pixel_values,其中当 num_images_per_sample=[1, 3, 1, 2] 且 max_num_images 为 3 时,image_batch_size 将为 7。

Idefics2ForConditionalGeneration

class transformers.Idefics2ForConditionalGeneration

< >

( config )

参数

  • config (Idefics2ConfigIdefics2VisionConfig) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。

带有语言建模头的 Idefics2 模型。它由 SigLIP 视觉编码器和顶部的语言建模头组成。此模型继承自 PreTrainedModel。查看超类文档以了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

此模型也是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档,了解所有与常规用法和行为相关的事项。

forward

< >

( input_ids: LongTensor = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None pixel_values: typing.Optional[torch.FloatTensor] = None pixel_attention_mask: typing.Optional[torch.BoolTensor] = None image_hidden_states: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None logits_to_keep: typing.Union[int, torch.Tensor] = 0 ) transformers.models.idefics2.modeling_idefics2.Idefics2CausalLMOutputWithPasttuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor,形状为 (batch_size, sequence_length)) — 词汇表中输入序列 tokens 的索引。如果您提供填充,默认情况下将被忽略。

    索引可以使用 AutoTokenizer 获得。 有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入 IDs?

  • attention_mask (torch.Tensor,形状为 (batch_size, sequence_length)可选) — 避免在填充 token 索引上执行 attention 的掩码。在 [0, 1] 中选择的掩码值:

    • 1 表示 未被掩码 的 token,
    • 0 表示 已被掩码 的 token。

    什么是 attention 掩码?

    索引可以使用 AutoTokenizer 获得。 有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    如果使用 past_key_values,则可以选择仅输入最后的 decoder_input_ids(请参阅 past_key_values)。

    如果您想更改填充行为,您应该阅读 modeling_opt._prepare_decoder_attention_mask 并根据您的需要进行修改。 有关默认策略的更多信息,请参阅 论文 中的图 1。

    • 1 表示 head 未被掩码
    • 0 表示 head 已被掩码
  • position_ids (torch.LongTensor,形状为 (batch_size, sequence_length)可选) — 位置嵌入中每个输入序列 token 的位置索引。在范围 [0, config.n_positions - 1] 中选择。 什么是位置 IDs?
  • past_key_values (tuple(tuple(torch.FloatTensor))可选,当传递 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstuple(tuple(torch.FloatTensor)) 元组,其中每个元组有 2 个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量和 2 个形状为 (batch_size, num_heads, encoder_sequence_length, embed_size_per_head) 的附加张量。

    包含预先计算的隐藏状态(自注意力模块和交叉注意力模块中的键和值),可以用于(请参阅 past_key_values 输入)加速顺序解码。

    如果使用 past_key_values,用户可以选择仅输入最后的 decoder_input_ids(那些没有将其过去的键值状态提供给此模型的),形状为 (batch_size, 1),而不是所有形状为 (batch_size, sequence_length)decoder_input_ids

  • inputs_embeds (torch.FloatTensor,形状为 (batch_size, sequence_length, hidden_size)可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。 如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将 input_ids 索引转换为关联的向量,这将非常有用。
  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, image_size, image_size)) -- 与输入图像对应的张量。像素值可以使用 [AutoImageProcessor](/docs/transformers/v4.50.0/en/model_doc/auto#transformers.AutoImageProcessor) 获得。 有关详细信息,请参阅 [CLIPImageProcessor.__call__()](/docs/transformers/v4.50.0/en/model_doc/vilt#transformers.ViltFeatureExtractor.__call__)([`LlavaProcessor`] 使用 CLIPImageProcessor 处理图像)。
  • pixel_attention_mask (torch.Tensor,形状为 (batch_size, image_size, image_size)可选) — 避免对填充像素索引执行 attention 的掩码。
  • image_hidden_states (torch.FloatTensor,形状为 (batch_size, num_channels, image_size, image_size)) — 模态投影和感知器重采样后图像编码器的隐藏状态。
  • use_cache (bool可选) — 如果设置为 True,则返回 past_key_values 键值状态,并且可以用于加速解码(请参阅 past_key_values)。
  • output_attentions (bool可选) — 是否返回所有 attention 层的 attention 张量。 有关更多详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool可选) — 是否返回 ModelOutput 而不是普通元组。
  • cache_position (torch.LongTensor,形状为 (sequence_length)可选) — 描绘输入序列 tokens 在序列中位置的索引。 与 position_ids 相反,此张量不受填充的影响。 它用于在正确的位置更新缓存,并推断完整的序列长度。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length)可选) — 用于计算掩码语言建模损失的标签。 索引应为 [0, ..., config.vocab_size]model.image_token_id(其中 model 是您的 Idefics2ForConditionalGeneration 实例)。 索引设置为 model.image_token_id 的 tokens 将被忽略(掩码),损失仅针对标签在 [0, ..., config.vocab_size] 中的 tokens 计算。
  • logits_to_keep (inttorch.Tensor可选) — 如果是 int,则计算最后 logits_to_keep 个 tokens 的 logits。 如果为 0,则计算所有 input_ids 的 logits(特殊情况)。 只有最后一个 token logits 是生成所需的,并且仅针对该 token 计算它们可以节省内存,这对于长序列或大词汇量大小而言变得非常重要。 如果是 torch.Tensor,则必须是与序列长度维度中要保留的索引对应的一维张量。 这在使用打包张量格式(批次和序列长度的单个维度)时非常有用。

返回

transformers.models.idefics2.modeling_idefics2.Idefics2CausalLMOutputWithPasttuple(torch.FloatTensor)

一个 transformers.models.idefics2.modeling_idefics2.Idefics2CausalLMOutputWithPasttorch.FloatTensor 元组(如果传递 return_dict=False 或当 config.return_dict=False 时),包含各种元素,具体取决于配置 (Idefics2Config) 和输入。

  • loss (torch.FloatTensor,形状为 (1,)可选,当提供 labels 时返回) — 语言建模损失(用于下一个 token 预测)。
  • logits (torch.FloatTensor,形状为 (batch_size, sequence_length, config.vocab_size)) — 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。
  • past_key_values (tuple(tuple(torch.FloatTensor))可选,当传递 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstuple(tuple(torch.FloatTensor)) 元组,其中每个元组有 2 个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量)。 包含预先计算的隐藏状态(自注意力模块中的键和值),可以用于(请参阅 past_key_values 输入)加速顺序解码。
  • hidden_states (tuple(torch.FloatTensor)可选,当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 元组(如果模型具有嵌入层,则一个用于嵌入的输出,+ 每个层的输出一个),形状为 (batch_size, sequence_length, hidden_size)。 每个层输出端的模型隐藏状态加上可选的初始嵌入输出。
  • attentions (tuple(torch.FloatTensor)可选,当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。 attention softmax 之后的 Attention 权重,用于计算自注意力头中的加权平均值。
  • image_hidden_states (tuple(torch.FloatTensor)可选) — torch.FloatTensor 元组(一个用于图像嵌入的输出,(batch_size, num_images, sequence_length, hidden_size)。 视觉编码器以及可选的感知器生成的模型的 image_hidden_states

Idefics2ForConditionalGeneration forward 方法,覆盖了 __call__ 特殊方法。

尽管 forward 传递的配方需要在该函数中定义,但之后应该调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例

>>> import requests
>>> import torch
>>> from PIL import Image
>>> from io import BytesIO

>>> from transformers import AutoProcessor, AutoModelForVision2Seq
>>> from transformers.image_utils import load_image

>>> # Note that passing the image urls (instead of the actual pil images) to the processor is also possible
>>> image1 = load_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg")
>>> image2 = load_image("https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg")
>>> image3 = load_image("https://cdn.britannica.com/68/170868-050-8DDE8263/Golden-Gate-Bridge-San-Francisco.jpg")

>>> processor = AutoProcessor.from_pretrained("HuggingFaceM4/idefics2-8b-base")
>>> model = AutoModelForVision2Seq.from_pretrained("HuggingFaceM4/idefics2-8b-base", device_map="auto")

>>> BAD_WORDS_IDS = processor.tokenizer(["<image>", "<fake_token_around_image>"], add_special_tokens=False).input_ids
>>> EOS_WORDS_IDS = [processor.tokenizer.eos_token_id]

>>> # Create inputs
>>> prompts = [
...   "<image>In this image, we can see the city of New York, and more specifically the Statue of Liberty.<image>In this image,",
...   "In which city is that bridge located?<image>",
... ]
>>> images = [[image1, image2], [image3]]
>>> inputs = processor(images=images, text=prompts, padding=True, return_tensors="pt").to("cuda")

>>> # Generate
>>> generated_ids = model.generate(**inputs, bad_words_ids=BAD_WORDS_IDS, max_new_tokens=20)
>>> generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)

>>> print(generated_texts)
['In this image, we can see the city of New York, and more specifically the Statue of Liberty. In this image, we can see the city of New York, and more specifically the Statue of Liberty.\n\n', 'In which city is that bridge located?\n\nThe bridge is located in the city of Pittsburgh, Pennsylvania.\n\n\nThe bridge is']

Idefics2ImageProcessor

class transformers.Idefics2ImageProcessor

< >

( do_convert_rgb: bool = True do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling = <Resampling.BILINEAR: 2> do_rescale: bool = True rescale_factor: float = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None do_pad: bool = True do_image_splitting: bool = False **kwargs )

参数

  • do_convert_rgb (bool, optional, defaults to True) — 是否将图像转换为 RGB 格式。 如果输入图像是其他格式(例如 RGBA),这将非常有用。 仅当输入图像为 PIL 格式时才有效。
  • do_resize (bool, optional, defaults to True) — 是否调整图像大小。 图像的最长边将被调整为 <= size["longest_edge"],最短边将被调整大小以保持输入宽高比,最小尺寸为 size["shortest_edge"]
  • size (Dict, optional) — 控制输出图像的大小。 这是一个字典,包含键 “shortest_edge” 和 “longest_edge”。
  • resample (Resampling, optional, defaults to Resampling.BILINEAR) — 调整图像大小时使用的重采样滤波器。
  • do_rescale (bool, optional, defaults to True) — 是否重新缩放图像。 如果设置为 True,图像将被重新缩放,使其像素值介于 0 和 1 之间。
  • rescale_factor (float, optional, defaults to 1/255) — 如果 do_rescale 设置为 True,则通过此缩放因子重新缩放图像。
  • do_normalize (bool, optional, defaults to True) — 是否标准化图像。 如果设置为 True,图像将被标准化为具有 image_mean 的均值和 image_std 的标准差。
  • image_mean (float or List[float], optional, defaults to IDEFICS_STANDARD_MEAN) — 如果标准化图像,则使用的均值。 这是一个浮点数或浮点数列表,其长度为图像中通道数。 可以通过 preprocess 方法中的 image_mean 参数覆盖。 可以通过 preprocess 方法中的 image_mean 参数覆盖。
  • image_std (float or List[float], optional, defaults to IDEFICS_STANDARD_STD) — 如果标准化图像,则使用的标准差。 这是一个浮点数或浮点数列表,其长度为图像中通道数。 可以通过 preprocess 方法中的 image_std 参数覆盖。 可以通过 preprocess 方法中的 image_std 参数覆盖。
  • do_pad (bool, optional, defaults to True) — 是否将批次中的图像填充到批次中最大高度和宽度,以及每个样本的图像数量,以便返回的张量形状为 (batch_size, max_num_images, num_channels, max_height, max_width)。
  • do_image_splitting (bool, optional, defaults to False) — 是否将图像分割成 4 个相等的子图像序列,并与原始图像连接。 该策略最初在 https://arxiv.org/abs/2311.06607 中引入。

构建 Idefics 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_convert_rgb: typing.Optional[bool] = None do_resize: typing.Optional[bool] = None size: typing.Optional[typing.Dict[str, int]] = None resample: Resampling = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None do_pad: typing.Optional[bool] = None do_image_splitting: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None input_data_format: typing.Optional[transformers.image_utils.ChannelDimension] = None data_format: typing.Optional[transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> )

参数

  • images (ImageInput) — 要预处理的图像列表。
  • do_convert_rgb (bool, optional, defaults to self.do_convert_rgb) — 是否将图像转换为 RGB 格式。
  • do_resize (bool, optional, defaults to self.do_resize) — 是否调整图像大小。
  • size (Dict[str, int], optional, defaults to self.size) — 调整大小后图像的尺寸。 图像的最短边将调整为 size[“shortest_edge”],最长边将调整大小以保持输入宽高比。
  • resample (int, optional, defaults to self.resample) — 如果调整图像大小,则使用的重采样滤波器。 这可以是枚举 PILImageResampling 之一。 仅当 do_resize 设置为 True 时才有效。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否重新缩放图像。
  • rescale_factor (float, optional, defaults to self.rescale_factor) — 如果 do_rescale 设置为 True,则通过此缩放因子重新缩放图像。
  • do_normalize (bool, optional, defaults to self.do_normalize) — 是否标准化图像。
  • image_mean (float or List[float], optional, defaults to self.image_mean) — 用于标准化的图像均值。 仅当 do_normalize 设置为 True 时才有效。
  • image_std (float or List[float], optional, defaults to self.image_std) — 用于标准化的图像标准差。 仅当 do_normalize 设置为 True 时才有效。
  • do_pad (bool, optional, defaults to self.do_pad) — 是否将批次中的图像填充到批次中最大高度和宽度。
  • do_image_splitting (bool, 可选, 默认为 self.do_image_splitting) — 是否将图像分割成 4 个相等的子图像序列,并与原始图像连接。该策略最初在 https://arxiv.org/abs/2311.06607 中引入。
  • return_tensors (strTensorType, 可选) — 返回的张量类型。可以是以下之一:
    • Unset: 返回 np.ndarray 列表。
    • TensorType.TENSORFLOW'tf': 返回 tf.Tensor 类型的批次。
    • TensorType.PYTORCH'pt': 返回 torch.Tensor 类型的批次。
    • TensorType.NUMPY'np': 返回 np.ndarray 类型的批次。
    • TensorType.JAX'jax': 返回 jax.numpy.ndarray 类型的批次。
  • data_format (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • Unset: 使用输入图像的通道维度格式。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,则通道维度格式从输入图像推断。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE: 图像格式为 (height, width)。

预处理一批图像。

Idefics2Processor

class transformers.Idefics2Processor

< >

( image_processor tokenizer = None image_seq_len: int = 64 chat_template: str = None **kwargs )

参数

  • image_processor (Idefics2ImageProcessor) — Idefics2ImageProcessor 的实例。图像处理器是必需的输入。
  • tokenizer (PreTrainedTokenizerBase, 可选) — PreTrainedTokenizerBase 的实例。这应该与模型的文本模型相对应。tokenizer 是必需的输入。
  • image_seq_len (int, 可选, 默认为 64) — 图像序列的长度,即输入中每个图像的 token 数量。此参数用于从输入提示和图像 token 构建字符串,并且应与所用模型的 config.perceiver_config.resampler_n_latents 值匹配。
  • chat_template (str, 可选) — Jinja 模板,将用于将聊天中的消息列表转换为可标记化的字符串。

构建一个 IDEFICS2 处理器,它将 LLama tokenizer 和 IDEFICS2 图像处理器包装到单个处理器中。

IdeficsProcessor 提供了 Idefics2ImageProcessorLlamaTokenizerFast 的所有功能。 有关更多信息,请参阅 call()decode() 的文档字符串。

__call__

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], typing.List[typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]], typing.List[typing.List[typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]]]] = None text: typing.Union[str, ForwardRef('PreTokenizedInput'), typing.List[str], typing.List[ForwardRef('PreTokenizedInput')]] = None audio = None videos = None **kwargs: typing_extensions.Unpack[transformers.models.idefics2.processing_idefics2.Idefics2ProcessorKwargs] )

参数

  • images (PIL.Image.Image, np.ndarray, torch.Tensor, List[PIL.Image.Image], List[np.ndarray], List[torch.Tensor], 可选) — 要准备的图像或图像批次。每个图像可以是 PIL 图像、NumPy 数组或 PyTorch 张量。如果是 List[ImageInput] 类型,则假定这是用于单个提示,即批次大小为 1。
  • text (Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]], 可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预标记化字符串)。如果序列以字符串列表(预标记化)的形式提供,则必须设置 is_split_into_words=True(以消除与序列批次的歧义)。

    每当遇到图像 token <image> 时,它都会扩展为 <fake_token_around_image> + <image> image_seq_len `。

  • return_tensors (Union[str, TensorType], 可选) — 如果设置,将返回特定框架的张量。有关更多信息,请参阅 PreTrainedTokenizerFast.call()

处理输入提示并返回 BatchEncoding。

示例

>>> import requests
>>> from transformers import Idefics2Processor
>>> from transformers.image_utils import load_image

>>> processor = Idefics2Processor.from_pretrained("HuggingFaceM4/idefics2-8b", image_seq_len=2)
>>> processor.image_processor.do_image_splitting = False  # Force as False to simplify the example

>>> url1 = "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
>>> url2 = "https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg"

>>> image1, image2 = load_image(url1), load_image(url2)
>>> images = [[image1], [image2]]

>>> text = [
...     "<image>In this image, we see",
...     "bla bla bla<image>",
... ]
>>> outputs = processor(images=images, text=text, return_tensors="pt", padding=True)
>>> input_ids = outputs.input_ids
>>> input_tokens = processor.tokenizer.batch_decode(input_ids)
>>> print(input_tokens)
['<s><fake_token_around_image><image><image><fake_token_around_image> In this image, we see', '<s> bla bla bla<fake_token_around_image><image><image><fake_token_around_image>']
< > Update on GitHub