Transformers 文档

视频视觉Transformer (ViViT)

Hugging Face's logo
加入 Hugging Face 社区

并获取增强的文档体验

开始使用

视频视觉 Transformer (ViViT)

PyTorch FlashAttention SDPA

概述

Vivit 模型由 Anurag Arnab、Mostafa Dehghani、Georg Heigold、Chen Sun、Mario Lučić、Cordelia Schmid 在 ViViT: 视频视觉 Transformer 中提出。该论文提出了首批基于纯 Transformer 的成功模型,用于视频理解。

该论文的摘要如下:

我们提出了用于视频分类的纯 Transformer 模型,借鉴了此类模型在图像分类中的最新成功。我们的模型从输入视频中提取时空标记,然后通过一系列 Transformer 层进行编码。为了处理视频中遇到的长序列标记,我们提出了几种高效的模型变体,它们分解了输入的空间和时间维度。虽然已知基于 Transformer 的模型仅在有大型训练数据集可用时才有效,但我们展示了如何在训练期间有效正则化模型,并利用预训练的图像模型来在相对较小的数据集上进行训练。我们进行了全面的消融研究,并在多个视频分类基准测试(包括 Kinetics 400 和 600、Epic Kitchens、Something-Something v2 和 Moments in Time)上取得了最先进的结果,优于之前基于深度 3D 卷积网络的方法。

此模型由 jegormeister 贡献。原始代码(用 JAX 编写)可以在这里找到。

使用缩放点积注意力 (SDPA)

PyTorch 包括一个原生的缩放点积注意力 (SDPA) 运算符,作为 torch.nn.functional 的一部分。此函数包含多种实现,可以根据输入和正在使用的硬件应用。有关更多信息,请参阅官方文档GPU 推理页面。

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

from transformers import VivitModel
model = VivitModel.from_pretrained("google/vivit-b-16x2-kinetics400", attn_implementation="sdpa", torch_dtype=torch.float16)
...

为了获得最佳加速,我们建议以半精度(例如 torch.float16torch.bfloat16)加载模型。

在本地基准测试(A100-40GB,PyTorch 2.3.0,OS Ubuntu 22.04)中使用 float32google/vivit-b-16x2-kinetics400 模型,我们在推理期间看到了以下加速。

训练

num_training_steps batch_size is cuda 加速 (%) Eager 峰值内存 (MB) sdpa 峰值内存 (MB) 内存节省 (%)
100 1 True 7.122 2575.28 5932.54 130.364

推理

num_batches batch_size is cuda is half 加速 (%) Mem eager (MB) Mem 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

class transformers.VivitConfig

< >

( image_size = 224 num_frames = 32 tubelet_size = [2, 16, 16] num_channels = 3 hidden_size = 768 num_hidden_layers = 12 num_attention_heads = 12 intermediate_size = 3072 hidden_act = 'gelu_fast' hidden_dropout_prob = 0.0 attention_probs_dropout_prob = 0.0 initializer_range = 0.02 layer_norm_eps = 1e-06 qkv_bias = True **kwargs )

参数

  • image_size (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) — Transformer 编码器中“中间”(即,前馈)层的维度。
  • hidden_act (strfunction, 可选, 默认为 "gelu_fast") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,则支持 "gelu""relu""selu""gelu_fast""gelu_new"
  • hidden_dropout_prob (float, 可选, 默认为 0.0) — 嵌入、编码器和池化器中所有全连接层的 dropout 概率。
  • attention_probs_dropout_prob (float, 可选, 默认为 0.0) — 注意力概率的 dropout 比率。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float, 可选, 默认为 1e-06) — 层归一化层使用的 epsilon 值。
  • qkv_bias (bool, 可选, 默认为 True) — 是否向查询、键和值添加偏差。

这是用于存储 VivitModel 配置的配置类。它用于根据指定的参数实例化 ViViT 模型,定义模型架构。使用默认值实例化配置将产生与 ViViT google/vivit-b-16x2-kinetics400 架构类似的配置。

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

示例

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

class transformers.VivitImageProcessor

< >

( do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling = <Resampling.BILINEAR: 2> do_center_crop: bool = True crop_size: typing.Dict[str, int] = None do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00784313725490196 offset: bool = True do_normalize: bool = True image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None **kwargs )

