Transformers 文档

LLaVA-NeXT

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

LLaVA-NeXT

PyTorch FlashAttention SDPA

概述

LLaVA-NeXT 模型在 LLaVA-NeXT: Improved reasoning, OCR, and world knowledge 中被提出,作者是 Haotian Liu, Chunyuan Li, Yuheng Li, Bo Li, Yuanhan Zhang, Sheng Shen, Yong Jae Lee。LLaVa-NeXT(也称为 LLaVa-1.6)在 LLaVa 的基础上进行了改进,增加了输入图像分辨率,并在改进的可视指令微调数据集上进行训练,以提高 OCR 和常识推理能力。

以下是该博客的介绍

*在 2023 年 10 月,我们发布了 LLaVA-1.5,它设计简洁高效,并在 12 个数据集的基准测试套件中表现出色。此后,它已成为许多关于大型多模态模型 (LMM) 的数据、模型和能力的综合研究的基础,并促成了各种新的应用。

今天,我们很高兴推出 LLaVA-NeXT,它在推理、OCR 和世界知识方面都有所改进。LLaVA-NeXT 甚至在几个基准测试中超过了 Gemini Pro。

与 LLaVA-1.5 相比,LLaVA-NeXT 有以下几项改进

将输入图像分辨率提高到 4 倍像素。这使其能够掌握更多视觉细节。它支持三种宽高比,分辨率高达 672x672、336x1344、1344x336。通过改进的可视指令微调数据混合,提高了视觉推理和 OCR 能力。更好的视觉对话,适用于更多场景,涵盖不同的应用。更好的世界知识和逻辑推理。使用 SGLang 实现高效部署和推理。除了性能改进外,LLaVA-NeXT 还保持了 LLaVA-1.5 的简约设计和数据效率。它重复使用了 LLaVA-1.5 的预训练连接器,并且仍然使用少于 100 万个视觉指令微调样本。最大的 34B 变体在 ~1 天内使用 32 个 A100 完成训练。*

drawing LLaVa-NeXT 通过编码输入图像的各种补丁来整合更高的输入分辨率。摘自原始论文。

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

使用技巧

  • 我们建议用户在计算批量生成时使用 padding_side="left",因为它能带来更准确的结果。只需确保在生成之前调用 processor.tokenizer.padding_side = "left" 即可。
  • Llava-Next 对图像使用不同数量的补丁,因此除了处理输入时进行的填充外,还必须在建模代码内部填充输入。如果模型处于 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}} 的警告。强烈建议如果您拥有模型检查点,则将这些属性添加到处理器,或者如果它不是您拥有的,则打开一个 PR。添加这些属性意味着 LLaVA 将尝试推断每张图像所需的图像令牌数量,并使用尽可能多的 <image> 占位符扩展文本,因为会有令牌。通常每张图像大约有 500 个令牌,因此请确保文本没有被截断,否则在合并嵌入时会出现故障。这些属性可以从模型配置中获得,如 model.config.vision_config.patch_sizemodel.config.vision_feature_select_strategy。如果视觉骨干网络添加了 CLS 令牌,则 num_additional_image_tokens 应为 1,如果未向视觉补丁添加任何额外内容,则应为 0

使用聊天模板格式化提示

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

重要提示

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

以下是如何构建输入的示例。我们将使用 llava-v1.6-mistral-7b-hf 以及文本和图像的对话历史记录。

from transformers import LlavaNextProcessor

processor = LlavaNextProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")

conversation = [
    {
        "role": "user",
        "content": [
            {"type": "image"},
            {"type": "text", "text": "What’s shown in this image?"},
        ],
    },
    {
        "role": "assistant",
        "content": [{"type": "text", "text": "This image shows a red stop sign."},]
    },
    {

        "role": "user",
        "content": [
            {"type": "text", "text": "Describe the image in more details."},
        ],
    },
]

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 images
print(text_prompt)
>>> "[INST] <image>\nWhat's shown in this image? [/INST] This image shows a red stop sign. [INST] Describe the image in more details. [/INST]"
"[INST] <image>\nWhat is shown in this image? [/INST]"

llava-v1.6-vicuna-7b-hfllava-v1.6-vicuna-13b-hf 需要以下格式

