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 上更新