Transformers 文件

X-CLIP

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

X-CLIP

PyTorch

概述

X-CLIP 模型由 Bolin Ni、Houwen Peng、Minghao Chen、Songyang Zhang、Gaofeng Meng、Jianlong Fu、Shiming Xiang 和 Haibin Ling 在 擴充套件語言-影像預訓練模型以用於通用影片識別 中提出。X-CLIP 是 CLIP 的一個最小擴充套件,用於影片。該模型由文字編碼器、跨幀視覺編碼器、多幀整合 Transformer 和影片專用提示生成器組成。

論文摘要如下:

對比語言-影像預訓練在從網路規模資料中學習視覺-文字聯合表示方面取得了巨大成功,展示了在各種影像任務中卓越的“零樣本”泛化能力。然而,如何有效地將這種新的語言-影像預訓練方法擴充套件到影片領域仍然是一個開放的問題。在這項工作中,我們提出了一種簡單而有效的方法,可以直接將預訓練的語言-影像模型應用於影片識別,而不是從頭開始預訓練一個新模型。更具體地說,為了捕獲幀沿時間維度的長程依賴關係,我們提出了一種跨幀注意力機制,該機制明確地在幀之間交換資訊。該模組輕量級,可以無縫地插入到預訓練的語言-影像模型中。此外,我們提出了一種影片專用提示方案,該方案利用影片內容資訊生成判別性文字提示。大量的實驗表明,我們的方法是有效的,並且可以推廣到不同的影片識別場景。特別是在全監督設定下,我們的方法在 Kinectics-400 上實現了 87.1% 的 top-1 準確率,而 FLOPs 消耗是 Swin-L 和 ViViT-H 的 12 分之一。在零樣本實驗中,我們的方法在兩種流行協議下在 top-1 準確率方面分別超過了現有最先進方法 +7.6% 和 +14.9%。在少樣本場景中,當標記資料極度有限時,我們的方法比之前的最佳方法分別高出 +32.1% 和 +23.1%。

技巧

  • X-CLIP 的用法與 CLIP 相同。
drawing X-CLIP 架構。摘自原始論文。

此模型由 nielsr 貢獻。原始程式碼可以在 此處 找到。

資源

以下是官方 Hugging Face 和社群(用 🌎 表示)資源列表,可幫助您開始使用 X-CLIP。

  • X-CLIP 的演示筆記本可以在 此處 找到。

如果您有興趣在此處提交資源,請隨時開啟 Pull Request,我們將對其進行審查!該資源最好能展示一些新內容,而不是重複現有資源。

XCLIPProcessor

class transformers.XCLIPProcessor

< >

( image_processor = None tokenizer = None **kwargs )

引數

構建一個 X-CLIP 處理器,它將 VideoMAE 影像處理器和 CLIP 分詞器封裝到一個單一的處理器中。

XCLIPProcessor 提供了 VideoMAEImageProcessorCLIPTokenizerFast 的所有功能。有關更多資訊,請參閱 __call__()decode()

batch_decode

< >

( *args **kwargs )

此方法將其所有引數轉發給 CLIPTokenizerFast 的 batch_decode()。有關更多資訊,請參閱此方法的文件字串。

decode

< >

( *args **kwargs )

此方法將其所有引數轉發給 CLIPTokenizerFast 的 decode()。有關更多資訊,請參閱此方法的文件字串。

XCLIPConfig

class transformers.XCLIPConfig

< >

( text_config = None vision_config = None projection_dim = 512 prompt_layers = 2 prompt_alpha = 0.1 prompt_hidden_act = 'quick_gelu' prompt_num_attention_heads = 8 prompt_attention_dropout = 0.0 prompt_projection_dropout = 0.0 logit_scale_init_value = 2.6592 **kwargs )