"A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions. USER: <image>\nWhat is shown in this image? ASSISTANT:"

llava-v1.6-34b-hf 需要以下格式

"<|im_start|>system\nAnswer the questions.<|im_end|><|im_start|>user\n<image>\nWhat is shown in this image?<|im_end|><|im_start|>assistant\n"

llama3-llava-next-8b-hf 需要以下格式

"<|start_header_id|>system<|end_header_id|>\n\nYou are a helpful language and vision assistant. You are able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language.<|eot_id|><|start_header_id|><|start_header_id|>user<|end_header_id|>\n\n<image>\nWhat is shown in this image?<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"

llava-next-72b-hfllava-next-110b-hf 需要以下格式

"<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n<image>\nWhat is shown in this image?<|im_end|>\n<|im_start|>assistant\n"

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

使用示例

单图像推理

以下是如何加载模型并在半精度 (torch.float16) 下执行推理

from transformers import LlavaNextProcessor, LlavaNextForConditionalGeneration
import torch
from PIL import Image
import requests

processor = LlavaNextProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")

model = LlavaNextForConditionalGeneration.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf", torch_dtype=torch.float16, low_cpu_mem_usage=True)
model.to("cuda:0")

# prepare image and text prompt, using the appropriate prompt template
url = "https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true"
image = Image.open(requests.get(url, stream=True).raw)

conversation = [
    {
        "role": "user",
        "content": [
            {"type": "image"},
            {"type": "text", "text": "What is shown in this image?"},
        ],
    },
]
prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
inputs = processor(image, prompt, return_tensors="pt").to("cuda:0")

# autoregressively complete prompt
output = model.generate(**inputs, max_new_tokens=100)

print(processor.decode(output[0], skip_special_tokens=True))

多图像推理

LLaVa-Next 可以使用多张图像作为输入执行推理,其中图像可以属于同一个提示或不同的提示(在批量推理中)。以下是如何操作

import requests
from PIL import Image
import torch
from transformers import AutoProcessor, AutoModelForImageTextToText

# Load the model in half-precision
model = AutoModelForImageTextToText.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf", torch_dtype=torch.float16, device_map="auto")
processor = AutoProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")

# Get three different images
url = "https://www.ilankelman.org/stopsigns/australia.jpg"
image_stop = Image.open(requests.get(url, stream=True).raw)

url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image_cats = Image.open(requests.get(url, stream=True).raw)

url = "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg"
image_snowman = Image.open(requests.get(url, stream=True).raw)

# Prepare a batch of two prompts, where the first one is a multi-turn conversation and the second is not
conversation_1 = [
    {
        "role": "user",
        "content": [
            {"type": "image"},
            {"type": "text", "text": "What is shown in this image?"},
            ],
    },
    {
        "role": "assistant",
        "content": [
            {"type": "text", "text": "There is a red stop sign in the image."},
            ],
    },
    {
        "role": "user",
        "content": [
            {"type": "image"},
            {"type": "text", "text": "What about this image? How many cats do you see?"},
            ],
    },
]

conversation_2 = [
    {
        "role": "user",
        "content": [
            {"type": "image"},
            {"type": "text", "text": "What is shown in this image?"},
            ],
    },
]

prompt_1 = processor.apply_chat_template(conversation_1, add_generation_prompt=True)
prompt_2 = processor.apply_chat_template(conversation_2, add_generation_prompt=True)
prompts = [prompt_1, prompt_2]

# We can simply feed images in the order they have to be used in the text prompt
# Each "<image>" token uses one image leaving the next for the subsequent "<image>" tokens
inputs = processor(images=[image_stop, image_cats, image_snowman], text=prompts, padding=True, return_tensors="pt").to(model.device)

# Generate
generate_ids = model.generate(**inputs, max_new_tokens=30)
processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)

模型优化

使用 Bitsandbytes 进行量化

该模型可以加载为 8 位或 4 位,大大降低内存需求,同时保持原始模型的性能。首先确保安装 bitsandbytes,pip install bitsandbytes,并访问库支持的 GPU/加速器。

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

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

只需将上面的代码片段更改为

