Transformers 文档
TVP
并获得增强的文档体验
开始使用
TVP
概览
文本-视觉提示(TVP)框架在论文 Text-Visual Prompting for Efficient 2D Temporal Video Grounding 中提出,作者为 Yimeng Zhang、Xin Chen、Jinghan Jia、Sijia Liu、Ke Ding。
该论文的摘要如下:
在本文中,我们研究了时间视频定位(TVG)问题,其目的是预测由文本句子描述的时刻在长未修剪视频中的开始/结束时间点。受益于细粒度的 3D 视觉特征,TVG 技术近年来取得了显著进展。然而,3D 卷积神经网络(CNN)的高复杂性使得提取密集的 3D 视觉特征非常耗时,这需要大量的内存和计算资源。为了实现高效的 TVG,我们提出了一种新颖的文本-视觉提示(TVP)框架,该框架将优化的扰动模式(我们称之为“提示”)融入到 TVG 模型的视觉输入和文本特征中。与 3D CNN 形成鲜明对比的是,我们表明 TVP 使我们能够有效地在 2D TVG 模型中共同训练视觉编码器和语言编码器,并仅使用低复杂度的稀疏 2D 视觉特征来提高跨模态特征融合的性能。此外,我们提出了一种时间距离 IoU(TDIoU)损失,用于高效学习 TVG。在两个基准数据集 Charades-STA 和 ActivityNet Captions 数据集上的实验结果表明,所提出的 TVP 显著提高了 2D TVG 的性能(例如,在 Charades-STA 上提高了 9.79%,在 ActivityNet Captions 上提高了 30.77%),并且在使用 3D 视觉特征的 TVG 上实现了 5 倍的推理加速。
这项研究解决了时间视频定位(TVG)问题,即精确定位长视频中由文本句子描述的特定事件的开始和结束时间。提出了文本-视觉提示(TVP)来增强 TVG。TVP 涉及将专门设计的模式(称为“提示”)集成到 TVG 模型的视觉(基于图像)和文本(基于单词)输入组件中。这些提示提供了额外的时空上下文,提高了模型准确确定视频中事件时间的能力。该方法采用 2D 视觉输入代替 3D 输入。虽然 3D 输入提供更丰富的时空细节,但它们也更耗时处理。使用 2D 输入和提示方法旨在更有效地提供相似水平的上下文和准确性。