参数

  • do_resize (bool, optional, defaults to True) — 是否将图像的(高度,宽度)尺寸调整为指定的 size。可以通过 preprocess 方法中的 do_resize 参数覆盖此设置。
  • size (Dict[str, int] optional, defaults to {"shortest_edge" -- 256}): 调整大小后输出图像的尺寸。图像的最短边将调整为 size["shortest_edge"],同时保持原始图像的宽高比。可以通过 preprocess 方法中的 size 参数覆盖此设置。
  • resample (PILImageResampling, optional, defaults to Resampling.BILINEAR) — 如果调整图像大小,要使用的重采样滤镜。可以通过 preprocess 方法中的 resample 参数覆盖此设置。
  • do_center_crop (bool, optional, defaults to True) — 是否将图像中心裁剪到指定的 crop_size。可以通过 preprocess 方法中的 do_center_crop 参数覆盖此设置。
  • crop_size (Dict[str, int], optional, defaults to {"height" -- 224, "width": 224}): 应用中心裁剪后图像的尺寸。可以通过 preprocess 方法中的 crop_size 参数覆盖此设置。
  • do_rescale (bool, optional, defaults to True) — 是否按指定的比例 rescale_factor 缩放图像。可以通过 preprocess 方法中的 do_rescale 参数覆盖此设置。
  • rescale_factor (int or float, optional, defaults to 1/127.5) — 定义缩放图像时要使用的比例因子。可以通过 preprocess 方法中的 rescale_factor 参数覆盖此设置。
  • offset (bool, optional, defaults to True) — 是否在负方向和正方向上缩放图像。可以通过 preprocess 方法中的 offset 参数覆盖此设置。
  • do_normalize (bool, optional, defaults to True) — 是否标准化图像。可以通过 preprocess 方法中的 do_normalize 参数覆盖此设置。
  • image_mean (float or List[float], optional, defaults to IMAGENET_STANDARD_MEAN) — 如果标准化图像,要使用的均值。这是一个浮点数或浮点数列表,其长度等于图像中通道的数量。可以通过 preprocess 方法中的 image_mean 参数覆盖此设置。
  • image_std (float or List[float], optional, defaults to IMAGENET_STANDARD_STD) — 如果标准化图像,要使用的标准差。这是一个浮点数或浮点数列表,其长度等于图像中通道的数量。可以通过 preprocess 方法中的 image_std 参数覆盖此设置。

构建 Vivit 图像处理器。

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 size: typing.Dict[str, int] = None resample: Resampling = None do_center_crop: bool = None crop_size: typing.Dict[str, int] = None do_rescale: bool = None rescale_factor: float = None offset: bool = None do_normalize: bool = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

