Transformers 文档
X-CLIP
并获取增强的文档体验
开始使用
X-CLIP
概述
X-CLIP 模型由 Bolin Ni、Houwen Peng、Minghao Chen、Songyang Zhang、Gaofeng Meng、Jianlong Fu、Shiming Xiang、Haibin Ling 在 Expanding Language-Image Pretrained Models for General Video Recognition 中提出。 X-CLIP 是 CLIP 的最小扩展,用于视频。 该模型由文本编码器、跨帧视觉编码器、多帧集成 Transformer 和特定于视频的提示生成器组成。
本文的摘要如下
对比语言-图像预训练在从网络规模数据中学习视觉-文本联合表示方面取得了巨大成功,为各种图像任务展示了卓越的“零样本”泛化能力。然而,如何有效地将这种新的语言-图像预训练方法扩展到视频领域仍然是一个开放性问题。在这项工作中,我们提出了一种简单而有效的方法,可以直接将预训练的语言-图像模型适应于视频识别,而不是从头开始预训练新模型。更具体地说,为了捕获帧沿时间维度的长程依赖关系,我们提出了一种跨帧注意力机制,该机制显式地跨帧交换信息。这种模块是轻量级的,可以无缝地插入到预训练的语言-图像模型中。此外,我们提出了一种特定于视频的提示方案,该方案利用视频内容信息来生成判别性文本提示。大量的实验表明,我们的方法是有效的,并且可以推广到不同的视频识别场景。特别是在完全监督的设置下,我们的方法在 Kinectics-400 上实现了 87.1% 的 top-1 准确率,同时与 Swin-L 和 ViViT-H 相比,FLOPs 减少了 12 倍。在零样本实验中,我们的方法在两种流行的协议下,top-1 准确率分别超过了当前最先进的方法 +7.6% 和 +14.9%。在少样本场景中,当标记数据非常有限时,我们的方法比以前的最佳方法高出 +32.1% 和 +23.1%。
提示
- X-CLIP 的用法与 CLIP 相同。