此模型由 Jiqing Feng 贡献。 原始代码可以在这里找到。
使用技巧和示例
提示是优化的扰动模式,将添加到输入视频帧或文本特征中。通用集指的是对任何输入使用完全相同的提示集,这意味着这些提示一致地添加到所有视频帧和文本特征中,而与输入的内容无关。
TVP 由视觉编码器和跨模态编码器组成。一组通用的视觉提示和文本提示分别集成到采样的视频帧和文本特征中。特别地,一组不同的视觉提示按顺序应用于一个未修剪视频的均匀采样的帧。
该模型的目的是将可训练的提示融入到视觉输入和文本特征中,以解决时间视频定位(TVG)问题。原则上,可以在提出的架构中应用任何视觉、跨模态编码器。
TvpProcessor 将 BertTokenizer 和 TvpImageProcessor 包装到单个实例中,以同时编码文本和分别准备图像。
以下示例演示了如何使用 TvpProcessor 和 TvpForVideoGrounding 运行时间视频定位。
import av
import cv2
import numpy as np
import torch
from huggingface_hub import hf_hub_download
from transformers import AutoProcessor, TvpForVideoGrounding
def pyav_decode(container, sampling_rate, num_frames, clip_idx, num_clips, target_fps):
'''
Convert the video from its original fps to the target_fps and decode the video with PyAV decoder.
Args:
container (container): pyav container.
sampling_rate (int): frame sampling rate (interval between two sampled frames).
num_frames (int): number of frames to sample.
clip_idx (int): if clip_idx is -1, perform random temporal sampling.
If clip_idx is larger than -1, uniformly split the video to num_clips
clips, and select the clip_idx-th video clip.
num_clips (int): overall number of clips to uniformly sample from the given video.
target_fps (int): the input video may have different fps, convert it to
the target video fps before frame sampling.
Returns:
frames (tensor): decoded frames from the video. Return None if the no
video stream was found.
fps (float): the number of frames per second of the video.
'''
video = container.streams.video[0]
fps = float(video.average_rate)
clip_size = sampling_rate * num_frames / target_fps * fps
delta = max(num_frames - clip_size, 0)
start_idx = delta * clip_idx / num_clips
end_idx = start_idx + clip_size - 1
timebase = video.duration / num_frames
video_start_pts = int(start_idx * timebase)
video_end_pts = int(end_idx * timebase)
seek_offset = max(video_start_pts - 1024, 0)
container.seek(seek_offset, any_frame=False, backward=True, stream=video)
frames = {}
for frame in container.decode(video=0):
if frame.pts < video_start_pts:
continue
frames[frame.pts] = frame
if frame.pts > video_end_pts:
break
frames = [frames[pts] for pts in sorted(frames)]
return frames, fps
def decode(container, sampling_rate, num_frames, clip_idx, num_clips, target_fps):
'''
Decode the video and perform temporal sampling.
Args:
container (container): pyav container.
sampling_rate (int): frame sampling rate (interval between two sampled frames).
num_frames (int): number of frames to sample.
clip_idx (int): if clip_idx is -1, perform random temporal sampling.
If clip_idx is larger than -1, uniformly split the video to num_clips
clips, and select the clip_idx-th video clip.
num_clips (int): overall number of clips to uniformly sample from the given video.
target_fps (int): the input video may have different fps, convert it to
the target video fps before frame sampling.
Returns:
frames (tensor): decoded frames from the video.
'''
assert clip_idx >= -2, "Not a valid clip_idx {}".format(clip_idx)
frames, fps = pyav_decode(container, sampling_rate, num_frames, clip_idx, num_clips, target_fps)
clip_size = sampling_rate * num_frames / target_fps * fps
index = np.linspace(0, clip_size - 1, num_frames)
index = np.clip(index, 0, len(frames) - 1).astype(np.int64)
frames = np.array([frames[idx].to_rgb().to_ndarray() for idx in index])
frames = frames.transpose(0, 3, 1, 2)
return frames
file = hf_hub_download(repo_id="Intel/tvp_demo", filename="AK2KG.mp4", repo_type="dataset")
model = TvpForVideoGrounding.from_pretrained("Intel/tvp-base")
decoder_kwargs = dict(
container=av.open(file, metadata_errors="ignore"),
sampling_rate=1,
num_frames=model.config.num_frames,
clip_idx=0,
num_clips=1,
target_fps=3,
)
raw_sampled_frms = decode(**decoder_kwargs)
text = "a person is sitting on a bed."
processor = AutoProcessor.from_pretrained("Intel/tvp-base")
model_inputs = processor(
text=[text], videos=list(raw_sampled_frms), return_tensors="pt", max_text_length=100#, size=size
)
model_inputs["pixel_values"] = model_inputs["pixel_values"].to(model.dtype)
output = model(**model_inputs)
def get_video_duration(filename):
cap = cv2.VideoCapture(filename)
if cap.isOpened():
rate = cap.get(5)
frame_num = cap.get(7)
duration = frame_num/rate
return duration
return -1
duration = get_video_duration(file)
start, end = processor.post_process_video_grounding(output.logits, duration)
print(f"The time slot of the video corresponding to the text \"{text}\" is from {start}s to {end}s")
提示
- TVP 的此实现使用 BertTokenizer 生成文本嵌入,并使用 Resnet-50 模型计算视觉嵌入。
- 预训练的 tvp-base 的检查点已发布。
- 有关 TVP 在时间视频定位任务上的性能,请参阅 表 2。
TvpConfig
class transformers.TvpConfig
< source >( backbone_config = None backbone = None use_pretrained_backbone = False use_timm_backbone = False backbone_kwargs = None distance_loss_weight = 1.0 duration_loss_weight = 0.1 visual_prompter_type = 'framepad' visual_prompter_apply = 'replace' visual_prompt_size = 96 max_img_size = 448 num_frames = 48 vocab_size = 30522 hidden_size = 768 intermediate_size = 3072 num_hidden_layers = 12 num_attention_heads = 12 max_position_embeddings = 512 max_grid_col_position_embeddings = 100 max_grid_row_position_embeddings = 100 hidden_dropout_prob = 0.1 hidden_act = 'gelu' layer_norm_eps = 1e-12 initializer_range = 0.02 attention_probs_dropout_prob = 0.1 **kwargs )
参数
- backbone_config (
PretrainedConfig
或dict
, 可选) — backbone 模型的配置。 - backbone (
str
, 可选) — 当backbone_config
为None
时要使用的 backbone 名称。如果use_pretrained_backbone
为True
,这将从 timm 或 transformers 库加载相应的预训练权重。如果use_pretrained_backbone
为False
,这将加载 backbone 的配置并使用它来初始化具有随机权重的 backbone。 - use_pretrained_backbone (
bool
, optional, defaults toFalse
) — 是否使用预训练的 backbone 权重。 - use_timm_backbone (
bool
, optional, defaults toFalse
) — 是否从 timm 库加载backbone
。如果为False
,则从 transformers 库加载 backbone。 - backbone_kwargs (
dict
, optional) — 从检查点加载时,传递给 AutoBackbone 的关键字参数,例如{'out_indices': (0, 1, 2, 3)}
。如果设置了backbone_config
,则不能指定此项。 - distance_loss_weight (
float
, optional, defaults to 1.0) — 距离损失的权重。 - duration_loss_weight (
float
, optional, defaults to 0.1) — 时长损失的权重。 - visual_prompter_type (
str
, optional, defaults to"framepad"
) — 视觉提示类型。填充类型。Framepad 表示在每个帧上填充。应为 “framepad” 或 “framedownpad” 之一 - visual_prompter_apply (
str
, optional, defaults to"replace"
) — 应用视觉提示的方式。“Replace” 表示使用提示的值来更改视觉输入中的原始值。应为 “replace”、“add” 或 “remove” 之一。 - visual_prompt_size (
int
, optional, defaults to 96) — 视觉提示的大小。 - max_img_size (
int
, optional, defaults to 448) — 帧的最大尺寸。 - num_frames (
int
, optional, defaults to 48) — 从视频中提取的帧数。 - vocab_size (
int
, optional, defaults to 30522) — Tvp 文本模型的词汇表大小。定义了调用 TvpModel 时传递的inputs_ids
可以表示的不同 token 的数量。 - hidden_size (
int
, optional, defaults to 768) — 编码器层的维度。 - intermediate_size (
int
, optional, defaults to 3072) — Transformer 编码器中“中间”层(即,前馈层)的维度。 - num_hidden_layers (
int
, optional, defaults to 12) — Transformer 编码器中隐藏层的数量。 - num_attention_heads (
int
, optional, defaults to 12) — Transformer 编码器中每个注意力层的注意力头数。 - max_position_embeddings (
int
, optional, defaults to 512) — 此模型可能使用的最大序列长度。通常设置为较大的值以防万一(例如,512 或 1024 或 2048)。 - max_grid_col_position_embeddings (
int
, optional, defaults to 100) — 来自视频帧的最大水平 patch 数量。 - max_grid_row_position_embeddings (
int
, optional, defaults to 100) — 来自视频帧的最大垂直 patch 数量。 - hidden_dropout_prob (
float
, optional, defaults to 0.1) — 隐藏层的 dropout 概率。 - hidden_act (
str
或function
, optional, defaults to"gelu"
) — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,则支持"gelu"
,"relu"
,"selu"
和"gelu_new"
"quick_gelu"
。 - layer_norm_eps (
float
, optional, defaults to 1e-12) — 层归一化层使用的 epsilon 值。 - initializer_range (
float
, optional, defaults to 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - attention_probs_dropout_prob (
float
, optional, defaults to 0.1) — 注意力层的 dropout 概率。
这是用于存储 TvpModel 配置的配置类。它用于根据指定的参数实例化 Tvp 模型,定义模型架构。使用默认值实例化配置将产生与 Tvp Intel/tvp-base 架构类似的配置。
配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PretrainedConfig 的文档。
from_backbone_config
< source >( backbone_config: PretrainedConfig **kwargs ) → TvpConfig
从预训练的 backbone 模型配置实例化 TvpConfig(或派生类)。
将此实例序列化为 Python 字典。覆盖默认的 to_dict()。
TvpImageProcessor
class transformers.TvpImageProcessor
< source >( do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling = <Resampling.BILINEAR: 2> do_center_crop: bool = True crop_size: typing.Dict[str, int] = None do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_pad: bool = True pad_size: typing.Dict[str, int] = None constant_values: typing.Union[float, typing.Iterable[float]] = 0 pad_mode: PaddingMode = <PaddingMode.CONSTANT: 'constant'> do_normalize: bool = True do_flip_channel_order: bool = True image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None **kwargs )
参数
- do_resize (
bool
, 可选, 默认为True
) — 是否将图像的 (高度, 宽度) 尺寸调整为指定的size
大小。可以被preprocess
方法中的do_resize
参数覆盖。 - size (
Dict[str, int]
可选, 默认为{"longest_edge" -- 448}
): 调整大小后输出图像的尺寸。图像的最长边将被调整为size["longest_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" -- 448, "width": 448}
): 应用中心裁剪后图像的尺寸。可以被preprocess
方法中的crop_size
参数覆盖。 - do_rescale (
bool
, 可选, 默认为True
) — 是否通过指定的缩放比例rescale_factor
重新缩放图像。可以被preprocess
方法中的do_rescale
参数覆盖。 - rescale_factor (
int
或float
, 可选, 默认为1/255
) — 定义重新缩放图像时使用的缩放因子。可以被preprocess
方法中的rescale_factor
参数覆盖。 - do_pad (
bool
, 可选, 默认为True
) — 是否填充图像。可以被preprocess
方法中的do_pad
参数覆盖。 - pad_size (
Dict[str, int]
, 可选, 默认为{"height" -- 448, "width": 448}
): 应用填充后图像的尺寸。可以被preprocess
方法中的pad_size
参数覆盖。 - constant_values (
Union[float, Iterable[float]]
, 可选, 默认为 0) — 填充图像时使用的填充值。 - pad_mode (
PaddingMode
, 可选, 默认为PaddingMode.CONSTANT
) — 填充时使用的模式类型。 - do_normalize (
bool
, 可选, 默认为True
) — 是否标准化图像。可以被preprocess
方法中的do_normalize
参数覆盖。 - do_flip_channel_order (
bool
, 可选, 默认为True
) — 是否将颜色通道从 RGB 翻转到 BGR。可以被preprocess
方法中的do_flip_channel_order
参数覆盖。 - image_mean (
float
或List[float]
, 可选, 默认为IMAGENET_STANDARD_MEAN
) — 标准化图像时使用的均值。这是一个浮点数或浮点数列表,其长度等于图像中的通道数。可以被preprocess
方法中的image_mean
参数覆盖。 - image_std (
float
或List[float]
, 可选, 默认为IMAGENET_STANDARD_STD
) — 标准化图像时使用的标准差。这是一个浮点数或浮点数列表,其长度等于图像中的通道数。可以被preprocess
方法中的image_std
参数覆盖。
构造 Tvp 图像处理器。
preprocess
< source >( videos: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], typing.List[typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]], typing.List[typing.List[typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]]]] do_resize: bool = None size: typing.Dict[str, int] = None resample: Resampling = None do_center_crop: bool = None crop_size: typing.Dict[str, int] = None do_rescale: bool = None rescale_factor: float = None do_pad: bool = None pad_size: typing.Dict[str, int] = None constant_values: typing.Union[float, typing.Iterable[float]] = None pad_mode: PaddingMode = None do_normalize: bool = None do_flip_channel_order: bool = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.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[transformers.image_utils.ChannelDimension, str, NoneType] = None )
参数
- videos (
ImageInput
或List[ImageInput]
或List[List[ImageInput]]
) — 要预处理的帧。 - 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
) — 是否将图像值重新缩放到 [0 - 1] 之间。 - rescale_factor (
float
, 可选, 默认为self.rescale_factor
) — 如果do_rescale
设置为True
,则使用此缩放因子重新缩放图像。 - do_pad (
bool
, optional, defaults toTrue
) — 是否填充图像。可以通过preprocess
方法中的do_pad
参数覆盖此设置。 - pad_size (
Dict[str, int]
, optional, defaults to{"height" -- 448, "width": 448}
): 应用填充后图像的尺寸。可以通过preprocess
方法中的pad_size
参数覆盖此设置。 - constant_values (
Union[float, Iterable[float]]
, optional, defaults to 0) — 填充图像时使用的填充值。 - pad_mode (
PaddingMode
, optional, defaults to “PaddingMode.CONSTANT”) — 填充时使用的模式类型。 - do_normalize (
bool
, optional, defaults toself.do_normalize
) — 是否标准化图像。 - do_flip_channel_order (
bool
, optional, defaults toself.do_flip_channel_order
) — 是否翻转图像的通道顺序。 - image_mean (
float
orList[float]
, optional, defaults toself.image_mean
) — 图像均值。 - image_std (
float
orList[float]
, optional, defaults toself.image_std
) — 图像标准差。 - return_tensors (
str
orTensorType
, optional) — 返回的张量类型。可以是以下之一:- 未设置:返回
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
orstr
, optional, defaults toChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:ChannelDimension.FIRST
:图像格式为 (num_channels, height, width)。ChannelDimension.LAST
:图像格式为 (height, width, num_channels)。- 未设置:使用输入图像的推断通道维度格式。
- input_data_format (
ChannelDimension
orstr
, optional) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
:图像格式为 (height, width)。
预处理图像或一批图像。
TvpProcessor
class transformers.TvpProcessor
< source >( image_processor = None tokenizer = None **kwargs )
参数
- image_processor (TvpImageProcessor, optional) — 图像处理器是必需的输入。
- tokenizer (BertTokenizerFast, optional) — 分词器是必需的输入。
构建一个 TVP 处理器,该处理器将 TVP 图像处理器和 Bert 分词器包装成一个单一的处理器。
TvpProcessor 提供 TvpImageProcessor 和 BertTokenizerFast 的所有功能。有关更多信息,请参阅 **call**() 和 decode()
。
__call__
< source >( text = None videos = None return_tensors = None **kwargs ) → BatchEncoding
参数
- text (
str
,List[str]
,List[List[str]]
) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果序列以字符串列表(预分词)的形式提供,则必须设置 `is_split_into_words=True`(以消除与序列批次的歧义)。 - videos (
List[PIL.Image.Image]
,List[np.ndarray]
,List[torch.Tensor]
,List[List[PIL.Image.Image]]
,List[List[np.ndarrray]]
, —List[List[torch.Tensor]]
): 要准备的视频或视频批次。每个视频应为帧列表,可以是 PIL 图像或 NumPy 数组。如果使用 NumPy 数组/PyTorch 张量,则每帧应具有形状 (H, W, C),其中 H 和 W 是帧的高度和宽度,C 是通道数。 - return_tensors (
str
or TensorType, optional) — 如果设置,将返回特定框架的张量。可接受的值为:'tf'
:返回 TensorFlowtf.constant
对象。'pt'
:返回 PyTorchtorch.Tensor
对象。'np'
:返回 NumPynp.ndarray
对象。'jax'
:返回 JAXjnp.ndarray
对象。
Returns
具有以下字段的 BatchEncoding
- input_ids — 要馈送到模型的 token id 列表。当
text
不为None
时返回。 - attention_mask — 指定模型应关注哪些 token 的索引列表(当 `return_attention_mask=True` 或如果 “attention_mask” 在 `self.model_input_names` 中且 `text` 不为 `None` 时)。
- pixel_values — 要馈送到模型的像素值。当
videos
不为None
时返回。
用于为模型准备一个或多个序列和图像的主要方法。如果 `text` 不为 `None` 以编码文本,此方法将 `text` 和 `kwargs` 参数转发到 BertTokenizerFast 的 **call**()。如果 `videos` 不为 `None`,此方法将 `videos` 和 `kwargs` 参数转发到 TvpImageProcessor 的 **call**() 以准备图像。有关更多信息,请参阅上述两种方法的文档字符串。
TvpModel
class transformers.TvpModel
< source >( config )
参数
- config (TvpConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
裸 Tvp 模型 Transformer,输出不带任何特定头部之上的 BaseModelOutputWithPooling 对象。此模型是 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.LongTensor] = None head_mask: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None interpolate_pos_encoding: bool = False ) → transformers.modeling_outputs.BaseModelOutputWithPooling or tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — 词汇表中输入序列 tokens 的索引。可以使用 AutoTokenizer 获取索引。 有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。 什么是输入 IDs? - pixel_values (
torch.FloatTensor
of shape(batch_size, num_frames, num_channels, height, width)
) — 像素值。可以使用 TvpImageProcessor 获取像素值。 有关详细信息,请参阅 TvpImageProcessor.call()。 - attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) — 用于避免在 padding token 索引上执行 attention 的掩码。 掩码值在[0, 1]
中选择:- 1 表示 tokens 未被掩盖,
- 0 表示 tokens 被掩盖。 什么是 attention masks?
- head_mask (
torch.FloatTensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional) — 用于 nullify self-attention 模块的选定 head 的掩码。 掩码值在[0, 1]
中选择:- 1 表示 head 未被掩盖,
- 0 表示 head 被掩盖。
- output_attentions (
bool
, optional) — 是否返回所有 attention 层的 attentions tensors。 有关更多详细信息,请参阅返回的 tensors 下的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的 hidden states。 有关更多详细信息,请参阅返回的 tensors 下的hidden_states
。 - return_dict (
bool
, optional) — 是否返回 ModelOutput 而不是纯元组。 - interpolate_pos_encoding (
bool
, optional, defaults toFalse
) — 是否插值预训练的图像 pad prompter 编码和位置编码。
Returns
transformers.modeling_outputs.BaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.BaseModelOutputWithPooling 或 torch.FloatTensor
的元组 (如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置 (<class 'transformers.models.tvp.configuration_tvp.TvpConfig'>
) 和输入。
-
last_hidden_state (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
) — 模型最后一层的输出端的 hidden-states 序列。 -
pooler_output (
torch.FloatTensor
of shape(batch_size, hidden_size)
) — 序列的第一个 token (classification token) 的最后一层 hidden-state,在通过用于辅助预训练任务的层进一步处理之后。 例如,对于 BERT 系列模型,这将返回通过线性层和 tanh 激活函数处理后的 classification token。 线性层权重通过预训练期间的 next sentence prediction(分类)目标进行训练。 -
hidden_states (
tuple(torch.FloatTensor)
, optional, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的元组(对于 embeddings 的输出,如果模型具有 embedding 层,则为一个;对于每个层的输出,则为一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出端的 Hidden-states 加上可选的初始 embedding 输出。
-
attentions (
tuple(torch.FloatTensor)
, optional, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的元组(对于每一层,则为一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 后的 Attention 权重,用于计算 self-attention heads 中的加权平均值。
TvpModel forward 方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的配方需要在该函数中定义,但应该在之后调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> import torch
>>> from transformers import AutoConfig, AutoTokenizer, TvpModel
>>> model = TvpModel.from_pretrained("Jiqing/tiny-random-tvp")
>>> tokenizer = AutoTokenizer.from_pretrained("Jiqing/tiny-random-tvp")
>>> pixel_values = torch.rand(1, 1, 3, 448, 448)
>>> text_inputs = tokenizer("This is an example input", return_tensors="pt")
>>> output = model(text_inputs.input_ids, pixel_values, text_inputs.attention_mask)
TvpForVideoGrounding
class transformers.TvpForVideoGrounding
< source >( config )
参数
- config (TvpConfig) — 带有模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型关联的权重,仅加载配置。 查看 from_pretrained() 方法以加载模型权重。
带有视频 grounding head 的 Tvp 模型,在顶部计算 IoU、距离和持续时间损失。
此模型是 PyTorch torch.nn.Module 子类。 将其用作常规 PyTorch Module,并参阅 PyTorch 文档以获取与常规用法和行为相关的所有事项。
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = None pixel_values: typing.Optional[torch.FloatTensor] = None attention_mask: typing.Optional[torch.LongTensor] = None labels: typing.Tuple[torch.Tensor] = None head_mask: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None interpolate_pos_encoding: bool = False ) → transformers.models.tvp.modeling_tvp.TvpVideoGroundingOutput
or tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — 词汇表中输入序列 tokens 的索引。可以使用 AutoTokenizer 获取索引。 有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。 什么是输入 IDs? - pixel_values (
torch.FloatTensor
of shape(batch_size, num_frames, num_channels, height, width)
) — 像素值。可以使用 TvpImageProcessor 获取像素值。 有关详细信息,请参阅 TvpImageProcessor.call()。 - attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) — 用于避免在 padding token 索引上执行 attention 的掩码。 掩码值在[0, 1]
中选择:- 1 表示 tokens 未被掩盖,
- 0 表示 tokens 被掩盖。 什么是 attention masks?
- head_mask (
torch.FloatTensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional) — 用于 nullify self-attention 模块的选定 head 的掩码。 掩码值在[0, 1]
中选择:- 1 表示 head 未被掩盖,
- 0 表示 head 被掩盖。
- output_attentions (
bool
, optional) — 是否返回所有 attention 层的 attentions tensors。 有关更多详细信息,请参阅返回的 tensors 下的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的 hidden states。 有关更多详细信息,请参阅返回的 tensors 下的hidden_states
。 - return_dict (
bool
, optional) — 是否返回 ModelOutput 而不是纯元组。 - interpolate_pos_encoding (
bool
, optional, defaults toFalse
) — 是否插值预训练的图像 pad prompter 编码和位置编码。 - labels (
torch.FloatTensor
of shape(batch_size, 3)
, optional) — labels 包含与文本对应的视频的持续时间、开始时间和结束时间。
Returns
transformers.models.tvp.modeling_tvp.TvpVideoGroundingOutput
或 tuple(torch.FloatTensor)
一个 transformers.models.tvp.modeling_tvp.TvpVideoGroundingOutput
或 torch.FloatTensor
的元组 (如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置 (<class 'transformers.models.tvp.configuration_tvp.TvpConfig'>
) 和输入。
- loss (
torch.FloatTensor
of shape(1,)
, optional, 当return_loss
为True
时返回) — 用于视频 grounding 的 Temporal-Distance IoU 损失。 - logits (
torch.FloatTensor
of shape(batch_size, 2)
) — 包含 start_time/duration 和 end_time/duration。 它是与输入文本对应的视频的时间段。 - hidden_states (
tuple(torch.FloatTensor)
, optional, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的元组(对于 embeddings 的输出,如果模型具有 embedding 层,则为一个;对于每个层的输出,则为一个),形状为(batch_size, sequence_length, hidden_size)
。 模型在每一层输出端的 Hidden-states 加上可选的初始 embedding 输出。 - attentions (
tuple(torch.FloatTensor)
, optional, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的元组(对于每一层,则为一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。
TvpForVideoGrounding forward 方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的配方需要在该函数中定义,但应该在之后调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> import torch
>>> from transformers import AutoConfig, AutoTokenizer, TvpForVideoGrounding
>>> model = TvpForVideoGrounding.from_pretrained("Jiqing/tiny-random-tvp")
>>> tokenizer = AutoTokenizer.from_pretrained("Jiqing/tiny-random-tvp")
>>> pixel_values = torch.rand(1, 1, 3, 448, 448)
>>> text_inputs = tokenizer("This is an example input", return_tensors="pt")
>>> output = model(text_inputs.input_ids, pixel_values, text_inputs.attention_mask)