from transformers import AutoModelForImageTextToText, 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 = AutoModelForImageTextToText.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf", quantization_config=quantization_config, device_map="auto")

使用 Flash-Attention 2 进一步加速生成

首先确保安装 flash-attn。关于该软件包的安装,请参考 Flash Attention 的原始仓库。只需将上面的代码片段更改为

from transformers import AutoModelForImageTextToText

model = AutoModelForImageTextToText.from_pretrained(
    model_id,
    torch_dtype=torch.float16,
    low_cpu_mem_usage=True,
    use_flash_attention_2=True
).to(0)

LlavaNextConfig

class transformers.LlavaNextConfig

< >

( vision_config = None text_config = None image_token_index = 32000 projector_hidden_act = 'gelu' vision_feature_select_strategy = 'default' vision_feature_layer = -2 image_grid_pinpoints = None tie_word_embeddings = False image_seq_length = 576 multimodal_projector_bias = True **kwargs )

参数

  • vision_config (Union[AutoConfig, dict], 可选, 默认为 CLIPVisionConfig) — 视觉骨干网络的配置对象或字典。
  • text_config (Union[AutoConfig, dict], 可选, 默认为 LlamaConfig) — 文本骨干网络的配置对象或字典。
  • image_token_index (int, 可选, 默认为 32000) — 用于编码图像提示的图像 token 索引。
  • projector_hidden_act (str, 可选, 默认为 "gelu") — 多模态投影器使用的激活函数。
  • 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) — 模型输入和输出词嵌入是否应该绑定。
  • image_seq_length (int, 可选, 默认为 576) — 一个图像嵌入的序列长度。
  • multimodal_projector_bias (bool, 可选, 默认为 True) — 是否在多模态投影器中使用偏置。

这是配置类,用于存储 LlavaNextForConditionalGeneration 的配置。它用于根据指定的参数实例化 Llava-NeXT 模型,定义模型架构。使用默认值实例化配置将产生与 llava-hf/llava-v1.6-mistral-7b-hf 模型类似的配置。

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

示例

>>> from transformers import LlavaNextForConditionalGeneration, LlavaNextConfig, CLIPVisionConfig, LlamaConfig

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

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

>>> # Initializing a Llava-Next llava-hf/llava-v1.6-mistral-7b-hf style configuration
>>> configuration = LlavaNextConfig(vision_config, text_config)

>>> # Initializing a model from the llava-hf/llava-v1.6-mistral-7b-hf style configuration
>>> model = LlavaNextForConditionalGeneration(configuration)

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

LlavaNextImageProcessor

class transformers.LlavaNextImageProcessor

< >