参数

  • videos (ImageInput) — 要预处理的视频帧。 期望单个或批量的视频帧,像素值范围为 0 到 255。如果传入像素值在 0 到 1 之间的帧,请设置 do_rescale=False
  • do_resize (bool, optional, defaults to self.do_resize) — 是否调整图像大小。
  • size (Dict[str, int], optional, defaults to self.size) — 应用调整大小后图像的尺寸。
  • resample (PILImageResampling, optional, defaults to self.resample) — 如果调整图像大小,要使用的重采样滤镜。这可以是 PILImageResampling 枚举之一,仅当 do_resize 设置为 `True` 时才生效。
  • do_center_crop (bool, optional, defaults to self.do_centre_crop) — 是否中心裁剪图像。
  • crop_size (Dict[str, int], optional, defaults to self.crop_size) — 应用中心裁剪后图像的尺寸。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 如果 offset 为 `True`,是否将图像值重新缩放到 `[-1 - 1]` 之间,否则缩放到 `[0, 1]` 之间。
  • rescale_factor (float, optional, defaults to self.rescale_factor) — 如果 do_rescale 设置为 `True`,则按此比例因子缩放图像。
  • offset (bool, optional, defaults to self.offset) — 是否在负方向和正方向上缩放图像。
  • do_normalize (bool, optional, defaults to self.do_normalize) — 是否标准化图像。
  • image_mean (float or List[float], optional, defaults to self.image_mean) — 图像均值。
  • image_std (float or List[float], optional, defaults to self.image_std) — 图像标准差。
  • return_tensors (str or TensorType, optional) — 返回张量的类型。可以是以下之一:
    • Unset: 返回 `np.ndarray` 列表。
    • TensorType.TENSORFLOW 或 `'tf'`:返回 `tf.Tensor` 类型的批次。
    • TensorType.PYTORCH 或 `'pt'`:返回 `torch.Tensor` 类型的批次。
    • TensorType.NUMPY 或 `'np'`:返回 `np.ndarray` 类型的批次。
    • TensorType.JAX 或 `'jax'`:返回 `jax.numpy.ndarray` 类型的批次。
  • data_format (ChannelDimension or str, optional, defaults to ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • Unset: 使用输入图像的推断通道维度格式。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,则通道维度格式将从输入图像中推断。 可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:(num_channels, height, width) 格式的图像。
    • "channels_last"ChannelDimension.LAST:(height, width, num_channels) 格式的图像。
    • "none"ChannelDimension.NONE:(height, width) 格式的图像。

预处理图像或一批图像。

VivitModel

class transformers.VivitModel

< >

( config add_pooling_layer = True )

参数

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

裸 ViViT Transformer 模型,输出原始隐藏状态,顶部没有任何特定的 head。此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解所有与常规用法和行为相关的事项。

forward

< >

( pixel_values: typing.Optional[torch.FloatTensor] = None head_mask: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None interpolate_pos_encoding: bool = False return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_frames, num_channels, height, width)) — 像素值。像素值可以使用 VivitImageProcessor 获得。有关详细信息,请参阅 VivitImageProcessor.preprocess()
  • head_mask (torch.FloatTensor,形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于置空自注意力模块中选定 head 的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示 head 未被掩蔽
    • 0 表示 head 被掩蔽
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参见返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的 hidden_states
  • interpolate_pos_encoding (bool, 可选, False) — 是否插值预训练的位置编码。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回值

transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

transformers.modeling_outputs.BaseModelOutputWithPoolingtorch.FloatTensor 的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种元素,具体取决于配置 (VivitConfig) 和输入。

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

  • pooler_output (torch.FloatTensor,形状为 (batch_size, hidden_size)) — 序列第一个标记(分类标记)的最后一层隐藏状态,在通过用于辅助预训练任务的层进一步处理之后。 例如,对于 BERT 系列模型,这将返回通过线性层和 tanh 激活函数处理后的分类标记。 线性层权重通过预训练期间的下一句预测(分类)目标进行训练。

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型具有嵌入层,则一个用于嵌入的输出;+ 每个层的输出一个),形状为 (batch_size, sequence_length, hidden_size)

    模型在每一层输出端的隐藏状态,加上可选的初始嵌入输出。

  • attentions (tuple(torch.FloatTensor), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 之后的注意力权重,用于计算自注意力 head 中的加权平均值。

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

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

示例

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

class transformers.VivitForVideoClassification

< >

( config )

参数

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

带有视频分类 head 的 ViViT Transformer 模型([CLS] 标记的最终隐藏状态顶部的线性层),例如用于 Kinetics-400。

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

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

forward

< >

( pixel_values: typing.Optional[torch.FloatTensor] = None head_mask: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None interpolate_pos_encoding: bool = False return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.ImageClassifierOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_frames, num_channels, height, width)) — 像素值。像素值可以使用 VivitImageProcessor 获得。有关详细信息,请参阅 VivitImageProcessor.preprocess()
  • head_mask (torch.FloatTensor,形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于置空自注意力模块中选定 head 的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示 head 未被掩蔽
    • 0 表示 head 被掩蔽
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参见返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的 hidden_states
  • interpolate_pos_encoding (bool, 可选, False) — 是否插值预训练的位置编码。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
  • labels (torch.LongTensor,形状为 (batch_size,), 可选) — 用于计算图像分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 中。如果 config.num_labels == 1,则计算回归损失(均方损失);如果 config.num_labels > 1,则计算分类损失(交叉熵损失)。

返回值

transformers.modeling_outputs.ImageClassifierOutputtuple(torch.FloatTensor)

transformers.modeling_outputs.ImageClassifierOutputtorch.FloatTensor 的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种元素,具体取决于配置 (VivitConfig) 和输入。

  • loss (torch.FloatTensor,形状为 (1,), 可选, 当提供 labels 时返回) — 分类(或回归,如果 config.num_labels==1)损失。

  • logits (torch.FloatTensor,形状为 (batch_size, config.num_labels)) — 分类(如果 config.num_labels==1,则为回归)得分(SoftMax 之前)。

  • hidden_states (tuple(torch.FloatTensor)可选,当传递 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则为嵌入的输出提供一个,加上每个阶段的输出提供一个),形状为 (batch_size, sequence_length, hidden_size)。模型在每个阶段输出的隐藏状态(也称为特征图)。

  • attentions (tuple(torch.FloatTensor)可选,当传递 output_attentions=Trueconfig.output_attentions=True 时返回) — torch.FloatTensor 的元组(每一层一个),形状为 (batch_size, num_heads, patch_size, sequence_length)

    注意力 softmax 之后的注意力权重,用于计算自注意力 head 中的加权平均值。

The VivitForVideoClassification forward 方法,覆盖了 __call__ 特殊方法。

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

示例

>>> 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
< > 在 GitHub 上更新