# 视频视觉 Transformer (ViViT)

## 概述

Vivit 模型由 Anurag Arnab、Mostafa Dehghani、Georg Heigold、Chen Sun、Mario Lučić 和 Cordelia Schmid 在 [ViViT: A Video Vision Transformer](https://huggingface.co/papers/2103.15691) 中提出。该论文提出了一套用于视频理解的最早成功的纯 Transformer 模型之一。

该论文的摘要如下：

*我们提出了基于纯 Transformer 的视频分类模型，借鉴了此类模型在图像分类中取得的近期成功。我们的模型从输入视频中提取时空 token，随后由一系列 Transformer 层进行编码。为了处理视频中遇到的长 token 序列，我们提出了模型的若干高效变体，将输入的维度和时间维度进行分解。尽管已知基于 Transformer 的模型仅在拥有大型训练数据集时才有效，但我们展示了如何在训练过程中对模型进行有效正则化，并利用预训练的图像模型，从而能够在相对较小的数据集上进行训练。我们进行了详尽的消融实验，并在包括 Kinetics 400 和 600、Epic Kitchens、Something-Something v2 以及 Moments in Time 在内的多个视频分类基准上取得了最先进的结果，超越了基于深度 3D 卷积网络的先前方法。*

该模型由 [jegormeister](https://huggingface.co/jegormeister) 贡献。原始代码（使用 JAX 编写）可在[此处](https://github.com/google-research/scenic/tree/main/scenic/projects/vivit)找到。

### 使用缩放点积注意力（SDPA）

PyTorch 在 `torch.nn.functional` 中包含了原生的缩放点积注意力（SDPA）算子。该函数涵盖了多种实现方式，可根据输入和所用硬件进行应用。有关更多信息，请参阅[官方文档](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html)或[GPU 推理](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention)页面。

当存在可用实现时，`torch>=2.1.1` 默认使用 SDPA，但您也可以在 `from_pretrained()` 中设置 `attn_implementation="sdpa"` 以显式请求使用 SDPA。

```python
from transformers import VivitModel

model = VivitModel.from_pretrained("google/vivit-b-16x2-kinetics400", attn_implementation="sdpa", device_map="auto")
...
```

为了获得最佳加速效果，我们建议以半精度（例如 `torch.float16` 或 `torch.bfloat16`）加载模型。

在本地基准测试（A100-40GB、PyTorch 2.3.0、操作系统 Ubuntu 22.04）中，使用 `float32` 和 `google/vivit-b-16x2-kinetics400` 模型，我们在推理过程中观察到以下加速效果。

### 训练

|   num_training_steps |   batch_size |   是 cuda |   加速比（%） |   Eager 峰值内存 (MB) |   sdpa 峰值内存 (MB) |   内存节省（%） |
|---------------------:|-------------:|----------:|--------------:|----------------------:|---------------------:|-----------------:|
|                  100 |            1 |      True |         7.122 |               2575.28 |              5932.54 |           130.364 |

### 推理

|   num_batches |   batch_size |   是 cuda |   是半 |   加速比（%） |   内存 eager (MB) |   内存 BT (MB) |   节省的内存（%） |
|---------------|--------------|-----------|-----------|---------------|------------------|---------------|-----------------|
|            20 |             1 |   True    |   False   |      15.422   |     715.807      |    317.079    |      125.75     |
|            20 |             2 |   True    |   False   |      17.146   |    1234.75       |    447.175    |      176.122    |
|            20 |             4 |   True    |   False   |      18.093   |    2275.82       |    709.864    |      220.6      |
|            20 |             8 |   True    |   False   |      19.284   |    4358.19       |   1233.24     |      253.393    |

## VivitConfig[[transformers.VivitConfig]]

#### transformers.VivitConfig[[transformers.VivitConfig]]

```python
transformers.VivitConfig(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, image_size: int | list[int] | tuple[int, int] = 224, num_frames: int = 32, tubelet_size: list[int] | tuple[int, ...] = (2, 16, 16), num_channels: int = 3, hidden_size: int = 768, num_hidden_layers: int = 12, num_attention_heads: int = 12, intermediate_size: int = 3072, hidden_act: str = 'gelu_fast', hidden_dropout_prob: float | int = 0.0, attention_probs_dropout_prob: float | int = 0.0, initializer_range: float = 0.02, layer_norm_eps: float = 1e-06, qkv_bias: bool = True, pooler_output_size: int | None = None, pooler_act: str = 'tanh')
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/vivit/configuration_vivit.py#L24)

**参数：**

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

num_frames (`int`，*可选*，默认为 32)：每个视频中的帧数。

tubelet_size (`list[int]`，*可选*，默认为 `[2, 16, 16]`)：每个 tubelet 的大小（分辨率）。

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

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_fast`)：解码器中的非线性激活函数（函数或字符串）。例如，`"gelu"`、`"relu"`、`"silu"` 等。

hidden_dropout_prob (`Union[float, int]`，*可选*，默认值为 `0.0`)：嵌入层、编码器和池化器中所有全连接层的 dropout 概率。

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

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

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

qkv_bias (`bool`，*可选*，默认为 `True`)：是否向查询、键和值添加偏置。

pooler_output_size (`int`, *可选*) : 池化层的维度。如果为 None，则默认为 `hidden_size`。

pooler_act (`str`，*可选*，默认为 `"tanh"`)：池化器所使用的激活函数。

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

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

示例：

```python
>>> from transformers import VivitConfig, VivitModel

>>> # Initializing a ViViT google/vivit-b-16x2-kinetics400 style configuration
>>> configuration = VivitConfig()

>>> # Initializing a model (with random weights) from the google/vivit-b-16x2-kinetics400 style configuration
>>> model = VivitModel(configuration)

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

## VivitImageProcessor[[transformers.VivitImageProcessor]]

#### transformers.VivitImageProcessor[[transformers.VivitImageProcessor]]

```python
transformers.VivitImageProcessor(do_resize: bool = True, size: dict[str, int] | None = None, resample: Resampling = <Resampling.BILINEAR: 2>, do_center_crop: bool = True, crop_size: dict[str, int] | None = None, do_rescale: bool = True, rescale_factor: int | float = 0.00784313725490196, offset: bool = True, do_normalize: bool = True, image_mean: float | list[float] | None = None, image_std: float | list[float] | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/vivit/image_processing_vivit.py#L63)

**参数：**

do_resize (`bool`，*可选*，默认为 `True`)：是否将图像的（高度，宽度）维度调整为指定的 `size`。可被 `preprocess` 方法中的 `do_resize` 参数覆盖。

size (`dict[str, int]` *可选*，默认为 `{"shortest_edge" : 256}`)：调整大小后输出图像的尺寸。图像的最短边将被调整为 `size["shortest_edge"]`，同时保持原始图像的宽高比。可以在 `preprocess` 方法中通过 `size` 进行覆盖。

resample (`PILImageResampling`，*可选*，默认为 `Resampling.BILINEAR`)：在调整图像大小时使用的重采样滤波器。可通过 `preprocess` 方法中的 `resample` 参数进行覆盖。

do_center_crop (`bool`，*可选*，默认为 `True`)：是否将图像中心裁剪至指定的 `crop_size`。可通过 `preprocess` 方法中的 `do_center_crop` 参数覆盖此设置。

crop_size (`dict[str, int]`，*可选*，默认为 `{"height" : 224, "width": 224}`)：应用中心裁剪后图像的尺寸。可通过 `preprocess` 方法中的 `crop_size` 参数进行覆盖。

do_rescale (`bool`，*可选*，默认为 `True`)：是否按指定的缩放因子 `rescale_factor` 对图像进行重新缩放。可被 `preprocess` 方法中的 `do_rescale` 参数覆盖。

rescale_factor (`int` 或 `float`，*可选*，默认为 `1/127.5`)：定义在对图像进行重新缩放时使用的缩放因子。可被 `preprocess` 方法中的 `rescale_factor` 参数覆盖。

offset (`bool`，*可选*，默认为 `True`)：是否同时在负方向和正方向上缩放图像。可被 `preprocess` 方法中的 `offset` 覆盖。

do_normalize (`bool`，*可选*，默认为 `True`)：是否对图像进行归一化。可通过 `preprocess` 方法中的 `do_normalize` 参数覆盖。

image_mean (`float` 或 `list[float]`，*可选*，默认为 `IMAGENET_STANDARD_MEAN`) : 对图像进行归一化时使用的均值。这是一个浮点数或浮点数列表，其长度等于图像的通道数。可以通过 `preprocess` 方法中的 `image_mean` 参数进行覆盖。

image_std (`float` 或 `list[float]`，*可选*，默认为 `IMAGENET_STANDARD_STD`) : 归一化图像时使用的标准差。这是一个浮点数或浮点数列表，其长度等于图像的通道数。可以通过 `preprocess` 方法中的 `image_std` 参数进行覆盖。

构建一个 Vivit 图像处理器。

#### preprocess[[transformers.VivitImageProcessor.preprocess]]

```python
preprocess(videos: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], do_resize: bool | None = None, size: dict[str, int] | None = None, resample: PIL.Image.Resampling | None = None, do_center_crop: bool | None = None, crop_size: dict[str, int] | None = None, do_rescale: bool | None = None, rescale_factor: float | None = None, offset: bool | None = None, do_normalize: bool | None = None, image_mean: float | list[float] | None = None, image_std: float | list[float] | None = None, return_tensors: str | transformers.utils.generic.TensorType | None = None, data_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'>, input_data_format: str | transformers.image_utils.ChannelDimension | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/vivit/image_processing_vivit.py#L285)

**参数：**

videos (`ImageInput`)：要预处理的视频帧。期望输入单个或一批像素值在 0 到 255 之间的视频帧。如果传入的帧像素值在 0 到 1 之间，请设置 `do_rescale=False`。

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

size (`dict[str, int]`，*可选*，默认为 `self.size`)：应用缩放后图像的尺寸。

resample (`PILImageResampling`，*可选*，默认为 `self.resample`)：如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

do_center_crop (`bool`，*可选*，默认为 `self.do_centre_crop`)：是否对图像进行居中裁剪。

crop_size (`dict[str, int]`，*可选*，默认为 `self.crop_size`)：应用中心裁剪后图像的尺寸。

do_rescale (`bool`, *可选*, 默认为 `self.do_rescale`) : 如果 `offset` 为 `True`，是否将图像值重新缩放到 `[-1 - 1]`；否则缩放到 `[0, 1]`。

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

offset (`bool`, *可选*, 默认为 `self.offset`) : 是否同时在负方向和正方向上缩放图像。

do_normalize (`bool`, *可选*, 默认为 `self.do_normalize`) : 是否对图像进行归一化。

image_mean (`float` 或 `list[float]`，*可选*，默认为 `self.image_mean`)：图像均值。

image_std (`float` 或 `list[float]`，*可选*，默认为 `self.image_std`)：图像标准差。

return_tensors (`str` 或 `TensorType`，*可选*) : 要返回的张量类型。可以是以下之一： - 未设置：返回 `np.ndarray` 列表。 - `TensorType.PYTORCH` 或 `'pt'`：返回类型为 `torch.Tensor` 的批次。 - `TensorType.NUMPY` 或 `'np'`：返回类型为 `np.ndarray` 的批次。

data_format (`ChannelDimension` 或 `str`，*可选*，默认为 `ChannelDimension.FIRST`)：输出图像的通道维度格式。可以是以下之一：- `ChannelDimension.FIRST`：图像为 (num_channels, height, width) 格式。- `ChannelDimension.LAST`：图像为 (height, width, num_channels) 格式。- 未设置：使用输入图像推断出的通道维度格式。

input_data_format (`ChannelDimension` 或 `str`，*可选*) : 输入图像的通道维度格式。如果未设置，则从输入图像中推断通道维度格式。可以是以下之一： - `"channels_first"` 或 `ChannelDimension.FIRST`：图像为 (num_channels, height, width) 格式。 - `"channels_last"` 或 `ChannelDimension.LAST`：图像为 (height, width, num_channels) 格式。 - `"none"` 或 `ChannelDimension.NONE`：图像为 (height, width) 格式。

预处理一张图像或一批图像。

## VivitVideoProcessor[[transformers.VivitVideoProcessor]]

#### transformers.VivitVideoProcessor[[transformers.VivitVideoProcessor]]

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

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/vivit/video_processing_vivit.py#L25)

**参数：**

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*，默认为 `{'shortest_edge' : 256}`)：描述输入到模型的最大尺寸。

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

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*，默认为 `2`) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

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

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

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

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

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.5, 0.5, 0.5]`) : 用于归一化的图像标准差。仅当 `do_normalize` 设置为 `True` 时生效。

do_center_crop (`bool`, *kwargs*, *可选*，默认为 `True`) : 是否对图像进行居中裁剪。

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

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'height' : 224, 'width': 224}`)：应用 `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/v5.23.0/zh/main_classes/processors#transformers.VideosKwargs), *optional*) : 每种模态（文本、图像、视频、音频）的额外处理选项。模型特定参数已在上方列出；有关支持参数的完整列表，请参阅 TypedDict 类。

