TimeSformer
概述
TimeSformer模型由Facebook Research在TimeSformer: Is Space-Time Attention All You Need for Video Understanding?中提出。 这项工作是动作识别领域的一个里程碑,是第一个视频Transformer。它激发了许多基于Transformer的视频理解和分类论文。
论文的摘要如下:
我们提出了一种无需卷积的视频分类方法,完全基于空间和时间上的自注意力机制。我们的方法名为“TimeSformer”,通过直接从帧级补丁序列中进行时空特征学习,将标准的Transformer架构应用于视频。我们的实验研究比较了不同的自注意力方案,并表明“分块注意力”,即在每个块内分别应用时间注意力和空间注意力,在所考虑的设计选择中能够带来最佳的视频分类准确率。尽管设计上有了全新的突破,TimeSformer在多个动作识别基准测试中取得了最先进的结果,包括在Kinetics-400和Kinetics-600上报告的最佳准确率。最后,与3D卷积网络相比,我们的模型训练速度更快,能够显著提高测试效率(在准确率略有下降的情况下),并且还可以应用于更长的视频片段(超过一分钟)。代码和模型可在以下网址获取:此https URL。
使用提示
有许多预训练变体。根据其训练的数据集选择您的预训练模型。此外,每个剪辑的输入帧数会根据模型大小而变化,因此在选择预训练模型时应考虑此参数。
资源
TimesformerConfig
类 transformers.TimesformerConfig
< source >( image_size = 224 patch_size = 16 num_channels = 3 num_frames = 8 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-06 qkv_bias = True attention_type = 'divided_space_time' drop_path_rate = 0 **kwargs )
参数
- image_size (
int
, optional, defaults to 224) — 每张图片的大小(分辨率)。 - patch_size (
int
, optional, defaults to 16) — 每个补丁的大小(分辨率)。 - num_channels (
int
, optional, defaults to 3) — 输入通道的数量。 - num_frames (
int
, optional, defaults to 8) — 每个视频中的帧数。 - hidden_size (
int
, optional, 默认为 768) — 编码器层和池化层的维度。 - num_hidden_layers (
int
, optional, 默认为 12) — Transformer 编码器中的隐藏层数量。 - num_attention_heads (
int
, optional, defaults to 12) — Transformer编码器中每个注意力层的注意力头数。 - intermediate_size (
int
, optional, 默认为 3072) — Transformer 编码器中“中间”(即前馈)层的维度。 - hidden_act (
str
或function
, 可选, 默认为"gelu"
) — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持"gelu"
、"relu"
、"selu"
和"gelu_new"
。 - hidden_dropout_prob (
float
, optional, 默认为 0.0) — 嵌入层、编码器和池化器中所有全连接层的 dropout 概率。 - attention_probs_dropout_prob (
float
, optional, defaults to 0.0) — 注意力概率的丢弃比率。 - initializer_range (
float
, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float
, optional, defaults to 1e-06) — 层归一化层使用的epsilon值。 - qkv_bias (
bool
, optional, defaults toTrue
) — 是否向查询、键和值添加偏置。 - attention_type (
str
, 可选, 默认为"divided_space_time"
) — 使用的注意力类型。必须是"divided_space_time"
,"space_only"
,"joint_space_time"
之一。 - drop_path_rate (
float
, optional, 默认为 0) — 随机深度的丢弃比例。
这是用于存储TimesformerModel配置的配置类。它用于根据指定的参数实例化一个TimeSformer模型,定义模型架构。使用默认值实例化配置将产生与TimeSformer facebook/timesformer-base-finetuned-k600架构类似的配置。
配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。
示例:
>>> from transformers import TimesformerConfig, TimesformerModel
>>> # Initializing a TimeSformer timesformer-base style configuration
>>> configuration = TimesformerConfig()
>>> # Initializing a model from the configuration
>>> model = TimesformerModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
TimesformerModel
类 transformers.TimesformerModel
< source >( config )
参数
- config (TimesformerConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
裸的TimeSformer模型转换器输出原始隐藏状态,没有任何特定的头部。 此模型是PyTorch torch.nn.Module的子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( pixel_values: FloatTensor 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 (
torch.FloatTensor
of shape(batch_size, num_frames, num_channels, height, width)
) — 像素值。像素值可以使用AutoImageProcessor获取。详情请参见 VideoMAEImageProcessor.preprocess(). - 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
时),包含各种
元素,具体取决于配置(TimesformerConfig)和输入。
-
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
时返回) — 由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 后的注意力权重,用于计算自注意力头中的加权平均值。
TimesformerModel 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> import av
>>> import numpy as np
>>> from transformers import AutoImageProcessor, TimesformerModel
>>> 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 8 frames
>>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=4, seg_len=container.streams.video[0].frames)
>>> video = read_video_pyav(container, indices)
>>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base")
>>> model = TimesformerModel.from_pretrained("facebook/timesformer-base-finetuned-k400")
>>> # 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, 1569, 768]
TimesformerForVideoClassification
类 transformers.TimesformerForVideoClassification
< source >( config )
参数
- config (TimesformerConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
TimeSformer 模型,顶部带有视频分类头(在[CLS]标记的最终隐藏状态之上的线性层),例如用于ImageNet。 该模型是PyTorch torch.nn.Module 的子类。将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( pixel_values: 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 (
torch.FloatTensor
of shape(batch_size, num_frames, num_channels, height, width)
) — 像素值。像素值可以使用AutoImageProcessor获取。详情请参见 VideoMAEImageProcessor.preprocess(). - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - 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.ImageClassifierOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.ImageClassifierOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(TimesformerConfig)和输入。
-
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 后的注意力权重,用于计算自注意力头中的加权平均值。
TimesformerForVideoClassification 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> import av
>>> import torch
>>> import numpy as np
>>> from transformers import AutoImageProcessor, TimesformerForVideoClassification
>>> 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 8 frames
>>> indices = sample_frame_indices(clip_len=8, 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 = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400")
>>> 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