引數

  • text_config (dict, 可選) — 用於初始化 XCLIPTextConfig 的配置選項字典。
  • vision_config (dict, 可選) — 用於初始化 XCLIPVisionConfig 的配置選項字典。
  • projection_dim (int, 可選, 預設為 512) — 文字和視覺投影層的維度。
  • prompt_layers (int, 可選, 預設為 2) — 影片專用提示生成器中的層數。
  • prompt_alpha (float, 可選, 預設為 0.1) — 影片專用提示生成器中使用的 Alpha 值。
  • prompt_hidden_act (strfunction, 可選, 預設為 "quick_gelu") — 影片專用提示生成器中的非線性啟用函式(函式或字串)。如果是字串,支援 "gelu""relu""selu""gelu_new" "quick_gelu"
  • prompt_num_attention_heads (int, 可選, 預設為 8) — 影片專用提示生成器中交叉注意力的注意力頭數量。
  • prompt_attention_dropout (float, 可選, 預設為 0.0) — 影片專用提示生成器中注意力層的 dropout 機率。
  • prompt_projection_dropout (float, 可選, 預設為 0.0) — 影片專用提示生成器中投影層的 dropout 機率。
  • logit_scale_init_value (float, 可選, 預設為 2.6592) — logit_scale 引數的初始值。預設值按照原始 XCLIP 實現使用。
  • kwargs (可選) — 關鍵字引數字典。

XCLIPConfig 是用於儲存 XCLIPModel 配置的配置類。它用於根據指定的引數例項化 X-CLIP 模型,定義文字模型和視覺模型配置。使用預設值例項化配置將生成與 X-CLIP microsoft/xclip-base-patch32 架構類似的配置。

配置物件繼承自 PretrainedConfig,可用於控制模型輸出。有關更多資訊,請閱讀 PretrainedConfig 的文件。

from_text_vision_configs

< >

( text_config: XCLIPTextConfig vision_config: XCLIPVisionConfig **kwargs ) XCLIPConfig

返回

XCLIPConfig

一個配置物件的例項

從 xclip 文字模型配置和 xclip 視覺模型配置例項化 XCLIPConfig(或派生類)。

XCLIPTextConfig

class transformers.XCLIPTextConfig

< >

( vocab_size = 49408 hidden_size = 512 intermediate_size = 2048 num_hidden_layers = 12 num_attention_heads = 8 max_position_embeddings = 77 hidden_act = 'quick_gelu' layer_norm_eps = 1e-05 attention_dropout = 0.0 initializer_range = 0.02 initializer_factor = 1.0 pad_token_id = 1 bos_token_id = 0 eos_token_id = 2 **kwargs )

引數

  • vocab_size (int, 可選, 預設為 49408) — X-CLIP 文字模型的詞彙表大小。定義了呼叫 XCLIPModel 時傳入的 inputs_ids 可以表示的不同詞元數量。
  • hidden_size (int, 可選, 預設為 512) — 編碼器層和池化器層的維度。
  • intermediate_size (int, 可選, 預設為 2048) — Transformer 編碼器中“中間”(即,前饋)層的維度。
  • num_hidden_layers (int, 可選, 預設為 12) — Transformer 編碼器中的隱藏層數量。
  • num_attention_heads (int, 可選, 預設為 8) — Transformer 編碼器中每個注意力層的注意力頭數量。
  • max_position_embeddings (int, 可選, 預設為 77) — 此模型可能使用的最大序列長度。通常為了以防萬一會將其設定為較大的值(例如 512、1024 或 2048)。
  • hidden_act (strfunction, 可選, 預設為 "quick_gelu") — 編碼器和池化器中的非線性啟用函式(函式或字串)。如果是字串,支援 "gelu""relu""selu""gelu_new" "quick_gelu"
  • layer_norm_eps (float, 可選, 預設為 1e-5) — 層歸一化層使用的 epsilon 值。
  • attention_dropout (float, 可選, 預設為 0.0) — 注意力機率的 dropout 比率。
  • initializer_range (float, 可選, 預設為 0.02) — 用於初始化所有權重矩陣的截斷正態分佈初始化器的標準差。
  • initializer_factor (float, 可選, 預設為 1) — 用於初始化所有權重矩陣的因子(應保持為 1,內部用於初始化測試)。

這是用於儲存 XCLIPModel 配置的配置類。它用於根據指定引數例項化 X-CLIP 模型,定義模型架構。使用預設值例項化配置將生成與 X-CLIP microsoft/xclip-base-patch32 架構類似的配置。

配置物件繼承自 PretrainedConfig,可用於控制模型輸出。有關更多資訊,請閱讀 PretrainedConfig 的文件。

示例

>>> from transformers import XCLIPTextModel, XCLIPTextConfig

>>> # Initializing a XCLIPTextModel with microsoft/xclip-base-patch32 style configuration
>>> configuration = XCLIPTextConfig()

>>> # Initializing a XCLIPTextConfig from the microsoft/xclip-base-patch32 style configuration
>>> model = XCLIPTextModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

