Transformers documentation

InstructBLIP

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2023-05-11 在 HF papers 上发布,并于 2023-06-26 贡献至 Hugging Face Transformers。

FlashAttention SDPA

InstructBLIP

概述

InstructBLIP 模型由 Wenliang Dai、Junnan Li、Dongxu Li、Anthony Meng Huat Tiong、Junqi Zhao、Weisheng Wang、Boyang Li、Pascale Fung 和 Steven Hoi 在 InstructBLIP: Towards General-purpose Vision-Language Models with Instruction Tuning 中提出。 InstructBLIP 利用 BLIP-2 架构进行视觉指令微调。

该论文的摘要如下:

在预训练和指令微调流程的推动下,能够解决多种语言领域任务的通用语言模型应运而生。然而,由于额外的视觉输入引入了更大的任务差异,构建通用视觉-语言模型颇具挑战性。尽管视觉-语言预训练已被广泛研究,但视觉-语言指令微调仍相对较少被探索。在本文中,我们基于预训练的 BLIP-2 模型,对视觉-语言指令微调进行了系统且全面的研究。我们收集了 26 个公开数据集,将其转换为指令微调格式,并将其划分为两个集群,分别用于保留集内的指令微调和保留集外的零样本评估。此外,我们引入了指令感知的视觉特征提取,这是一种关键方法,使模型能够针对给定指令提取具有信息量的特征。所得的 InstructBLIP 模型在所有 13 个保留集外数据集上均达到了最先进的零样本性能,显著优于 BLIP-2 以及规模更大的 Flamingo。当在单个下游任务上进行微调时,我们的模型同样取得了最先进的性能(例如,在 ScienceQA IMG 上达到 90.7% 的准确率)。此外,我们还从定性角度展示了 InstructBLIP 相较于同期多模态模型的优势。

drawing InstructBLIP architecture. Taken from the original paper.

该模型由 nielsr 贡献。 原始代码可在此处找到。

使用技巧

InstructBLIP 采用与 BLIP-2 相同的架构,但有一个微小却重要的区别:它还会将文本提示(指令)输入到 Q-Former 中。

在 v4.46 版本发布后,BLIP 模型将发出警告,提示需要添加 processor.num_query_tokens = {{num_query_tokens}} 并扩展模型嵌入层以添加特殊的 <image> 标记。如果您拥有该模型检查点,强烈建议为处理器添加这些属性;如果该检查点不属于您,则建议提交一个 PR。添加这些属性意味着 BLIP 将添加每张图像所需的查询标记数量,并扩展文本,使其包含与查询标记数量相同数量的 <image> 占位符。通常每张图像大约需要 500 个标记,因此请确保文本未被截断,否则在合并嵌入时将会失败。 这些属性可以从模型配置中获取,即 model.config.num_query_tokens,而模型嵌入的扩展可以按照 此链接 中的说明进行操作。

InstructBlipConfig

class transformers.InstructBlipConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneqformer_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonenum_query_tokens: int = 32image_token_index: int | None = Noneinitializer_factor: float = 1.0initializer_range: float = 0.02 )

参数

  • vision_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 视觉骨干网络的配置对象或字典。
  • qformer_config (dict, 可选) — 用于初始化 InstructBlipQFormerConfig 的配置选项字典。
  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 文本骨干网络的配置对象或字典。
  • num_query_tokens (int,可选,默认为 32) — 通过 Transformer 传递的查询 token 数量。
  • image_token_index (int, 可选) — 用作输入图像占位符的图像 token 索引。
  • initializer_factor (float,可选,默认为 1.0) — 用于初始化所有权重矩阵的系数(应保持为 1,内部用于初始化测试)。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

这是用于存储 InstructBlipModel 配置的类。它根据指定的参数实例化 Instructblip 模型,并定义模型架构。使用默认值实例化配置,将得到与 Salesforce/instructblip-flan-t5-xl 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例:

>>> from transformers import (
...     InstructBlipVisionConfig,
...     InstructBlipQFormerConfig,
...     OPTConfig,
...     InstructBlipConfig,
...     InstructBlipForConditionalGeneration,
... )

