Transformers 文档

TVP

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

TVP

PyTorch

概述

文本-视觉提示 (TVP) 框架由 Yimeng Zhang, Xin Chen, Jinghan Jia, Sijia Liu, Ke Ding 在论文 Text-Visual Prompting for Efficient 2D Temporal Video Grounding 中提出。

论文摘要如下:

在本文中,我们研究了时间视频定位 (TVG) 问题,该问题旨在预测长未剪辑视频中由文本语句描述的时刻的开始/结束时间点。得益于细粒度的 3D 视觉特征,TVG 技术近年来取得了显著进展。然而,3D 卷积神经网络 (CNN) 的高复杂性使得提取密集 3D 视觉特征非常耗时,这需要大量的内存和计算资源。为了实现高效的 TVG,我们提出了一种新颖的文本-视觉提示 (TVP) 框架,该框架将优化后的扰动模式(我们称之为“提示”)整合到 TVG 模型的视觉输入和文本特征中。与 3D CNN 形成鲜明对比的是,我们展示了 TVP 允许我们有效地协同训练 2D TVG 模型中的视觉编码器和语言编码器,并仅使用低复杂度的稀疏 2D 视觉特征提高跨模态特征融合的性能。此外,我们提出了一种用于 TVG 高效学习的时间-距离 IoU (TDIoU) 损失。在 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 输入和提示方法旨在更有效地提供类似级别的上下文和准确性。

drawing TVP 架构。摘自原始论文。

此模型由 Jiqing Feng 贡献。原始代码可在此处找到。

使用技巧和示例

提示是优化的扰动模式,将添加到输入视频帧或文本特征中。通用集是指对任何输入使用完全相同的提示集,这意味着这些提示会一致地添加到所有视频帧和文本特征中,而不管输入内容如何。

TVP 由一个视觉编码器和跨模态编码器组成。一套通用的视觉提示和文本提示将分别整合到采样的视频帧和文本特征中。特别地,一组不同的视觉提示将按顺序应用于一个未剪辑视频的均匀采样帧。

此模型的目标是将可训练提示集成到视觉输入和文本特征中,以解决时间视频定位 (TVG) 问题。原则上,可以在所提出的架构中应用任何视觉、跨模态编码器。

TvpProcessorBertTokenizerTvpImageProcessor 包装成一个单一实例,用于分别编码文本和准备图像。

以下示例展示了如何使用 TvpProcessorTvpForVideoGrounding 运行时间视频定位。

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

transformers.TvpConfig

< >

