# InstructBlipVideo

## 概述

InstructBLIPVideo 是 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](https://huggingface.co/papers/2305.06500) 中提出的模型的扩展。InstructBLIPVideo 采用与 [InstructBLIP](instructblip) 相同的架构，并使用与 [InstructBLIP](instructblip) 相同的检查点。唯一的区别在于其具备处理视频的能力。

该论文的摘要如下：

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

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/instructblip_architecture.jpg"
alt="drawing" width="600"/>

 InstructBLIPVideo 架构。摘自原始论文。

该模型由 [RaushanTurganbay](https://huggingface.co/RaushanTurganbay) 贡献。原始代码可在[此处](https://github.com/salesforce/LAVIS/tree/main/projects/instructblip)找到。

## 使用技巧

- 该模型在训练时每个视频采样 4 帧，因此建议采样 4 帧

> [!NOTE]
> 在 v4.46 版本发布后，BLIP 模型将发出警告，提示需要添加 `processor.num_query_tokens = {{num_query_tokens}}` 并扩展模型嵌入层以添加特殊的 `<image>` 标记。如果您拥有该模型检查点，强烈建议为处理器添加这些属性；如果检查点不属于您，则建议提交一个 PR。添加这些属性意味着 BLIP 将为每张图片添加所需数量的查询标记，并根据查询标记的数量在文本中扩展相应数量的 `<image>` 占位符。通常每张图片大约需要 500 个标记，因此请确保文本未被截断，否则在合并嵌入时将会失败。
这些属性可以从模型配置中获取，例如 `model.config.num_query_tokens`，而模型嵌入的扩展可以按照 [此链接](https://gist.github.com/zucchini-nlp/e9f20b054fa322f84ac9311d9ab67042) 进行操作。

## InstructBlipVideoConfig[[transformers.InstructBlipVideoConfig]]

#### transformers.InstructBlipVideoConfig[[transformers.InstructBlipVideoConfig]]

```python
transformers.InstructBlipVideoConfig(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, vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, qformer_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, num_query_tokens: int = 32, initializer_factor: float = 1.0, initializer_range: float = 0.02, video_token_index: int | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py#L109)

**参数：**

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

qformer_config (`dict`, *可选*) : 用于初始化 [InstructBlipVideoQFormerConfig](/docs/transformers/main/zh/model_doc/instructblipvideo#transformers.InstructBlipVideoQFormerConfig) 的配置选项字典。

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

num_query_tokens (`int`，*可选*，默认为 32)：通过 Transformer 传递的查询 token 数量。

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

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

video_token_index (`int`, *可选*) : 用作输入视频占位符的视频标记索引。

这是用于存储 InstructBlipVideoModel 配置的类。它根据指定的参数实例化 Instructblipvideo 模型，并定义模型架构。使用默认值实例化配置，将得到与 [Salesforce/instructblip-flan-t5-xl](https://huggingface.co/Salesforce/instructblip-flan-t5-xl) 类似的配置。

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

示例：

```python
>>> from transformers import (
...     InstructBlipVideoVisionConfig,
...     InstructBlipVideoQFormerConfig,
...     OPTConfig,
...     InstructBlipVideoConfig,
...     InstructBlipVideoForConditionalGeneration,
... )

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

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

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

>>> # We can also initialize a InstructBlipVideoConfig from a InstructBlipVideoVisionConfig, InstructBlipVideoQFormerConfig and any PreTrainedConfig

>>> # Initializing Instructblipvideo vision, Instructblipvideo Q-Former and language model configurations
>>> vision_config = InstructBlipVideoVisionConfig()
>>> qformer_config = InstructBlipVideoQFormerConfig()
>>> text_config = OPTConfig()

>>> config = InstructBlipVideoConfig(vision_config=vision_config, qformer_config=qformer_config, text_config=text_config)
```

## InstructBlipVideoVisionConfig[[transformers.InstructBlipVideoVisionConfig]]

#### transformers.InstructBlipVideoVisionConfig[[transformers.InstructBlipVideoVisionConfig]]

```python
transformers.InstructBlipVideoVisionConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_size: int = 1408, intermediate_size: int = 6144, num_hidden_layers: int = 39, num_attention_heads: int = 16, image_size: int | list[int] | tuple[int, int] = 224, patch_size: int | list[int] | tuple[int, int] = 14, hidden_act: str = 'gelu', layer_norm_eps: float = 1e-06, attention_dropout: float | int = 0.0, initializer_range: float = 1e-10, qkv_bias: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py#L32)

**参数：**

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`)：是否向查询、键和值添加偏置。

这是用于存储 InstructBlipVideoModel 配置的类。它根据指定的参数实例化 Instructblipvideo 模型，并定义模型架构。使用默认值实例化配置，将得到与 [Salesforce/instructblip-flan-t5-xl](https://huggingface.co/Salesforce/instructblip-flan-t5-xl) 类似的配置。

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

示例：

```python
>>> from transformers import InstructBlipVideoVisionConfig, InstructBlipVideoVisionModel

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

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

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

## InstructBlipVideoQFormerConfig[[transformers.InstructBlipVideoQFormerConfig]]

#### transformers.InstructBlipVideoQFormerConfig[[transformers.InstructBlipVideoQFormerConfig]]

```python
transformers.InstructBlipVideoQFormerConfig(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 = 30522, hidden_size: int = 768, num_hidden_layers: int = 12, num_attention_heads: int = 12, intermediate_size: int = 3072, hidden_act: str = 'gelu', hidden_dropout_prob: float | int = 0.1, attention_probs_dropout_prob: float | int = 0.1, max_position_embeddings: int = 512, initializer_range: float = 0.02, layer_norm_eps: float = 1e-12, pad_token_id: int | None = 0, cross_attention_frequency: int = 2, encoder_hidden_size: int = 1408)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py#L67)

**参数：**

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)：交叉注意力中隐藏状态的隐藏层大小。

这是用于存储 InstructBlipVideoModel 配置的类。它根据指定的参数实例化 Instructblipvideo 模型，并定义模型架构。使用默认值实例化配置，将得到与 [Salesforce/instructblip-flan-t5-xl](https://huggingface.co/Salesforce/instructblip-flan-t5-xl) 类似的配置。

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

示例：

```python
>>> from transformers import InstructBlipVideoQFormerConfig, InstructBlipVideoQFormerModel

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

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

## InstructBlipVideoProcessor[[transformers.InstructBlipVideoProcessor]]

#### transformers.InstructBlipVideoProcessor[[transformers.InstructBlipVideoProcessor]]

```python
transformers.InstructBlipVideoProcessor(video_processor, tokenizer, qformer_tokenizer, num_query_tokens = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblipvideo/processing_instructblipvideo.py#L35)

**参数：**

video_processor (`InstructBlipVideoVideoProcessor`)：视频处理器是必需的输入。

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

qformer_tokenizer (`AutoTokenizer`)：['PreTrainedTokenizer`'] 的一个实例。Q-Former 分词器是必需的输入。

num_query_tokens (`int`, *可选*) : Qformer 用作查询的 token 数量，应与模型配置中的值相同。

构造一个 InstructBlipVideoProcessor，它将视频处理器、分词器和 qformer 分词器封装为单一处理器。

[InstructBlipVideoProcessor](/docs/transformers/main/zh/model_doc/instructblipvideo#transformers.InstructBlipVideoProcessor) 提供了 [InstructBlipVideoVideoProcessor](/docs/transformers/main/zh/model_doc/instructblipvideo#transformers.InstructBlipVideoVideoProcessor)、[GPT2Tokenizer](/docs/transformers/main/zh/model_doc/gpt2#transformers.GPT2Tokenizer) 和 `{qformer_tokenizer_class}` 的所有功能。有关更多信息，请参阅 [~InstructBlipVideoVideoProcessor](/docs/transformers/main/zh/model_doc/instructblipvideo#transformers.InstructBlipVideoVideoProcessor)、[~GPT2Tokenizer](/docs/transformers/main/zh/model_doc/gpt2#transformers.GPT2Tokenizer) 和 `~{qformer_tokenizer_class}`。

## InstructBlipVideoVideoProcessor[[transformers.InstructBlipVideoVideoProcessor]]

#### transformers.InstructBlipVideoVideoProcessor[[transformers.InstructBlipVideoVideoProcessor]]

```python
transformers.InstructBlipVideoVideoProcessor(**kwargs: *<class 'transformers.processing_utils.VideosKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblipvideo/video_processing_instructblipvideo.py#L30)

**参数：**

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' : 384, 'width': 384}`)：描述输入到模型的最大尺寸。

default_to_square (`bool`，*kwargs*，*可选*，默认为 `True`)：当 size 为整数时，是否在调整大小时默认使用正方形图像。

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_center_crop (`bool`, *kwargs*, *可选*) : 是否对图像进行居中裁剪。

do_pad (`bool`, *kwargs*, *可选*) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 应用 `center_crop` 后输出图像的尺寸。

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*)：用于处理视频的设备。如果未设置，则从输入视频中推断设备。

do_sample_frames (`bool`, *kwargs*, *可选*，默认为 `False`)：是否在处理前从视频中采样帧，还是处理整个视频。

video_metadata (`Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None]`, *kwargs*) : 视频的元数据，包含总时长、帧率（fps）和总帧数等信息。该元数据将用于从视频中采样帧或计算时间戳。除非您打算在预处理之前手动解码视频，否则请勿传入任何元数据。

fps (`Annotated[int | float | None, None]`, *kwargs*) : 当 `do_sample_frames=True` 时，每秒采样的目标帧数。

num_frames (`Annotated[int | None, None]`, *kwargs*) : 当 `do_sample_frames=True` 时，要采样的最大帧数。

return_metadata (`bool`, *kwargs*, *可选*，默认为 `False`) : 是否返回视频元数据。视频元数据是一个包含视频时长、帧率、解码后端等信息的对象。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 如果设置，将返回特定框架的张量。可接受的值为： - `'pt'`：返回 PyTorch `torch.Tensor` 对象。 - `'np'`：返回 NumPy `np.ndarray` 对象。

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

构造一个 InstructBlipVideoVideoProcessor 视频处理器。

#### preprocess[[transformers.InstructBlipVideoVideoProcessor.preprocess]]

```python
preprocess(videos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]]], **kwargs: *<class 'transformers.processing_utils.VideosKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/video_processing_utils.py#L98)

**参数：**

videos (`Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]]`) : 待预处理的视频。期望输入单个视频或一批视频，其像素值范围为 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 时，是否在调整大小时默认使用正方形图像。

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_center_crop (`bool`, *kwargs*, *可选*) : 是否对图像进行居中裁剪。

do_pad (`bool`, *kwargs*, *可选*) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 应用 `center_crop` 后输出图像的尺寸。

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*)：用于处理视频的设备。如果未设置，则从输入视频中推断设备。

do_sample_frames (`bool`, *kwargs*, *可选*) : 是否在处理前从视频中采样帧，还是处理整个视频。

video_metadata (`Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None]`, *kwargs*) : 视频的元数据，包含总时长、帧率（fps）和总帧数等信息。该元数据将用于从视频中采样帧或计算时间戳。除非您打算在预处理之前手动解码视频，否则请勿传入任何元数据。

fps (`Annotated[int | float | None, None]`, *kwargs*) : 当 `do_sample_frames=True` 时，每秒采样的目标帧数。

num_frames (`Annotated[int | None, None]`, *kwargs*) : 当 `do_sample_frames=True` 时，要采样的最大帧数。

return_metadata (`bool`, *kwargs*, *可选*) : 是否返回视频元数据。视频元数据是一个包含视频时长、帧率、解码后端等信息的对象。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

**返回：** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- 由 __call__ 方法返回的列表/数组/张量字典（例如 'pixel_values'）。
- **tensor_type** (`Union[None, str, TensorType]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

