Transformers 文档
VideoMAE
并获得增强的文档体验
开始使用
VideoMAE
概述
VideoMAE 模型是由 Zhan Tong、Yibing Song、Jue Wang、Limin Wang 在 VideoMAE: 用于自监督视频预训练的数据高效学习器蒙版自编码器 中提出的。VideoMAE 将蒙版自编码器 (MAE) 扩展到视频领域,声称在多个视频分类基准上实现了最先进的性能。
论文摘要如下:
通常需要在大规模数据集上预训练视频 Transformer,才能在相对较小的数据集上获得卓越性能。在本文中,我们展示了视频蒙版自编码器 (VideoMAE) 是用于自监督视频预训练 (SSVP) 的数据高效学习器。我们受到近期 ImageMAE 的启发,并提出了定制的视频管遮罩和重建。这些简单的设计被证明能有效克服视频重建过程中时间相关性导致的信息泄露。我们在 SSVP 上获得了三个重要发现:(1) 即使是极高的遮罩比例(即 90% 到 95%),VideoMAE 仍然能产生令人满意的性能。时间上冗余的视频内容允许比图像更高的遮罩比例。(2) VideoMAE 在非常小的数据集(即约 3k-4k 视频)上无需使用任何额外数据即可实现令人印象深刻的结果。这部分归因于视频重建的挑战性任务,它强制进行高层次结构学习。(3) VideoMAE 表明,对于 SSVP,数据质量比数据数量更重要。预训练和目标数据集之间的领域差异是 SSVP 中的重要问题。值得注意的是,我们的 VideoMAE 在没有使用任何额外数据的情况下,使用普通的 ViT 主干网络在 Kinects-400 上达到 83.9%,在 Something-Something V2 上达到 75.3%,在 UCF101 上达到 90.8%,在 HMDB51 上达到 61.1%。

