Transformers 文档
LLaVa
并获得增强的文档体验
开始使用
LLaVa
概述
LLaVa 是一个开源聊天机器人,通过在 GPT 生成的多模态指令跟随数据上微调 LlamA/Vicuna 训练而成。它是一个基于 transformer 架构的自回归语言模型。换句话说,它是 LLM 的多模态版本,针对聊天/指令进行了微调。
LLaVa 模型在 视觉指令调优 中提出,并在 Haotian Liu、Chunyuan Li、Yuheng Li 和 Yong Jae Lee 的 通过视觉指令调优改进基线 中得到改进。
该论文的摘要如下:
大型多模态模型 (LMM) 最近在视觉指令调优方面取得了令人鼓舞的进展。在本说明中,我们表明 LLaVA 中全连接的视觉-语言跨模态连接器非常强大且数据高效。通过对 LLaVA 进行简单修改,即使用带有 MLP 投影的 CLIP-ViT-L-336px,并添加带有简单响应格式化提示的面向学术任务的 VQA 数据,我们建立了更强大的基线,在 11 个基准测试中实现了最先进的水平。我们最终的 13B 检查点仅使用了 120 万个公开可用的数据,并在单个 8-A100 节点上约 1 天内完成了完整训练。我们希望这能使最先进的 LMM 研究更易于访问。代码和模型将公开提供