## InstructBlipVideoVisionModel[[transformers.InstructBlipVideoVisionModel]]

#### transformers.InstructBlipVideoVisionModel[[transformers.InstructBlipVideoVisionModel]]

```python
transformers.InstructBlipVideoVisionModel(config: InstructBlipVideoVisionConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py#L393)

#### forward[[transformers.InstructBlipVideoVisionModel.forward]]

```python
forward(pixel_values: typing.Optional[torch.Tensor] = None, interpolate_pos_encoding: bool = False, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py#L413)

**参数：**

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

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

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

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

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

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

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

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

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

## InstructBlipVideoQFormerModel[[transformers.InstructBlipVideoQFormerModel]]

#### transformers.InstructBlipVideoQFormerModel[[transformers.InstructBlipVideoQFormerModel]]

```python
transformers.InstructBlipVideoQFormerModel(config: InstructBlipVideoQFormerConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py#L708)

用于 InstructBlipVideo 的 Querying Transformer (Q-Former)。由于它还将指令作为输入，因此对 BLIP-2 进行了略微修改。

#### forward[[transformers.InstructBlipVideoQFormerModel.forward]]

```python
forward(input_ids: LongTensor, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, query_embeds: typing.Optional[torch.Tensor] = None, encoder_hidden_states: typing.Optional[torch.Tensor] = None, encoder_attention_mask: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py#L746)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`)：输入序列词元在词汇表中的索引。默认情况下，填充部分将被忽略。可以使用 [AutoTokenizer](/docs/transformers/main/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#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)

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)`，*可选*)：用于避免对编码器输入中填充标记索引执行注意力机制的掩码。如果模型被配置为解码器，此掩码将用于交叉注意力。在 `[0, 1]` 中选择的掩码值： - 对于**未掩码**的标记，值为 1； - 对于**已掩码**的标记，值为 0。

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

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

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

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

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

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

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

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

## InstructBlipVideoModel[[transformers.InstructBlipVideoModel]]

#### transformers.InstructBlipVideoModel[[transformers.InstructBlipVideoModel]]

```python
transformers.InstructBlipVideoModel(config: InstructBlipVideoConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py#L849)

**参数：**

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

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

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.InstructBlipVideoModel.forward]]