XCLIPVisionConfig

class transformers.XCLIPVisionConfig

< >

( hidden_size = 768 intermediate_size = 3072 num_hidden_layers = 12 num_attention_heads = 12 mit_hidden_size = 512 mit_intermediate_size = 2048 mit_num_hidden_layers = 1 mit_num_attention_heads = 8 num_channels = 3 image_size = 224 patch_size = 32 num_frames = 8 hidden_act = 'quick_gelu' layer_norm_eps = 1e-05 attention_dropout = 0.0 initializer_range = 0.02 initializer_factor = 1.0 drop_path_rate = 0.0 **kwargs )

引數

  • hidden_size (int, 可選, 預設為 768) — 編碼器層和池化層維度。
  • intermediate_size (int, 可選, 預設為 3072) — Transformer 編碼器中“中間”(即前饋)層的維度。
  • num_hidden_layers (int, 可選, 預設為 12) — Transformer 編碼器中隱藏層的數量。
  • num_attention_heads (int, 可選, 預設為 12) — Transformer 編碼器中每個注意力層頭的數量。
  • mit_hidden_size (int, 可選, 預設為 512) — 多幀整合 Transformer(MIT)編碼器層的維度。
  • mit_intermediate_size (int, 可選, 預設為 2048) — 多幀整合 Transformer(MIT)中“中間”(即前饋)層的維度。
  • mit_num_hidden_layers (int, 可選, 預設為 1) — 多幀整合 Transformer(MIT)中隱藏層的數量。
  • mit_num_attention_heads (int, 可選, 預設為 8) — 多幀整合 Transformer(MIT)中每個注意力層頭的數量。
  • image_size (int, 可選, 預設為 224) — 每張影像的大小(解析度)。
  • patch_size (int, 可選, 預設為 32) — 每個影像塊的大小(解析度)。
  • hidden_act (strfunction, 可選, 預設為 "quick_gelu") — 編碼器和池化器中的非線性啟用函式(函式或字串)。如果為字串,則支援 "gelu""relu""selu""gelu_new""quick_gelu"
  • layer_norm_eps (float, 可選, 預設為 1e-5) — 層歸一化層使用的 epsilon 值。
  • attention_dropout (float, 可選, 預設為 0.0) — 注意力機率的 dropout 比率。
  • initializer_range (float, 可選, 預設為 0.02) — 用於初始化所有權重矩陣的 truncated_normal_initializer 的標準差。
  • initializer_factor (float, 可選, 預設為 1) — 用於初始化所有權重矩陣的因子(應保持為 1,內部用於初始化測試)。
  • drop_path_rate (float, 可選, 預設為 0.0) — 隨機深度率。

這是用於儲存 XCLIPModel 配置的配置類。它用於根據指定引數例項化 X-CLIP 模型,定義模型架構。使用預設值例項化配置將生成與 X-CLIP microsoft/xclip-base-patch32 架構類似的配置。

配置物件繼承自 PretrainedConfig,可用於控制模型輸出。有關更多資訊,請閱讀 PretrainedConfig 的文件。

示例

>>> from transformers import XCLIPVisionModel, XCLIPVisionConfig

>>> # Initializing a XCLIPVisionModel with microsoft/xclip-base-patch32 style configuration
>>> configuration = XCLIPVisionConfig()

>>> # Initializing a XCLIPVisionModel model from the microsoft/xclip-base-patch32 style configuration
>>> model = XCLIPVisionModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

XCLIPModel

class transformers.XCLIPModel

< >

( config: XCLIPConfig )

引數

  • config (XCLIPConfig) — 包含模型所有引數的模型配置類。使用配置檔案例項化不會載入與模型相關的權重,只加載配置。請檢視 from_pretrained() 方法以載入模型權重。

裸 X Clip 模型,不帶任何特定頭部地輸出原始隱藏狀態。

此模型繼承自 PreTrainedModel。請檢視超類文件,瞭解庫為其所有模型實現的一般方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。

