Transformers 文档
Video-LLaVA
并获得增强的文档体验
开始使用
Video-LLaVA
概述
Video-LLaVa 是一个开源多模态 LLM,通过在 Llava1.5 和 VideChat 生成的多模态指令跟随数据上微调 LlamA/Vicuna 进行训练。它是一个基于 transformer 架构的自回归语言模型。Video-LLaVa 将视觉表示统一到语言特征空间,并使 LLM 能够同时对图像和视频执行视觉推理能力。
Video-LLaVA 模型在 Video-LLaVA: Learning United Visual Representation by Alignment Before Projection 中提出,作者为 Bin Lin, Yang Ye, Bin Zhu, Jiaxi Cui, Munang Ning, Peng Jin, Li Yuan。
论文摘要如下:
大型视觉语言模型 (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 贡献。原始代码可以在这里找到。
[!NOTE] 在 v4.46 版本之后,LLaVA 模型会引发关于添加
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 将尝试推断每个图像所需的图像令牌数量,并使用尽可能多的<image>
占位符扩展文本,因为会有令牌。通常,每个图像大约 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 支持预计在 Q4/Q1 之前完成。有关安装说明和最新的后端更新,请访问 此链接。
我们重视您的反馈,以帮助在全面发布之前识别错误!查看这些文档以获取更多详细信息和反馈链接。
只需添加 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 是模型内部使用的注意力机制的更快实现。
首先,确保安装最新版本的 Flash Attention 2
pip install -U flash-attn --no-build-isolation
此外,您应该拥有与 Flash-Attention 2 兼容的硬件。在 flash attention repository 的官方文档中阅读更多相关信息。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
< source >( 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 )
Parameters
- vision_config (
VideoLlavaVisionConfig
, 可选) — 自定义视觉配置或字典。如果未指定,则默认为CLIPVisionConfig
。 - text_config (
Union[AutoConfig, dict]
, 可选) — 文本骨干网络的配置对象。可以是LlamaConfig
或MistralConfig
中的任何一个。如果未指定,则默认为LlamaConfig
。 - image_token_index (
int
, 可选, 默认为 32000) — 用于编码图像提示的图像 token 索引。 - video_token_index (
int
, 可选, 默认为 32001) — 用于编码图像提示的视频 token 索引。 - 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
< source >( do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling = <Resampling.BICUBIC: 3> 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 )
Parameters
- 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 图像处理器。
preprocess
< source >( images: typing.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.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: 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] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )
Parameters
- 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
, 可选) — 返回张量的类型。 可以是以下之一:- Unset: 返回
np.ndarray
列表。 TensorType.TENSORFLOW
或'tf'
: 返回tf.Tensor
类型的批次。TensorType.PYTORCH
或'pt'
: 返回torch.Tensor
类型的批次。TensorType.NUMPY
或'np'
: 返回np.ndarray
类型的批次。TensorType.JAX
或'jax'
: 返回jax.numpy.ndarray
类型的批次。
- Unset: 返回
- data_format (
ChannelDimension
或str
, 可选, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。 可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。- Unset: 使用输入图像的通道维度格式。
- 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
< source >( image: ndarray size: typing.Dict[str, int] 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 )
Parameters
调整图像大小。 图像的最短边将被调整为 size[“shortest_edge”],最长边将调整大小以保持输入宽高比。
VideoLlavaProcessor
class transformers.VideoLlavaProcessor
< source >( image_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 )
Parameters
- image_processor (VideoLlavaImageProcessor, 可选) — 图像处理器是必需的输入。
- tokenizer (LlamaTokenizerFast, 可选) — 分词器是必需的输入。
- patch_size (
int
, 可选, 默认为 14) — 来自视觉塔的 Patch 大小。 - vision_feature_select_strategy (
str
, 可选, 默认为"default"
) — 用于从视觉骨干网络中选择视觉特征的特征选择策略。应与模型配置中的策略相同 - image_token (
str
, 可选, 默认为"<image>"
) — 用于表示图像位置的特殊 token。 - video_token (
str
, 可选, 默认为"<video>"
) — 用于表示视频位置的特殊 token。 - chat_template (
str
, 可选) — Jinja 模板,用于将聊天中的消息列表转换为可标记化的字符串。 - num_additional_image_tokens (
int
, 可选, 默认为 1) — 添加到图像嵌入的额外 token 数量,例如 CLS (+1)。如果骨干网络没有 CLS 或其他附加的额外 token,则无需设置此参数。
构建 VideoLlava 处理器,该处理器将 VideoLlava 图像处理器和 Llava 分词器包装到单个处理器中。
VideoLlavaProcessor 提供 VideoLlavaImageProcessor 和 LlamaTokenizerFast 的所有功能。 有关更多信息,请参阅 __call__()
和 decode()。
此方法将其所有参数转发到 LlamaTokenizerFast 的 batch_decode()。 有关更多信息,请参阅此方法的文档字符串。
此方法将其所有参数转发到 LlamaTokenizerFast 的 decode()。 有关更多信息,请参阅此方法的文档字符串。
VideoLlavaForConditionalGeneration
class transformers.VideoLlavaForConditionalGeneration
< source >( config: VideoLlavaConfig )
Parameters
- config (VideoLlavaConfig 或
VideoLlavaVisionConfig
) — 具有模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型关联的权重,仅加载配置。 查看 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[typing.List[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None vision_feature_layer: typing.Union[int, typing.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 **lm_kwargs ) → transformers.models.video_llava.modeling_video_llava.VideoLlavaCausalLMOutputWithPast
or tuple(torch.FloatTensor)
Parameters
- input_ids (
torch.LongTensor
,形状为(batch_size, sequence_length)
) — 词汇表中输入序列 token 的索引。 默认情况下,如果您提供 padding,则会被忽略。索引可以使用 AutoTokenizer 获取。 有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call() 。
- pixel_values_images (
torch.FloatTensor
,形状为(batch_size, num_channels, image_size, image_size))
-- 与输入图像对应的张量。 像素值可以使用 [AutoImageProcessor](/docs/transformers/v4.50.0/en/model_doc/auto#transformers.AutoImageProcessor) 获取。 有关详细信息,请参阅 [VideoLlavaImageProcessor.__call__()](/docs/transformers/v4.50.0/en/model_doc/vilt#transformers.ViltFeatureExtractor.__call__) ([]LlavaProcessor
] 使用 VideoLlavaImageProcessor 处理图像)。 - pixel_values_videos (
torch.FloatTensor
,形状为(batch_size, num_frames, num_channels, image_size, image_size))
-- 与输入视频对应的张量。 像素值可以使用 [AutoImageProcessor](/docs/transformers/v4.50.0/en/model_doc/auto#transformers.AutoImageProcessor) 获取。 有关详细信息,请参阅 [VideoLlavaImageProcessor.__call__()](/docs/transformers/v4.50.0/en/model_doc/vilt#transformers.ViltFeatureExtractor.__call__) ([]LlavaProcessor
] 使用 VideoLlavaImageProcessor 处理视频)。 - attention_mask (
torch.Tensor
,形状为(batch_size, sequence_length)
, 可选) — 用于避免在 padding token 索引上执行 attention 的 Mask。 Mask 值在[0, 1]
中选择:- 1 表示 未被 mask 的 token,
- 0 表示 已被 mask 的 token。
索引可以使用 AutoTokenizer 获取。 有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call() 。
如果使用
past_key_values
,则可以选择仅输入最后的decoder_input_ids
(请参阅past_key_values
)。如果您想更改 padding 行为,则应阅读
modeling_opt._prepare_decoder_attention_mask
并根据您的需要进行修改。 有关默认策略的更多信息,请参见 论文 中的图 1 。- 1 表示 head 未被 mask,
- 0 表示 head 已被 mask。
- position_ids (
torch.LongTensor
,形状为(batch_size, sequence_length)
, 可选) — 位置嵌入中每个输入序列 token 的位置索引。 在范围[0, config.n_positions - 1]
中选择。 什么是位置 ID? - past_key_values (
tuple(tuple(torch.FloatTensor))
, 可选, 当传递use_cache=True
或config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(tuple(torch.FloatTensor))
元组,其中每个元组包含 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
的张量,以及 2 个形状为(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
的附加张量。包含预先计算的隐藏状态(自注意力模块和交叉注意力模块中的 key 和 value),这些状态可用于(请参阅
past_key_values
输入)加速顺序解码。如果使用
past_key_values
,则用户可以选择仅输入形状为(batch_size, 1)
的最后一个decoder_input_ids
(那些没有将其过去的 key value 状态提供给此模型的),而不是形状为(batch_size, sequence_length)
的所有decoder_input_ids
。 - inputs_embeds (
torch.FloatTensor
,形状为(batch_size, sequence_length, hidden_size)
, 可选) — (可选)您可以选择直接传递嵌入表示,而不是传递input_ids
。 如果您想要更好地控制如何将input_ids
索引转换为关联向量,而不是模型的内部嵌入查找矩阵,这将非常有用。 - vision_feature_layer (
Union[int, List[int]], *optional*, defaults to -2
) — 选择视觉特征的层索引。如果提供多个索引,则会将相应索引的视觉特征连接起来以形成视觉特征。 - vision_feature_select_strategy (
str
, optional, defaults to"default"
) — 用于从视觉主干网络中选择视觉特征的特征选择策略。 可以是"default"
或"full"
中的一个 - use_cache (
bool
, optional) — 如果设置为True
,则返回past_key_values
键值状态,并可用于加速解码(请参阅past_key_values
)。 - output_attentions (
bool
, optional) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, optional) — 是否返回 ModelOutput 而不是纯元组。 - cache_position (
torch.LongTensor
of shape(sequence_length)
, optional) — 索引,描述输入序列 tokens 在序列中的位置。 与position_ids
相反,此张量不受 padding 的影响。 它用于在正确的位置更新缓存,并推断完整的序列长度。 - labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — 用于计算掩码语言建模损失的标签。 索引应为[0, ..., config.vocab_size]
或 -100(请参阅input_ids
文档字符串)。 索引设置为-100
的 tokens 将被忽略(掩码),损失仅针对标签在[0, ..., config.vocab_size]
中的 tokens 计算。 - logits_to_keep (
int
ortorch.Tensor
, optional) — 如果是int
,则计算最后logits_to_keep
个 tokens 的 logits。 如果是0
,则计算所有input_ids
的 logits(特殊情况)。 只有最后一个 token logits 是生成所需的,并且仅针对该 token 计算它们可以节省内存,这对于长序列或大型词汇表大小而言变得非常重要。 如果是torch.Tensor
,则必须是 1D,对应于要在序列长度维度中保留的索引。 这在使用 packed tensor 格式(批量和序列长度的单维度)时很有用。
返回
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
of shape(1,)
, optional, 当提供labels
时返回) — 语言建模损失(用于下一个 token 预测)。 -
logits (
torch.FloatTensor
of shape(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。 -
past_key_values (
tuple(tuple(torch.FloatTensor))
, optional, 当传递了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)
, optional, 当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
元组(如果模型具有嵌入层,则为嵌入输出,+ 每个层的输出一个)形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出端的隐藏状态,以及可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
, optional, 当传递了output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 之后的注意力权重,用于计算自注意力头中的加权平均值。
-
image_hidden_states (
torch.FloatTensor
, optional) — 大小为 (batch_size, num_images, sequence_length, hidden_size)` 的torch.FloatTensor
。 由视觉编码器生成并在投影最后一个隐藏状态之后的模型的 image_hidden_states。 -
video_hidden_states (
torch.FloatTensor
, optional) — 大小为(batch_size * num_frames, num_videos, sequence_length, hidden_size)
的torch.FloatTensor
。 由视觉编码器生成并在投影最后一个隐藏状态之后的模型的 video_hidden_states。
VideoLlavaForConditionalGeneration forward 方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数内定义,但应在此之后调用 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']