```python
forward(pixel_values: Tensor, qformer_input_ids: Tensor, qformer_attention_mask: typing.Optional[torch.LongTensor] = None, input_ids: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.LongTensor] = None, decoder_input_ids: typing.Optional[torch.LongTensor] = None, decoder_attention_mask: typing.Optional[torch.LongTensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, interpolate_pos_encoding: bool = False, use_cache: bool | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py#L901)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 `image_processor_class` 获取像素值。有关详细信息，请参阅 `image_processor_class.__call__`（[InstructBlipVideoProcessor](/docs/transformers/main/zh/model_doc/instructblipvideo#transformers.InstructBlipVideoProcessor) 使用 `image_processor_class` 处理图像）。

qformer_input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列词元在 Q-Former 词汇表中的索引。可选择性地提供输入词元作为文本提示，Q-Former 模型将对其进行编码。可使用 [InstructBlipVideoProcessor](/docs/transformers/main/zh/model_doc/instructblipvideo#transformers.InstructBlipVideoProcessor) 获取索引。有关详细信息，请参阅 `InstructBlipVideoProcessor.__call__()`。[什么是输入 ID？](../glossary#input-ids)

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

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

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

decoder_input_ids (`torch.LongTensor`，形状为 `(batch_size, target_sequence_length)`，*可选*)：解码器输入序列中词元在词汇表中的索引。 可以使用 [AutoTokenizer](/docs/transformers/main/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。 有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。 [什么是解码器输入 ID？](../glossary#decoder-input-ids)

decoder_attention_mask (`torch.BoolTensor`，形状为 `(batch_size, target_sequence_length)`，*可选*) : 默认行为：生成一个忽略 `decoder_input_ids` 中填充标记的张量。默认情况下也会使用因果掩码。 仅在使用编码器-解码器语言模型（如 T5）时相关。

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

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

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

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

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

[InstructBlipVideoModel](/docs/transformers/main/zh/model_doc/instructblipvideo#transformers.InstructBlipVideoModel) 的 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`）-- 语言模型的输出。

