Transformers 文档

LLaVa-NeXT-Video

Hugging Face's logo
加入 Hugging Face 社区

并获取增强的文档体验

开始使用

LLaVa-NeXT-Video

PyTorch FlashAttention SDPA

概述

LLaVa-NeXT-Video 模型在 LLaVA-NeXT: A Strong Zero-shot Video Understanding Model 中提出,作者是 Yuanhan Zhang, Bo Li, Haotian Liu, Yong Jae Lee, Liangke Gui, Di Fu, Jiashi Feng, Ziwei Liu, Chunyuan Li。LLaVa-NeXT-Video 在 LLaVa-NeXT 的基础上进行了改进,通过在视频和图像数据集上进行微调,从而提高了模型在视频上的性能。

LLaVA-NeXT 令人惊讶地在使用 AnyRes 技术以零样本方式理解视频内容方面表现出色。AnyRes 技术自然地将高分辨率图像表示为多个图像。这项技术自然可以推广到表示视频,因为视频可以被视为一组帧(类似于 LLaVa-NeXT 中的一组图像)。当前版本的 LLaVA-NeXT 利用 AnyRes,并在 LLaVA-Next 的基础上对视频数据进行监督微调 (SFT),以实现更好的视频理解能力。该模型是 VideoMME bench 上开源模型中的当前 SOTA。

以下是博客的介绍:

2024 年 1 月 30 日,我们发布了 LLaVA-NeXT,这是一款仅在文本-图像数据上训练的开源大型多模态模型 (LMM)。借助提出的 AnyRes 技术,它提升了推理、OCR 和世界知识方面的能力,在各种基于图像的多模态理解任务中表现出色,甚至在多个图像基准测试(例如 MMMU 和 MathVista)上超越了 Gemini-Pro。

**在今天的探索中,我们将深入研究 LLaVA-NeXT 在视频理解任务领域的性能。我们揭示了 LLaVA-NeXT 令人惊讶地在理解视频内容方面表现出色。当前用于视频的 LLaVA-NeXT 版本有几项改进:**

  • 使用 AnyRes 的零样本视频表示能力:AnyRes 技术自然地将高分辨率图像表示为多个预训练的 VIT 能够消化的图像,并将它们组合成一个连接序列。这项技术自然可以推广到表示视频(由多个帧组成),使仅在图像上训练的 LLaVA-Next 模型在视频任务上表现出令人惊讶的良好性能。值得注意的是,这是 LMM 首次展示出强大的零样本模态迁移能力。
  • 长度泛化的推理改进了较长视频的效果。线性缩放技术实现了长度泛化,使 LLaVA-NeXT 能够有效地处理超出 LLM “max_token_length” 限制的长视频。
  • 强大的视频理解能力。(1) LLaVA-Next-Image 结合了上述两种技术,比在视频上微调的开源 LMM 产生了更优越的零样本性能。(2) LLaVA-Next-Video 在视频数据上进一步监督微调 (SFT) LLaVA-Next-Image,与 LLaVA-Next-Image 相比,实现了更好的视频理解能力。(3) LLaVA-Next-Video-DPO 使用直接偏好优化 (DPO) 将模型响应与 AI 反馈对齐,显示出显著的性能提升。
  • 使用 SGLang 进行高效部署和推理。它允许在视频任务上实现 5 倍更快的推理速度,从而实现更可扩展的服务,例如百万级的视频重新字幕。请参阅我们 repo 中的说明。**

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

使用技巧

  • 我们建议用户在计算批量生成时使用 padding_side="left",因为它会产生更准确的结果。只需确保在生成之前调用 processor.tokenizer.padding_side = "left" 即可。
  • Llava-Next 对图像使用不同数量的 patches,因此除了处理输入时完成的 padding 外,还必须在建模代码内部填充输入。如果模型处于 eval() 模式,则默认设置为“左填充”,否则为“右填充”。