构建一个 VivitVideoProcessor 视频处理器。

#### preprocess[[transformers.VivitVideoProcessor.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/v5.23.0/src/transformers/models/vivit/video_processing_vivit.py#L49)

**参数：**

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 张量中的整数列表进行转换。

## VivitModel[[transformers.VivitModel]]

#### transformers.VivitModel[[transformers.VivitModel]]

```python
transformers.VivitModel(config: VivitConfig, add_pooling_layer: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/vivit/modeling_vivit.py#L318)

**参数：**

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

add_pooling_layer (`bool`，*可选*，默认为 `True`)：是否添加池化层

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

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

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

#### forward[[transformers.VivitModel.forward]]

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

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/vivit/modeling_vivit.py#L333)

**参数：**

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

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

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

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

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

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

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

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

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

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

示例：

```python
>>> import av
>>> import numpy as np

>>> from transformers import VivitImageProcessor, VivitModel
>>> from huggingface_hub import hf_hub_download

>>> np.random.seed(0)

>>> 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])

>>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
...     '''
...     Sample a given number of frame indices from the video.
...     Args:
...         clip_len (`int`): Total number of frames to sample.
...         frame_sample_rate (`int`): Sample every n-th frame.
...         seg_len (`int`): Maximum allowed index of sample's last frame.
...     Returns:
...         indices (`list[int]`): List of sampled frame indices
...     '''
...     converted_len = int(clip_len * frame_sample_rate)
...     end_idx = np.random.randint(converted_len, seg_len)
...     start_idx = end_idx - converted_len
...     indices = np.linspace(start_idx, end_idx, num=clip_len)
...     indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
...     return indices