( 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_pad: typing.Optional[bool] = True 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 重写。
  • image_grid_pinpoints (List 可选, 默认为 [[672, 336], [336, 672], [672, 672], [336, 1008], [1008, 336]]) — 用于处理高分辨率图像的可能分辨率列表。最佳分辨率是根据图像的原始尺寸选择的。可以在 preprocess 方法中通过 image_grid_pinpoints 重写。
  • 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 (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_pad (bool, 可选, 默认为 True) — 是否填充图像。如果为 True,则会将批次中图像的 patch 维度填充到批次中最大的 patch 数量。填充将应用于底部和右侧,使用零值。
  • do_convert_rgb (bool, 可选, 默认为 True) — 是否将图像转换为 RGB 格式。

构建 LLaVa-NeXT 图像处理器。基于 CLIPImageProcessor,并结合了处理高分辨率图像的附加技术,如 LLaVa 论文 中所述。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_resize: bool = None size: typing.Dict[str, int] = None image_grid_pinpoints: typing.List = 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_pad: typing.Optional[bool] = 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 (ImageInput) — 要预处理的图像。 接受单个或一批像素值范围为 0 到 255 的图像。 如果传入像素值在 0 到 1 之间的图像,请设置 do_rescale=False
  • do_resize (bool, 可选, 默认为 self.do_resize) — 是否调整图像大小。
  • size (Dict[str, int], 可选, 默认为 self.size) — 调整大小后图像的尺寸。图像的最短边将调整为 size[“shortest_edge”],最长边将调整为保持输入宽高比。
  • image_grid_pinpoints (List 可选, 默认为 self.image_grid_pinpoints) — 用于处理高分辨率图像的可能分辨率列表。最佳分辨率会根据图像的原始大小进行选择。
  • 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 (floatList[float], 可选, 默认为 self.image_mean) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时才有效。
  • image_std (floatList[float], 可选, 默认为 self.image_std) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时才有效。
  • do_pad (bool, 可选, 默认为 self.do_pad) — 是否填充图像。如果为 True,则会将批次中图像的 patch 维度填充到批次中最大的 patch 数量。填充将应用于底部和右侧,使用零值。
  • do_convert_rgb (bool, 可选, 默认为 self.do_convert_rgb) — 是否将图像转换为 RGB 格式。
  • return_tensors (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 (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • Unset: 使用输入图像的通道维度格式。
  • 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)。

LlavaNextImageProcessorFast

class transformers.LlavaNextImageProcessorFast

< >

( **kwargs: typing_extensions.Unpack[transformers.models.llava_next.image_processing_llava_next_fast.LlavaNextFastImageProcessorKwargs] )

参数

  • do_resize (bool, 可选, 默认为 self.do_resize) — 是否将图像的 (height, width) 尺寸调整为指定的 size 大小。可以被 preprocess 方法中的 do_resize 参数覆盖。
  • size (dict, 可选, 默认为 self.size) — 调整大小后输出图像的尺寸。可以被 preprocess 方法中的 size 参数覆盖。
  • default_to_square (bool, 可选, 默认为 self.default_to_square) — 如果 size 是整数,是否默认将图像调整为正方形。
  • resample (PILImageResampling, 可选, 默认为 self.resample) — 如果调整图像大小,则使用的重采样滤波器。仅当 do_resize 设置为 True 时才有效。可以被 preprocess 方法中的 resample 参数覆盖。
  • do_center_crop (bool, 可选, 默认为 self.do_center_crop) — 是否将图像中心裁剪为指定的 crop_size 大小。可以被 preprocess 方法中的 do_center_crop 参数覆盖。
  • crop_size (Dict[str, int] 可选, 默认为 self.crop_size) — 应用 center_crop 后输出图像的尺寸。可以被 preprocess 方法中的 crop_size 参数覆盖。
  • do_rescale (bool, 可选, 默认为 self.do_rescale) — 是否按指定的比例 rescale_factor 缩放图像。仅当 do_rescale 设置为 True 时才有效。可以被 preprocess 方法中的 do_rescale 参数覆盖。
  • rescale_factor (intfloat, 可选, 默认为 self.rescale_factor) — 如果缩放图像,则使用的缩放因子。仅当 do_rescale 设置为 True 时才有效。可以被 preprocess 方法中的 rescale_factor 参数覆盖。
  • do_normalize (bool, 可选, 默认为 self.do_normalize) — 是否对图像进行归一化。可以被 preprocess 方法中的 do_normalize 参数覆盖。可以被 preprocess 方法中的 do_normalize 参数覆盖。
  • image_mean (floatList[float], 可选, 默认为 self.image_mean) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或浮点数列表,其长度等于图像中的通道数。可以被 preprocess 方法中的 image_mean 参数覆盖。可以被 preprocess 方法中的 image_mean 参数覆盖。
  • image_std (floatList[float], 可选, 默认为 self.image_std) — 如果对图像进行归一化,则使用的标准差。这是一个浮点数或浮点数列表,其长度等于图像中的通道数。可以被 preprocess 方法中的 image_std 参数覆盖。可以被 preprocess 方法中的 image_std 参数覆盖。
  • do_convert_rgb (bool, 可选, 默认为 self.do_convert_rgb) — 是否将图像转换为 RGB 格式。
  • return_tensors (strTensorType, 可选, 默认为 self.return_tensors) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。
  • data_format (ChannelDimensionstr, 可选, 默认为 self.data_format) — 仅支持 ChannelDimension.FIRST。为与慢速处理器兼容而添加。
  • input_data_format (ChannelDimensionstr, 可选, 默认为 self.input_data_format) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE: 图像格式为 (height, width)。
  • device (torch.device, 可选, 默认为 self.device) — 处理图像的设备。如果未设置,则从输入图像推断设备。
  • image_grid_pinpoints (List[List[int]], 可选) — 用于处理高分辨率图像的可能分辨率列表。最佳分辨率会根据图像的原始大小进行选择。可以被 preprocess 方法中的 image_grid_pinpoints 参数覆盖。
  • do_pad (bool, 可选) — 是否填充图像。如果为 True,则会将批次中图像的 patch 维度填充到批次中最大的 patch 数量。填充将应用于底部和右侧,并使用零值。

构建一个快速的 ConvNeXT 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] **kwargs: typing_extensions.Unpack[transformers.models.llava_next.image_processing_llava_next_fast.LlavaNextFastImageProcessorKwargs] )

参数

  • images (ImageInput) — 要预处理的图像。 接受单张或批量图像,像素值范围为 0 到 255。 如果传入像素值在 0 到 1 之间的图像,请设置 do_rescale=False
  • do_resize (bool, 可选, 默认为 self.do_resize) — 是否调整图像大小。
  • size (Dict[str, int], 可选, 默认为 self.size) — 描述模型的最大输入尺寸。
  • resample (PILImageResamplingInterpolationMode, 可选, 默认为 self.resample) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举类型 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时才有效。
  • do_center_crop (bool, 可选, 默认为 self.do_center_crop) — 是否对图像进行中心裁剪。
  • crop_size (Dict[str, int], 可选, 默认为 self.crop_size) — 应用 center_crop 后输出图像的尺寸。
  • do_rescale (bool, 可选, 默认为 self.do_rescale) — 是否缩放图像。
  • rescale_factor (float, 可选, 默认为 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, 可选, 默认为 self.return_tensors) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。
  • data_format (ChannelDimensionstr, 可选, 默认为 self.data_format) — 仅支持 ChannelDimension.FIRST。为了与慢速处理器兼容而添加。
  • input_data_format (ChannelDimensionstr, 可选, 默认为 self.input_data_format) — 输入图像的通道维度格式。如果未设置,则通道维度格式从输入图像推断。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE:图像格式为 (height, width)。
  • device (torch.device, 可选, 默认为 self.device) — 用于处理图像的设备。如果未设置,则设备从输入图像推断。 image_grid_pinpoints (List, 可选): 用于处理高分辨率图像的可能分辨率列表。列表中的每个项目都应为 (height, width) 形式的元组或列表。 do_pad (bool, 可选): 是否填充图像。如果为 True,则将批次中图像的 patch 维度填充到批次中最大 patch 数量。填充将使用零应用于底部和右侧。

预处理单个图像或一批图像。

LlavaNextProcessor

class transformers.LlavaNextProcessor

< >

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

参数

  • image_processor (LlavaNextImageProcessor, 可选) — 图像处理器是必需的输入。
  • tokenizer (LlamaTokenizerFast, 可选) — 分词器是必需的输入。
  • patch_size (int, 可选) — 来自视觉塔的 patch 大小。
  • vision_feature_select_strategy (str, 可选) — 用于从视觉骨干网络中选择视觉特征的特征选择策略。应与模型配置中的策略相同
  • chat_template (str, 可选) — Jinja 模板,用于将聊天中的消息列表转换为可标记化的字符串。
  • image_token (str, 可选, 默认为 "<image>") — 用于表示图像位置的特殊 token。
  • num_additional_image_tokens (int, 可选, 默认为 0) — 添加到图像 embeddings 的额外 token 数量,例如 CLS (+1)。如果骨干网络没有 CLS 或其他附加的额外 token,则无需设置此参数。

构建一个 LLaVa-NeXT processor,它将 LLaVa-NeXT 图像处理器和 LLaMa 分词器包装到单个处理器中。

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

batch_decode

< >

( *args **kwargs )

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

decode

< >

( *args **kwargs )

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

LlavaNextForConditionalGeneration

class transformers.LlavaNextForConditionalGeneration

< >

( config: LlavaNextConfig )

参数

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

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

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

forward

< >

( input_ids: LongTensor = None pixel_values: 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.modeling_llava_next.LlavaNextCausalLMOutputWithPasttuple(torch.FloatTensor)

参数

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

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

    什么是输入 ID?

  • pixel_values (torch.FloatTensor, 形状为 `(batch_size, num_channels, image_size, image_size)`) — 对应于输入图像的张量。像素值可以使用 AutoImageProcessor 获得。有关详细信息,请参阅 LlavaNextImageProcessor.call()LlavaProcessor 使用 LlavaNextImageProcessor 处理图像。
  • image_sizes (torch.LongTensor, 形状为 (batch_size, 2), *可选*) — 批次中图像的尺寸,每张图像为 (高度, 宽度)。
  • attention_mask (torch.Tensor, 形状为 (batch_size, sequence_length), *可选*) — 用于避免在填充 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 (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_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) 的附加张量。

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

    如果使用 past_key_values,用户可以选择仅输入最后的 decoder_input_ids(那些没有将其过去的键值状态提供给此模型的),形状为 (batch_size, 1),而不是所有形状为 (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]], *可选*, 默认为 -2) — 用于选择视觉特征的层索引。如果提供多个索引,则会将相应索引的视觉特征连接起来以形成视觉特征。
  • vision_feature_select_strategy (str, *可选*, 默认为 "default") — 用于从视觉 backbone 中选择视觉特征的特征选择策略。可以是 "default""full" 之一。如果为 "default",则从视觉特征中移除 CLS token。如果为 "full",则使用完整的视觉特征。
  • use_cache (bool, *可选*) — 如果设置为 True,则返回 past_key_values 键值状态,并可用于加速解码(请参阅 past_key_values)。
  • output_attentions (bool, *可选*) — 是否返回所有 attention 层的 attentions 张量。 有关更多详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, *可选*) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, *可选*) — 是否返回 ModelOutput 而不是普通元组。
  • cache_position (torch.LongTensor, 形状为 (sequence_length), *可选*) — 描述输入序列 token 在序列中位置的索引。与 position_ids 相反,此张量不受填充的影响。它用于在正确的位置更新缓存并推断完整的序列长度。
  • labels (torch.LongTensor, 形状为 (batch_size, sequence_length), *可选*) — 用于计算掩码语言建模损失的标签。索引应为 [0, ..., config.vocab_size] 或 -100(请参阅 input_ids 文档字符串)。索引设置为 -100 的 token 将被忽略(掩码),损失仅针对标签在 [0, ..., config.vocab_size] 中的 token 计算。
  • logits_to_keep (inttorch.Tensor, *可选*) — 如果是 int,则计算最后 logits_to_keep 个 token 的 logits。 如果是 0,则计算所有 input_ids 的 logits(特殊情况)。 只需要最后一个 token logits 用于生成,并且仅为该 token 计算它们可以节省内存,这对于长序列或大词汇量大小而言变得非常重要。 如果是 torch.Tensor,则必须是与序列长度维度中要保留的索引相对应的 1D 张量。 这在使用打包张量格式(批次和序列长度的单个维度)时很有用。

返回

transformers.models.llava_next.modeling_llava_next.LlavaNextCausalLMOutputWithPasttuple(torch.FloatTensor)

一个 transformers.models.llava_next.modeling_llava_next.LlavaNextCausalLMOutputWithPasttorch.FloatTensor 的元组 (如果传递 return_dict=False 或当 config.return_dict=False 时) ,包含各种元素,具体取决于配置 (LlavaNextConfig) 和输入。

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

  • logits (torch.FloatTensor, 形状为 (batch_size, sequence_length, config.vocab_size)) — 语言建模 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) 的张量)

    包含预先计算的隐藏状态(自注意力模块中的键和值),可以用于(请参阅 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)

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

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

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

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

示例

>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, LlavaNextForConditionalGeneration

>>> model = LlavaNextForConditionalGeneration.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")
>>> processor = AutoProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")

>>> prompt = "[INST] <image>\nWhat is shown in this image? [/INST]"
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> inputs = processor(images=image, text=prompt, return_tensors="pt")

>>> # Generate
>>> generate_ids = model.generate(**inputs, max_length=30)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"[INST]  \nWhat is shown in this image? [/INST] The image appears to be a radar chart, which is a type of multi-dimensional plot (...)"
< > 在 GitHub 上更新