Transformers 文档

视频-LLaVA

视频-LLaVA

概述

Video-LLaVa 是一个开源的多模态LLM,通过在Llava1.5和VideChat生成的多模态指令跟随数据上微调LlamA/Vicuna进行训练。它是一个基于transformer架构的自回归语言模型。Video-LLaVa将视觉表示统一到语言特征空间,并使LLM能够同时对图像和视频进行视觉推理。

Video-LLaVA模型由Bin Lin、Yang Ye、Bin Zhu、Jiaxi Cui、Munang Ning、Peng Jin、Li Yuan在Video-LLaVA: Learning United Visual Representation by Alignment Before Projection中提出。

论文的摘要如下:

大型视觉语言模型(LVLM)提升了视觉语言理解中各种下游任务的性能。大多数现有方法将图像和视频编码为单独的特征空间,然后将其作为输入提供给大型语言模型。然而,由于缺乏对图像和视频的统一标记化,即投影前的未对齐,大型语言模型(LLM)从几个较差的投影层学习多模态交互变得具有挑战性。在这项工作中,我们将视觉表示统一到语言特征空间中,以推动基础LLM向统一的LVLM发展。因此,我们建立了一个简单但强大的LVLM基线,Video-LLaVA,它从图像和视频的混合数据集中学习,相互增强。Video-LLaVA在5个图像问答数据集和4个图像基准工具包中的9个图像基准上表现出色。此外,我们的Video-LLaVA在MSRVTT、MSVD、TGIF和ActivityNet上分别比Video-ChatGPT高出5.8%、9.9%、18.6%和10.1%。值得注意的是,大量实验表明,Video-LLaVA在统一的视觉表示中相互受益于图像和视频,优于专门为图像或视频设计的模型。我们希望这项工作能为LLM的多模态输入提供一些见解。

使用提示:

  • 我们建议用户在计算批量生成时使用 padding_side=“left”,因为它会带来更准确的结果。只需确保在生成之前调用 processor.tokenizer.padding_side = “left”。

  • 请注意,该模型并未明确训练以处理同一提示中的多个图像/视频,尽管这在技术上是可行的,但您可能会遇到不准确的结果。

  • 请注意,视频输入应恰好包含8帧,因为模型是在这种设置下训练的。

该模型由RaushanTurganbay贡献。 原始代码可以在这里找到。