使用缩放点积注意力 (SDPA)
PyTorch 包含一个原生缩放点积注意力 (SDPA) 运算符,作为 torch.nn.functional
的一部分。此函数包含几种实现,可根据输入和所使用的硬件进行应用。更多信息请参阅官方文档或 GPU 推理 页面。
当实现可用时,SDPA 默认用于 `torch>=2.1.1`,但你也可以在 `from_pretrained()` 中设置 `attn_implementation="sdpa"` 来明确请求使用 SDPA。
from transformers import VideoMAEForVideoClassification
model = VideoMAEForVideoClassification.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics", attn_implementation="sdpa", torch_dtype=torch.float16)
...
为了获得最佳加速效果,我们建议以半精度(例如 `torch.float16` 或 `torch.bfloat16`)加载模型。
在本地基准测试(A100-40GB,PyTorch 2.3.0,操作系统 Ubuntu 22.04)上,使用 float32
和 MCG-NJU/videomae-base-finetuned-kinetics
模型,我们在推理过程中观察到以下加速。
批次大小 | 平均推理时间(毫秒),eager 模式 | 平均推理时间(毫秒),sdpa 模型 | 加速,Sdpa / Eager (x) |
---|---|---|---|
1 | 37 | 10 | 3.7 |
2 | 24 | 18 | 1.33 |
4 | 43 | 32 | 1.34 |
8 | 84 | 60 | 1.4 |
资源
一份官方 Hugging Face 和社区(以 🌎 标示)资源列表,帮助您开始使用 VideoMAE。如果您有兴趣提交资源以包含在此处,请随时打开一个拉取请求,我们将对其进行审查!该资源应理想地展示一些新内容,而不是重复现有资源。
视频分类
- 一个 notebook 展示了如何在自定义数据集上微调 VideoMAE 模型。
- 视频分类任务指南
- 一个 🤗 Space 展示了如何使用视频分类模型进行推理。
VideoMAEConfig
class transformers.VideoMAEConfig
< 来源 >( image_size = 224 patch_size = 16 num_channels = 3 num_frames = 16 tubelet_size = 2 hidden_size = 768 num_hidden_layers = 12 num_attention_heads = 12 intermediate_size = 3072 hidden_act = 'gelu' hidden_dropout_prob = 0.0 attention_probs_dropout_prob = 0.0 initializer_range = 0.02 layer_norm_eps = 1e-12 qkv_bias = True use_mean_pooling = True decoder_num_attention_heads = 6 decoder_hidden_size = 384 decoder_num_hidden_layers = 4 decoder_intermediate_size = 1536 norm_pix_loss = True **kwargs )
参数
- image_size (
int
, 可选, 默认为 224) — 每个图像的大小(分辨率)。 - patch_size (
int
, 可选, 默认为 16) — 每个补丁的大小(分辨率)。 - num_channels (
int
, 可选, 默认为 3) — 输入通道数。 - num_frames (
int
, 可选, 默认为 16) — 每个视频中的帧数。 - tubelet_size (
int
, 可选, 默认为 2) — 小块(tubelet)的数量。 - 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"
) — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持"gelu"
,"relu"
,"selu"
和"gelu_new"
。 - hidden_dropout_prob (
float
, 可选, 默认为 0.0) — 嵌入、编码器和池化器中所有全连接层的 dropout 概率。 - attention_probs_dropout_prob (
float
, 可选, 默认为 0.0) — 注意力概率的 dropout 比例。 - initializer_range (
float
, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。 - layer_norm_eps (
float
, 可选, 默认为 1e-12) — 层归一化层使用的 epsilon 值。 - qkv_bias (
bool
, 可选, 默认为True
) — 是否在查询、键和值中添加偏置。 - use_mean_pooling (
bool
, 可选, 默认为True
) — 是否对最终隐藏状态进行平均池化,而不是使用 [CLS] token 的最终隐藏状态。 - decoder_num_attention_heads (
int
, 可选, 默认为 6) — 解码器中每个注意力层的注意力头数量。 - decoder_hidden_size (
int
, 可选, 默认为 384) — 解码器的维度。 - decoder_num_hidden_layers (
int
, 可选, 默认为 4) — 解码器中的隐藏层数量。 - decoder_intermediate_size (
int
, 可选, 默认为 1536) — 解码器中“中间”(即前馈)层的维度。 - norm_pix_loss (
bool
, 可选, 默认为True
) — 是否归一化目标像素。
这是用于存储 VideoMAEModel 配置的配置类。它用于根据指定参数实例化 VideoMAE 模型,定义模型架构。使用默认值实例化配置将生成与 VideoMAE MCG-NJU/videomae-base 架构相似的配置。
配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PretrainedConfig 的文档。
示例
>>> from transformers import VideoMAEConfig, VideoMAEModel
>>> # Initializing a VideoMAE videomae-base style configuration
>>> configuration = VideoMAEConfig()
>>> # Randomly initializing a model from the configuration
>>> model = VideoMAEModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
VideoMAEFeatureExtractor
预处理单张或批量图像。
VideoMAEImageProcessor
class transformers.VideoMAEImageProcessor
< 来源 >( 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.00392156862745098 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
) — 是否将图像的高度和宽度调整为指定大小。可以通过preprocess
方法中的do_resize
参数覆盖。 - size (
dict[str, int]
可选, 默认为{"shortest_edge" -- 224}
): 调整大小后的输出图像尺寸。图像的最短边将调整为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/255
) — 如果do_rescale
设置为True
,则用于重新缩放图像的比例因子。可以通过preprocess
方法中的rescale_factor
参数覆盖。 - 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
参数覆盖。
构建一个 VideoMAE 图像处理器。
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: 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 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 )
参数
- images (
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
) — 是否将图像值重新缩放至 [0 - 1] 之间。 - rescale_factor (
float
, 可选, 默认为self.rescale_factor
) — 如果do_rescale
设置为True
,则用于重新缩放图像的比例因子。 - 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) 格式。
预处理一张或一批图像。
VideoMAEModel
class transformers.VideoMAEModel
< source >( config )
参数
- config (VideoMAEModel) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法加载模型权重。
裸露的 VideoMAE 模型,直接输出原始隐藏状态,没有额外的特定头部。
此模型继承自 PreTrainedModel。请查看超类文档,了解该库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
此模型也是 PyTorch torch.nn.Module 子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档中与通用用法和行为相关的所有事项。
前向传播
< source >( pixel_values: FloatTensor bool_masked_pos: typing.Optional[torch.BoolTensor] = None head_mask: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutput 或 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}
处理图像)。 - bool_masked_pos (形状为
(batch_size, sequence_length)
的torch.BoolTensor
, 可选) — 布尔遮罩位置。指示哪些补丁被遮罩(1)和哪些未被遮罩(0)。批次中的每个视频必须具有相同数量的遮罩补丁。如果为None
,则考虑所有补丁。序列长度为(num_frames // tubelet_size) * (image_size // patch_size) ** 2
。 - head_mask (形状为
(num_heads,)
或(num_layers, num_heads)
的torch.Tensor
, 可选) — 用于使自注意力模块的选定头部无效的掩码。掩码值选择在[0, 1]
之间:- 1 表示头部未被遮罩,
- 0 表示头部被遮罩.
- output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回
transformers.modeling_outputs.BaseModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.BaseModelOutput 或一个 torch.FloatTensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含根据配置 (VideoMAEConfig) 和输入的不同元素。
-
last_hidden_state (
torch.FloatTensor
, 形状为(batch_size, sequence_length, hidden_size)
) — 模型最后一层输出的隐藏状态序列。 -
hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 形状为(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
元组(如果模型具有嵌入层,则为一个嵌入层输出,加上每个层的一个输出)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, sequence_length)
的torch.FloatTensor
元组(每个层一个)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
VideoMAEModel 的前向传播方法,覆盖了 __call__
特殊方法。
尽管前向传播的配方需要在该函数中定义,但在此之后应该调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。
示例
>>> import av
>>> import numpy as np
>>> from transformers import AutoImageProcessor, VideoMAEModel
>>> 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 16 frames
>>> indices = sample_frame_indices(clip_len=16, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
>>> video = read_video_pyav(container, indices)
>>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base")
>>> model = VideoMAEModel.from_pretrained("MCG-NJU/videomae-base")
>>> # 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, 1568, 768]
VideoMAEForPreTraining
VideoMAEForPreTraining
包含顶部的解码器,用于自监督预训练。
class transformers.VideoMAEForPreTraining
< source >( config )
参数
- config (VideoMAEForPreTraining) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法加载模型权重。
VideoMAE 模型转换器,顶部带有解码器,用于自监督预训练。
此模型继承自 PreTrainedModel。请查看超类文档,了解该库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
此模型也是 PyTorch torch.nn.Module 子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档中与通用用法和行为相关的所有事项。
前向传播
< source >( pixel_values: FloatTensor bool_masked_pos: BoolTensor head_mask: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.models.videomae.modeling_videomae.VideoMAEForPreTrainingOutput
或 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}
处理图像)。 - bool_masked_pos (形状为
(batch_size, sequence_length)
的torch.BoolTensor
) — 布尔遮罩位置。指示哪些补丁被遮罩(1)和哪些未被遮罩(0)。批次中的每个视频必须具有相同数量的遮罩补丁。序列长度为(num_frames // tubelet_size) * (image_size // patch_size) ** 2
。 - head_mask (形状为
(num_heads,)
或(num_layers, num_heads)
的torch.Tensor
, 可选) — 用于使自注意力模块的选定头部无效的掩码。掩码值选择在[0, 1]
之间:- 1 表示头部未被遮罩,
- 0 表示头部被遮罩.
- output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回
transformers.models.videomae.modeling_videomae.VideoMAEForPreTrainingOutput
或 tuple(torch.FloatTensor)
一个 transformers.models.videomae.modeling_videomae.VideoMAEForPreTrainingOutput
或一个 torch.FloatTensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含根据配置 (VideoMAEConfig) 和输入的不同元素。
-
loss (
torch.FloatTensor
,形状为(1,)
) — 像素重建损失。 -
logits (形状为
(batch_size, patch_size ** 2 * num_channels)
的torch.FloatTensor
) — 像素重建逻辑。 -
hidden_states (
tuple[torch.FloatTensor]
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 形状为(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
元组(如果模型具有嵌入层,则为一个嵌入层输出,加上每个层的一个输出)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
-
attentions (
tuple[torch.FloatTensor]
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, sequence_length)
的torch.FloatTensor
元组(每个层一个)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
VideoMAEForPreTraining 的前向传播方法,覆盖了 __call__
特殊方法。
尽管前向传播的配方需要在该函数中定义,但在此之后应该调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, VideoMAEForPreTraining
>>> import numpy as np
>>> import torch
>>> num_frames = 16
>>> video = list(np.random.randint(0, 256, (num_frames, 3, 224, 224)))
>>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base")
>>> model = VideoMAEForPreTraining.from_pretrained("MCG-NJU/videomae-base")
>>> pixel_values = image_processor(video, return_tensors="pt").pixel_values
>>> num_patches_per_frame = (model.config.image_size // model.config.patch_size) ** 2
>>> seq_length = (num_frames // model.config.tubelet_size) * num_patches_per_frame
>>> bool_masked_pos = torch.randint(0, 2, (1, seq_length)).bool()
>>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
>>> loss = outputs.loss
VideoMAEForVideoClassification
class transformers.VideoMAEForVideoClassification
< source >( config )
参数
- config (VideoMAEForVideoClassification) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法加载模型权重。
VideoMAE 模型转换器,顶部带有一个视频分类头部(所有 token 平均池化隐藏状态顶部的线性层),例如用于 ImageNet。
此模型继承自 PreTrainedModel。请查看超类文档,了解该库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
此模型也是 PyTorch torch.nn.Module 子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档中与通用用法和行为相关的所有事项。
前向传播
< source >( pixel_values: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.ImageClassifierOutput 或 tuple(torch.FloatTensor)
参数
- pixel_values (形状为
(batch_size, num_channels, image_size, image_size)
的torch.Tensor
, 可选) — 对应于输入图像的张量。像素值可以使用{image_processor_class}
获取。有关详细信息,请参见{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
处理图像)。 - head_mask (形状为
(num_heads,)
或(num_layers, num_heads)
的torch.Tensor
, 可选) — 用于使自注意力模块的选定头部无效的掩码。掩码值选择在[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
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回
transformers.modeling_outputs.ImageClassifierOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.ImageClassifierOutput 或一个 torch.FloatTensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含根据配置 (VideoMAEConfig) 和输入的不同元素。
-
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
时返回) — 形状为(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
元组(如果模型具有嵌入层,则为一个嵌入层输出,加上每个阶段的一个输出)。模型在每个阶段输出的隐藏状态(也称为特征图)。 -
attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, patch_size, sequence_length)
的torch.FloatTensor
元组(每个层一个)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
VideoMAEForVideoClassification 的前向传播方法,覆盖了 __call__
特殊方法。
尽管前向传播的配方需要在该函数中定义,但在此之后应该调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。
示例
>>> import av
>>> import torch
>>> import numpy as np
>>> from transformers import AutoImageProcessor, VideoMAEForVideoClassification
>>> 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 16 frames
>>> indices = sample_frame_indices(clip_len=16, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
>>> video = read_video_pyav(container, indices)
>>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics")
>>> model = VideoMAEForVideoClassification.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics")
>>> 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])
eating spaghetti