Transformers 文档
LLaVA-NeXT
并获得增强的文档体验
开始使用
LLaVA-NeXT
概述
LLaVA-NeXT 模型由 Haotian Liu、Chunyuan Li、Yuheng Li、Bo Li、Yuanhan Zhang、Sheng Shen、Yong Jae Lee 在 LLaVA-NeXT: 改进的推理、OCR 和世界知识 中提出。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 的预训练连接器,并且仍然使用不到 1M 的视觉指令微调样本。最大的 34B 变体在约 1 天内使用 32 个 A100 完成训练。*

使用技巧
- 我们建议用户在计算批生成时使用
padding_side="left"
,因为它能带来更准确的结果。只需确保在生成前调用processor.tokenizer.padding_side = "left"
。
- Llava-Next 对图像使用不同数量的补丁,因此除了在处理输入时进行的填充之外,还必须在建模代码内部填充输入。如果模型处于
eval()
模式,默认设置为“左填充”,否则为“右填充”。
[!注意] 版本 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 将尝试推断每张图像所需的图像 token 数量,并用与 token 数量相同的<image>
占位符来扩展文本。通常每张图像大约有 500 个 token,因此请确保文本没有被截断,否则在合并嵌入时会出现故障。这些属性可以从模型配置中获取,如model.config.vision_config.patch_size
或model.config.vision_feature_select_strategy
。如果视觉骨干网络添加了 CLS token,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]"
- 如果您想自己构建聊天提示,下面是可能格式的列表。llava-v1.6-mistral-7b-hf 需要以下格式
"[INST] <image>\nWhat is shown in this image? [/INST]"
llava-v1.6-vicuna-7b-hf 和 llava-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-hf 和 llava-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)
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 正在进行中,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,
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.Optional[dict[str, int]] = None image_grid_pinpoints: typing.Optional[list] = 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_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 (
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
参数覆盖。 - do_pad (
bool
, 可选, 默认为True
) — 是否填充图像。如果为True
,则会将批次中图像的补丁维度填充到批次中最大补丁数。填充将应用于底部和右侧,并用零填充。 - do_convert_rgb (
bool
, 可选, 默认为True
) — 是否将图像转换为 RGB。
构建一个 LLaVa-NeXT 图像处理器。基于 CLIPImageProcessor,并结合了 LLaVa 论文 中解释的 用于处理高分辨率图像的附加技术。
预处理
< 来源 >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None image_grid_pinpoints: typing.Optional[list] = 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_pad: typing.Optional[bool] = 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
。 - 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 (
float
或list[float]
, 可选, 默认为self.image_mean
) — 用于归一化的图像平均值。仅当do_normalize
设置为True
时才生效。 - image_std (
float
或list[float]
, 可选, 默认为self.image_std
) — 用于归一化的图像标准差。仅当do_normalize
设置为True
时才生效。 - do_pad (
bool
, 可选, 默认为self.do_pad
) — 是否填充图像。如果设置为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) 格式。
LlavaNextImageProcessorFast
class transformers.LlavaNextImageProcessorFast
< source >( **kwargs: typing_extensions.Unpack[transformers.models.llava_next.image_processing_llava_next_fast.LlavaNextFastImageProcessorKwargs] )
构建一个快速 Llava Next 图像处理器。
预处理
< source >( 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] ) → <class 'transformers.image_processing_base.BatchFeature'>
参数
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]
) — 要预处理的图像。需要单张或批量图像,像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False
。 - do_resize (
bool
, 可选) — 是否调整图像大小。 - size (
dict[str, int]
, 可选) — 模型的最大输入尺寸。 - default_to_square (
bool
, 可选) — 如果尺寸为整数,调整大小时是否默认使用方形图像。 - resample (
Union[PILImageResampling, F.InterpolationMode, NoneType]
) — 如果调整图像大小,则使用的重采样过滤器。可以是枚举PILImageResampling
之一。仅当do_resize
设置为True
时才生效。 - do_center_crop (
bool
, 可选) — 是否对图像进行中心裁剪。 - crop_size (
dict[str, int]
, 可选) — 应用center_crop
后输出图像的尺寸。 - do_rescale (
bool
, 可选) — 是否重新缩放图像。 - rescale_factor (
Union[int, float, NoneType]
) — 如果do_rescale
设置为True
,则按此重新缩放因子对图像进行重新缩放。 - do_normalize (
bool
, 可选) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], NoneType]
) — 用于归一化的图像平均值。仅当do_normalize
设置为True
时才生效。 - image_std (
Union[float, list[float], NoneType]
) — 用于归一化的图像标准差。仅当do_normalize
设置为True
时才生效。 - do_convert_rgb (
bool
, 可选) — 是否将图像转换为 RGB。 - return_tensors (
Union[str, ~utils.generic.TensorType, NoneType]
) — 如果设置为 `pt` 则返回堆叠的张量,否则返回张量列表。 - data_format (
~image_utils.ChannelDimension
, 可选) — 仅支持ChannelDimension.FIRST
。为与慢速处理器兼容而添加。 - 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) 格式。
- device (
torch.device
, 可选) — 处理图像的设备。如果未设置,则从输入图像推断设备。 - disable_grouping (
bool
, 可选) — 是否禁用按尺寸分组图像以单独而非批量处理它们。如果为 None,则如果图像在 CPU 上,将设置为 True,否则设置为 False。此选择基于经验观察,详情见此:https://github.com/huggingface/transformers/pull/38157 - image_grid_pinpoints (
list[list[int]]
, 可选) — 用于处理高分辨率图像的可能分辨率列表。根据图像的原始尺寸选择最佳分辨率。可以通过preprocess
方法中的image_grid_pinpoints
覆盖。 - do_pad (
bool
, 可选) — 是否填充图像。如果设置为True
,将把批次中图像的补丁维度填充到批次中最大的补丁数量。填充将应用于底部和右侧,填充值为零。
返回
<class 'transformers.image_processing_base.BatchFeature'>
- data (
dict
) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。 - tensor_type (
Union[None, str, TensorType]
, 可选) — 您可以在此处提供一个`tensor_type`,以便在初始化时将整数列表转换为PyTorch/TensorFlow/Numpy张量。
LlavaNextProcessor
class transformers.LlavaNextProcessor
< source >( 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
, 可选) — 视觉编码器的补丁大小。 - vision_feature_select_strategy (
str
, 可选) — 用于从视觉骨干网选择视觉特征的特征选择策略。应与模型配置中的策略相同。 - chat_template (
str
, 可选) — 一个 Jinja 模板,用于将聊天中的消息列表转换为可标记化的字符串。 - image_token (
str
, 可选, 默认为"<image>"
) — 用于表示图像位置的特殊标记。 - num_additional_image_tokens (
int
, 可选, 默认为 0) — 添加到图像嵌入的额外标记数量,例如 CLS (+1)。如果骨干网没有 CLS 或其他额外标记,则无需设置此参数。
构建 LLaVa-NeXT 处理器,它将 LLaVa-NeXT 图像处理器和 LLaMa 分词器包装成一个单一的处理器。
LlavaNextProcessor 提供了 LlavaNextImageProcessor 和 LlamaTokenizerFast 的所有功能。有关更多信息,请参阅 __call__()
和 decode()。
此方法将其所有参数转发给 LlamaTokenizerFast 的 batch_decode()。有关更多信息,请参阅此方法的文档字符串。
此方法将其所有参数转发给 LlamaTokenizerFast 的 decode()。有关更多信息,请参阅此方法的文档字符串。
LlavaNextModel
class transformers.LlavaNextModel
< source >( config: LlavaNextConfig )
参数
- config (LlavaNextConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。请查看 from_pretrained() 方法加载模型权重。
Llava-Next 模型由一个视觉骨干和一个没有语言建模头的语言模型组成。
此模型继承自 PreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
此模型也是 PyTorch torch.nn.Module 子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档了解所有与通用用法和行为相关的事项。
forward
< source >( 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[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.llava_next.modeling_llava_next.LlavaNextModelOutputWithPast
或 tuple(torch.FloatTensor)
参数
- input_ids (形状为
(batch_size, sequence_length)
的torch.LongTensor
) — 词汇表中输入序列 token 的索引。默认情况下将忽略填充。可以使用 AutoTokenizer 获取索引。有关详细信息,请参见 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- pixel_values (形状为
(batch_size, num_channels, image_size, image_size)
的torch.FloatTensor
) — 对应于输入图像的张量。可以使用{image_processor_class}
获取像素值。有关详细信息,请参见{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
处理图像)。 - image_sizes (形状为
(batch_size, 2)
的torch.LongTensor
, 可选) — 批处理中图像的大小,每个图像为 (height, width)。 - attention_mask (形状为
(batch_size, sequence_length)
的torch.Tensor
, 可选) — 避免对填充 token 索引执行注意力操作的掩码。掩码值选择在[0, 1]
之间:- 1 表示**未被掩码**的 token,
- 0 表示**被掩码**的 token。
- position_ids (形状为
(batch_size, sequence_length)
的torch.LongTensor
, 可选) — 每个输入序列 token 在位置嵌入中的位置索引。选择范围为[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(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
(那些没有将其过去的键值状态提供给此模型的 token),而不是形状为(batch_size, sequence_length)
的所有input_ids
。 - inputs_embeds (形状为
(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对input_ids
索引如何转换为相关向量有更多的控制权,而不是模型的内部嵌入查找矩阵,这将很有用。 - vision_feature_layer (
Union[int, list[int], NoneType]
) — 选择视觉特征的层索引。如果提供了多个索引,则相应索引的视觉特征将连接起来形成视觉特征。 - 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
, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。 - cache_position (形状为
(sequence_length)
的torch.LongTensor
, 可选) — 表示输入序列 token 在序列中的位置的索引。与position_ids
不同,此张量不受填充影响。它用于在正确位置更新缓存并推断完整的序列长度。
返回
transformers.models.llava_next.modeling_llava_next.LlavaNextModelOutputWithPast
或 tuple(torch.FloatTensor)
一个 transformers.models.llava_next.modeling_llava_next.LlavaNextModelOutputWithPast
或一个 torch.FloatTensor
的元组(如果传入 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置 (LlavaNextConfig) 和输入。
-
last_hidden_state (形状为
(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
, 可选) — 模型最后一层输出的隐藏状态序列。 -
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
时返回) — 形状为(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
元组(如果模型有嵌入层,则一个用于嵌入输出,加上一个用于每个层的输出)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
-
attentions (
tuple[torch.FloatTensor, ...]
, 可选, 当output_attentions=True
传入或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, sequence_length)
的torch.FloatTensor
元组(每个层一个)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
-
image_hidden_states (
torch.FloatTensor
, 可选) — 形状为(batch_size, num_images, sequence_length, hidden_size)
的torch.FloatTensor
。由视觉编码器生成并经过最后隐藏状态投影后的模型图像隐藏状态。
LlavaNextModel forward 方法,覆盖了 __call__
特殊方法。
尽管前向传播的配方需要在此函数中定义,但在此之后应该调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。
get_image_features
< source >( pixel_values: FloatTensor image_sizes: Tensor vision_feature_layer: typing.Union[int, list[int], NoneType] = None vision_feature_select_strategy: typing.Optional[str] = None ) → image_features (listtorch.Tensor
)
参数
- pixel_values (形状为
(batch_size, num_patches, channels, height, width)
的torch.FloatTensor]
) — 对应于输入图像的张量。 - image_sizes (形状为
(num_images, 2)
的torch.Tensor
) — 每张图像的实际图像大小 (H, W)。 - vision_feature_layer (
Union[int, list[int]]
, 可选) — 选择视觉特征的层索引。如果提供了多个索引,则相应索引的视觉特征将连接起来形成视觉特征。 - vision_feature_select_strategy (
str
, 可选) — 用于从视觉骨干选择视觉特征的特征选择策略。可以是"default"
或"full"
返回
image_features (listtorch.Tensor
)
图像特征张量列表,每个张量包含所有补丁的所有视觉特征,形状为 (num_patches, image_length, embed_dim)
。
从视觉塔获取图像最后隐藏状态并应用多模态投影。
pack_image_features
< source >( image_features image_sizes vision_feature_select_strategy image_newline = None )
参数
- image_features (长度为 num_images 的
list[torch.Tensor]
,每个形状为(num_patches, image_length, embed_dim)
) — 图像特征张量列表,每个张量包含所有补丁的所有视觉特征。 - image_sizes (形状为
(num_images, 2)
的torch.Tensor
) — 每张图像的实际图像大小 (H, W)。 - vision_feature_select_strategy (
str
) — 用于从视觉骨干选择视觉特征的特征选择策略。 - image_newline (形状为
(embed_dim)
的torch.Tensor
) — 换行嵌入向量。
重塑、取消填充,然后将每个 image_feature
打包成一个包含所有视觉向量的单个 image_features
张量。
LlavaNextForConditionalGeneration
class transformers.LlavaNextForConditionalGeneration
< source >( config: LlavaNextConfig )
参数
- config (LlavaNextConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。请查看 from_pretrained() 方法加载模型权重。
LLAVA-NeXT 模型由一个视觉骨干和一个语言模型组成。
此模型继承自 PreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
此模型也是 PyTorch torch.nn.Module 子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档了解所有与通用用法和行为相关的事项。
forward
< source >( 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[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 cache_position: typing.Optional[torch.LongTensor] = None logits_to_keep: typing.Union[int, torch.Tensor] = 0 **kwargs: typing_extensions.Unpack[transformers.models.llava_next.modeling_llava_next.KwargsForCausalLM] ) → transformers.models.llava_next.modeling_llava_next.LlavaNextCausalLMOutputWithPast
或 tuple(torch.FloatTensor)
参数
- input_ids (形状为
(batch_size, sequence_length)
的torch.LongTensor
) — 词汇表中输入序列 token 的索引。默认情况下将忽略填充。可以使用 AutoTokenizer 获取索引。有关详细信息,请参见 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- pixel_values (形状为
(batch_size, num_channels, image_size, image_size)
的torch.FloatTensor
) — 对应于输入图像的张量。可以使用{image_processor_class}
获取像素值。有关详细信息,请参见{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
处理图像)。 - image_sizes (形状为
(batch_size, 2)
的torch.LongTensor
, 可选) — 批处理中图像的大小,每个图像为 (height, width)。 - attention_mask (形状为
(batch_size, sequence_length)
的torch.Tensor
, 可选) — 避免对填充 token 索引执行注意力操作的掩码。掩码值选择在[0, 1]
之间:- 1 表示**未被掩码**的 token,
- 0 表示**被掩码**的 token。
- position_ids (形状为
(batch_size, sequence_length)
的torch.LongTensor
, 可选) — 每个输入序列 token 在位置嵌入中的位置索引。选择范围为[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(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
(那些没有将其过去的键值状态提供给此模型的 token),而不是形状为(batch_size, sequence_length)
的所有input_ids
。 - inputs_embeds (形状为
(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对input_ids
索引如何转换为相关向量有更多的控制权,而不是模型的内部嵌入查找矩阵,这将很有用。 - vision_feature_layer (
Union[int, list[int], NoneType]
) — 选择视觉特征的层索引。如果提供了多个索引,则相应索引的视觉特征将连接起来形成视觉特征。 - vision_feature_select_strategy (
str
, 可选, 默认为"default"
) — 用于从视觉骨干选择视觉特征的特征选择策略。可以是"default"
或"full"
。如果为"default"
,则从视觉特征中移除 CLS token。如果为"full"
,则使用完整的视觉特征。 - labels (形状为
(batch_size, sequence_length)
的torch.LongTensor
, 可选) — 用于计算掩码语言建模损失的标签。索引应为[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
。 - cache_position (
torch.LongTensor
,形状为(sequence_length)
,可选) — 表示输入序列标记在序列中位置的索引。与position_ids
不同,此张量不受填充影响。它用于在正确位置更新缓存并推断完整的序列长度。 - logits_to_keep (
Union[int, torch.Tensor]
,默认为0
) — 如果是int
,则计算最后logits_to_keep
个标记的 logits。如果是0
,则计算所有input_ids
的 logits(特殊情况)。生成时只需要最后一个标记的 logits,仅计算该标记的 logits 可以节省内存,这对于长序列或大词汇量来说非常重要。如果是torch.Tensor
,则必须是 1D,对应于在序列长度维度中要保留的索引。这在使用 packed tensor 格式(批次和序列长度的单维度)时非常有用。
返回
transformers.models.llava_next.modeling_llava_next.LlavaNextCausalLMOutputWithPast
或 tuple(torch.FloatTensor)
一个 transformers.models.llava_next.modeling_llava_next.LlavaNextCausalLMOutputWithPast
或一个 torch.FloatTensor
元组(如果传递 return_dict=False
或当 config.return_dict=False
时),根据配置(LlavaNextConfig)和输入包含各种元素。
-
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_patches, num_images, sequence_length, hidden_size)
的torch.FloatTensor
。由视觉编码器生成并投影最后一个隐藏状态后的模型图像隐藏状态。
LlavaNextForConditionalGeneration 前向方法,覆盖 __call__
特殊方法。
尽管前向传播的配方需要在此函数中定义,但在此之后应该调用 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 (...)"