Transformers 文档
视频视觉Transformer (ViViT)
并获得增强的文档体验
开始使用
视频视觉Transformer (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.float16` 或 `torch.bfloat16`)加载模型。
在本地基准测试(A100-40GB,PyTorch 2.3.0,操作系统 Ubuntu 22.04)中,使用 float32
和 google/vivit-b-16x2-kinetics400
模型,我们在推理过程中观察到以下加速。
训练
训练步数 | 批处理大小 | 是cuda | 加速(%) | Eager 峰值内存(MB) | sdpa 峰值内存 (MB) | 内存节省(%) |
---|---|---|---|---|---|---|
100 | 1 | True | 7.122 | 2575.28 | 5932.54 | 130.364 |
推理
批次数量 | 批处理大小 | 是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
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 (
str
或function
, 可选, 默认为"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
) — 是否为 queries、keys 和 values 添加偏置。
这是用于存储 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.Optional[dict[str, int]] = None resample: Resampling = <Resampling.BILINEAR: 2> do_center_crop: bool = True crop_size: typing.Optional[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, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None **kwargs )
参数
- 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
) — 如果do_rescale
设置为True
,用于重新缩放图像的缩放因子。可在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 图像处理器。
预处理
< 源 >( videos: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None resample: Resampling = None do_center_crop: typing.Optional[bool] = None crop_size: typing.Optional[dict[str, int]] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None offset: typing.Optional[bool] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, 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
, 可选, 默认为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.TENSORFLOW
或'tf'
: 返回类型为tf.Tensor
的批次。TensorType.PYTORCH
或'pt'
: 返回类型为torch.Tensor
的批次。TensorType.NUMPY
或'np'
: 返回类型为np.ndarray
的批次。TensorType.JAX
或'jax'
: 返回类型为jax.numpy.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)。
预处理一张或一批图像。
VivitModel
class transformers.VivitModel
< 源 >( config add_pooling_layer = True )
参数
- config (VivitModel) — 模型配置类,包含模型的所有参数。用配置文件初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法来加载模型权重。
- add_pooling_layer (
bool
, 可选, 默认为True
) — 是否添加池化层
裸 Vivit 模型,输出原始隐藏状态,顶部没有任何特定头部。
此模型继承自 PreTrainedModel。请查看超类文档,了解库为其所有模型实现的一般方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
此模型也是 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.BaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
参数
- pixel_values (形状为
(batch_size, num_channels, image_size, image_size)
的torch.FloatTensor
, 可选) — 对应输入图像的张量。像素值可以使用{image_processor_class}
获取。有关详细信息,请参阅{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
处理图像)。 - head_mask (形状为
(num_heads,)
或(num_layers, num_heads)
的torch.FloatTensor
, 可选) — 用于使自注意力模块的选定头部无效的掩码。掩码值选择在[0, 1]
之间:- 1 表示头部未被掩盖,
- 0 表示头部被掩盖。
- output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。更多详情请参阅返回张量中的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。更多详情请参阅返回张量中的hidden_states
。 - interpolate_pos_encoding (
bool
, 默认为False
) — 是否插值预训练的位置编码。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通的元组。
返回
transformers.modeling_outputs.BaseModelOutputWithPooling 或 tuple(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 (形状为
(batch_size, hidden_size)
的torch.FloatTensor
) — 序列的第一个令牌(分类令牌)的最后一层隐藏状态,经过用于辅助预训练任务的层进一步处理。例如,对于 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 的 forward 方法,覆盖了 __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
class transformers.VivitForVideoClassification
< 源 >( config )
参数
- config (VivitForVideoClassification) — 模型配置类,包含模型的所有参数。用配置文件初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法来加载模型权重。
ViViT Transformer 模型,顶部带有一个视频分类头(在 [CLS] token 的最终隐藏状态之上添加一个线性层),例如用于 Kinetics-400。
请注意,通过在模型的 forward 中将 interpolate_pos_encoding
设置为 True
,可以在比其训练图像更高分辨率的图像上微调 ViT。这将把预训练的位置嵌入插值到更高分辨率。
此模型继承自 PreTrainedModel。请查看超类文档,了解库为其所有模型实现的一般方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
此模型也是 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.ImageClassifierOutput 或 tuple(torch.FloatTensor)
参数
- pixel_values (形状为
(batch_size, num_channels, image_size, image_size)
的torch.FloatTensor
, 可选) — 对应输入图像的张量。像素值可以使用{image_processor_class}
获取。有关详细信息,请参阅{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
处理图像)。 - head_mask (形状为
(num_heads,)
或(num_layers, num_heads)
的torch.FloatTensor
, 可选) — 用于使自注意力模块的选定头部无效的掩码。掩码值选择在[0, 1]
之间:- 1 表示头部未被掩盖,
- 0 表示头部被掩盖。
- labels (形状为
(batch_size,)
的torch.LongTensor
, 可选) — 用于计算图像分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]
之间。如果config.num_labels == 1
,则计算回归损失(均方损失);如果config.num_labels > 1
,则计算分类损失(交叉熵)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。更多详情请参阅返回张量中的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。更多详情请参阅返回张量中的hidden_states
。 - interpolate_pos_encoding (
bool
, 默认为False
) — 是否插值预训练的位置编码。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通的元组。
返回
transformers.modeling_outputs.ImageClassifierOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.ImageClassifierOutput 或 torch.FloatTensor
的元组(如果传入 return_dict=False
或当 config.return_dict=False
时),包含根据配置(VivitConfig)和输入而变化的各种元素。
-
loss (形状为
(1,)
的torch.FloatTensor
,可选,当提供labels
时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。 -
logits (形状为
(batch_size, config.num_labels)
的torch.FloatTensor
) — 分类(如果 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 的 forward 方法,覆盖了 __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