>>> # Initializing a InstructBlipConfig with Salesforce/instructblip-flan-t5-xl style configuration
>>> configuration = InstructBlipConfig()

>>> # Initializing a InstructBlipForConditionalGeneration (with random weights) from the Salesforce/instructblip-flan-t5-xl style configuration
>>> model = InstructBlipForConditionalGeneration(configuration)

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

>>> # We can also initialize a InstructBlipConfig from a InstructBlipVisionConfig, InstructBlipQFormerConfig and any PreTrainedConfig

>>> # Initializing InstructBLIP vision, InstructBLIP Q-Former and language model configurations
>>> vision_config = InstructBlipVisionConfig()
>>> qformer_config = InstructBlipQFormerConfig()
>>> text_config = OPTConfig()

>>> config = InstructBlipConfig(vision_config=vision_config, qformer_config=qformer_config, text_config=text_config)

InstructBlipVisionConfig

class transformers.InstructBlipVisionConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 1408intermediate_size: int = 6144num_hidden_layers: int = 39num_attention_heads: int = 16image_size: int | list[int] | tuple[int, int] = 224patch_size: int | list[int] | tuple[int, int] = 14hidden_act: str = 'gelu'layer_norm_eps: float = 1e-06attention_dropout: float | int = 0.0initializer_range: float = 1e-10qkv_bias: bool = True )

参数

  • hidden_size (int,可选,默认为 1408) — 隐藏表示的维度。
  • intermediate_size (int,可选,默认为 6144) — MLP 表示的维度。
  • num_hidden_layers (int,可选,默认为 39) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 16) — Transformer 解码器中每个注意力层的注意力头数量。
  • image_size (Union[int, list[int], tuple[int, int]],可选,默认为 224) — 每张图片的尺寸(分辨率)。
  • patch_size (Union[int, list[int], tuple[int, int]],可选,默认为 14) — 每个 patch 的大小(分辨率)。
  • hidden_act (str,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • layer_norm_eps (float,可选,默认为 1e-06) — 层归一化层所使用的 epsilon 值。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • initializer_range (float,可选,默认为 1e-10) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • qkv_bias (bool,可选,默认为 True) — 是否向查询、键和值添加偏置。

这是用于存储 InstructBlipModel 配置的类。它根据指定的参数实例化 Instructblip 模型,并定义模型架构。使用默认值实例化配置,将得到与 Salesforce/instructblip-flan-t5-xl 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例:

>>> from transformers import InstructBlipVisionConfig, InstructBlipVisionModel

>>> # Initializing a InstructBlipVisionConfig with Salesforce/instructblip-flan-t5-xl style configuration
>>> configuration = InstructBlipVisionConfig()

>>> # Initializing a InstructBlipVisionModel (with random weights) from the Salesforce/instructblip-flan-t5-xl style configuration
>>> model = InstructBlipVisionModel(configuration)

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

InstructBlipQFormerConfig

class transformers.InstructBlipQFormerConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevocab_size: int = 30522hidden_size: int = 768num_hidden_layers: int = 12num_attention_heads: int = 12intermediate_size: int = 3072hidden_act: str = 'gelu'hidden_dropout_prob: float | int = 0.1attention_probs_dropout_prob: float | int = 0.1max_position_embeddings: int = 512initializer_range: float = 0.02layer_norm_eps: float = 1e-12pad_token_id: int | None = 0cross_attention_frequency: int = 2encoder_hidden_size: int = 1408 )

参数

  • vocab_size (int,可选,默认为 30522) — 模型的词汇表大小。定义了 input_ids 可以表示的不同 token 数量。
  • hidden_size (int,可选,默认为 768) — 隐藏表示的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 12) — Transformer 解码器中每个注意力层的注意力头数量。
  • intermediate_size (int,可选,默认为 3072) — MLP 表示的维度。
  • hidden_act (str,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • hidden_dropout_prob (Union[float, int],可选,默认为 0.1) — 嵌入层、编码器和池化层中所有全连接层的 dropout 概率。
  • attention_probs_dropout_prob (Union[float, int],可选,默认为 0.1) — 注意力概率的 dropout 比率。
  • max_position_embeddings (int,可选,默认为 512) — 该模型可能使用的最大序列长度。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float,可选,默认为 1e-12) — 层归一化层所使用的 epsilon 值。
  • pad_token_id (int, 可选,默认为 0) — 词表中用于填充的 token id。
  • cross_attention_frequency (int,可选,默认为 2) — 在 Transformer 层中添加交叉注意力的频率。
  • encoder_hidden_size (int,可选,默认为 1408) — 交叉注意力中隐藏状态的隐藏层大小。

