Transformers 文档
Video-LLaVA
并获得增强的文档体验
开始使用
Video-LLaVA
概述
Video-LLaVA 是一个开源多模态大型语言模型(LLM),通过在由 Llava1.5 和 VideChat 生成的多模态指令遵循数据上进行微调而训练。它是一个基于 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_size` 或 `model.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 正在进行中,预计在第四季度/第一季度支持 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.float16` 或 `torch.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
class transformers.VideoLlavaConfig
< 来源 >( vision_config = None text_config = None image_token_index = 32000 video_token_index = 32001 projector_hidden_act = 'gelu' vision_feature_select_strategy = 'default' vision_feature_layer = -2 image_seq_length = 256 video_seq_length = 2056 multimodal_projector_bias = True **kwargs )
参数
- vision_config (`VideoLlavaVisionConfig`, _可选_) — 自定义视觉配置或字典。如果未指定,默认为 `CLIPVisionConfig`。
- text_config (`Union[AutoConfig, dict]`, _可选_) — 文本主干的配置对象。可以是 `LlamaConfig` 或 `MistralConfig` 中的任何一种。如果未指定,默认为 `LlamaConfig`。
- image_token_index (`int`, _可选_, 默认为 32000) — 用于编码图像提示的图像标记索引。
- video_token_index (`int`, _可选_, 默认为 32001) — 用于编码图像提示的视频标记索引。
- projector_hidden_act (`str`, _可选_, 默认为 `"gelu"`) — 多模态投影仪使用的激活函数。
- vision_feature_select_strategy (`str`, _可选_, 默认为 `"default"`) — 用于从 CLIP 主干中选择视觉特征的特征选择策略。可以是 `"full"` 以选择所有特征,也可以是 `"default"` 以选择不带 `CLS` 的特征。
- vision_feature_layer (`Union[int, list[int]]`, _可选_, 默认为 -2) — 选择视觉特征的层索引。如果提供多个索引,则相应索引的视觉特征将被连接以形成视觉特征。
- image_seq_length (`int`, _可选_, 默认为 256) — 一幅图像嵌入的序列长度。
- video_seq_length (`int`, _可选_, 默认为 2056) — 一个视频嵌入的序列长度。
- multimodal_projector_bias (`bool`, _可选_, 默认为 `True`) — 是否在多模态投影仪中使用偏置。
这是用于存储 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
class transformers.VideoLlavaImageProcessor
< 来源 >( do_resize: bool = True size: typing.Optional[dict[str, int]] = None resample: Resampling = <Resampling.BICUBIC: 3> 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_normalize: bool = True image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, 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]` _可选_, 默认为 224) — 应用 `center_crop` 后输出图像的大小。可以通过 `preprocess` 方法中的 `crop_size` 覆盖。
- do_rescale (`bool`, _可选_, 默认为 `True`) — 是否按指定的比例 `rescale_factor` 重新缩放图像。可以通过 `preprocess` 方法中的 `do_rescale` 覆盖。
- rescale_factor (`int` 或 `float`, _可选_, 默认为 `1/255`) — 如果重新缩放图像,则使用的比例因子。可以通过 `preprocess` 方法中的 `rescale_factor` 覆盖。
- do_normalize (`bool`, _可选_, 默认为 `True`) — 是否对图像进行归一化。可以通过 `preprocess` 方法中的 `do_normalize` 覆盖。
- image_mean (`float` 或 `list[float]`, _可选_, 默认为 `[0.48145466, 0.4578275, 0.40821073]`) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或浮点数列表,长度与图像中的通道数相同。可以通过 `preprocess` 方法中的 `image_mean` 参数覆盖。
- image_std (`float` 或 `list[float]`, _可选_, 默认为 `[0.26862954, 0.26130258, 0.27577711]`) — 如果对图像进行归一化,则使用的标准差。这是一个浮点数或浮点数列表,长度与图像中的通道数相同。可以通过 `preprocess` 方法中的 `image_std` 参数覆盖。可以通过 `preprocess` 方法中的 `image_std` 参数覆盖。
- do_convert_rgb (`bool`, _可选_, 默认为 `True`) — 是否将图像转换为 RGB。
构建 CLIP 图像处理器。
预处理
< 来源 >( images: typing.Optional[list[typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]]] = None videos: typing.Optional[list[typing.Union[list['PIL.Image.Image'], ForwardRef('np.ndarray'), ForwardRef('torch.Tensor'), list['np.ndarray'], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list['np.ndarrray']], list[list['torch.Tensor']]]]] = None 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[int] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None do_convert_rgb: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Optional[transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )
参数
- images (`ImageInput`, _可选_) — 要预处理的图像列表。期望单个或批处理图像,像素值范围从 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 `do_rescale=False`。
- videos (`VideoInput`, _可选_) — 要预处理的视频列表。期望单个或批处理视频,像素值范围从 0 到 255。如果传入的视频像素值在 0 到 1 之间,请设置 `do_rescale=False`。
- do_resize (`bool`, _可选_, 默认为 `self.do_resize`) — 是否调整图像大小。
- size (`dict[str, int]`, _可选_, 默认为 `self.size`) — 调整大小后图像的大小。图像的最短边将调整为 size["shortest_edge"],最长边将调整为保持输入宽高比。
- resample (
int
, 可选, 默认为self.resample
) — 如果调整图像大小,要使用的重采样滤镜。这可以是枚举PILImageResampling
之一。仅当do_resize
设置为True
时有效。 - do_center_crop (
bool
, 可选, 默认为self.do_center_crop
) — 是否对图像进行中心裁剪。 - crop_size (
dict[str, int]
, 可选, 默认为self.crop_size
) — 中心裁剪的大小。仅当do_center_crop
设置为True
时有效。 - do_rescale (
bool
, 可选, 默认为self.do_rescale
) — 是否缩放图像。 - rescale_factor (
float
, 可选, 默认为self.rescale_factor
) — 如果do_rescale
设置为True
,用于缩放图像的缩放因子。 - do_normalize (
bool
, 可选, 默认为self.do_normalize
) — 是否对图像进行归一化。 - image_mean (
float
或list[float]
, 可选, 默认为self.image_mean
) — 用于归一化的图像平均值。仅当do_normalize
设置为True
时有效。 - image_std (
float
或list[float]
, 可选, 默认为self.image_std
) — 用于归一化的图像标准差。仅当do_normalize
设置为True
时有效。 - do_convert_rgb (
bool
, 可选, 默认为self.do_convert_rgb
) — 是否将图像转换为RGB。 - return_tensors (
str
或TensorType
, 可选) — 要返回的张量类型。可以是以下之一:- 未设置:返回
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
或str
, 可选, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:图像为 (num_channels, height, width) 格式。"channels_last"
或ChannelDimension.LAST
:图像为 (height, width, num_channels) 格式。- 未设置:使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension
或str
, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:图像为 (num_channels, height, width) 格式。"channels_last"
或ChannelDimension.LAST
:图像为 (height, width, num_channels) 格式。"none"
或ChannelDimension.NONE
:图像为 (height, width) 格式。
预处理一张或一批图像。
resize
< 源 >( image: ndarray size: dict resample: Resampling = <Resampling.BICUBIC: 3> data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None **kwargs )
调整图像大小。图像的最短边调整为 size[“shortest_edge”],最长边保持输入纵横比不变。
VideoLlavaVideoProcessor
类 transformers.VideoLlavaVideoProcessor
< 源 >( **kwargs: typing_extensions.Unpack[transformers.models.video_llava.video_processing_video_llava.VideoLlavaFastVideoProcessorInitKwargs] )
VideoLlavaProcessor
类 transformers.VideoLlavaProcessor
< 源 >( image_processor = None video_processor = None tokenizer = None patch_size = 14 vision_feature_select_strategy = 'default' image_token = '<image>' video_token = '<video>' chat_template = None num_additional_image_tokens = 1 **kwargs )
参数
- image_processor (VideoLlavaImageProcessor, 可选) — 图像处理器是必需的输入。
- video_processor (VideoLlavaVideoProcessor, 可选) — 视频处理器是必需的输入。
- tokenizer (LlamaTokenizerFast, 可选) — 分词器是必需的输入。
- patch_size (
int
, 可选, 默认为 14) — 视觉编码器的补丁大小。 - vision_feature_select_strategy (
str
, 可选, 默认为"default"
) — 用于从视觉骨干网络中选择视觉特征的特征选择策略。应与模型配置中的相同。 - image_token (
str
, 可选, 默认为"<image>"
) — 用于表示图像位置的特殊标记。 - video_token (
str
, 可选, 默认为"<video>"
) — 用于表示视频位置的特殊标记。 - chat_template (
str
, 可选) — 用于将聊天中的消息列表转换为可分词字符串的 Jinja 模板。 - num_additional_image_tokens (
int
, 可选, 默认为 1) — 添加到图像嵌入的额外标记数量,例如 CLS (+1)。如果骨干网络没有 CLS 或其他额外标记附加,则无需设置此参数。
构建一个 VideoLlava 处理器,它将 VideoLlava 图像处理器和 Llava 分词器封装到一个单一的处理器中。
VideoLlavaProcessor 提供 VideoLlavaImageProcessor 和 LlamaTokenizerFast 的所有功能。有关更多信息,请参阅 __call__()
和 decode()。
此方法将其所有参数转发给 LlamaTokenizerFast 的 batch_decode()。有关更多信息,请参阅此方法的文档字符串。
VideoLlavaModel
类 transformers.VideoLlavaModel
< 源 >( config: VideoLlavaConfig )
参数
- config (VideoLlavaConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法加载模型权重。
VideoLlava 模型,由视觉骨干网络和无语言建模头的语言模型组成。
此模型继承自 PreTrainedModel。请查看超类文档,了解库为其所有模型实现的一般方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
此模型也是 PyTorch torch.nn.Module 子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档中与一般用法和行为相关的所有事项。
forward
< 源 >( 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[list[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None vision_feature_layer: typing.Union[int, list[int], NoneType] = None vision_feature_select_strategy: typing.Optional[str] = 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 **kwargs: typing_extensions.Unpack[transformers.modeling_flash_attention_utils.FlashAttentionKwargs] ) → transformers.models.video_llava.modeling_video_llava.VideoLlavaModelOutputWithPast
或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
形状为(batch_size, sequence_length)
) — 词汇表中输入序列标记的索引。默认情况下会忽略填充。可以使用 AutoTokenizer 获取索引。有关详细信息,请参见 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- pixel_values_images (
torch.FloatTensor
形状为(batch_size, num_channels, image_size, image_size)
) — 对应于输入图像的张量。像素值可以使用 [AutoImageProcessor](/docs/transformers/v4.53.3/en/model_doc/auto#transformers.AutoImageProcessor) 获取。有关详细信息,请参阅 [VideoLlavaImageProcessor.__call__()](/docs/transformers/v4.53.3/en/model_doc/deformable_detr#transformers.DeformableDetrFeatureExtractor.__call__)([`LlavaProcessor`] 使用 VideoLlavaImageProcessor 处理图像)。 - pixel_values_videos (
torch.FloatTensor
形状为(batch_size, num_frames, num_channels, image_size, image_size)
) — 对应于输入视频的张量。像素值可以使用 [AutoImageProcessor](/docs/transformers/v4.53.3/en/model_doc/auto#transformers.AutoImageProcessor) 获取。有关详细信息,请参阅 [VideoLlavaImageProcessor.__call__()](/docs/transformers/v4.53.3/en/model_doc/deformable_detr#transformers.DeformableDetrFeatureExtractor.__call__)([`LlavaProcessor`] 使用 VideoLlavaImageProcessor 处理视频)。 - attention_mask (
torch.Tensor
形状为(batch_size, sequence_length)
, 可选) — 掩码,用于避免对填充标记索引执行注意力。掩码值选择在[0, 1]
之间:- 1 表示未被掩码的标记,
- 0 表示被掩码的标记。
- position_ids (
torch.LongTensor
形状为(batch_size, sequence_length)
, 可选) — 每个输入序列标记在位置嵌入中的位置索引。选择范围为[0, config.n_positions - 1]
。 - past_key_values (
list[torch.FloatTensor]
, 可选) — 预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常包括模型在先前解码阶段返回的past_key_values
,当use_cache=True
或config.use_cache=True
时。允许两种格式:
- Cache 实例,请参阅我们的 kv 缓存指南;
config.n_layers
长度的tuple(torch.FloatTensor)
元组,每个元组包含 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
的张量)。这也被称为旧版缓存格式。
模型将输出与输入相同的缓存格式。如果没有传递
past_key_values
,则将返回旧版缓存格式。如果使用
past_key_values
,用户可以选择只输入形状为(batch_size, 1)
的最后一个input_ids
(那些没有将过去键值状态提供给此模型的),而不是所有形状为(batch_size, sequence_length)
的input_ids
。 - inputs_embeds (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对input_ids
索引如何转换为相关向量有更多控制,而不是模型的内部嵌入查找矩阵,这将很有用。 - vision_feature_layer (
Union[int, list[int], NoneType]
) — 选择视觉特征的层的索引。如果提供了多个索引,则相应索引的视觉特征将连接起来形成视觉特征。 - vision_feature_select_strategy (
str
, 可选) — 用于从视觉骨干网络中选择视觉特征的特征选择策略。可以是"default"
或"full"
之一。 - use_cache (
bool
, 可选) — 如果设置为True
,将返回past_key_values
键值状态,可用于加速解码(请参阅past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。更多详细信息请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。更多详细信息请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是纯元组。 - cache_position (
torch.LongTensor
形状为(sequence_length)
, 可选) — 描述输入序列标记在序列中位置的索引。与position_ids
相反,此张量不受填充影响。它用于在正确位置更新缓存并推断完整的序列长度。
返回
transformers.models.video_llava.modeling_video_llava.VideoLlavaModelOutputWithPast
或 tuple(torch.FloatTensor)
一个 transformers.models.video_llava.modeling_video_llava.VideoLlavaModelOutputWithPast
或 torch.FloatTensor
元组(如果传递 return_dict=False
或当 config.return_dict=False
时),包含根据配置(VideoLlavaConfig)和输入的不同元素。
-
last_hidden_state (
<class 'torch.FloatTensor'>.last_hidden_state
形状为(batch_size, sequence_length, hidden_size)
, 默认为None
) — 模型最后一层的隐藏状态序列。 -
past_key_values (
tuple(tuple(torch.FloatTensor))
, 可选, 当传递use_cache=True
或当config.use_cache=True
时返回) —config.n_layers
长度的tuple(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
。由视觉编码器生成并投影最后隐藏状态后的模型图像隐藏状态。 -
video_hidden_states (
torch.FloatTensor
, 可选) — 形状为(batch_size * num_frames, num_videos, sequence_length, hidden_size)
的torch.FloatTensor
。由视觉编码器生成并投影最后隐藏状态后的模型视频隐藏状态。
VideoLlavaModel 的 forward 方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的配方需要在此函数中定义,但在此之后应该调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则静默忽略它们。
get_image_features
< 源 >( pixel_values_images: FloatTensor vision_feature_layer: typing.Union[int, list[int], NoneType] = None vision_feature_select_strategy: typing.Optional[str] = None ) → image_features (torch.Tensor
)
参数
- pixel_values_images (
torch.FloatTensor]
,形状为(batch_size, channels, height, width)
) — 对应于输入图像的张量。 - vision_feature_layer (
Union[int, list[int]]
, 可选) — 用于选择视觉特征的层索引。如果提供了多个索引,则对应索引的视觉特征将被连接起来形成视觉特征。 - vision_feature_select_strategy (
str
, 可选) — 用于从视觉骨干网络中选择视觉特征的特征选择策略。可以是"default"
或"full"
之一。
返回
image_features (torch.Tensor
)
形状为 (num_images, image_length, embed_dim)
的图像特征张量。
从视觉塔获取图像最后隐藏状态并应用多模态投影。
get_video_features
< source >( pixel_values_videos: FloatTensor vision_feature_layer: typing.Union[int, list[int], NoneType] = None ) → video_features (torch.Tensor
)
参数
- pixel_values_videos (
torch.FloatTensor]
,形状为(batch_size, num_frames, channels, height, width)
) — 对应于输入视频的张量。 - vision_feature_layer (
Union[int, list[int]]
, 可选) — 用于选择视觉特征的层索引。如果提供了多个索引,则对应索引的视觉特征将被连接起来形成视觉特征。
返回
video_features (torch.Tensor
)
视频特征张量,形状为 (num_videos * num_frames, image_length, embed_dim)
)。frames (int
):视频的帧数。
从视觉塔中获取视频的最后一个隐藏状态并应用多模态投影。
VideoLlavaForConditionalGeneration
class transformers.VideoLlavaForConditionalGeneration
< source >( config: VideoLlavaConfig )
参数
- config (VideoLlavaConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只加载配置。请查阅 from_pretrained() 方法以加载模型权重。
VideoLlava 模型由视觉骨干和语言模型组成。
此模型继承自 PreTrainedModel。请查看超类文档,了解库为其所有模型实现的一般方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
此模型也是 PyTorch torch.nn.Module 子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档中与一般用法和行为相关的所有事项。
forward
< source >( 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[list[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None vision_feature_layer: typing.Union[int, list[int], NoneType] = 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 logits_to_keep: typing.Union[int, torch.Tensor] = 0 **kwargs: typing_extensions.Unpack[transformers.models.video_llava.modeling_video_llava.KwargsForCausalLM] ) → transformers.models.video_llava.modeling_video_llava.VideoLlavaCausalLMOutputWithPast
or tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
,形状为(batch_size, sequence_length)
) — 词汇表中输入序列 token 的索引。默认情况下会忽略填充。索引可以通过 AutoTokenizer 获取。详情请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- pixel_values_images (
torch.FloatTensor
,形状为(batch_size, num_channels, image_size, image_size)) -- 对应于输入图像的张量。像素值可以使用 [AutoImageProcessor](/docs/transformers/v4.53.3/en/model_doc/auto#transformers.AutoImageProcessor) 获取。详见 [VideoLlavaImageProcessor.__call__()](/docs/transformers/v4.53.3/en/model_doc/deformable_detr#transformers.DeformableDetrFeatureExtractor.__call__)([]
LlavaProcessor`] 使用 VideoLlavaImageProcessor 处理图像)。 - pixel_values_videos (
torch.FloatTensor
,形状为(batch_size, num_frames, num_channels, image_size, image_size)) -- 对应于输入视频的张量。像素值可以使用 [AutoImageProcessor](/docs/transformers/v4.53.3/en/model_doc/auto#transformers.AutoImageProcessor) 获取。详见 [VideoLlavaImageProcessor.__call__()](/docs/transformers/v4.53.3/en/model_doc/deformable_detr#transformers.DeformableDetrFeatureExtractor.__call__)([]
LlavaProcessor`] 使用 VideoLlavaImageProcessor 处理视频)。 - attention_mask (
torch.Tensor
,形状为(batch_size, sequence_length)
, 可选) — 掩码,用于避免在填充 token 索引上执行注意力。掩码值选择在[0, 1]
之间:- 1 表示**未被掩码**的 token,
- 0 表示**被掩码**的 token。
- position_ids (
torch.LongTensor
,形状为(batch_size, sequence_length)
, 可选) — 每个输入序列 token 在位置嵌入中的位置索引。选择范围为[0, config.n_positions - 1]
。 - past_key_values (
list[torch.FloatTensor]
, 可选) — 预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常包括模型在解码前期返回的past_key_values
,当use_cache=True
或config.use_cache=True
时。允许两种格式:
- 一个 Cache 实例,请参阅我们的 kv cache 指南;
- 长度为
config.n_layers
的tuple(torch.FloatTensor)
元组,每个元组包含 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
的张量)。这也被称为传统缓存格式。
模型将输出与作为输入提供的缓存格式相同的缓存格式。如果没有传递
past_key_values
,将返回传统缓存格式。如果使用了
past_key_values
,用户可以选择只输入最后一个input_ids
(那些没有将其过去键值状态提供给此模型的)的形状(batch_size, 1)
,而不是所有input_ids
的形状(batch_size, sequence_length)
。 - inputs_embeds (
torch.FloatTensor
,形状为(batch_size, sequence_length, hidden_size)
, 可选) — 可选地,你可以选择直接传递嵌入表示,而不是传递input_ids
。如果你想对如何将input_ids
索引转换为相关向量拥有比模型内部嵌入查找矩阵更多的控制,这会很有用。 - vision_feature_layer (
Union[int, list[int], NoneType]
) — 用于选择视觉特征的层索引。如果提供了多个索引,则对应索引的视觉特征将被连接起来形成视觉特征。 - vision_feature_select_strategy (
str
, 可选) — 用于从视觉骨干网络中选择视觉特征的特征选择策略。可以是"default"
或"full"
。 - labels (
torch.LongTensor
,形状为(batch_size, sequence_length)
, 可选) — 用于计算掩码语言建模损失的标签。索引应在[0, ..., config.vocab_size]
或 -100 之间(参见input_ids
文档字符串)。索引设置为-100
的 token 将被忽略(掩码),损失只对标签在[0, ..., config.vocab_size]
范围内的 token 计算。 - use_cache (
bool
, 可选) — 如果设置为True
,将返回past_key_values
键值状态,可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。更多详细信息请参阅返回张量中的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。更多详细信息请参阅返回张量中的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。 - cache_position (
torch.LongTensor
,形状为(sequence_length)
, 可选) — 描述输入序列 token 在序列中位置的索引。与position_ids
不同,此张量不受填充影响。它用于在正确位置更新缓存并推断完整的序列长度。 - logits_to_keep (
Union[int, torch.Tensor]
, 默认为0
) — 如果是int
,则计算最后logits_to_keep
个 token 的对数。如果是0
,则计算所有input_ids
的对数(特殊情况)。生成时只需要最后一个 token 的对数,只计算该 token 可以节省内存,这对于长序列或大词汇量来说非常显著。如果是torch.Tensor
,则必须是 1D,对应于序列长度维度中要保留的索引。这在使用打包张量格式(批次和序列长度的单一维度)时很有用。
返回
transformers.models.video_llava.modeling_video_llava.VideoLlavaCausalLMOutputWithPast
或 tuple(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
时返回) — 语言建模损失(用于下一个 token 预测)。 -
logits (形状为
(batch_size, sequence_length, config.vocab_size)
的torch.FloatTensor
) — 语言建模头部的预测分数(SoftMax 之前的每个词汇标记的分数)。 -
past_key_values (
tuple(tuple(torch.FloatTensor))
, 可选, 当传递use_cache=True
或当config.use_cache=True
时返回) —config.n_layers
长度的tuple(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
。由视觉编码器生成并投影最后隐藏状态后的模型图像隐藏状态。 -
video_hidden_states (
torch.FloatTensor
, 可选) — 形状为(batch_size * num_frames, num_videos, sequence_length, hidden_size)
的torch.FloatTensor
。由视觉编码器生成并投影最后隐藏状态后的模型视频隐藏状态。
VideoLlavaForConditionalGeneration 的前向方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的配方需要在此函数中定义,但在此之后应该调用 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']