( 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 (PretrainedConfigdict, 可选) — 骨干模型的配置。
  • backbone (str, 可选) — 当 backbone_configNone 时使用的骨干模型的名称。如果 use_pretrained_backboneTrue,这将从 timm 或 transformers 库加载相应的预训练权重。如果 use_pretrained_backboneFalse,这将加载骨干模型的配置并使用它来初始化具有随机权重的骨干模型。
  • use_pretrained_backbone (bool, 可选, 默认为 False) — 是否使用骨干模型的预训练权重。
  • use_timm_backbone (bool, 可选, 默认为 False) — 是否从 timm 库加载 backbone。如果为 False,则从 transformers 库加载骨干模型。
  • backbone_kwargs (dict, 可选) — 加载检查点时传递给 AutoBackbone 的关键字参数,例如 {'out_indices': (0, 1, 2, 3)}。如果设置了 backbone_config,则不能指定此参数。
  • distance_loss_weight (float, 可选, 默认为 1.0) — 距离损失的权重。
  • duration_loss_weight (float, 可选, 默认为 0.1) — 持续时间损失的权重。
  • visual_prompter_type (str, 可选, 默认为 "framepad") — 视觉提示类型。填充类型。Framepad 表示在每个帧上填充。应为“framepad”或“framedownpad”之一。
  • visual_prompter_apply (str, 可选, 默认为 "replace") — 视觉提示的应用方式。Replace 表示使用提示的值来改变视觉输入中的原始值。应为“replace”、“add”或“remove”之一。
  • visual_prompt_size (int, 可选, 默认为 96) — 视觉提示的大小。
  • max_img_size (int, 可选, 默认为 448) — 帧的最大尺寸。
  • num_frames (int, 可选, 默认为 48) — 从视频中提取的帧数。
  • vocab_size (int, 可选, 默认为 30522) — Tvp 文本模型的词汇表大小。定义了调用 TvpModel 时可以通过 inputs_ids 表示的不同标记的数量。
  • hidden_size (int, 可选, 默认为 768) — 编码器层的维度。
  • intermediate_size (int, 可选, 默认为 3072) — Transformer 编码器中“中间”(即前馈)层的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 编码器中的隐藏层数量。
  • num_attention_heads (int, 可选, 默认为 12) — Transformer 编码器中每个注意力层的注意力头数量。
  • max_position_embeddings (int, 可选, 默认为 512) — 此模型可能使用的最大序列长度。通常为了以防万一设置为较大的值(例如 512 或 1024 或 2048)。
  • max_grid_col_position_embeddings (int, 可选, 默认为 100) — 视频帧中水平补丁的最大数量。
  • max_grid_row_position_embeddings (int, 可选, 默认为 100) — 视频帧中垂直补丁的最大数量。
  • hidden_dropout_prob (float, 可选, 默认为 0.1) — 隐藏层的 dropout 概率。
  • hidden_act (strfunction, 可选, 默认为 "gelu") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,则支持 "gelu", "relu", "selu""gelu_new" "quick_gelu"
  • layer_norm_eps (float, 可选, 默认为 1e-12) — 层归一化层使用的 epsilon 值。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • attention_probs_dropout_prob (float, 可选, 默认为 0.1) — 注意力层的 dropout 概率。

这是用于存储 TvpModel 配置的配置类。它用于根据指定的参数实例化 Tvp 模型,定义模型架构。使用默认值实例化配置将产生与 Tvp Intel/tvp-base 架构类似的配置。

配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PretrainedConfig 的文档。

from_backbone_config

< >

( backbone_config: PretrainedConfig **kwargs ) TvpConfig

参数

返回

TvpConfig

一个配置对象的实例

从预训练的骨干模型配置实例化 TvpConfig(或派生类)。

to_dict

< >

( ) dict[str, any]

返回

dict[str, any]

所有构成此配置实例的属性的字典,

将此实例序列化为 Python 字典。覆盖默认的 to_dict()

TvpImageProcessor

transformers.TvpImageProcessor

< >

( do_resize: bool = True size: typing.Optional[dict[str, int]] = None resample: Resampling = <Resampling.BILINEAR: 2> do_center_crop: bool = True crop_size: typing.Optional[dict[str, int]] = None do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_pad: bool = True pad_size: typing.Optional[dict[str, int]] = None constant_values: typing.Union[float, collections.abc.Iterable[float]] = 0 pad_mode: PaddingMode = <PaddingMode.CONSTANT: 'constant'> do_normalize: bool = True do_flip_channel_order: bool = True image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None **kwargs )

参数

  • do_resize (bool, optional, defaults to 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 (intfloat, 可选, 默认为 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 (floatlist[float], 可选, 默认为 IMAGENET_STANDARD_MEAN) — 归一化图像时使用的均值。这是一个浮点数或浮点数列表,长度与图像中的通道数相同。可以通过 preprocess 方法中的 image_mean 参数覆盖。
  • image_std (floatlist[float], 可选, 默认为 IMAGENET_STANDARD_STD) — 归一化图像时使用的标准差。这是一个浮点数或浮点数列表,长度与图像中的通道数相同。可以通过 preprocess 方法中的 image_std 参数覆盖。

构造一个 Tvp 图像处理器。

预处理

< >

( videos: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], list[typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]], list[list[typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]]]] do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None resample: Resampling = None do_center_crop: typing.Optional[bool] = None crop_size: typing.Optional[dict[str, int]] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_pad: typing.Optional[bool] = None pad_size: typing.Optional[dict[str, int]] = None constant_values: typing.Union[float, collections.abc.Iterable[float], NoneType] = None pad_mode: PaddingMode = None do_normalize: typing.Optional[bool] = None do_flip_channel_order: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

参数

  • videos (ImageInputlist[ImageInput]list[list[ImageInput]]) — 要预处理的帧。
  • do_resize (bool, 可选, 默认为 self.do_resize) — 是否调整图像大小。
  • size (dict[str, int], 可选, 默认为 self.size) — 调整大小后图像的尺寸。
  • resample (PILImageResampling, 可选, 默认为 self.resample) — 调整图像大小(如果 do_resize 设置为 True)时使用的重采样过滤器。这可以是 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, 可选, 默认为 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, 可选, 默认为 self.do_normalize) — 是否对图像进行归一化。
  • do_flip_channel_order (bool, 可选, 默认为 self.do_flip_channel_order) — 是否翻转图像的通道顺序。
  • image_mean (floatlist[float], 可选, 默认为 self.image_mean) — 图像均值。
  • image_std (floatlist[float], 可选, 默认为 self.image_std) — 图像标准差。
  • return_tensors (strTensorType, 可选) — 要返回的张量类型。可以是以下之一:
    • 未设置:返回 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 (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。
    • ChannelDimension.LAST:图像格式为 (height, width, num_channels)。
    • 未设置:使用输入图像推断的通道维度格式。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "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

< >

( image_processor = None tokenizer = None **kwargs )

参数

构造一个 TVP 处理器,它将 TVP 图像处理器和 Bert 分词器封装在一个处理器中。

TvpProcessor 提供了 TvpImageProcessorBertTokenizerFast 的所有功能。有关更多信息,请参阅 call()decode() 的文档字符串。

__call__

< >

( 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.ndarray]], — list[list[torch.Tensor]]):要准备的视频或视频批次。每个视频都应该是一个帧列表,可以是 PIL 图像或 NumPy 数组。如果是 NumPy 数组/PyTorch 张量,每个帧的形状应为 (H, W, C),其中 H 和 W 是帧的高度和宽度,C 是通道数。
  • return_tensors (strTensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:

    • 'tf':返回 TensorFlow tf.constant 对象。
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。
    • 'jax':返回 JAX jnp.ndarray 对象。

返回

BatchEncoding

一个 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,此方法将 textkwargs 参数转发给 BertTokenizerFast 的 call() 以编码文本。如果 videos 不为 None,此方法将 videoskwargs 参数转发给 TvpImageProcessor 的 call() 以准备图像。有关更多信息,请参阅上述两种方法的文档字符串。

TvpModel

class transformers.TvpModel

< >

( config )

参数

  • config (TvpModel) — 包含模型所有参数的模型配置类。用配置文件初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法以加载模型权重。

裸 TVP 模型transformer 输出 BaseModelOutputWithPooling 对象,顶部没有任何特定头部。

此模型继承自 PreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头部等)。