此模型由 ArthurZ 和 ybelkada 贡献。 原始代码可以在这里找到。
使用技巧
我们建议用户在计算批量生成时使用
padding_side="left"
,因为它会带来更准确的结果。只需确保在生成之前调用processor.tokenizer.padding_side = "left"
即可。请注意,该模型尚未经过明确训练以处理同一提示中的多张图像,尽管这在技术上是可行的,但您可能会遇到不准确的结果。
[!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
。
使用聊天模板格式化提示
每个 检查点 都是使用特定的提示格式训练的,具体取决于底层大型语言模型骨干。为确保格式正确,请使用处理器的 apply_chat_template
方法。
重要提示
- 您必须构建对话历史记录 - 传递纯字符串将不起作用。
- 每条消息都应是一个字典,其中包含
"role"
和"content"
键。 "content"
应该是一个字典列表,用于不同的模态,如"text"
和"image"
。
以下是如何构建输入的示例。我们将使用 llava-hf/llava-1.5-7b-hf 和文本和图像的对话历史记录。每个内容字段都必须是字典列表,如下所示
from transformers import AutoProcessor
processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-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)
>>> "USER: <image>\n<What’s shown in this image? ASSISTANT: This image shows a red stop sign.</s>USER: Describe the image in more details. ASSISTANT:"
- 如果您想自己构建聊天提示,以下是每个 llava 检查点接受的提示格式列表
llava-interleave 模型 需要以下格式
"<|im_start|>user <image>\nWhat is shown in this image?<|im_end|><|im_start|>assistant"
用于多轮对话
"<|im_start|>user <image>\n<prompt1><|im_end|><|im_start|>assistant <answer1><|im_end|><|im_start|>user <image>\n<prompt1><|im_end|><|im_start|>assistant "
llava-1.5 模型 需要以下格式
"USER: <image>\n<prompt> ASSISTANT:"
用于多轮对话
"USER: <image>\n<prompt1> ASSISTANT: <answer1></s>USER: <prompt2> ASSISTANT: <answer2></s>USER: <prompt3> ASSISTANT:"
🚀 奖励: 如果您使用的是 transformers>=4.49.0
,您还可以从 apply_chat_template
获取矢量化输出。 有关如何使用它的更多详细信息,请参阅下面的 使用示例。
使用示例
单输入推理
import torch
from transformers import AutoProcessor, LlavaForConditionalGeneration
# Load the model in half-precision
model = LlavaForConditionalGeneration.from_pretrained("llava-hf/llava-1.5-7b-hf", torch_dtype=torch.float16, device_map="auto")
processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")
conversation = [
{
"role": "user",
"content": [
{"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"},
{"type": "text", "text": "What is shown in this image?"},
],
},
]
inputs = processor.apply_chat_template(
conversation,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
return_tensors="pt"
).to(model.device, torch.float16)
# Generate
generate_ids = model.generate(**inputs, max_new_tokens=30)
processor.batch_decode(generate_ids, skip_special_tokens=True)
批量推理
LLaVa 也支持批量推理。以下是如何操作的方法
import torch
from transformers import AutoProcessor, LlavaForConditionalGeneration
# Load the model in half-precision
model = LlavaForConditionalGeneration.from_pretrained("llava-hf/llava-1.5-7b-hf", torch_dtype=torch.float16, device_map="auto")
processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")
# Prepare a batch of two prompts
conversation_1 = [
{
"role": "user",
"content": [
{"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"},
{"type": "text", "text": "What is shown in this image?"},
],
},
]
conversation_2 = [
{
"role": "user",
"content": [
{"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"},
{"type": "text", "text": "What is shown in this image?"},
],
},
]
inputs = processor.apply_chat_template(
[conversation_1, conversation_2],
add_generation_prompt=True,
tokenize=True,
return_dict=True,
padding=True,
return_tensors="pt"
).to(model.device, torch.float16)
# Generate
generate_ids = model.generate(**inputs, max_new_tokens=30)
processor.batch_decode(generate_ids, skip_special_tokens=True)
关于复现原始实现的注意事项
为了匹配 原始实现 的 logits,需要在实例化 LLavaImageProcessor
时额外指定 do_pad=True
from transformers import LLavaImageProcessor
image_processor = LLavaImageProcessor.from_pretrained("https://huggingface.co/llava-hf/llava-1.5-7b-hf", do_pad=True)
使用 Flash Attention 2
Flash Attention 2 是先前优化的更快、更优化的版本,请参阅性能文档的 Flash Attention 2 部分。
资源
Hugging Face 官方和社区(🌎 表示)资源的列表,可帮助您开始使用 BEiT。
- 关于如何在免费层 Google colab 实例上利用 4 位推理运行 Llava 的 Google Colab 演示。
- 一个 类似的 notebook,展示了批量推理。 🌎
LlavaConfig
class transformers.LlavaConfig
< source >( vision_config = None text_config = None image_token_index = 32000 projector_hidden_act = 'gelu' vision_feature_select_strategy = 'default' vision_feature_layer = -2 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"
之一。 - vision_feature_layer (
Union[int, List[int]]
, 可选, 默认为 -2) — 用于选择视觉特征的层索引。 如果提供多个索引,则会将相应索引的视觉特征连接起来以形成视觉特征。 - image_seq_length (
int
, 可选, 默认为 576) — 单个图像嵌入的序列长度。 - multimodal_projector_bias (
bool
, 可选, 默认为True
) — 是否在多模态投影器中使用偏置。
这是用于存储 LlavaForConditionalGeneration 配置的配置类。 它用于根据指定的参数实例化 Llava 模型,定义模型架构。 使用默认值实例化配置将产生与 Llava-9B 类似的配置。
配置对象继承自 PretrainedConfig,可用于控制模型输出。 有关更多信息,请阅读 PretrainedConfig 的文档。
示例
>>> from transformers import LlavaForConditionalGeneration, LlavaConfig, CLIPVisionConfig, LlamaConfig
>>> # Initializing a CLIP-vision config
>>> vision_config = CLIPVisionConfig()
>>> # Initializing a Llama config
>>> text_config = LlamaConfig()
>>> # Initializing a Llava llava-1.5-7b style configuration
>>> configuration = LlavaConfig(vision_config, text_config)
>>> # Initializing a model from the llava-1.5-7b style configuration
>>> model = LlavaForConditionalGeneration(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
LlavaImageProcessor
class transformers.LlavaImageProcessor
< source >( do_pad: bool = False 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 )
参数
- do_pad (
bool
, 可选, 默认为False
) — 是否根据最长边将图像填充为正方形。 填充值由image_mean
参数确定。 可以被preprocess
方法中的do_pad
重写。 - 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 格式。
构建 LLaVa 图像处理器。
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_pad: bool = None do_resize: typing.Optional[bool] = None size: typing.Optional[typing.Dict[str, int]] = None resample: typing.Optional[PIL.Image.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, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None do_convert_rgb: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Optional[transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None **kwargs )
参数
- images (
ImageInput
) — 要预处理的图像。 期望单个或批量的图像,像素值范围为 0 到 255。 如果传入像素值在 0 到 1 之间的图像,请设置do_rescale=False
。 - do_pad (
bool
, 可选, 默认为self.do_pad
) — 是否根据最长边将图像填充为正方形。 填充值由image_mean
参数确定。 - 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)。
预处理图像或图像批次。
LlavaImageProcessorFast
class transformers.LlavaImageProcessorFast
< source >( **kwargs: typing_extensions.Unpack[transformers.models.llava.image_processing_llava_fast.LlavaFastImageProcessorKwargs] )
参数
- 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
重新缩放图像。可以被preprocess
方法中的do_rescale
参数覆盖。 - rescale_factor (
int
或float
, 可选, 默认为self.rescale_factor
) — 如果重新缩放图像,则使用的比例因子。仅在do_rescale
设置为True
时有效。可以被preprocess
方法中的rescale_factor
参数覆盖。 - do_normalize (
bool
, 可选, 默认为self.do_normalize
) — 是否对图像进行归一化。可以被preprocess
方法中的do_normalize
参数覆盖。可以被preprocess
方法中的do_normalize
参数覆盖。 - image_mean (
float
或List[float]
, 可选, 默认为self.image_mean
) — 如果归一化图像,则使用的均值。这是一个浮点数或浮点数列表,其长度与图像中的通道数相同。可以被preprocess
方法中的image_mean
参数覆盖。可以被preprocess
方法中的image_mean
参数覆盖。 - image_std (
float
或List[float]
, 可选, 默认为self.image_std
) — 如果归一化图像,则使用的标准差。这是一个浮点数或浮点数列表,其长度与图像中的通道数相同。可以被preprocess
方法中的image_std
参数覆盖。可以被preprocess
方法中的image_std
参数覆盖。 - do_convert_rgb (
bool
, 可选, 默认为self.do_convert_rgb
) — 是否将图像转换为 RGB 格式。 - return_tensors (
str
或TensorType
, 可选, 默认为self.return_tensors
) — 如果设置为 `pt`,则返回堆叠张量,否则返回张量列表。 - data_format (
ChannelDimension
或str
, 可选, 默认为self.data_format
) — 仅支持ChannelDimension.FIRST
。为与慢速处理器兼容而添加。 - input_data_format (
ChannelDimension
或str
, 可选, 默认为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
) — 处理图像的设备。如果未设置,则设备从输入图像推断。 - do_pad (
bool
, 可选, 默认为self.do_pad
) — 是否基于最长边将图像填充为正方形。可以被do_pad
参数覆盖
构建快速 Llava 图像处理器。
preprocess
< 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.image_processing_llava_fast.LlavaFastImageProcessorKwargs] )
参数
- images (
ImageInput
) — 要预处理的图像。 接受单个或批量的图像,像素值范围为 0 到 255。如果传入的图像像素值介于 0 和 1 之间,请设置do_rescale=False
。 - do_resize (
bool
, 可选, 默认为self.do_resize
) — 是否调整图像大小。 - size (
Dict[str, int]
, 可选, 默认为self.size
) — 描述模型的最大输入尺寸。 - resample (
PILImageResampling
或InterpolationMode
, 可选, 默认为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 (
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
, 可选, 默认为self.return_tensors
) — 如果设置为 `pt`,则返回堆叠张量,否则返回张量列表。 - data_format (
ChannelDimension
或str
, 可选, 默认为self.data_format
) — 仅支持ChannelDimension.FIRST
。为了与慢速处理器兼容而添加。 - input_data_format (
ChannelDimension
或str
, 可选, 默认为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
) — 处理图像的设备。如果未设置,则设备从输入图像推断。 do_pad (bool
, 可选, 默认为self.do_pad
): 是否基于最长边将图像填充为正方形。可以被do_pad
参数覆盖
预处理图像或图像批次。
LlavaProcessor
class transformers.LlavaProcessor
< 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 (LlavaImageProcessor, 可选) — 图像处理器是必需的输入。
- 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) — 添加到图像嵌入的其他 token 数量,例如 CLS (+1)。如果 backbone 没有 CLS 或其他附加的额外 token,则无需设置此参数。
构建一个 LLaVa processor,它将 LLaVa 图像 processor 和 LLaMa tokenizer 封装到一个单独的 processor 中。
LlavaProcessor 提供了 LlavaImageProcessor 和 LlamaTokenizerFast 的所有功能。 有关更多信息,请参阅 __call__()
和 decode()。
此方法将其所有参数转发到 LlamaTokenizerFast 的 batch_decode()。 有关更多信息,请参阅此方法的文档字符串。
此方法将其所有参数转发到 LlamaTokenizerFast 的 decode()。 有关更多信息,请参阅此方法的文档字符串。
LlavaForConditionalGeneration
class transformers.LlavaForConditionalGeneration
< source >( config: LlavaConfig )
参数
- config (LlavaConfig 或
LlavaVisionConfig
) — 带有模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型关联的权重,仅加载配置。 查看 from_pretrained() 方法加载模型权重。
LLAVA 模型由视觉 backbone 和语言模型组成。 此模型继承自 PreTrainedModel。 查看超类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝 head 等)。
此模型也是 PyTorch torch.nn.Module 子类。 将其用作常规 PyTorch 模块,并参阅 PyTorch 文档,了解与常规用法和行为相关的所有事项。
forward
< source >( input_ids: LongTensor = None pixel_values: 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 image_sizes: Tensor = None **lm_kwargs ) → transformers.models.llava.modeling_llava.LlavaCausalLMOutputWithPast
或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
,形状为(batch_size, sequence_length)
) — 词汇表中输入序列 token 的索引。 如果您提供 padding,默认情况下 padding 将被忽略。索引可以使用 AutoTokenizer 获取。 有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- pixel_values (
torch.FloatTensor
,形状为(batch_size, num_channels, image_size, image_size)
) -- 对应于输入图像的 tensor。 像素值可以使用 [AutoImageProcessor](/docs/transformers/v4.50.0/en/model_doc/auto#transformers.AutoImageProcessor) 获取。 有关详细信息,请参阅 [CLIPImageProcessor.__call__()](/docs/transformers/v4.50.0/en/model_doc/vilt#transformers.ViltFeatureExtractor.__call__) (`LlavaProcessor` 使用 CLIPImageProcessor 处理图像)。 - attention_mask (
torch.Tensor
,形状为(batch_size, sequence_length)
, 可选) — 用于避免在 padding token 索引上执行 attention 的 Mask。 Mask 值在[0, 1]
中选择:- 1 表示 token 未被 mask,
- 0 表示 token 已被 mask。
索引可以使用 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))
,其中每个 tuple 都有 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
的 tensor 和 2 个形状为(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
的附加 tensor。包含预先计算的 hidden-state(self-attention 块和 cross-attention 块中的 key 和 value),可以用于(请参阅
past_key_values
输入)加速顺序解码。如果使用
past_key_values
,则用户可以选择仅输入最后的decoder_input_ids
(那些没有将其过去的 key value 状态提供给此模型的),形状为(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"
之一。 - use_cache (
bool
, 可选) — 如果设置为True
,则返回past_key_values
键值状态,并且可以用于加速解码(请参阅past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有 attention 层的 attention tensor。 有关更多详细信息,请参见返回的 tensor 下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的 hidden state。 有关更多详细信息,请参见返回的 tensor 下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是纯 tuple。 - cache_position (
torch.LongTensor
,形状为(sequence_length)
, 可选) — 索引,描述输入序列 token 在序列中的位置。 与position_ids
相反,此 tensor 不受 padding 的影响。 它用于在正确的位置更新缓存并推断完整的序列长度。 - labels (
torch.LongTensor
,形状为(batch_size, sequence_length)
, 可选) — 用于计算 masked language modeling loss 的标签。 索引应为[0, ..., config.vocab_size]
或 -100(请参阅input_ids
文档字符串)。 索引设置为-100
的 token 将被忽略(masked),loss 仅针对标签在[0, ..., config.vocab_size]
中的 token 计算。 - logits_to_keep (
int
或torch.Tensor
, 可选) — 如果是int
,则计算最后logits_to_keep
个 token 的 logits。 如果是0
,则计算所有input_ids
的 logits(特殊情况)。 只需要最后一个 token 的 logits 用于生成,并且仅针对该 token 计算可以节省内存,这对于长序列或大型词汇表大小而言变得非常重要。 如果是torch.Tensor
,则必须是与序列长度维度中要保留的索引相对应的 1D 张量。 这在使用 packed tensor 格式(批次和序列长度的单维度)时很有用。
返回
transformers.models.llava.modeling_llava.LlavaCausalLMOutputWithPast
或 tuple(torch.FloatTensor)
一个 transformers.models.llava.modeling_llava.LlavaCausalLMOutputWithPast
或一个 torch.FloatTensor
元组 (如果传递了 return_dict=False
或当 config.return_dict=False
时),其中包含各种元素,具体取决于配置 (LlavaConfig) 和输入。
-
loss (
torch.FloatTensor
,形状为(1,)
,可选,当提供labels
时返回) — 语言建模损失(用于下一个 token 预测)。 -
logits (
torch.FloatTensor
,形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。 -
past_key_values (
tuple(tuple(torch.FloatTensor))
,可选,当传递了use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(torch.FloatTensor)
元组,每个元组有 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
的张量)包含预先计算的隐藏状态(自注意力模块中的键和值),可以用于(参见
past_key_values
输入)加速顺序解码。 -
hidden_states (
tuple(torch.FloatTensor)
,可选,当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
元组(如果模型具有嵌入层,则为嵌入层输出 + 每层输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出以及可选的初始嵌入输出处的隐藏状态。
-
attentions (
tuple(torch.FloatTensor)
,可选,当传递了output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 之后的注意力权重,用于计算自注意力头中的加权平均值。
-
image_hidden_states (
torch.FloatTensor
, 可选) — 大小为 (batch_size, num_images, sequence_length, hidden_size)` 的torch.FloatTensor
。 视觉编码器生成并在投影最后一个隐藏状态之后的模型的 image_hidden_states。
LlavaForConditionalGeneration forward 方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数内定义,但应该在之后调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, LlavaForConditionalGeneration
>>> model = LlavaForConditionalGeneration.from_pretrained("llava-hf/llava-1.5-7b-hf")
>>> processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")
>>> prompt = "USER: <image>\nWhat's the content of the image? ASSISTANT:"
>>> 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_new_tokens=15)
>>> 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 features a busy city street with a stop sign prominently displayed"