## InstructBlipVideoForConditionalGeneration[[transformers.InstructBlipVideoForConditionalGeneration]]

#### transformers.InstructBlipVideoForConditionalGeneration[[transformers.InstructBlipVideoForConditionalGeneration]]

```python
transformers.InstructBlipVideoForConditionalGeneration(config: InstructBlipVideoConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py#L1042)

**参数：**

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

InstructBlipVideo 模型，用于根据图像和可选的文本提示生成文本。该模型由视觉编码器、查询 Transformer（Q-Former）和语言模型组成。

可以选择向模型传入 `input_ids` 作为文本提示，以便让语言模型继续生成该提示。否则，语言模型将从 [BOS]（序列起始）标记开始生成文本。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.InstructBlipVideoForConditionalGeneration.forward]]

```python
forward(pixel_values: Tensor, qformer_input_ids: Tensor, qformer_attention_mask: typing.Optional[torch.LongTensor] = None, input_ids: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.LongTensor] = None, decoder_input_ids: typing.Optional[torch.LongTensor] = None, decoder_attention_mask: typing.Optional[torch.LongTensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.LongTensor] = None, interpolate_pos_encoding: bool = False, use_cache: bool | None = None, mm_encoder_outputs: transformers.modeling_outputs.BaseModelOutputWithPooling | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py#L1119)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 `image_processor_class` 获取像素值。有关详细信息，请参阅 `image_processor_class.__call__`（[InstructBlipVideoProcessor](/docs/transformers/main/zh/model_doc/instructblipvideo#transformers.InstructBlipVideoProcessor) 使用 `image_processor_class` 处理图像）。