此模型也是 PyTorch torch.nn.Module 子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档以了解所有与一般用法和行为相关的事项。

前向

< >

( 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 )

参数

  • input_ids (torch.LongTensor,形状为 (batch_size, sequence_length)可选) — 输入序列标记在词汇表中的索引。默认情况下会忽略填充。

    索引可以使用 AutoTokenizer 获取。详情请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入 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.LongTensor,形状为 (batch_size, sequence_length)可选) — 用于避免对填充标记索引执行注意力操作的掩码。掩码值选择范围为 [0, 1]

    • 1 表示标记未被掩盖
    • 0 表示标记已被掩盖

    什么是注意力掩码?

  • head_mask (torch.FloatTensor,形状为 (num_heads,)(num_layers, num_heads)可选) — 用于使自注意力模块的选定头部无效的掩码。掩码值选择范围为 [0, 1]

    • 1 表示头部未被掩盖
    • 0 表示头部已被掩盖
  • output_attentions (bool可选) — 是否返回所有注意力层的注意力张量。更多详情请参阅返回张量下的 attentions
  • output_hidden_states (bool可选) — 是否返回所有层的隐藏状态。更多详情请参阅返回张量下的 hidden_states
  • return_dict (bool可选) — 是否返回 ModelOutput 而非普通的元组。
  • interpolate_pos_encoding (bool,默认为 False) — 是否插值预训练的位置编码。

TvpModel 的 forward 方法,重写了 __call__ 特殊方法。

尽管前向传播的实现需要在该函数中定义,但在此之后应调用 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

< >

( config )

参数

  • config (TvpForVideoGrounding) — 包含模型所有参数的模型配置类。使用配置文件初始化并不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法来加载模型权重。

Tvp 模型,顶部带有一个视频定位头,用于计算 IoU、距离和持续时间损失。

此模型继承自 PreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头部等)。

此模型也是 PyTorch torch.nn.Module 子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档以了解所有与一般用法和行为相关的事项。

前向

< >

( input_ids: typing.Optional[torch.LongTensor] = None pixel_values: typing.Optional[torch.FloatTensor] = None attention_mask: typing.Optional[torch.LongTensor] = None labels: typing.Optional[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 )

参数

  • input_ids (torch.LongTensor,形状为 (batch_size, sequence_length)可选) — 输入序列标记在词汇表中的索引。默认情况下会忽略填充。

    索引可以使用 AutoTokenizer 获取。详情请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入 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.LongTensor,形状为 (batch_size, sequence_length)可选) — 用于避免对填充标记索引执行注意力操作的掩码。掩码值选择范围为 [0, 1]

    • 1 表示标记未被掩盖
    • 0 表示标记已被掩盖

    什么是注意力掩码?

  • labels (torch.FloatTensor,形状为 (batch_size, 3)可选) — 标签包含与文本对应的视频的持续时间、开始时间和结束时间。
  • head_mask (torch.FloatTensor,形状为 (num_heads,)(num_layers, num_heads)可选) — 用于使自注意力模块的选定头部无效的掩码。掩码值选择范围为 [0, 1]

    • 1 表示头部未被掩盖
    • 0 表示头部已被掩盖
  • output_attentions (bool可选) — 是否返回所有注意力层的注意力张量。更多详情请参阅返回张量下的 attentions
  • output_hidden_states (bool可选) — 是否返回所有层的隐藏状态。更多详情请参阅返回张量下的 hidden_states
  • return_dict (bool可选) — 是否返回 ModelOutput 而非普通的元组。
  • interpolate_pos_encoding (bool,默认为 False) — 是否插值预训练的位置编码。

TvpForVideoGrounding 的 forward 方法,重写了 __call__ 特殊方法。

尽管前向传播的实现需要在该函数中定义,但在此之后应调用 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)
< > 在 GitHub 上更新