[!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}}` 的警告。强烈建议如果您拥有模型检查点,则将这些属性添加到 processor,或者如果不是您拥有,则打开 PR。添加这些属性意味着 LLaVA 将尝试推断每个图像所需的图像 tokens 数量,并使用与 tokens 数量相同的 <image> 占位符扩展文本。通常每个图像大约有 500 个 tokens,因此请确保文本没有被截断,否则在合并 embeddings 时会出现故障。这些属性可以从模型配置中获取,如 model.config.vision_config.patch_sizemodel.config.vision_feature_select_strategy。如果 vision backbone 添加了 CLS token,则 num_additional_image_tokens 应为 1,如果 vision patches 没有添加额外内容,则应为 0

使用 Chat Templates 格式化提示

每个检查点都使用特定的提示格式进行训练,具体取决于底层大型语言模型 backbone。为确保格式正确,请使用 processor 的 apply_chat_template 方法。

重要提示

  • 您必须构建对话历史记录 — 传递纯字符串将不起作用。
  • 每条消息都应该是一个字典,其中包含 "role""content" 键。
  • 对于不同的模态(如 "text""image"),"content" 应该是一个字典列表。

以下是如何构建输入的示例。我们将使用 LLaVA-NeXT-Video-7B-hf 和视频和图像的对话历史记录。

from transformers import LlavaNextVideoProcessor

processor = LlavaNextVideoProcessor.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf")

conversation = [
    {
        "role": "system",
        "content": [
            {"type": "text", "text": "A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions."},
            ],
    },
    {
        "role": "user",
        "content": [
            {"type": "text", "text": "What’s shown in this image?"},
            {"type": "image"},
            ],
    },
    {
        "role": "assistant",
        "content": [{"type": "text", "text": "This image shows a red stop sign."},]
    },
    {

        "role": "user",
        "content": [
            {"type": "text", "text": "Why is this video funny?"},
            {"type": "video"},
            ],
    },
]

text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)

# Note that the template simply formats your prompt, you still have to tokenize it and obtain pixel values for your visuals
print(text_prompt)

🚀 奖励: 如果您使用的是 transformers>=4.49.0,您还可以从 apply_chat_template 获取向量化输出。请参阅下面的使用示例,了解有关如何使用它的更多详细信息。

使用示例

单媒体模式

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

from huggingface_hub import hf_hub_download
import torch
from transformers import LlavaNextVideoForConditionalGeneration, LlavaNextVideoProcessor

# Load the model in half-precision
model = LlavaNextVideoForConditionalGeneration.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf", torch_dtype=torch.float16, device_map="auto")
processor = LlavaNextVideoProcessor.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf")

# Load the video as an np.array, sampling uniformly 8 frames (can sample more for longer videos)
video_path = hf_hub_download(repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset")

conversation = [
    {

        "role": "user",
        "content": [
            {"type": "text", "text": "Why is this video funny?"},
            {"type": "video", "path": video_path},
            ],
    },
]

inputs = processor.apply_chat_template(conversation, num_frames=8, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt")

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

混合媒体模式

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


# Generate from image and video mixed inputs
conversation = [
    {

        "role": "user",
        "content": [
            {"type": "text", "text": "How many cats are there in the image?"},
            {"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"},
            ],
    },
    {

        "role": "assistant",
        "content": [{"type": "text", "text": "There are two cats"}],
    },
    {

        "role": "user",
        "content": [
            {"type": "text", "text": "Why is this video funny?"},
            {"type": "video", "path": video_path},
            ],
    },
]
inputs = processor.apply_chat_template(conversation, num_frames=8, add_generation_prompt=True, tokenize=True, return_dict=True, 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 进行量化以提高内存效率

该模型可以以较低的 bits 加载,从而显著减少内存负担,同时保持原始模型的性能。这允许在资源受限的情况下进行高效部署。

首先,请确保运行 pip install bitsandbytes 安装 bitsandbytes,并有权访问库支持的 GPU/加速器。

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

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

然后,只需添加 BitsAndBytesConfig 即可加载量化模型,如下所示:

from transformers import LlavaNextVideoForConditionalGeneration, LlavaNextVideoProcessor

# 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 = LlavaNextVideoForConditionalGeneration.from_pretrained("llava-hf/LLaVA-NeXT-Video-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.float16torch.bfloat16 格式加载时使用。

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

from transformers import LlavaNextVideoForConditionalGeneration

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

LlavaNextVideoConfig

class transformers.LlavaNextVideoConfig

< >

( vision_config = None text_config = None image_token_index = 32001 projector_hidden_act = 'gelu' multimodal_projector_bias = True vision_feature_select_strategy = 'default' vision_feature_layer = -2 image_grid_pinpoints = None tie_word_embeddings = False video_token_index = 32000 spatial_pool_mode = 'average' spatial_pool_stride = 2 image_seq_length = 576 video_seq_length = 288 **kwargs )

参数

  • vision_config (Union[AutoConfig, dict], 可选, 默认为 CLIPVisionConfig) — 视觉主干网络的配置对象或字典。
  • text_config (Union[AutoConfig, dict], 可选, 默认为 LlamaConfig) — 文本主干网络的配置对象或字典。
  • image_token_index (int, 可选, 默认为 32001) — 用于编码图像提示的图像 token 索引。
  • projector_hidden_act (str, 可选, 默认为 "gelu") — 多模态投影器使用的激活函数。
  • multimodal_projector_bias (bool, 可选, 默认为 True) — 是否在多模态投影器中使用偏置。
  • vision_feature_select_strategy (str, 可选, 默认为 "default") — 用于从视觉主干网络中选择视觉特征的特征选择策略。可以是 "default""full" 之一。如果为 "default",则从视觉特征中移除 CLS token。如果为 "full",则使用完整的视觉特征。
  • vision_feature_layer (Union[int, List[int]], 可选, 默认为 -2) — 用于选择视觉特征的层索引。如果提供多个索引,则会将相应索引的视觉特征连接起来以形成视觉特征。
  • image_grid_pinpoints (List, 可选, 默认为 [[336, 672], [672, 336], [672, 672], [1008, 336], [336, 1008]]) — 用于处理高分辨率图像的可能分辨率列表。列表中的每个项目都应为 (height, width) 形式的元组或列表。
  • tie_word_embeddings (bool, 可选, 默认为 False) — 模型输入和输出词嵌入是否应该绑定。
  • video_token_index (int, 可选, 默认为 32000) — 用于编码图像提示的视频 token 索引。
  • spatial_pool_mode (str, 可选, 默认为 "average") — 用于视频的池化模式。可以是 “average”、“max” 或 “conv”。
  • spatial_pool_stride (int, 可选, 默认为 2) — 视频池化层中使用的步幅。
  • image_seq_length (int, 可选, 默认为 576) — 单个图像嵌入的序列长度。
  • video_seq_length (int, 可选, 默认为 288) — 单个视频嵌入的序列长度。

这是用于存储 LlavaNextVideoForConditionalGeneration 配置的配置类。它用于根据指定的参数实例化 Llava-NeXT 模型,定义模型架构。使用默认值实例化配置将产生与 llava-hf/LLaVA-NeXT-Video-7B-hf 模型类似的配置。配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PretrainedConfig 的文档。

示例

>>> from transformers import LlavaNextVideoForConditionalGeneration, LlavaNextVideoConfig, CLIPVisionConfig, LlamaConfig

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

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

>>> configuration = LlavaNextVideoConfig(vision_config, text_config)

>>> model = LlavaNextVideoForConditionalGeneration(configuration)

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

LlavaNextVideoProcessor

class transformers.LlavaNextVideoProcessor

< >

( video_processor = None image_processor = None tokenizer = None chat_template = None patch_size = None vision_feature_select_strategy = None video_token = '<video>' image_token = '<image>' num_additional_image_tokens = 0 **kwargs )

参数

  • video_processor (LlavaNextVideoImageProcessor, 可选) — 视频处理器是必需的输入。
  • image_processor (LlavaNextImageProcessor, 可选) — 图像处理器是必需的输入。
  • tokenizer (LlamaTokenizerFast, 可选) — 分词器是必需的输入。
  • chat_template (str, 可选) — 将在分词器的 apply_chat_template 中使用的 Jinja 聊天模板
  • patch_size (int, optional) — 来自视觉塔的 Patch 大小。
  • vision_feature_select_strategy (str, optional) — 用于从视觉骨干网络中选择视觉特征的特征选择策略。应与模型配置中的策略相同。
  • video_token (str, optional, defaults to "<video>") — 用于表示视频位置的特殊 token,默认为 "<video>"
  • image_token (str, optional, defaults to "<image>") — 用于表示图像位置的特殊 token,默认为 "<image>"
  • num_additional_image_tokens (int, optional, defaults to 0) — 添加到图像嵌入中的额外 token 数量,例如 CLS (+1)。如果骨干网络没有 CLS 或其他附加的额外 token,则无需设置此参数,默认为 0。

构建一个 LLaVa-NeXT-Video 处理器,它将 LLaVa-NeXT 图像处理器、LLaVa-NeXT-Video 视频处理器和一个 LLaMa tokenizer 封装到一个处理器中。

LlavaNextVideoProcessor 提供了 LlavaNextImageProcessorLlavaNextVideoImageProcessorLlamaTokenizerFast 的所有功能。 有关更多信息,请参阅 __call__()decode()

batch_decode

< >

( *args **kwargs )

此方法将其所有参数转发到 LlamaTokenizerFast 的 batch_decode()。 有关更多信息,请参阅此方法的文档字符串。

decode

< >

( *args **kwargs )

此方法将其所有参数转发到 LlamaTokenizerFast 的 decode()。 有关更多信息,请参阅此方法的文档字符串。

LlavaNextVideoImageProcessor

class transformers.LlavaNextVideoImageProcessor

< >

( do_resize: bool = True size: typing.Dict[str, int] = None image_grid_pinpoints: typing.List = 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 )

参数

  • do_resize (bool, optional, defaults to True) — 是否将图像的(高度,宽度)尺寸调整为指定的 size。可以被 preprocess 方法中的 do_resize 覆盖,默认为 True
  • size (Dict[str, int] optional, defaults to {"shortest_edge" -- 224}): 调整大小后图像的大小。图像的最短边将调整为 size[“shortest_edge”],最长边调整大小以保持输入纵横比。可以被 preprocess 方法中的 size 覆盖,默认为 {"shortest_edge" -- 224}
  • image_grid_pinpoints (List optional, defaults to [[672, 336], [336, 672], [672, 672], [336, 1008], [1008, 336]]) — 用于处理高分辨率图像的可能分辨率列表。最佳分辨率根据图像的原始大小选择。可以被 preprocess 方法中的 image_grid_pinpoints 覆盖,默认为 [[672, 336], [336, 672], [672, 672], [336, 1008], [1008, 336]]。不用于处理视频。
  • resample (PILImageResampling, optional, defaults to Resampling.BICUBIC) — 如果调整图像大小,则使用的重采样滤波器。可以被 preprocess 方法中的 resample 覆盖,默认为 Resampling.BICUBIC
  • do_center_crop (bool, optional, defaults to True) — 是否将图像中心裁剪到指定的 crop_size。可以被 preprocess 方法中的 do_center_crop 覆盖,默认为 True
  • crop_size (Dict[str, int] optional, defaults to 224) — 应用 center_crop 后输出图像的大小。可以被 preprocess 方法中的 crop_size 覆盖,默认为 224。
  • do_rescale (bool, optional, defaults to True) — 是否按指定的比例 rescale_factor 缩放图像。可以被 preprocess 方法中的 do_rescale 覆盖,默认为 True
  • rescale_factor (int or float, optional, defaults to 1/255) — 如果缩放图像,则使用的缩放因子。可以被 preprocess 方法中的 rescale_factor 覆盖,默认为 1/255
  • do_normalize (bool, optional, defaults to True) — 是否标准化图像。可以被 preprocess 方法中的 do_normalize 覆盖,默认为 True
  • image_mean (float or List[float], optional, defaults to [0.48145466, 0.4578275, 0.40821073]) — 如果标准化图像,则使用的均值。这是一个浮点数或浮点数列表,其长度为图像中的通道数。可以被 preprocess 方法中的 image_mean 参数覆盖,默认为 [0.48145466, 0.4578275, 0.40821073]
  • image_std (float or List[float], optional, defaults to [0.26862954, 0.26130258, 0.27577711]) — 如果标准化图像,则使用的标准差。这是一个浮点数或浮点数列表,其长度为图像中的通道数。可以被 preprocess 方法中的 image_std 参数覆盖。可以被 preprocess 方法中的 image_std 参数覆盖,默认为 [0.26862954, 0.26130258, 0.27577711]
  • do_convert_rgb (bool, optional, defaults to True) — 是否将图像转换为 RGB 格式,默认为 True

构建一个 LLaVa-NeXT-Video 视频处理器。基于 CLIPImageProcessor,并结合了处理每个视频帧的功能。

preprocess

< >

( images: 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']]] 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 )

参数

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

参数

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

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

LlavaNextVideoForConditionalGeneration

class transformers.LlavaNextVideoForConditionalGeneration

< >

( config: LlavaNextVideoConfig )

参数

  • config (LlavaNextVideoConfig or LlavaNextVideoVisionConfig) — 带有模型所有参数的模型配置类 (LlavaNextVideoConfigLlavaNextVideoVisionConfig)。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法来加载模型权重。

LLAVA-NeXT 模型,由视觉骨干网络和语言模型组成。此模型继承自 PreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

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

forward

< >

( input_ids: LongTensor = None pixel_values: FloatTensor = None pixel_values_videos: FloatTensor = None image_sizes: typing.Optional[torch.LongTensor] = 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.llava_next_video.modeling_llava_next_video.LlavaNextVideoCausalLMOutputWithPasttuple(torch.FloatTensor)

参数

  • input_ids (形状为 (batch_size, sequence_length)torch.LongTensor) — 词汇表中输入序列 tokens 的索引。如果您提供填充,默认情况下填充将被忽略。

    索引可以使用 AutoTokenizer 获得。 有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入 IDs?

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.FloatTensor) — 对应于输入图像的张量。像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参阅 LlavaNextVideoImageProcessor.call()LlavaProcessor 使用 LlavaNextVideoImageProcessor 处理图像。
  • image_sizes (形状为 (batch_size, 2)torch.LongTensor, 可选) — 批次中图像的大小,对于每个图像为 (高度,宽度)。
  • attention_mask (形状为 (batch_size, sequence_length)torch.Tensor, 可选) — 掩码,用于避免在填充 token 索引上执行 attention。掩码值在 [0, 1] 中选择:

    • 1 表示 token 未被掩码
    • 0 表示 token 已被掩码

    什么是 attention 掩码?

    索引可以使用 AutoTokenizer 获得。 有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    如果使用 past_key_values,则可以选择仅输入最后的 decoder_input_ids(请参阅 past_key_values)。

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

    • 1 表示 head 未被掩码
    • 0 表示 head 已被掩码
  • position_ids (形状为 (batch_size, sequence_length)torch.LongTensor, 可选) — 每个输入序列 token 在位置嵌入中的位置索引。在范围 [0, config.n_positions - 1] 中选择。 什么是位置 IDs?
  • past_key_values (tuple(tuple(torch.FloatTensor)), 可选, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstuple(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) 的附加张量。

    包含预先计算的 hidden-states(自注意力模块和交叉注意力模块中的键和值),可用于加速顺序解码(请参阅 past_key_values 输入)。

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

  • inputs_embeds (形状为 (batch_size, sequence_length, hidden_size)torch.FloatTensor, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。 如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将 input_ids 索引转换为关联的向量,这将非常有用。
  • vision_feature_layer (Union[int, List[int]], 可选, 默认为 -2) — 选择视觉特征的层索引。 如果提供多个索引,则相应索引的视觉特征将被连接以形成视觉特征。
  • vision_feature_select_strategy (str, 可选, 默认为 "default") — 用于从视觉骨干网络中选择视觉特征的特征选择策略。 可以是 "default""full" 之一。 如果为 "default",则从视觉特征中删除 CLS token。 如果为 "full",则使用完整的视觉特征。
  • use_cache (bool, 可选) — 如果设置为 True,则返回 past_key_values 键值状态,并可用于加速解码(请参阅 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有 attention 层的 attention 张量。 有关更多详细信息,请参见返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参见返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
  • cache_position (形状为 (sequence_length)torch.LongTensor, 可选) — 描述输入序列 tokens 在序列中位置的索引。 与 position_ids 相反,此张量不受填充的影响。 它用于在正确的位置更新缓存并推断完整序列长度。
  • pixel_values_videos (形状为 (batch_size, num_frames, num_channels, image_size, image_size)torch.FloatTensor) -- 对应于输入视频的张量。 像素值可以使用 [AutoImageProcessor](/docs/transformers/v4.50.0/en/model_doc/auto#transformers.AutoImageProcessor) 获得。 有关详细信息,请参阅 LlavaNextVideoVideoProcessor.call。 [LlavaProcessor](/docs/transformers/v4.50.0/en/model_doc/llava#transformers.LlavaProcessor) 使用 LlavaNextVideoVideoProcessor 处理视频。
  • labels (形状为 (batch_size, sequence_length)torch.LongTensor, 可选) — 用于计算掩码语言建模损失的标签。 索引应在 [0, ..., config.vocab_size] 或 -100 中(请参阅 input_ids 文档字符串)。 索引设置为 -100 的 tokens 将被忽略(掩码),损失仅针对标签在 [0, ..., config.vocab_size] 中的 tokens 计算。
  • logits_to_keep (inttorch.Tensor, 可选) — 如果是 int,则计算最后 logits_to_keep 个 tokens 的 logits。 如果为 0,则计算所有 input_ids 的 logits(特殊情况)。 仅生成最后一个 token 的 logits 是必需的,并且仅针对该 token 计算它们可以节省内存,这对于长序列或大词汇表大小而言变得非常重要。 如果是 torch.Tensor,则必须是 1D,对应于要在序列长度维度中保留的索引。 这在使用 packed tensor 格式(批次和序列长度的单维度)时很有用。

返回值

transformers.models.llava_next_video.modeling_llava_next_video.LlavaNextVideoCausalLMOutputWithPasttuple(torch.FloatTensor)

一个 transformers.models.llava_next_video.modeling_llava_next_video.LlavaNextVideoCausalLMOutputWithPasttorch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),其中包含各种元素,具体取决于配置 (LlavaNextVideoConfig) 和输入。

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

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

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

    包含预先计算的 hidden-states(自注意力模块中的键和值),可用于加速顺序解码(请参阅 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)

    模型在每一层输出端的 hidden-states,以及可选的初始嵌入输出。

  • attentions (tuple(torch.FloatTensor), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    attention softmax 之后的 attention 权重,用于计算自注意力 head 中的加权平均值。

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

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

LlavaNextVideoForConditionalGeneration forward 方法,覆盖了 __call__ 特殊方法。

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

示例

>>> from PIL import Image
>>> import requests
>>> import av
>>> from transformers import AutoProcessor, LlavaNextVideoForConditionalGeneration

>>> 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 = LlavaNextVideoForConditionalGeneration.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf", device_map="auto")
>>> processor = AutoProcessor.from_pretrained("llava-hf/LLaVA-NeXT-Video-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 (model was trained with 32 frames per video, but this video is short)
>>> 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_video = processor(text=prompt, videos=clip, return_tensors="pt").to(model.device)

>>> # load an image to generate from an image
>>> prompt = "USER:<image>\nWhat is shown in this image? ASSISTANT:"
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs_image = processor(text=prompt, images=image, return_tensors="pt").to(model.device)

>>> # Generate from video
>>> generate_ids = model.generate(**inputs_video, max_length=50)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"USER:\nWhy is this video funny? ASSISTANT: The humor in this video comes from the unexpected and endearing sight of a baby wearing glasses and (...)"

>>> # Generate from image
>>> generate_ids = model.generate(**inputs_image, max_length=30)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"USER: \nWhat's the content of the image? ASSISTANT: The image shows a red stop sign on a pole, with a traditional Chinese archway (...)"
< > 在 GitHub 上更新