此模型也是 PyTorch torch.nn.Module 子類。將其作為常規 PyTorch Module 使用,並參考 PyTorch 文件以瞭解所有與一般用法和行為相關的事項。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = None pixel_values: typing.Optional[torch.FloatTensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None return_loss: typing.Optional[bool] = 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.models.x_clip.modeling_x_clip.XCLIPOutputtuple(torch.FloatTensor)

引數

  • input_ids (torch.LongTensor 形狀為 (batch_size, sequence_length), 可選) — 詞彙表中輸入序列 token 的索引。預設情況下會忽略填充。

    可以使用 AutoTokenizer 獲取索引。有關詳細資訊,請參閱 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什麼是 input ID?

  • pixel_values (torch.FloatTensor 形狀為 (batch_size, num_channels, image_size, image_size), 可選) — 對應於輸入影像的張量。可以使用 {image_processor_class} 獲取畫素值。有關詳細資訊,請參閱 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 處理影像)。
  • attention_mask (torch.Tensor 形狀為 (batch_size, sequence_length), 可選) — 掩碼,用於避免在填充 token 索引上執行注意力。掩碼值選擇在 [0, 1]:

    • 1 表示**未被掩碼**的 token,
    • 0 表示**被掩碼**的 token。

    什麼是注意力掩碼?

  • position_ids (torch.LongTensor 形狀為 (batch_size, sequence_length), 可選) — 每個輸入序列 token 在位置嵌入中的位置索引。選擇範圍為 [0, config.n_positions - 1]

    什麼是 position ID?

  • return_loss (bool, 可選) — 是否返回對比損失。
  • output_attentions (bool, 可選) — 是否返回所有注意力層的注意力張量。有關詳細資訊,請參閱返回張量中的 attentions
  • output_hidden_states (bool, 可選) — 是否返回所有層的隱藏狀態。有關詳細資訊,請參閱返回張量中的 hidden_states
  • interpolate_pos_encoding (bool, 預設為 False) — 是否插值預訓練的位置編碼。
  • return_dict (bool, 可選) — 是否返回 ModelOutput 而不是普通元組。

返回

transformers.models.x_clip.modeling_x_clip.XCLIPOutputtuple(torch.FloatTensor)