qformer_input_ids (`torch.LongTensor`，形状为 (batch_size, sequence_length))：用作提示并输入到 Q-Former 模块的序列。

qformer_attention_mask (`torch.LongTensor`，形状为 (batch_size, sequence_length)，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。

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

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

decoder_input_ids (`torch.LongTensor`，形状为 `(batch_size, target_sequence_length)`，*可选*)：解码器输入序列中词元在词汇表中的索引。 可以使用 [AutoTokenizer](/docs/transformers/main/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。 有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。 [什么是解码器输入 ID？](../glossary#decoder-input-ids)

decoder_attention_mask (`torch.LongTensor`，形状为 `(batch_size, target_sequence_length)`，*可选*)：用于避免对特定 token 索引执行注意力机制的掩码。默认情况下，会使用因果掩码，以确保模型只能查看之前的输入来预测未来。

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

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

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

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

mm_encoder_outputs (`~modeling_outputs.BaseModelOutputWithPooling`, *可选*) : 一个字典，其中键为支持的模态，值为该模态的编码输出。每个编码输出是一个元组，由 (`pooler_output`, *可选*: `last_hidden_states`, *可选*: `hidden_states`, *可选*: `attentions`) `pooler_output` 形状为 `(batch_size, sequence_length, hidden_size)`, *可选*) 组成，它是编码器生成的多模态特征序列，已合并到文本嵌入中。

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

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

[InstructBlipVideoForConditionalGeneration](/docs/transformers/main/zh/model_doc/instructblipvideo#transformers.InstructBlipVideoForConditionalGeneration) 的 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`）-- 语言模型的输出。

示例：

```python
>>> from transformers import InstructBlipVideoProcessor, InstructBlipVideoForConditionalGeneration
>>> import torch
>>> from huggingface_hub import hf_hub_download
>>> import av
>>> import numpy as np

>>> def read_video_pyav(container, indices):
...     '''
...     Decode the video with PyAV decoder.
...     Args:
...         container (`av.container.input.InputContainer`): PyAV container.
...         indices (`list[int]`): List of frame indices to decode.
...     Returns:
...         result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
...     '''
...     frames = []
...     container.seek(0)
...     start_index = indices[0]
...     end_index = indices[-1]
...     for i, frame in enumerate(container.decode(video=0)):
...         if i > end_index:
...             break
...         if i >= start_index and i in indices:
...             frames.append(frame)
...     return np.stack([x.to_ndarray(format="rgb24") for x in frames])

>>> model = InstructBlipVideoForConditionalGeneration.from_pretrained("Salesforce/instructblip-vicuna-7b", device_map="auto")
>>> processor = InstructBlipVideoProcessor.from_pretrained("Salesforce/instructblip-vicuna-7b")

>>> file_path = hf_hub_download(
...       repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
... )
>>> container = av.open(file_path)

>>> # sample uniformly 4 frames from the video
>>> total_frames = container.streams.video[0].frames
>>> indices = np.arange(0, total_frames, total_frames / 4).astype(int)
>>> clip = read_video_pyav(container, indices)

>>> prompt = "What is happening in the video?"
>>> inputs = processor(text=prompt, images=clip, return_tensors="pt").to(model.device)

>>> outputs = model.generate(
...     **inputs,
...     do_sample=False,
...     num_beams=5,
...     max_length=256,
...     repetition_penalty=1.5,
...     length_penalty=1.0,
... )
>>> generated_text = processor.batch_decode(outputs, skip_special_tokens=True)[0].strip()
>>> print(generated_text)
"A person is eating a bowl of pasta, and they are using a fork to eat it. The person is sitting at a table, and the plate of pasta is on the table in front"
```

#### generate[[transformers.InstructBlipVideoForConditionalGeneration.generate]]

```python
generate(pixel_values: Tensor, qformer_input_ids: typing.Optional[torch.LongTensor] = None, qformer_attention_mask: typing.Optional[torch.LongTensor] = None, input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.LongTensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, interpolate_pos_encoding: bool = False, **generate_kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py#L1261)

**参数：**

pixel_values (`torch.Tensor`，形状为 (batch_size, num_channels, height, width) 或 : (batch_size, num_frames, 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）标记索引执行注意力机制的掩码。

input_ids (`torch.LongTensor`，形状为 (batch_size, sequence_length)，*可选*)：用作生成提示的序列。

attention_mask (`torch.LongTensor`，形状为 (batch_size, sequence_length)，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。

inputs_embeds (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`)：输入的嵌入表示。应为浮点数，而非整数 token。

interpolate_pos_encoding (`bool`, *可选*, 默认为 `False`) : 是否对图像嵌入的位置编码进行插值。

**返回：** `captions (list)`

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

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

#### get_video_features[[transformers.InstructBlipVideoForConditionalGeneration.get_video_features]]

```python
get_video_features(pixel_values: Tensor, qformer_input_ids: LongTensor, qformer_attention_mask: typing.Optional[torch.LongTensor] = None, interpolate_pos_encoding: bool | None = False, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py#L1331)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。

qformer_input_ids (`torch.LongTensor`，形状为 (batch_size, sequence_length))：用作提示并输入到 Q-Former 模块的序列。

qformer_attention_mask (`torch.LongTensor`，形状为 (batch_size, sequence_length)，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。

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

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

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

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

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

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。
- **vision_outputs** (`~modeling_outputs.BaseModelOutputWithPooling`，*可选*) -- 视觉编码器的输出。
- **qformer_outputs** (`~modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions`，*可选*) -- Q-Former（Querying Transformer）的输出。

示例：

```python
>>> from PIL import Image
>>> from transformers import AutoProcessor, InstructBlipVideoForConditionalGeneration

>>> model = InstructBlipVideoForConditionalGeneration.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]
```

