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