[!注意] LLaVA模型在发布v4.46版本后,将会发出关于添加processor.patch_size = {{patch_size}}processor.num_additional_image_tokens = {{num_additional_image_tokens}}和processor.vision_feature_select_strategy = {{vision_feature_select_strategy}}的警告。强烈建议如果您拥有模型检查点,请将这些属性添加到处理器中,或者如果不是您拥有的,请提交一个PR。添加这些属性意味着LLaVA将尝试推断每张图像所需的图像令牌数量,并使用尽可能多的占位符扩展文本。通常每张图像大约有500个令牌,因此请确保文本没有被截断,否则在合并嵌入时会出现失败。这些属性可以从模型配置中获取,如model.config.vision_config.patch_sizemodel.config.vision_feature_select_strategy。如果视觉骨干添加了CLS令牌,则num_additional_image_tokens应为1,如果没有向视觉补丁添加额外内容,则应为0`。

使用示例

单媒体模式

模型可以接受图像和视频作为输入。以下是一个半精度推理的示例代码(torch.float16):

import av
import torch
import numpy as np
from transformers import VideoLlavaForConditionalGeneration, VideoLlavaProcessor

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

# Load the model in half-precision
model = VideoLlavaForConditionalGeneration.from_pretrained("LanguageBind/Video-LLaVA-7B-hf", torch_dtype=torch.float16, device_map="auto")
processor = VideoLlavaProcessor.from_pretrained("LanguageBind/Video-LLaVA-7B-hf")

# Load the video as an np.arrau, sampling uniformly 8 frames
video_path = hf_hub_download(repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset")
container = av.open(video_path)
total_frames = container.streams.video[0].frames
indices = np.arange(0, total_frames, total_frames / 8).astype(int)
video = read_video_pyav(container, indices)

# For better results, we recommend to prompt the model in the following format
prompt = "USER: <video>\nWhy is this funny? ASSISTANT:"
inputs = processor(text=prompt, videos=video, return_tensors="pt")

out = model.generate(**inputs, max_new_tokens=60)
processor.batch_decode(out, skip_special_tokens=True, clean_up_tokenization_spaces=True)

对于多轮对话,将提示格式更改为:

"USER: <video>\nWhat do you see in this video? ASSISTANT: A baby reading a book. USER: Why is the it funny? ASSISTANT:"

混合媒体模式

该模型还可以从交错的图像-视频输入中生成内容。但请注意,它并未在交错的图像-视频设置中进行训练,这可能会影响性能。以下是混合媒体输入的示例用法,将以下行添加到上述代码片段中:

from PIL import Image
import requests

# Generate from image and video mixed inputs
# Load and image and write a new prompt
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
prompt = "USER: <image>\nHow many cats are there in the image? ASSISTANT: There are two cats. USER: <video>\nWhy is this video funny? ASSISTANT:"

inputs = processor(text=prompt, images=image, videos=clip, padding=True, return_tensors="pt")

# Generate
generate_ids = model.generate(**inputs, max_length=50)
processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)

模型优化

使用Bitsandbytes进行量化以提高内存效率

模型可以以较低的位数加载,显著减少内存负担,同时保持原始模型的性能。这使得在资源受限的情况下能够高效部署。

首先确保通过运行pip install bitsandbytes来安装bitsandbytes,并且确保可以访问该库支持的GPU/加速器。

bitsandbytes 正在进行重构,以支持除 CUDA 之外的多种后端。目前,ROCm(AMD GPU)和 Intel CPU 的实现已经成熟,Intel XPU 正在开发中,预计将在 Q4/Q1 支持 Apple Silicon。有关安装说明和最新后端更新,请访问 此链接

我们重视您的反馈,以帮助在正式发布前识别错误!查看这些文档以获取更多详细信息和反馈链接。

通过简单地添加BitsAndBytesConfig来加载量化模型,如下所示:

from transformers import VideoLlavaForConditionalGeneration, BitsAndBytesConfig

# specify how to quantize the model
quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.float16,
)

model = VideoLlavaForConditionalGeneration.from_pretrained("LanguageBind/Video-LLaVA-7B-hf", quantization_config=quantization_config, device_map="auto")

Flash-Attention 2 加速生成

此外,我们可以通过使用Flash Attention大大加快模型推理速度,这是模型内部使用的注意力机制的更快实现。

首先,请确保安装最新版本的 Flash Attention 2:

pip install -U flash-attn --no-build-isolation

此外,您应该拥有与Flash-Attention 2兼容的硬件。更多信息请参阅flash attention仓库的官方文档。FlashAttention-2只能在模型以torch.float16torch.bfloat16加载时使用。

要使用Flash Attention-2加载并运行模型,只需在加载模型时添加attn_implementation="flash_attention_2",如下所示:

from transformers import VideoLlavaForConditionalGeneration

model = VideoLlavaForConditionalGeneration.from_pretrained(
    "LanguageBind/Video-LLaVA-7B-hf", 
    torch_dtype=torch.float16, 
    attn_implementation="flash_attention_2",
).to(0)

VideoLlavaConfig

transformers.VideoLlavaConfig

< >

( vision_config = 无 text_config = 无 ignore_index = -100 image_token_index = 32000 video_token_index = 32001 projector_hidden_act = 'gelu' vision_feature_select_strategy = '默认' vision_feature_layer = -2 image_seq_length = 256 video_seq_length = 2056 **kwargs )

参数

  • vision_config (VideoLlavaVisionConfig, 可选) — 自定义视觉配置或字典。如果未指定,默认为 CLIPVisionConfig.
  • text_config (Union[AutoConfig, dict], 可选) — 文本主干的配置对象。可以是LlamaConfigMistralConfig中的任意一个。 如果未指定,则默认为LlamaConfig
  • ignore_index (int, 可选, 默认为 -100) — 损失函数的忽略索引。
  • image_token_index (int, optional, defaults to 32000) — 用于编码图像提示的图像令牌索引。
  • video_token_index (int, optional, 默认为 32001) — 用于编码图像提示的视频令牌索引。
  • projector_hidden_act (str, optional, defaults to "gelu") — 多模态投影器使用的激活函数。
  • vision_feature_select_strategy (str, 可选, 默认为 "default") — 用于从CLIP骨干中选择视觉特征的特征选择策略。 可以是“full”以选择所有特征,或“default”以选择不包含CLS的特征。
  • vision_feature_layer (int, 可选, 默认为 -2) — 选择视觉特征的层的索引。
  • image_seq_length (int, optional, defaults to 256) — 一张图像嵌入的序列长度。
  • video_seq_length (int, optional, defaults to 2056) — 一个视频嵌入的序列长度。

这是用于存储VideoLlavaForConditionalGeneration配置的配置类。它用于根据指定的参数实例化一个VideoLlava模型,定义模型架构。使用默认值实例化配置将产生类似于LanguageBind/Video-LLaVA-7B-hf的配置。

例如 LanguageBind/Video-LLaVA-7B-hf

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

示例:

>>> from transformers import VideoLlavaForConditionalGeneration, VideoLlavaConfig, CLIPVisionConfig, LlamaConfig

>>> # Initializing a CLIP-vision config
>>> vision_config = CLIPVisionConfig()

>>> # Initializing a Llama config
>>> text_config = LlamaConfig()

>>> # Initializing a VideoLlava video_llava-1.5-7b style configuration
>>> configuration = VideoLlavaConfig(vision_config, text_config)

>>> # Initializing a model from the video_llava-1.5-7b style configuration
>>> model = VideoLlavaForConditionalGeneration(configuration)

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

VideoLlavaImageProcessor

transformers.VideoLlavaImageProcessor

< >

( do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling = 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_normalize: bool = True image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None do_convert_rgb: bool = True **kwargs )

参数

  • do_resize (bool, 可选, 默认为 True) — 是否将图像的(高度,宽度)尺寸调整为指定的 size。可以在 preprocess 方法中被 do_resize 覆盖。
  • size (Dict[str, int] 可选, 默认为 {"shortest_edge" -- 224}): 调整大小后的图像尺寸。图像的短边将调整为size[“shortest_edge”],长边将按比例调整以保持输入的宽高比。可以在preprocess方法中通过size覆盖此设置。
  • resample (PILImageResampling, 可选, 默认为 Resampling.BICUBIC) — 如果调整图像大小,则使用的重采样过滤器。可以在 preprocess 方法中通过 resample 覆盖此设置。
  • do_center_crop (bool, 可选, 默认为 True) — 是否将图像中心裁剪到指定的 crop_size。可以在 preprocess 方法中通过 do_center_crop 覆盖此设置。
  • crop_size (Dict[str, int] optional, 默认为 224) — 应用 center_crop 后输出图像的大小。可以在 preprocess 方法中通过 crop_size 覆盖此设置。
  • do_rescale (bool, 可选, 默认为 True) — 是否通过指定的比例 rescale_factor 重新缩放图像。可以在 preprocess 方法中被 do_rescale 覆盖。
  • rescale_factor (intfloat, 可选, 默认为 1/255) — 如果重新缩放图像,则使用的缩放因子。可以在 preprocess 方法中被 rescale_factor 覆盖。
  • do_normalize (bool, 可选, 默认为 True) — 是否对图像进行归一化。可以在 preprocess 方法中通过 do_normalize 进行覆盖。
  • image_mean (floatList[float], 可选, 默认为 [0.48145466, 0.4578275, 0.40821073]) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或浮点数列表,长度为图像中的通道数。可以通过 preprocess 方法中的 image_mean 参数进行覆盖。
  • image_std (floatList[float], 可选, 默认为 [0.26862954, 0.26130258, 0.27577711]) — 如果对图像进行归一化,则使用的标准差。这是一个浮点数或与图像通道数长度相同的浮点数列表。可以在 preprocess 方法中通过 image_std 参数覆盖。 可以在 preprocess 方法中通过 image_std 参数覆盖。
  • do_convert_rgb (bool, optional, defaults to True) — 是否将图像转换为RGB。

构建一个CLIP图像处理器。

预处理

< >

( images: typing.List[typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]]] = None videos: typing.List[typing.Union[typing.List[ForwardRef('PIL.Image.Image')], ForwardRef('np.ndarray'), ForwardRef('torch.Tensor'), typing.List[ForwardRef('np.ndarray')], typing.List[ForwardRef('torch.Tensor')], typing.List[typing.List[ForwardRef('PIL.Image.Image')]], typing.List[typing.List[ForwardRef('np.ndarrray')]], typing.List[typing.List[ForwardRef('torch.Tensor')]]]] = None do_resize: bool = None size: typing.Dict[str, int] = None resample: Resampling = None do_center_crop: bool = None crop_size: int = None do_rescale: bool = None rescale_factor: float = None do_normalize: bool = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None do_convert_rgb: bool = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Optional[transformers.image_utils.ChannelDimension] = input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

参数

  • 图像 (ImageInput, 可选) — 要预处理的图像列表。期望输入单个或批量的图像,像素值范围在0到255之间。如果传入的图像像素值在0到1之间,请设置do_rescale=False.
  • 视频 (VideoInput, 可选) — 要预处理的视频列表。期望输入单个或批量的视频,像素值范围在0到255之间。如果传入的视频像素值在0到1之间,请设置do_rescale=False.
  • do_resize (bool, optional, defaults to self.do_resize) — 是否调整图像大小.
  • size (Dict[str, int], 可选, 默认为 self.size) — 调整大小后的图像尺寸。图像的最短边将调整为 size[“shortest_edge”],最长边将按比例调整以保持输入的宽高比。
  • resample (int, 可选, 默认为 self.resample) — 如果调整图像大小,则使用的重采样过滤器。这可以是枚举 PILImageResampling 中的一个。只有在 do_resize 设置为 True 时才会生效。
  • do_center_crop (bool, optional, defaults to self.do_center_crop) — 是否对图像进行中心裁剪。
  • crop_size (Dict[str, int], 可选, 默认为 self.crop_size) — 中心裁剪的大小。仅在 do_center_crop 设置为 True 时有效。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否对图像进行重新缩放.
  • rescale_factor (float, optional, defaults to self.rescale_factor) — 如果 do_rescale 设置为 True,则用于重新缩放图像的重新缩放因子。
  • do_normalize (bool, 可选, 默认为 self.do_normalize) — 是否对图像进行归一化处理.
  • image_mean (floatList[float], 可选, 默认为 self.image_mean) — 用于归一化的图像均值。仅在 do_normalize 设置为 True 时有效。
  • image_std (floatList[float], 可选, 默认为 self.image_std) — 用于归一化的图像标准差。仅在 do_normalize 设置为 True 时有效。
  • do_convert_rgb (bool, 可选, 默认为 self.do_convert_rgb) — 是否将图像转换为RGB.
  • 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) — 输出图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"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)。

预处理一张图像或一批图像。

调整大小

< >

( image: ndarray size: typing.Dict[str, int] resample: Resampling = data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None **kwargs )

参数

  • image (np.ndarray) — 要调整大小的图像。
  • size (Dict[str, int]) — 输出图像的大小。
  • resample (PILImageResampling, 可选, 默认为 PILImageResampling.BICUBIC) — 调整图像大小时使用的重采样过滤器。
  • data_format (strChannelDimension, 可选) — 图像的通道维度格式。如果未提供,将与输入图像相同。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未提供,将自动推断。

调整图像大小。图像的最短边将调整为size["shortest_edge"],最长边将调整以保持输入的宽高比。

VideoLlavaProcessor

transformers.VideoLlavaProcessor

< >

( image_processor = 无 tokenizer = 无 patch_size = 14 vision_feature_select_strategy = '默认' image_token = '' video_token = ' chat_template = 无 num_additional_image_tokens = 1 **kwargs )

参数

  • image_processor (VideoLlavaImageProcessor, optional) — 图像处理器是一个必需的输入。
  • tokenizer (LlamaTokenizerFast, optional) — tokenizer 是一个必需的输入。
  • patch_size (int, optional, defaults to 14) — 视觉塔中的补丁大小。
  • vision_feature_select_strategy (str, 可选, 默认为 "default") — 用于从视觉骨干中选择视觉特征的特征选择策略。 应与模型配置中的相同
  • image_token (str, optional, defaults to "") — 用于表示图像位置的特殊标记。
  • video_token (str, optional, defaults to ") — 用于表示视频位置的特殊标记。
  • chat_template (str, optional) — 一个Jinja模板,用于将聊天中的消息列表转换为可标记的字符串。
  • num_additional_image_tokens (int, 可选, 默认为 1) — 添加到图像嵌入中的额外令牌数量,例如 CLS (+1)。如果骨干网络没有 CLS 或其他额外令牌附加,则无需设置此参数。

构建一个VideoLlava处理器,它将VideoLlava图像处理器和Llava分词器封装到一个单一的处理器中。

VideoLlavaProcessor 提供了 VideoLlavaImageProcessorLlamaTokenizerFast 的所有功能。更多信息请参见 __call__()decode()

batch_decode

< >

( *args **kwargs )

此方法将其所有参数转发给LlamaTokenizerFast的batch_decode()。请参考该方法的文档字符串以获取更多信息。

解码

< >

( *args **kwargs )

此方法将其所有参数转发给LlamaTokenizerFast的decode()。请参考该方法的文档字符串以获取更多信息。

VideoLlavaForConditionalGeneration

transformers.VideoLlavaForConditionalGeneration

< >

( config: VideoLlavaConfig )

参数

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

VideoLlava模型由一个视觉主干和一个语言模型组成。 该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: LongTensor = None pixel_values_images: FloatTensor = None pixel_values_videos: FloatTensor = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None vision_feature_layer: typing.Optional[int] = None vision_feature_select_strategy: typing.Optional[str] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None num_logits_to_keep: int = 0 ) transformers.models.video_llava.modeling_video_llava.VideoLlavaCausalLMOutputWithPasttuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.

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

    什么是输入ID?

  • pixel_values_images (torch.FloatTensor of shape (batch_size, num_channels, image_size, image_size)) -- 对应于输入图像的张量。可以使用 [AutoImageProcessor](/docs/transformers/v4.47.1/en/model_doc/auto#transformers.AutoImageProcessor) 获取像素值。详情请参见 [VideoLlavaImageProcessor.__call__()](/docs/transformers/v4.47.1/en/model_doc/imagegpt#transformers.ImageGPTFeatureExtractor.__call__) ([]LlavaProcessor`] 使用 VideoLlavaImageProcessor 处理图像)。
  • pixel_values_videos (torch.FloatTensor of shape (batch_size, num_frames, num_channels, image_size, image_size)) -- 对应于输入视频的张量。可以使用 [AutoImageProcessor](/docs/transformers/v4.47.1/en/model_doc/auto#transformers.AutoImageProcessor) 获取像素值。详情请参见 [VideoLlavaImageProcessor.__call__()](/docs/transformers/v4.47.1/en/model_doc/imagegpt#transformers.ImageGPTFeatureExtractor.__call__) ([]LlavaProcessor`] 使用 VideoLlavaImageProcessor 处理视频).
  • attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

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

    如果使用了past_key_values,则可以选择性地仅输入最后一个decoder_input_ids(参见past_key_values)。

    如果你想改变填充行为,你应该阅读modeling_opt._prepare_decoder_attention_mask 并根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。

    • 1 indicates the head is not masked,
    • 0 indicates the head is masked.
  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — 每个输入序列标记在位置嵌入中的位置索引。选择范围在 [0, config.n_positions - 1] 内。What are position IDs?
  • past_key_values (tuple(tuple(torch.FloatTensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) — Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head).

    包含预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),这些状态可用于(参见past_key_values输入)以加速顺序解码。

    如果使用了past_key_values,用户可以选择只输入形状为(batch_size, 1)的最后一个decoder_input_ids(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)的所有decoder_input_ids

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望对如何将 input_ids 索引转换为相关向量有更多控制权,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • vision_feature_layer (int, optional, defaults to -2) — 选择视觉特征的层的索引。
  • vision_feature_select_strategy (str, 可选, 默认为 "default") — 用于从视觉骨干中选择视觉特征的特征选择策略。 可以是 "default""full"
  • use_cache (bool, 可选) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — 表示输入序列标记在序列中的位置的索引。与position_ids相反, 这个张量不受填充的影响。它用于在正确的位置更新缓存并推断 完整的序列长度。
  • Args — labels (torch.LongTensor of shape (batch_size, sequence_length), optional): Labels for computing the masked language modeling loss. Indices should either be in [0, ..., config.vocab_size] or -100 (see input_ids docstring). Tokens with indices set to -100 are ignored (masked), the loss is only computed for the tokens with labels in [0, ..., config.vocab_size].

    num_logits_to_keep (int, 可选): 计算最后num_logits_to_keep个token的logits。如果为0,则计算所有input_ids的logits(特殊情况)。生成时只需要最后一个token的logits,仅计算该token的logits可以节省内存,这对于长序列或大词汇量来说非常重要。

返回

transformers.models.video_llava.modeling_video_llava.VideoLlavaCausalLMOutputWithPasttuple(torch.FloatTensor)

一个 transformers.models.video_llava.modeling_video_llava.VideoLlavaCausalLMOutputWithPast 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含根据配置(VideoLlavaConfig)和输入而定的各种元素。

  • loss (torch.FloatTensor 形状为 (1,)可选,当提供 labels 时返回) — 语言建模损失(用于下一个标记的预测)。

  • logits (torch.FloatTensor 形状为 (batch_size, sequence_length, config.vocab_size)) — 语言建模头的预测分数(SoftMax 之前每个词汇标记的分数)。

  • past_key_values (tuple(tuple(torch.FloatTensor))可选,当传递 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstuple(torch.FloatTensor) 元组,每个元组包含 2 个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量。

    包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • 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 后的注意力权重,用于计算自注意力头中的加权平均值。

  • image_hidden_states (torch.FloatTensor可选) — 一个形状为 (batch_size, num_images, sequence_length, hidden_size) 的 torch.FloatTensor。 由视觉编码器生成并在投影最后一个隐藏状态后的模型的 image_hidden_states。

  • video_hidden_states (torch.FloatTensor可选) — 一个形状为 (batch_size * num_frames, num_videos, sequence_length, hidden_size)torch.FloatTensor。 由视觉编码器生成并在投影最后一个隐藏状态后的模型的 video_hidden_states。

VideoLlavaForConditionalGeneration 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from PIL import Image
>>> import requests
>>> import numpy as np
>>> import av
>>> from huggingface_hub import hf_hub_download
>>> from transformers import VideoLlavaProcessor, VideoLlavaForConditionalGeneration


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

>>> model = VideoLlavaForConditionalGeneration.from_pretrained("LanguageBind/Video-LLaVA-7B-hf")
>>> processor = VideoLlavaProcessor.from_pretrained("LanguageBind/Video-LLaVA-7B-hf")

>>> prompt = "USER: <video>\nWhy is this video funny? ASSISTANT:"
>>> video_path = hf_hub_download(repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset")
>>> container = av.open(video_path)

>>> # sample uniformly 8 frames from the video
>>> total_frames = container.streams.video[0].frames
>>> indices = np.arange(0, total_frames, total_frames / 8).astype(int)
>>> clip = read_video_pyav(container, indices)

>>> inputs = processor(text=prompt, videos=clip, return_tensors="pt")

>>> # Generate
>>> generate_ids = model.generate(**inputs, max_length=80)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"USER:  Why is this video funny? ASSISTANT: The video is funny because the baby is playing with a Wii remote while sitting on the floor, and the baby is wearing glasses.Ъ. The baby's actions are amusing because it is a young child trying to interact with a video game, which is not a typical activity for a"

>>> # to generate from image and video mix
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> prompt = [
...     "USER: <image>\nHow many cats do you see? ASSISTANT:",
...     "USER: <video>\nWhy is this video funny? ASSISTANT:"
... ]
>>> inputs = processor(text=prompt, images=image, videos=clip, padding=True, return_tensors="pt")

>>> # Generate
>>> generate_ids = model.generate(**inputs, max_length=50)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)
['USER:   How many cats do you see? ASSISTANT: There are two cats visible in the image. (or three, if you count the one in the background).', 'USER:  Why is this video funny? ASSISTANT: The video is funny because it shows a baby sitting on a bed and playing with a Wii remote.Ъ. The baby is holding the remote']
< > Update on GitHub