transformers.models.x_clip.modeling_x_clip.XCLIPOutputtorch.FloatTensor 的元組(如果傳入 return_dict=Falseconfig.return_dict=False)包含各種元素,具體取決於配置(XCLIPConfig)和輸入。

  • loss (torch.FloatTensor 形狀為 (1,), 可選, 當 return_lossTrue 時返回) — 影片-文字相似度的對比損失。
  • logits_per_video (torch.FloatTensor 形狀為 (video_batch_size, text_batch_size)) — video_embedstext_embeds 之間的縮放點積分數。這表示影片-文字相似度分數。
  • logits_per_text (torch.FloatTensor 形狀為 (text_batch_size, video_batch_size)) — text_embedsvideo_embeds 之間的縮放點積分數。這表示文字-影片相似度分數。
  • text_embeds (torch.FloatTensor 形狀為 (batch_size, output_dim) — 透過將投影層應用於 XCLIPTextModel 的池化輸出獲得的文字嵌入。
  • video_embeds (torch.FloatTensor 形狀為 (batch_size, output_dim) — 透過將投影層應用於 XCLIPVisionModel 的池化輸出獲得的影片嵌入。
  • text_model_output (<class '~modeling_outputs.BaseModelOutputWithPooling'>.text_model_output, 預設為 None) — XCLIPTextModel 的輸出。
  • vision_model_output (<class '~modeling_outputs.BaseModelOutputWithPooling'>.vision_model_output, 預設為 None) — XCLIPVisionModel 的輸出。
  • mit_output (<class '~modeling_outputs.BaseModelOutputWithPooling'>.mit_output, 預設為 None) — XCLIPMultiframeIntegrationTransformer(簡稱 MIT)的輸出。

XCLIPModel 的 forward 方法,覆蓋了 __call__ 特殊方法。

儘管在此函式中需要定義前向傳播的配方,但之後應呼叫 Module 例項,而不是此函式,因為前者負責執行預處理和後處理步驟,而後者則靜默忽略它們。

示例

>>> import av
>>> import torch
>>> import numpy as np

>>> from transformers import AutoProcessor, AutoModel
>>> 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)

>>> processor = AutoProcessor.from_pretrained("microsoft/xclip-base-patch32")
>>> model = AutoModel.from_pretrained("microsoft/xclip-base-patch32")

>>> inputs = processor(
...     text=["playing sports", "eating spaghetti", "go shopping"],
...     videos=list(video),
...     return_tensors="pt",
...     padding=True,
... )

>>> # forward pass
>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> logits_per_video = outputs.logits_per_video  # this is the video-text similarity score
>>> probs = logits_per_video.softmax(dim=1)  # we can take the softmax to get the label probabilities
>>> print(probs)
tensor([[1.9496e-04, 9.9960e-01, 2.0825e-04]])

get_text_features

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) text_features (torch.FloatTensor 形狀為 (batch_size, output_dim)

引數

  • input_ids (torch.Tensor 形狀為 (batch_size, sequence_length), 可選) — 詞彙表中輸入序列 token 的索引。預設情況下會忽略填充。

    可以使用 AutoTokenizer 獲取索引。有關詳細資訊,請參閱 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什麼是 input ID?

  • attention_mask (torch.Tensor 形狀為 (batch_size, sequence_length), 可選) — 掩碼,用於避免在填充 token 索引上執行注意力。掩碼值選擇在 [0, 1]:

    • 1 表示**未被掩碼**的 token,
    • 0 表示**被掩碼**的 token。

    什麼是注意力掩碼?

  • position_ids (torch.Tensor 形狀為 (batch_size, sequence_length), 可選) — 每個輸入序列 token 在位置嵌入中的位置索引。選擇範圍為 [0, config.n_positions - 1]

    什麼是 position ID?

  • output_attentions (bool, 可選) — 是否返回所有注意力層的注意力張量。有關詳細資訊,請參閱返回張量中的 attentions
  • output_hidden_states (bool, 可選) — 是否返回所有層的隱藏狀態。有關詳細資訊,請參閱返回張量中的 hidden_states
  • return_dict (bool, 可選) — 是否返回 ModelOutput 而不是普通元組。

返回

text_features (torch.FloatTensor, 形狀為 (batch_size, output_dim)

透過將投影層應用於 XCLIPTextModel 的池化輸出獲得的文字嵌入。

示例

>>> from transformers import AutoTokenizer, AutoModel

>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/xclip-base-patch32")
>>> model = AutoModel.from_pretrained("microsoft/xclip-base-patch32")

>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
>>> text_features = model.get_text_features(**inputs)

get_video_features

< >

( pixel_values: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) video_features (torch.FloatTensor 形狀為 (batch_size, output_dim)

引數

  • pixel_values (torch.FloatTensor 形狀為 (batch_size, num_channels, image_size, image_size), 可選) — 對應於輸入影像的張量。可以使用 {image_processor_class} 獲取畫素值。有關詳細資訊,請參閱 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 處理影像)。
  • output_attentions (bool, 可選) — 是否返回所有注意力層的注意力張量。有關詳細資訊,請參閱返回張量中的 attentions
  • output_hidden_states (bool, 可選) — 是否返回所有層的隱藏狀態。有關詳細資訊,請參閱返回張量中的 hidden_states
  • return_dict (bool, 可選) — 是否返回 ModelOutput 物件而不是普通元組。

返回

video_features (torch.FloatTensor, 形狀為 (batch_size, output_dim))

透過將投影層應用於 XCLIPVisionModelXCLIPMultiframeIntegrationTransformer 的池化輸出而獲得的影片嵌入。

示例

>>> import av
>>> import torch
>>> import numpy as np

>>> from transformers import AutoProcessor, AutoModel
>>> 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)

>>> processor = AutoProcessor.from_pretrained("microsoft/xclip-base-patch32")
>>> model = AutoModel.from_pretrained("microsoft/xclip-base-patch32")

>>> inputs = processor(videos=list(video), return_tensors="pt")

>>> video_features = model.get_video_features(**inputs)

XCLIPTextModel

class transformers.XCLIPTextModel

< >

( config: XCLIPTextConfig )

forward

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: 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.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

引數

  • input_ids (torch.Tensor, 形狀為 (batch_size, sequence_length), 可選) — 詞彙表中輸入序列 token 的索引。填充預設會被忽略。

    索引可以使用 AutoTokenizer 獲取。詳情請參閱 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什麼是 input ID?

  • attention_mask (torch.Tensor, 形狀為 (batch_size, sequence_length), 可選) — 避免對填充 token 索引執行注意力操作的掩碼。掩碼值在 [0, 1] 中選擇:

    • 1 表示 未被掩蓋 的 token,
    • 0 表示 被掩蓋 的 token。

    什麼是注意力掩碼?

  • position_ids (torch.Tensor, 形狀為 (batch_size, sequence_length), 可選) — 每個輸入序列 token 在位置嵌入中的位置索引。選擇範圍為 [0, config.n_positions - 1]

    什麼是位置 ID?

  • output_attentions (bool, 可選) — 是否返回所有注意力層的注意力張量。更多詳情請參閱返回張量下的 attentions
  • output_hidden_states (bool, 可選) — 是否返回所有層的隱藏狀態。更多詳情請參閱返回張量下的 hidden_states
  • return_dict (bool, 可選) — 是否返回 ModelOutput 物件而不是普通元組。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

一個 transformers.modeling_outputs.BaseModelOutputWithPooling 物件,或者一個 torch.FloatTensor 元組(如果傳入 return_dict=False 或當 config.return_dict=False 時),其中包含根據配置 (XCLIPConfig) 和輸入而定的各種元素。

  • last_hidden_state (torch.FloatTensor, 形狀為 (batch_size, sequence_length, hidden_size)) — 模型最後一層輸出的隱藏狀態序列。

  • pooler_output (torch.FloatTensor, 形狀為 (batch_size, hidden_size)) — 序列中第一個 token (分類 token) 的最後一層隱藏狀態,經過用於輔助預訓練任務的層進一步處理。例如,對於 BERT 家族模型,這表示分類 token 經過線性層和 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 後的注意力權重,用於計算自注意力頭中的加權平均值。

XCLIPTextModel 的前向傳播方法,覆蓋了 __call__ 特殊方法。

儘管在此函式中需要定義前向傳播的配方,但之後應呼叫 Module 例項,而不是此函式,因為前者負責執行預處理和後處理步驟,而後者則靜默忽略它們。

示例

>>> from transformers import AutoTokenizer, XCLIPTextModel

>>> model = XCLIPTextModel.from_pretrained("microsoft/xclip-base-patch32")
>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/xclip-base-patch32")

>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")

>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output  # pooled (EOS token) states

XCLIPVisionModel

class transformers.XCLIPVisionModel

< >

( config: XCLIPVisionConfig )

forward

< >

( pixel_values: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

引數

  • pixel_values (torch.FloatTensor, 形狀為 (batch_size, num_channels, image_size, image_size), 可選) — 對應輸入影像的張量。畫素值可以使用 {image_processor_class} 獲取。詳情請參閱 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 處理影像)。
  • output_attentions (bool, 可選) — 是否返回所有注意力層的注意力張量。更多詳情請參閱返回張量下的 attentions
  • output_hidden_states (bool, 可選) — 是否返回所有層的隱藏狀態。更多詳情請參閱返回張量下的 hidden_states
  • return_dict (bool, 可選) — 是否返回 ModelOutput 物件而不是普通元組。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

一個 transformers.modeling_outputs.BaseModelOutputWithPooling 物件,或者一個 torch.FloatTensor 元組(如果傳入 return_dict=False 或當 config.return_dict=False 時),其中包含根據配置 (XCLIPConfig) 和輸入而定的各種元素。

  • last_hidden_state (torch.FloatTensor, 形狀為 (batch_size, sequence_length, hidden_size)) — 模型最後一層輸出的隱藏狀態序列。

  • pooler_output (torch.FloatTensor, 形狀為 (batch_size, hidden_size)) — 序列中第一個 token (分類 token) 的最後一層隱藏狀態,經過用於輔助預訓練任務的層進一步處理。例如,對於 BERT 家族模型,這表示分類 token 經過線性層和 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 後的注意力權重,用於計算自注意力頭中的加權平均值。

XCLIPVisionModel 的前向傳播方法,覆蓋了 __call__ 特殊方法。

儘管在此函式中需要定義前向傳播的配方,但之後應呼叫 Module 例項,而不是此函式,因為前者負責執行預處理和後處理步驟,而後者則靜默忽略它們。

示例

>>> import av
>>> import torch
>>> import numpy as np

>>> from transformers import AutoProcessor, XCLIPVisionModel
>>> 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=8, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
>>> video = read_video_pyav(container, indices)

>>> processor = AutoProcessor.from_pretrained("microsoft/xclip-base-patch32")
>>> model = XCLIPVisionModel.from_pretrained("microsoft/xclip-base-patch32")

>>> pixel_values = processor(videos=list(video), return_tensors="pt").pixel_values

>>> batch_size, num_frames, num_channels, height, width = pixel_values.shape
>>> pixel_values = pixel_values.reshape(-1, num_channels, height, width)

>>> outputs = model(pixel_values)
>>> last_hidden_state = outputs.last_hidden_state
< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.