Transformers documentation

视频视觉 Transformer (ViViT)

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2021-03-29 在 HF papers 上发表,并于 2023-07-11 贡献至 Hugging Face Transformers。

视频视觉 Transformer (ViViT)

FlashAttention SDPA

概述

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_stepsbatch_size是 cuda加速比(%)Eager 峰值内存 (MB)sdpa 峰值内存 (MB)内存节省(%)
1001True7.1222575.285932.54130.364

推理

num_batchesbatch_size是 cuda是半加速比(%)内存 eager (MB)内存 BT (MB)节省的内存(%)
201TrueFalse15.422715.807317.079125.75
202TrueFalse17.1461234.75447.175176.122
204TrueFalse18.0932275.82709.864220.6
208TrueFalse19.2844358.191233.24253.393

VivitConfig

class transformers.VivitConfig

< >

( 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.config

VivitImageProcessor

class transformers.VivitImageProcessor

< >

( 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 图像处理器。

预处理

< >

( 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 的批次。
  • 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

< >

( **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':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。
  • **kwargs (VideosKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。

构建一个 VivitVideoProcessor 视频处理器。

预处理

< >

( 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

< >

( 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

< >

( 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

< >

( 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

< >

( 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
Update on GitHub