Transformers documentation
视频视觉 Transformer (ViViT)
该模型于 2021-03-29 在 HF papers 上发表,并于 2023-07-11 贡献至 Hugging Face Transformers。
视频视觉 Transformer (ViViT)
概述
Vivit 模型由 Anurag Arnab、Mostafa Dehghani、Georg Heigold、Chen Sun、Mario Lučić 和 Cordelia Schmid 在 ViViT: A Video Vision Transformer 中提出。 该论文提出了一套用于视频理解的最早成功的纯 Transformer 模型之一。
该论文的摘要如下:
我们提出了基于纯 Transformer 的视频分类模型,借鉴了此类模型在图像分类中取得的近期成功。我们的模型从输入视频中提取时空 token,随后由一系列 Transformer 层进行编码。为了处理视频中遇到的长 token 序列,我们提出了模型的若干高效变体,将输入的维度和时间维度进行分解。尽管已知基于 Transformer 的模型仅在拥有大型训练数据集时才有效,但我们展示了如何在训练过程中对模型进行有效正则化,并利用预训练的图像模型,从而能够在相对较小的数据集上进行训练。我们进行了详尽的消融实验,并在包括 Kinetics 400 和 600、Epic Kitchens、Something-Something v2 以及 Moments in Time 在内的多个视频分类基准上取得了最先进的结果,超越了基于深度 3D 卷积网络的先前方法。
该模型由 jegormeister 贡献。原始代码(使用 JAX 编写)可在此处找到。
使用缩放点积注意力(SDPA)
PyTorch 在 torch.nn.functional 中包含了原生的缩放点积注意力(SDPA)算子。该函数涵盖了多种实现方式,可根据输入和所用硬件进行应用。有关更多信息,请参阅官方文档或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", device_map="auto")
...为了获得最佳加速效果,我们建议以半精度(例如 torch.float16 或 torch.bfloat16)加载模型。
在本地基准测试(A100-40GB、PyTorch 2.3.0、操作系统 Ubuntu 22.04)中,使用 float32 和 google/vivit-b-16x2-kinetics400 模型,我们在推理过程中观察到以下加速效果。
训练
| num_training_steps | batch_size | 是 cuda | 加速比(%) | Eager 峰值内存 (MB) | sdpa 峰值内存 (MB) | 内存节省(%) |
|---|---|---|---|---|---|---|
| 100 | 1 | True | 7.122 | 2575.28 | 5932.54 | 130.364 |
推理
| num_batches | batch_size | 是 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
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Noneimage_size: int | list[int] | tuple[int, int] = 224num_frames: int = 32tubelet_size: list[int] | tuple[int, ...] = (2, 16, 16)num_channels: int = 3hidden_size: int = 768num_hidden_layers: int = 12num_attention_heads: int = 12intermediate_size: int = 3072hidden_act: str = 'gelu_fast'hidden_dropout_prob: float | int = 0.0attention_probs_dropout_prob: float | int = 0.0initializer_range: float = 0.02layer_norm_eps: float = 1e-06qkv_bias: bool = Truepooler_output_size: int | None = Nonepooler_act: str = 'tanh' )
参数
- image_size (
Union[int, list[int], tuple[int, 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) — MLP 表示的维度。 - hidden_act (
str,可选,默认为gelu_fast) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - hidden_dropout_prob (
Union[float, int],可选,默认为0.0) — 嵌入层、编码器和池化层中所有全连接层的 dropout 概率。 - attention_probs_dropout_prob (
Union[float, int],可选,默认为0.0) — 注意力概率的 dropout 比率。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float,可选,默认为1e-06) — 层归一化层所使用的 epsilon 值。 - qkv_bias (
bool,可选,默认为True) — 是否向查询、键和值添加偏置。 - pooler_output_size (
int, 可选) — 池化层的维度。如果为 None,则默认为hidden_size。 - pooler_act (
str,可选,默认为"tanh") — 池化器所使用的激活函数。
这是用于存储 VivitModel 配置的类。它根据指定的参数实例化 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.configVivitImageProcessor
class transformers.VivitImageProcessor
< source >( do_resize: bool = Truesize: dict[str, int] | None = Noneresample: Resampling = <Resampling.BILINEAR: 2>do_center_crop: bool = Truecrop_size: dict[str, int] | None = Nonedo_rescale: bool = Truerescale_factor: int | float = 0.00784313725490196offset: bool = Truedo_normalize: bool = Trueimage_mean: float | list[float] | None = Noneimage_std: float | list[float] | None = 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) — 定义在对图像进行重新缩放时使用的缩放因子。可被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 图像处理器。
预处理
< source >( 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 = Nonesize: dict[str, int] | None = Noneresample: PIL.Image.Resampling | None = Nonedo_center_crop: bool | None = Nonecrop_size: dict[str, int] | None = Nonedo_rescale: bool | None = Nonerescale_factor: float | None = Noneoffset: bool | None = Nonedo_normalize: bool | None = Noneimage_mean: float | list[float] | None = Noneimage_std: float | list[float] | None = Nonereturn_tensors: str | transformers.utils.generic.TensorType | None = Nonedata_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'>input_data_format: str | transformers.image_utils.ChannelDimension | None = None )
参数
- videos (
ImageInput) — 要预处理的视频帧。期望输入单个或一批视频帧,其像素值范围为 0 到 255。如果传入的帧像素值在 0 到 1 之间,请设置do_rescale=False。 - do_resize (
bool,可选,默认为self.do_resize) — 是否调整图像大小。 - size (
dict[str, int],可选,默认为self.size) — 应用 resize 后图像的尺寸。 - 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, 可选) — 要返回的张量类型。可以是以下之一:- Unset:返回一个
np.ndarray列表。 TensorType.PYTORCH或'pt':返回类型为torch.Tensor的批次。TensorType.NUMPY或'np':返回类型为np.ndarray的批次。
- Unset:返回一个
- data_format (
ChannelDimension或str, 可选, 默认为ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。- Unset:使用输入图像推断出的通道维度格式。
- 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) 格式。
预处理一张图像或一批图像。
VivitVideoProcessor
class transformers.VivitVideoProcessor
< source >( **kwargs: *<class 'transformers.processing_utils.VideosKwargs'> )
参数
- do_convert_rgb (
bool,kwargs,可选,默认为True) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选,默认为True) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为{'shortest_edge' -- 256}): 描述输入到模型的最大尺寸。 - default_to_square (
bool,kwargs,可选,默认为False) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时才会生效。 - do_rescale (
bool,kwargs,可选,默认为True) — 是否对图像进行重新缩放。 - rescale_factor (
float,kwargs,可选,默认为0.00784313725490196) — 当do_rescale设置为True时,用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选,默认为True) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.5, 0.5, 0.5]) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.5, 0.5, 0.5]) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_center_crop (
bool,kwargs,可选,默认为True) — 是否对图像进行中心裁剪。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为{'height' -- 224, 'width': 224}): 应用center_crop后输出图像的尺寸。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - do_sample_frames (
bool,kwargs,可选,默认为False) — 是否在处理前从视频中采样帧,还是处理整个视频。 - video_metadata (
Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None], kwargs) — 视频的元数据,包含总时长、帧率(fps)和总帧数等信息。该元数据将用于从视频中采样帧或计算时间戳。除非您打算在预处理之前手动解码视频,否则请勿传入任何元数据。 - fps (
Annotated[int | float | None, None], kwargs) — 当do_sample_frames=True时,每秒要采样的目标帧数。 - num_frames (
Annotated[int | None, None], kwargs) — 当do_sample_frames=True时,要采样的最大帧数。 - return_metadata (
bool,kwargs,可选,默认为False) — 是否返回视频元数据。视频元数据是一个包含视频时长、帧率、解码后端等信息的对象。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置,将返回特定框架的张量。可接受的值为:'pt':返回 PyTorchtorch.Tensor对象。'np':返回 NumPynp.ndarray对象。
- **kwargs (VideosKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。
构建一个 VivitVideoProcessor 视频处理器。
预处理
< source >( videos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]]]**kwargs: *<class 'transformers.processing_utils.VideosKwargs'> ) → ~image_processing_base.BatchFeature
参数
- videos (
Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]]) — 要预处理的视频。期望输入单个视频或一批视频,其像素值范围为 0 到 255。如果传入的像素值在 0 到 1 之间,请设置do_rescale=False。 - do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。 - default_to_square (
bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时生效。 - do_rescale (
bool,kwargs,可选) — 是否对图像进行重新缩放。 - rescale_factor (
float, kwargs, 可选) — 如果do_rescale设置为True,则用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - do_sample_frames (
bool, kwargs, 可选) — 是否在处理前对视频进行帧采样,还是处理整个视频。 - video_metadata (
Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None], kwargs) — 视频的元数据,包含总时长、帧率(fps)和总帧数等信息。该元数据将用于从视频中采样帧或计算时间戳。除非您打算在预处理之前手动解码视频,否则请勿传入任何元数据。 - fps (
Annotated[int | float | None, None], kwargs) — 当do_sample_frames=True时,每秒要采样的目标帧数。 - num_frames (
Annotated[int | None, None], kwargs) — 当do_sample_frames=True时,要采样的最大帧数。 - return_metadata (
bool, kwargs, 可选) — 是否返回视频元数据。视频元数据是一个包含视频时长、帧率、解码后端等信息的对象。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。
返回值
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
VivitModel
class transformers.VivitModel
< source >( config: VivitConfigadd_pooling_layer: bool = True )
参数
- config (VivitConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
- add_pooling_layer (
bool,可选,默认为True) — 是否添加池化层
未添加任何特定头部的裸 Vivit 模型,直接输出原始隐藏状态。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = Noneinterpolate_pos_encoding: bool = Falseattention_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 VivitImageProcessor 获取像素值。有关详细信息,请参阅 VivitImageProcessor.call()(processor_class使用 VivitImageProcessor 处理图像)。 - interpolate_pos_encoding (
bool,可选,默认为False) — 是否对预训练的位置编码进行插值。 - attention_mask (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自[0, 1]:- 1 表示未被屏蔽的 token,
- 对于被掩码的 token,值为 0。
返回值
BaseModelOutputWithPooling 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(VivitConfig)和输入。
VivitModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor)— 模型最后一层输出的隐藏状态序列。pooler_output (
torch.Tensor,形状为(batch_size, hidden_size)) — 序列中第一个 token(分类 token)的最后一层隐藏状态,经过用于辅助预训练任务的层进一步处理后得到。例如,对于 BERT 系列模型,这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重在预训练期间通过下一句预测(分类)目标进行训练。hidden_states (
tuple(torch.Tensor),可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
示例:
>>> 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
< source >( config: VivitConfig )
参数
- config (VivitConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
在 [CLS] token 的最终隐藏状态之上添加一个线性层作为视频分类头,例如用于 Kinetics-400 的 ViViT Transformer 模型。
请注意,可以通过在模型的前向传播中将
interpolate_pos_encoding设置为True,在比训练时更高分辨率的图像上对 ViT 进行微调。这会将预训练的位置嵌入插值到更高分辨率。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneinterpolate_pos_encoding: bool = False**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → ImageClassifierOutput or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 VivitImageProcessor 获取像素值。有关详细信息,请参阅 VivitImageProcessor.call()(processor_class使用 VivitImageProcessor 处理图像)。 - labels(形状为
(batch_size,)的torch.LongTensor,可选)— 用于计算图像分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]范围内。如果config.num_labels == 1,则计算回归损失(均方损失);如果config.num_labels > 1,则计算分类损失(交叉熵)。 - interpolate_pos_encoding (
bool,可选,默认为False) — 是否对预训练的位置编码进行插值。
返回值
ImageClassifierOutput 或 tuple(torch.Tensor)
一个 ImageClassifierOutput 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(VivitConfig)和输入。
VivitForVideoClassification 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss (
torch.Tensor,形状为(1,),可选,当提供labels时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。logits(形状为
(batch_size, config.num_labels)的torch.Tensor)— 分类(或当 config.num_labels==1 时为回归)得分(SoftMax 之前)。hidden_states (
tuple(torch.Tensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个阶段输出的一个张量),形状为(batch_size, sequence_length, hidden_size)。模型在每个阶段输出处的隐藏状态(也称为特征图)。attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, patch_size, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
示例:
>>> 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