>>> # video clip consists of 300 frames (10 seconds at 30 FPS)
>>> file_path = hf_hub_download(
...     repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
... )
>>> container = av.open(file_path)

>>> # sample 32 frames
>>> indices = sample_frame_indices(clip_len=32, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
>>> video = read_video_pyav(container=container, indices=indices)

>>> image_processor = VivitImageProcessor.from_pretrained("google/vivit-b-16x2-kinetics400")
>>> model = VivitModel.from_pretrained("google/vivit-b-16x2-kinetics400")

>>> # prepare video for the model
>>> inputs = image_processor(list(video), return_tensors="pt")

>>> # forward pass
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 3137, 768]
```

## VivitForVideoClassification[[transformers.VivitForVideoClassification]]

#### transformers.VivitForVideoClassification[[transformers.VivitForVideoClassification]]

```python
transformers.VivitForVideoClassification(config: VivitConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/vivit/modeling_vivit.py#L447)

**参数：**

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

在顶部带有视频分类头的 ViViT Transformer 模型（在 [CLS] token 的最终隐藏状态之上添加一个线性层），例如用于 Kinetics-400。

请注意，通过在模型的前向传播中将 `interpolate_pos_encoding` 设置为 `True`，可以在比训练时更高分辨率的图像上对 ViT 进行微调。这会将预训练的位置嵌入插值到更高分辨率。

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

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

#### forward[[transformers.VivitForVideoClassification.forward]]

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

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/vivit/modeling_vivit.py#L460)

**参数：**

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

labels (`torch.LongTensor`，形状为 `(batch_size,)`，*可选*) : 用于计算图像分类/回归损失的标签。索引应在 `[0, ..., config.num_labels - 1]` 范围内。如果 `config.num_labels == 1`，则计算回归损失（均方损失）；如果 `config.num_labels > 1`，则计算分类损失（交叉熵）。

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

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

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

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

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

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 分类损失（如果 config.num_labels==1，则为回归损失）。
- **logits**（形状为 `(batch_size, config.num_labels)` 的 `torch.Tensor`）-- 分类（或当 config.num_labels==1 时为回归）得分（SoftMax 之前）。
- **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, patch_size, sequence_length)`。

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

示例：

```python
>>> import av
>>> import numpy as np
>>> import torch