这是用于存储 InstructBlipModel 配置的类。它根据指定的参数实例化 Instructblip 模型,并定义模型架构。使用默认值实例化配置,将得到与 Salesforce/instructblip-flan-t5-xl 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例:

>>> from transformers import InstructBlipQFormerConfig, InstructBlipQFormerModel

>>> # Initializing a InstructBLIP Salesforce/instructblip-flan-t5-xl style configuration
>>> configuration = InstructBlipQFormerConfig()

>>> # Initializing a model (with random weights) from the Salesforce/instructblip-flan-t5-xl style configuration
>>> model = InstructBlipQFormerModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config

InstructBlipProcessor

class transformers.InstructBlipProcessor

< >

( image_processortokenizerqformer_tokenizernum_query_tokens = None**kwargs )

参数

  • image_processor (BlipImageProcessor) — 图像处理器是必需的输入。
  • tokenizer (GPT2Tokenizer) — 分词器是必需的输入。
  • qformer_tokenizer (AutoTokenizer) — [‘PreTrainedTokenizer`] 的一个实例。Q-Former 分词器是必需的输入。
  • num_query_tokens (int, 可选) — ” Qformer 用作查询的 token 数量,应与模型配置中的值相同。

构建一个 InstructBlipProcessor,它将图像处理器、分词器和 qformer 分词器封装为单一处理器。

InstructBlipProcessor 提供了 BlipImageProcessor、GPT2Tokenizer 和 {qformer_tokenizer_class} 的所有功能。有关更多信息,请参阅 ~BlipImageProcessor、~GPT2Tokenizer 和 ~{qformer_tokenizer_class}。

__call__

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonetext: str | list[str] | list[list[str]] = None**kwargs: *<class 'transformers.models.instructblip.processing_instructblip.InstructBlipProcessorKwargs'> ) → ~image_processing_base.BatchFeature

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], 可选) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False。
  • text (Union[str, list[str], list[list[str]]],可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果传入预分词输入,请设置 is_split_into_words=True,以避免与批量输入产生歧义。
  • return_tensors (str 或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。
  • **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。

返回值

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

InstructBlipVisionModel

class transformers.InstructBlipVisionModel

< >

( config: InstructBlipVisionConfig )

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = Noneinterpolate_pos_encoding: bool = False**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 BlipImageProcessor 获取像素值。有关详细信息,请参阅 BlipImageProcessor.call()(InstructBlipProcessor 使用 BlipImageProcessor 处理图像)。
  • interpolate_pos_encoding (bool,可选,默认为 False) — 是否对预训练的位置编码进行插值。

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(InstructBlipConfig)和输入。

InstructBlipVisionModel 的 forward 方法重写了 __call__ 特殊方法。

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

  • last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor)— 模型最后一层输出的隐藏状态序列。

  • pooler_output (torch.Tensor,形状为 (batch_size, hidden_size)) — 序列中第一个 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 之后的权重,用于在自注意力头中计算加权平均值。

InstructBlipQFormerModel

类 transformers.InstructBlipQFormerModel

< >

( config: InstructBlipQFormerConfig )

Querying Transformer (Q-Former),用于 InstructBLIP。与 BLIP-2 略有不同,因为它还将指令作为输入。

forward

< >

( input_ids: LongTensorattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonequery_embeds: typing.Optional[torch.Tensor] = Noneencoder_hidden_states: typing.Optional[torch.Tensor] = Noneencoder_attention_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPoolingAndCrossAttentions or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length)) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

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

    什么是输入 ID?

  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • query_embeds (torch.Tensor,形状为 (batch_size, sequence_length, hidden_size)) — 用于注意力计算的隐藏状态。如果是交叉注意力,将用作查询(即键和值将使用 encoder_hidden_states)。
  • encoder_hidden_states (torch.Tensor,形状为 (batch_size, sequence_length, hidden_size),可选) — 编码器最后一层输出的隐藏状态序列。如果模型被配置为解码器,则用于交叉注意力。
  • encoder_attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), 可选) — 用于避免对编码器输入中的填充 token 索引执行注意力机制的掩码。如果模型被配置为解码器,此掩码将用于交叉注意力。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

返回值

BaseModelOutputWithPoolingAndCrossAttentions 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPoolingAndCrossAttentions 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(InstructBlipConfig)和输入。

InstructBlipQFormerModel 的 forward 方法重写了 __call__ 特殊方法。

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

  • last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor)— 模型最后一层输出的隐藏状态序列。

  • pooler_output (torch.Tensor,形状为 (batch_size, hidden_size)) — 序列中第一个 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 之后的权重,用于在自注意力头中计算加权平均值。

  • cross_attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 且 config.add_cross_attention=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 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值,以及如果 config.is_encoder_decoder=True 则还包括交叉注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

InstructBlipModel

class transformers.InstructBlipModel

< >

( config: InstructBlipConfig )

参数

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

InstructBLIP 基础模型,由语言模型、qformer 和视觉编码器组成。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( pixel_values: Tensorqformer_input_ids: Tensorqformer_attention_mask: typing.Optional[torch.LongTensor] = Noneinput_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneinterpolate_pos_encoding: bool = False**kwargs: *<class 'transformers.modeling_flash_attention_utils.FlashAttentionKwargs'> ) → InstructBlipForConditionalGenerationModelOutput or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 BlipImageProcessor 获取像素值。有关详细信息,请参阅 BlipImageProcessor.call()(InstructBlipProcessor 使用 BlipImageProcessor 处理图像)。
  • qformer_input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — Q-Former 词表中输入序列 token 的索引。可选择性地提供输入 token 作为文本提示,Q-Former 模型将对其进行编码。

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

    什么是输入 ID?

  • qformer_attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • input_ids (torch.Tensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中各 token 在词表中的索引。默认情况下,填充(padding)将被忽略。

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

    什么是输入 ID?

  • attention_mask (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充(padding)标记索引执行注意力机制的掩码。掩码值取自 [0, 1]:1 表示未屏蔽的标记,0 表示被屏蔽的标记。什么是注意力掩码? [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • decoder_input_ids (torch.LongTensor 形状为 (batch_size, target_sequence_length), ,可选) — 解码器输入序列中各 token 在词汇表中的索引。可通过 AutoTokenizer 获取索引。详情请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。什么是解码器输入 ID?

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

    什么是解码器输入 ID?

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

    仅在使用编码器-解码器语言模型(如 T5)时相关。

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • interpolate_pos_encoding (bool,可选,默认为 False) — 是否对预训练的位置编码进行插值。

返回值

InstructBlipForConditionalGenerationModelOutput 或 tuple(torch.Tensor)

InstructBlipForConditionalGenerationModelOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(InstructBlipConfig)和输入。

InstructBlipModel 的 forward 方法重写了 __call__ 特殊方法。

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

  • loss (torch.Tensor,可选,当提供 labels 时返回,形状为 (1,) 的 torch.Tensor) — 来自语言模型的语言建模损失。
  • logits(形状为 (batch_size, sequence_length, config.vocab_size) 的 torch.Tensor)— 语言模型的语言建模头的预测分数。
  • vision_outputs (~modeling_outputs.BaseModelOutputWithPooling,可选) — 视觉编码器的输出。
  • qformer_outputs (~modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions,可选) — Q-Former(Querying Transformer)的输出。
  • language_model_outputs(CausalLMOutputWithPast 或 Seq2SeqLMOutput)—— 语言模型的输出。

get_placeholder_mask

< >

( input_ids: LongTensorinputs_embeds: Tensor )

从 input_ids 或 inputs_embeds 中获取多模态占位符掩码。

InstructBlipForConditionalGeneration

class transformers.InstructBlipForConditionalGeneration

< >

( config: InstructBlipConfig )

参数

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

InstructBLIP 模型用于根据图像和可选的文本提示生成文本。该模型由视觉编码器、Querying Transformer (Q-Former) 和语言模型组成。

可以选择向模型传入 input_ids 作为文本提示,让语言模型继续生成该提示的内容。否则,语言模型将从 [BOS](序列起始)标记开始生成文本。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( pixel_values: Tensorqformer_input_ids: Tensorqformer_attention_mask: typing.Optional[torch.LongTensor] = Noneinput_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneinterpolate_pos_encoding: bool = Falsemm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → InstructBlipForConditionalGenerationModelOutput or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 BlipImageProcessor 获取像素值。有关详细信息,请参阅 BlipImageProcessor.call()(InstructBlipProcessor 使用 BlipImageProcessor 处理图像)。
  • qformer_input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — Q-Former 词表中输入序列 token 的索引。可选择性地提供输入 token 作为文本提示,Q-Former 模型将对其进行编码。

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

    什么是输入 ID?

  • qformer_attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • input_ids (torch.Tensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中各 token 在词表中的索引。默认情况下,填充(padding)将被忽略。

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

    什么是输入 ID?

  • attention_mask (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充(padding)标记索引执行注意力机制的掩码。掩码值取自 [0, 1]:1 表示未屏蔽的标记,0 表示被屏蔽的标记。什么是注意力掩码? [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • decoder_input_ids (torch.LongTensor 形状为 (batch_size, target_sequence_length), ,可选) — 解码器输入序列中各 token 在词汇表中的索引。可通过 AutoTokenizer 获取索引。详情请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。什么是解码器输入 ID?

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

    什么是解码器输入 ID?

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

    仅在使用编码器-解码器语言模型(如 T5)时相关。

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • labels(形状为 (batch_size,) 的 torch.LongTensor,可选) — 用于计算语言建模损失的标签。索引应在 [-100, 0, ..., config.vocab_size - 1] 范围内。所有设置为 -100 的标签都会被忽略(被掩码),损失仅针对 [0, ..., config.vocab_size] 范围内的标签进行计算。
  • interpolate_pos_encoding (bool,可选,默认为 False) — 是否对预训练的位置编码进行插值。
  • mm_encoder_outputs (dict[str, ~modeling_outputs.BaseModelOutputWithPooling], 可选) — 一个字典,其中键为支持的模态,值为该模态的编码输出。每个编码输出是一个元组,由 (pooler_output、可选:last_hidden_states、可选:hidden_states、可选:attentions) pooler_output,形状为 (batch_size, sequence_length, hidden_size),可选) 组成,它是编码器融合到文本嵌入中的多模态特征序列。

返回值

InstructBlipForConditionalGenerationModelOutput 或 tuple(torch.Tensor)

InstructBlipForConditionalGenerationModelOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(InstructBlipConfig)和输入。

InstructBlipForConditionalGeneration 的 forward 方法重写了 __call__ 特殊方法。

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

  • loss (torch.Tensor,可选,当提供 labels 时返回,形状为 (1,) 的 torch.Tensor) — 来自语言模型的语言建模损失。
  • logits(形状为 (batch_size, sequence_length, config.vocab_size) 的 torch.Tensor)— 语言模型的语言建模头的预测分数。
  • vision_outputs (~modeling_outputs.BaseModelOutputWithPooling,可选) — 视觉编码器的输出。
  • qformer_outputs (~modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions,可选) — Q-Former(Querying Transformer)的输出。
  • language_model_outputs(CausalLMOutputWithPast 或 Seq2SeqLMOutput)—— 语言模型的输出。

示例:

>>> from transformers import InstructBlipProcessor, InstructBlipForConditionalGeneration
>>> import torch
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> model = InstructBlipForConditionalGeneration.from_pretrained("Salesforce/instructblip-vicuna-7b")
>>> processor = InstructBlipProcessor.from_pretrained("Salesforce/instructblip-vicuna-7b")

>>> device = "cuda" if torch.cuda.is_available() else "cpu"
>>> model.to(device)
>>> url = "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/lavis_confusing_pictures.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read())).convert("RGB")
>>> prompt = "What is unusual about this image?"
>>> inputs = processor(images=image, text=prompt, return_tensors="pt").to(device)

>>> outputs = model.generate(
...     **inputs,
...     do_sample=False,
...     num_beams=5,
...     max_length=256,
...     min_length=1,
...     top_p=0.9,
...     repetition_penalty=1.5,
...     length_penalty=1.0,
...     temperature=1,
... )
>>> generated_text = processor.batch_decode(outputs, skip_special_tokens=True)[0].strip()
>>> print(generated_text)
The unusual aspect of this image is that a man is ironing clothes on the back of a yellow SUV, which is parked in the middle of a busy city street. This is an unconventional approach to ironing clothes, as it requires the man to balance himself and his ironing equipment on top of the vehicle while navigating through traffic. Additionally, the presence of taxis and other vehicles in the scene further emphasizes the unusual nature of this situation.

generate

< >

( pixel_values: Tensorqformer_input_ids: typing.Optional[torch.LongTensor] = Noneqformer_attention_mask: typing.Optional[torch.LongTensor] = Noneinput_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneinterpolate_pos_encoding: bool = False**generate_kwargs ) → captions (list)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, height, width)) — 要处理的输入图像。
  • qformer_input_ids (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用作提示并输入到 Q-Former 模块的序列。
  • qformer_attention_mask (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于避免对填充(padding)token 索引执行注意力机制的掩码。
  • input_ids(形状为 (batch_size, sequence_length) 的 torch.LongTensor,可选) — 用作生成提示的序列。
  • attention_mask (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于避免在填充 token 索引上执行注意力的掩码。
  • inputs_embeds (torch.Tensor,形状为 (batch_size, sequence_length, hidden_size)) — 输入的嵌入表示。应为浮点数,而非整数 token。
  • interpolate_pos_encoding (bool,可选,默认为 False) — 是否对图像嵌入的位置编码进行插值。

返回值

captions(列表)

一个长度为 batch_size * num_captions 的字符串列表。

重写 generate 函数,以便将模型用作条件生成器。

get_image_features

< >

( pixel_values: Tensorqformer_input_ids: LongTensorqformer_attention_mask: typing.Optional[torch.LongTensor] = Noneinterpolate_pos_encoding: bool | None = False**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithVisionQformerOutputs or tuple(torch.Tensor)

参数

  • pixel_values(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor)— 与输入图像对应的张量。
  • qformer_input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — Q-Former 词表中输入序列 token 的索引。可选择性地提供输入 token 作为文本提示,Q-Former 模型将对其进行编码。

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

    什么是输入 ID?

  • qformer_attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • interpolate_pos_encoding (bool,可选,默认为 False) — 是否对预训练的位置编码进行插值。

返回值

BaseModelOutputWithVisionQformerOutputs 或 tuple(torch.Tensor)

BaseModelOutputWithVisionQformerOutputs 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(InstructBlipConfig)和输入。

  • last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor)— 模型最后一层输出的隐藏状态序列。

  • pooler_output (torch.Tensor,形状为 (batch_size, hidden_size)) — 序列中第一个 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 之后的权重,用于在自注意力头中计算加权平均值。

  • vision_outputs (~modeling_outputs.BaseModelOutputWithPooling,可选) — 视觉编码器的输出。

  • qformer_outputs (~modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions,可选) — Q-Former(Querying Transformer)的输出。

示例:

>>> from PIL import Image
>>> from transformers import AutoProcessor, InstructBlipForConditionalGeneration

>>> model = InstructBlipForConditionalGeneration.from_pretrained("Salesforce/instructblip-flan-t5-xl")
>>> processor = AutoProcessor.from_pretrained("Salesforce/instructblip-flan-t5-xl")

>>> messages = [
...     {
...         "role": "user", "content": [
...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
...             {"type": "text", "text": "Where is the cat standing?"},
...         ]
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     return_dict=True,
...     return_tensors="pt",
...     add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]
Update on GitHub