Transformers 文档

视频视觉变换器 (ViViT)

视频视觉变换器 (ViViT)

概述

Vivit模型由Anurag Arnab、Mostafa Dehghani、Georg Heigold、Chen Sun、Mario Lučić和Cordelia Schmid在ViViT: A Video Vision 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 推理 页面。

默认情况下,当有可用实现时,SDPA 用于 torch>=2.1.1,但你也可以在 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,操作系统 Ubuntu 22.04)中,使用float32google/vivit-b-16x2-kinetics400模型,我们在推理过程中看到了以下加速效果。

训练

训练步数 批量大小 是否使用cuda 加速百分比 (%) Eager峰值内存 (MB) sdpa峰值内存 (MB) 内存节省百分比 (%)
100 1 True 7.122 2575.28 5932.54 130.364

推理

批次数量 批次大小 是否使用cuda 是否使用半精度 加速百分比 (%) 内存急切 (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

< >

( 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, optional, 默认为 224) — 每张图片的大小(分辨率)。
  • num_frames (int, optional, defaults to 32) — 每个视频中的帧数。
  • tubelet_size (List[int], 可选, 默认为 [2, 16, 16]) — 每个tubelet的大小(分辨率)。
  • num_channels (int, optional, defaults to 3) — 输入通道的数量。
  • hidden_size (int, 可选, 默认为 768) — 编码器层和池化层的维度。
  • num_hidden_layers (int, optional, 默认为 12) — Transformer 编码器中的隐藏层数量。
  • num_attention_heads (int, optional, 默认为 12) — Transformer 编码器中每个注意力层的注意力头数。
  • intermediate_size (int, optional, 默认为 3072) — Transformer 编码器中“中间”(即前馈)层的维度。
  • hidden_act (strfunction, 可选, 默认为 "gelu_fast") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持 "gelu", "relu", "selu", "gelu_fast""gelu_new".
  • hidden_dropout_prob (float, optional, 默认为 0.0) — 嵌入层、编码器和池化器中所有全连接层的 dropout 概率。
  • attention_probs_dropout_prob (float, optional, 默认为 0.0) — 注意力概率的丢弃比例。
  • initializer_range (float, optional, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float, optional, defaults to 1e-06) — 层归一化层使用的epsilon值。
  • qkv_bias (bool, optional, defaults to 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

transformers.VivitImageProcessor

< >

( do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling = 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, 可选, 默认为 True) — 是否将图像的(高度,宽度)尺寸调整为指定的 size。可以在 preprocess 方法中通过 do_resize 参数覆盖此设置。
  • size (Dict[str, int] optional, defaults to {"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 (intfloat, 可选, 默认为 1/127.5) — 定义在重新缩放图像时使用的比例因子。可以在 preprocess 方法中通过 rescale_factor 参数覆盖此值。
  • offset (bool, 可选, 默认为 True) — 是否在负方向和正方向上缩放图像。可以在 preprocess 方法中被 offset 覆盖。
  • do_normalize (bool, 可选, 默认为 True) — 是否对图像进行归一化。可以在 preprocess 方法中通过 do_normalize 参数进行覆盖。
  • image_mean (floatList[float], 可选, 默认为 IMAGENET_STANDARD_MEAN) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或与图像通道数长度相同的浮点数列表。可以通过 preprocess 方法中的 image_mean 参数进行覆盖。
  • image_std (floatList[float], 可选, 默认为 IMAGENET_STANDARD_STD) — 如果对图像进行归一化,则使用的标准差。这是一个浮点数或与图像通道数长度相同的浮点数列表。可以通过 preprocess 方法中的 image_std 参数进行覆盖。

构建一个Vivit图像处理器。

预处理

< >

( videos: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('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 = input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

参数

  • 视频 (ImageInput) — 要预处理的视频帧。期望输入单个或批量的视频帧,像素值范围从0到255。如果传入的帧像素值在0到1之间,请设置do_rescale=False.
  • do_resize (bool, optional, defaults to self.do_resize) — 是否调整图像大小.
  • size (Dict[str, int], 可选, 默认为 self.size) — 应用调整大小后的图像尺寸。
  • resample (PILImageResampling, 可选, 默认为 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, 可选, 默认为 self.do_rescale) — 是否在 offsetTrue 时将图像值重新缩放到 [-1 - 1] 之间,否则缩放到 [0, 1] 之间。
  • rescale_factor (float, optional, defaults to self.rescale_factor) — 如果 do_rescale 设置为 True,则用于重新缩放图像的重新缩放因子。
  • offset (bool, 可选, 默认为 self.offset) — 是否在正负两个方向上缩放图像。
  • do_normalize (bool, 可选, 默认为 self.do_normalize) — 是否对图像进行归一化处理.
  • image_mean (floatList[float], 可选, 默认为 self.image_mean) — 图像均值.
  • image_std (float or List[float], optional, defaults to self.image_std) — 图像标准差.
  • return_tensors (strTensorType, 可选) — 返回的张量类型。可以是以下之一:
    • 未设置:返回一个 np.ndarray 列表。
    • TensorType.TENSORFLOW'tf':返回一个类型为 tf.Tensor 的批次。
    • TensorType.PYTORCH'pt':返回一个类型为 torch.Tensor 的批次。
    • TensorType.NUMPY'np':返回一个类型为 np.ndarray 的批次。
    • TensorType.JAX'jax':返回一个类型为 jax.numpy.ndarray 的批次。
  • data_format (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • 未设置:使用输入图像的推断通道维度格式。
  • 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

transformers.VivitModel

< >

( config add_pooling_layer = True )

参数

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

裸的ViViT Transformer模型输出原始隐藏状态,没有任何特定的头部。 此模型是PyTorch torch.nn.Module 的子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( 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 of shape (batch_size, num_frames, num_channels, height, width)) — 像素值。像素值可以使用VivitImageProcessor获取。详情请参见 VivitImageProcessor.preprocess().
  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • interpolate_pos_encoding (bool, optional, False) — 是否插值预训练的位置编码.
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.BaseModelOutputWithPooling 或一个由 torch.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后的注意力权重,用于计算自注意力头中的加权平均值。

VivitModel 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用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

transformers.VivitForVideoClassification

< >

( config )

参数

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

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

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

该模型是一个PyTorch torch.nn.Module 子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( 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 of shape (batch_size, num_frames, num_channels, height, width)) — 像素值。像素值可以使用VivitImageProcessor获取。详情请参见 VivitImageProcessor.preprocess().
  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • interpolate_pos_encoding (bool, optional, False) — 是否插值预训练的位置编码.
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
  • labels (torch.LongTensor of shape (batch_size,), optional) — 用于计算图像分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失),如果 config.num_labels > 1,则计算分类损失(交叉熵)。

返回

transformers.modeling_outputs.ImageClassifierOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.ImageClassifierOutput 或一个由 torch.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=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, patch_size, sequence_length)

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

VivitForVideoClassification 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用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
< > Update on GitHub