>>> from transformers import VivitImageProcessor, VivitForVideoClassification
>>> from huggingface_hub import hf_hub_download

>>> np.random.seed(0)

>>> 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])

>>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
...     '''
...     Sample a given number of frame indices from the video.
...     Args:
...         clip_len (`int`): Total number of frames to sample.
...         frame_sample_rate (`int`): Sample every n-th frame.
...         seg_len (`int`): Maximum allowed index of sample's last frame.
...     Returns:
...         indices (`list[int]`): List of sampled frame indices
...     '''
...     converted_len = int(clip_len * frame_sample_rate)
...     end_idx = np.random.randint(converted_len, seg_len)
...     start_idx = end_idx - converted_len
...     indices = np.linspace(start_idx, end_idx, num=clip_len)
...     indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
...     return indices

>>> # video clip consists of 300 frames (10 seconds at 30 FPS)
>>> file_path = hf_hub_download(
...     repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
... )
>>> container = av.open(file_path)

>>> # sample 32 frames
>>> indices = sample_frame_indices(clip_len=32, frame_sample_rate=4, seg_len=container.streams.video[0].frames)
>>> video = read_video_pyav(container=container, indices=indices)

>>> image_processor = VivitImageProcessor.from_pretrained("google/vivit-b-16x2-kinetics400")
>>> model = VivitForVideoClassification.from_pretrained("google/vivit-b-16x2-kinetics400")

>>> inputs = image_processor(list(video), return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**inputs)
...     logits = outputs.logits

>>> # model predicts one of the 400 Kinetics-400 classes
>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])
LABEL_116
```