此模型由 nielsr 贡献。 原始代码可以在 此处 找到。
资源
官方 Hugging Face 和社区(🌎 表示)资源列表,可帮助您开始使用 X-CLIP。
- X-CLIP 的演示 notebook 可以在此处找到。
如果您有兴趣提交资源以包含在此处,请随时打开 Pull Request,我们将对其进行审核! 该资源最好展示一些新的东西,而不是重复现有资源。
XCLIPProcessor
class transformers.XCLIPProcessor
< source >( image_processor = None tokenizer = None **kwargs )
参数
- image_processor (VideoMAEImageProcessor, 可选) — 图像处理器是必需的输入。
- tokenizer (CLIPTokenizerFast, 可选) — 分词器是必需的输入。
构建一个 X-CLIP 处理器,它将 VideoMAE 图像处理器和 CLIP 分词器包装到单个处理器中。
XCLIPProcessor 提供 VideoMAEImageProcessor 和 CLIPTokenizerFast 的所有功能。 有关更多信息,请参阅 __call__()
和 decode()。
此方法将其所有参数转发到 CLIPTokenizerFast 的 batch_decode()。 有关更多信息,请参阅此方法的文档字符串。
此方法将其所有参数转发给 CLIPTokenizerFast 的 decode() 方法。有关更多信息,请参阅此方法的文档字符串。
XCLIPConfig
class transformers.XCLIPConfig
< source >( 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 (
str
或function
, 可选, 默认为"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
< source >( text_config: XCLIPTextConfig vision_config: XCLIPVisionConfig **kwargs ) → XCLIPConfig
从 xclip 文本模型配置和 xclip 视觉模型配置实例化 XCLIPConfig(或派生类)。
XCLIPTextConfig
class transformers.XCLIPTextConfig
< source >( 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
可以表示的不同 token 的数量。 - 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 (
str
或function
, 可选, 默认为"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
< source >( 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 (
str
或function
,可选,默认为"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,内部用于初始化测试)。 - 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
< source >( config: XCLIPConfig )
参数
- config ( XCLIPConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解所有与常规用法和行为相关的事项。
forward
< source >( 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.XCLIPOutput
或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
,形状为(batch_size, sequence_length)
) — 词汇表中输入序列 tokens 的索引。如果您提供 padding,默认情况下 padding 将被忽略。索引可以使用 AutoTokenizer 获得。 有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor
,形状为(batch_size, sequence_length)
,可选) — Mask,用于避免在 padding token 索引上执行 attention。 Mask 值在[0, 1]
中选择:- 1 表示 未被 mask 的 tokens,
- 0 表示 被 mask 的 tokens。
- position_ids (
torch.LongTensor
,形状为(batch_size, sequence_length)
,可选) — 每个输入序列 tokens 在 position embeddings 中的位置索引。在范围[0, config.max_position_embeddings - 1]
中选择。 - pixel_values (
torch.FloatTensor
,形状为(batch_size, num_channels, height, width)
) — 像素值。如果您提供 padding,默认情况下 padding 将被忽略。像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参阅 CLIPImageProcessor.call()。 - return_loss (
bool
,可选) — 是否返回对比损失。 - output_attentions (
bool
,可选) — 是否返回所有 attention 层的 attentions tensors。 有关更多详细信息,请参阅返回的 tensors 下的attentions
。 - output_hidden_states (
bool
,可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参阅返回的 tensors 下的hidden_states
。 - interpolate_pos_encoding (
bool
,可选,默认为False
) — 是否插值预训练的位置编码。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是普通 tuple。
返回值
transformers.models.x_clip.modeling_x_clip.XCLIPOutput
或 tuple(torch.FloatTensor)
一个 transformers.models.x_clip.modeling_x_clip.XCLIPOutput
或一个 torch.FloatTensor
的 tuple (如果传递 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置 (<class 'transformers.models.x_clip.configuration_x_clip.XCLIPConfig'>
) 和输入。
- loss (
torch.FloatTensor
,形状为(1,)
,可选,当return_loss
为True
时返回) — 视频-文本相似度的对比损失。 - logits_per_video (
torch.FloatTensor
,形状为(video_batch_size, text_batch_size)
) —video_embeds
和text_embeds
之间缩放的点积分数。 这表示视频-文本相似度分数。 - logits_per_text (
torch.FloatTensor
,形状为(text_batch_size, video_batch_size)
) —text_embeds
和video_embeds
之间缩放的点积分数。 这表示文本-视频相似度分数。 - text_embeds(
torch.FloatTensor
,形状为(batch_size, output_dim
) — 通过将 projection 层应用于 XCLIPTextModel 的 pooled output 获得的文本 embeddings。 - video_embeds(
torch.FloatTensor
,形状为(batch_size, output_dim
) — 通过将 projection 层应用于 XCLIPVisionModel 的 pooled output 获得的视频 embeddings。 - text_model_output (
BaseModelOutputWithPooling
) — XCLIPTextModel 的输出。 - vision_model_output (
BaseModelOutputWithPooling
) — XCLIPVisionModel 的输出。 - mit_output (
BaseModelOutputWithPooling
) —XCLIPMultiframeIntegrationTransformer
(简称 MIT) 的输出。
XCLIPModel forward 方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的 recipe 需要在此函数中定义,但应在之后调用 Module
实例而不是此函数,因为前者负责运行 pre 和 post processing 步骤,而后者会默默地忽略它们。
示例
>>> 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
< source >( 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.LongTensor
,形状为(batch_size, sequence_length)
) — 词汇表中输入序列 tokens 的索引。如果您提供 padding,默认情况下 padding 将被忽略。索引可以使用 AutoTokenizer 获得。 有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor
,形状为(batch_size, sequence_length)
,可选) — Mask,用于避免在 padding token 索引上执行 attention。 Mask 值在[0, 1]
中选择:- 1 表示 未被 mask 的 tokens,
- 0 表示 被 mask 的 tokens。
- position_ids (
torch.LongTensor
,形状为(batch_size, sequence_length)
,可选) — 每个输入序列 tokens 在 position embeddings 中的位置索引。在范围[0, config.max_position_embeddings - 1]
中选择。 - output_attentions (
bool
,可选) — 是否返回所有 attention 层的 attentions tensors。 有关更多详细信息,请参阅返回的 tensors 下的attentions
。 - output_hidden_states (
bool
,可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参阅返回的 tensors 下的hidden_states
。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是普通 tuple。
返回值
text_features (torch.FloatTensor
,形状为 (batch_size, output_dim
)
通过将 projection 层应用于 XCLIPTextModel 的 pooled output 获得的文本 embeddings。
XCLIPModel forward 方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的 recipe 需要在此函数中定义,但应在之后调用 Module
实例而不是此函数,因为前者负责运行 pre 和 post processing 步骤,而后者会默默地忽略它们。
示例
>>> 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
< source >( 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, height, width)
) — 像素值。如果您提供 padding,默认情况下 padding 将被忽略。像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参阅 CLIPImageProcessor.call()。 - output_attentions (
bool
,可选) — 是否返回所有 attention 层的 attentions tensors。 有关更多详细信息,请参阅返回的 tensors 下的attentions
。 - output_hidden_states (
bool
,可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参阅返回的 tensors 下的hidden_states
。 - interpolate_pos_encoding (
bool
,可选,默认为False
) — 是否插值预训练的位置编码。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是普通 tuple。
返回值
video_features (torch.FloatTensor
,形状为 (batch_size, output_dim
)
通过将 projection 层应用于 XCLIPVisionModel 和 XCLIPMultiframeIntegrationTransformer
的 pooled output 获得的视频 embeddings。
XCLIPModel forward 方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的 recipe 需要在此函数中定义,但应在之后调用 Module
实例而不是此函数,因为前者负责运行 pre 和 post processing 步骤,而后者会默默地忽略它们。
示例
>>> 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
forward
< source >( 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.BaseModelOutputWithPooling or tuple(torch.FloatTensor)
参数
- input_ids (形状为
(batch_size, sequence_length)
的torch.LongTensor
) — 词汇表中输入序列 tokens 的索引。 如果您提供 padding,默认情况下将被忽略。索引可以使用 AutoTokenizer 获得。 有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (形状为
(batch_size, sequence_length)
的torch.Tensor
, 可选) — Mask 以避免在 padding token 索引上执行 attention。 Mask 值在[0, 1]
中选择:- 1 代表 未被 mask 的 tokens,
- 0 代表 被 mask 的 tokens。
- position_ids (形状为
(batch_size, sequence_length)
的torch.LongTensor
, 可选) — 位置 embeddings 中每个输入序列 tokens 的位置索引。 在范围[0, config.max_position_embeddings - 1]
中选择。 - output_attentions (
bool
, 可选) — 是否返回所有 attention 层的 attentions tensors。 有关更多详细信息,请参阅返回的 tensors 下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参阅返回的 tensors 下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的 tuple。
返回值
transformers.modeling_outputs.BaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.BaseModelOutputWithPooling 或一个 torch.FloatTensor
的 tuple (如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置 (<class 'transformers.models.x_clip.configuration_x_clip.XCLIPTextConfig'>
) 和输入。
-
last_hidden_state (形状为
(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
) — 模型最后一层的输出端的 hidden-states 序列。 -
pooler_output (形状为
(batch_size, hidden_size)
的torch.FloatTensor
) — 序列的第一个 token (分类 token) 的最后一层 hidden-state,在通过用于辅助预训练任务的层进一步处理之后。 例如,对于 BERT 系列模型,这返回通过线性层和 tanh 激活函数处理后的分类 token。 线性层权重通过预训练期间的下一句预测(分类)目标进行训练。 -
hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的 tuple (如果模型具有 embedding 层,则为 embedding 的输出 + 每层的输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出端的 Hidden-states 加上可选的初始 embedding 输出。
-
attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的 tuple (每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 Attentions 权重,用于计算 self-attention heads 中的加权平均值。
XCLIPTextModel 的 forward 方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的 recipe 需要在此函数中定义,但应在之后调用 Module
实例而不是此函数,因为前者负责运行 pre 和 post processing 步骤,而后者会默默地忽略它们。
示例
>>> 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
forward
< source >( 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.BaseModelOutputWithPooling or tuple(torch.FloatTensor)
参数
- pixel_values (形状为
(batch_size, num_channels, height, width)
的torch.FloatTensor
) — 像素值。 如果您提供 padding,默认情况下将被忽略。 像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参阅 CLIPImageProcessor.call() 。 - output_attentions (
bool
, 可选) — 是否返回所有 attention 层的 attentions tensors。 有关更多详细信息,请参阅返回的 tensors 下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参阅返回的 tensors 下的hidden_states
。 - interpolate_pos_encoding (
bool
, 可选, 默认为False
) — 是否插值预训练的位置编码。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的 tuple。
返回值
transformers.modeling_outputs.BaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.BaseModelOutputWithPooling 或一个 torch.FloatTensor
的 tuple (如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置 (<class 'transformers.models.x_clip.configuration_x_clip.XCLIPVisionConfig'>
) 和输入。
-
last_hidden_state (形状为
(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
) — 模型最后一层的输出端的 hidden-states 序列。 -
pooler_output (形状为
(batch_size, hidden_size)
的torch.FloatTensor
) — 序列的第一个 token (分类 token) 的最后一层 hidden-state,在通过用于辅助预训练任务的层进一步处理之后。 例如,对于 BERT 系列模型,这返回通过线性层和 tanh 激活函数处理后的分类 token。 线性层权重通过预训练期间的下一句预测(分类)目标进行训练。 -
hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的 tuple (如果模型具有 embedding 层,则为 embedding 的输出 + 每层的输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出端的 Hidden-states 加上可选的初始 embedding 输出。
-
attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的 tuple (每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 Attentions 权重,用于计算 self-attention heads 中的加权平均值。
XCLIPVisionModel 的 forward 方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的 recipe 需要在此函数中定义,但应在之后调用 Module
实例而不是此函数,因为前者负责运行 pre 和 post processing 步骤,而后者会默默地忽略它们。
示例
>>> 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