Transformers 文档
LLaVA-OneVision
并获得增强的文档体验
开始使用
LLaVA-OneVision
概述
LLaVA-OneVision 模型由 <Bo Li, Yuanhan Zhang, Dong Guo, Renrui Zhang, Feng Li, Hao Zhang, Kaichen Zhang, Yanwei Li, Ziwei Liu, Chunyuan Li> 在 LLaVA-OneVision: Easy Visual Task Transfer 中提出。
LLaVA-OneVision 是一个视觉-语言模型,可以生成以单张或多张图像/视频为条件的文本。该模型由 SigLIP 视觉编码器和 Qwen2 语言骨干组成。图像通过 anyres-9 技术处理,其中图像被分割成 9 个补丁,以更好地处理高分辨率图像并捕获尽可能多的细节。然而,视频被池化到每个帧总共 196 个 tokens 的序列长度,以实现更节省内存的计算。LLaVA-OneVision 提供三种尺寸:0.5B、7B 和 72B,并在基准评估中取得了显著的性能。
论文摘要如下:
我们提出了 LLaVA-OneVision,一个开放的大型多模态模型 (LMM) 系列,通过巩固我们在 LLaVA-NeXT 博客系列中对数据、模型和视觉表示的见解而开发。我们的实验结果表明,LLaVA-OneVision 是首个能够同时推动开放 LMM 在三种重要的计算机视觉场景(单图像、多图像和视频场景)中性能边界的单一模型。重要的是,LLaVAOneVision 的设计允许跨不同模态/场景的强大迁移学习,从而产生新的新兴能力。特别是,通过从图像到视频的任务迁移,证明了强大的视频理解和跨场景能力。

提示
- 我们建议用户在计算批量生成时使用
padding_side="left"
,因为它会产生更准确的结果。只需确保在生成之前调用processor.tokenizer.padding_side = "left"
即可。
- Llava-OneVision 对图像使用不同数量的补丁,因此除了处理输入时完成的填充外,还必须在建模代码内部填充输入。如果模型处于
eval()
模式,则默认设置为“左填充”,否则为“右填充”。
使用 Chat Templates 格式化提示词
每个检查点都使用特定的提示格式进行训练,具体取决于底层大型语言模型骨干。为确保格式正确,请使用 processor 的 apply_chat_template
方法。
重要提示
- 您必须构建对话历史记录——传递纯字符串将不起作用。
- 每条消息都应该是一个字典,包含
"role"
和"content"
键。 - 对于不同的模态(如
"text"
和"image"
),"content"
应该是一个字典列表。
以下是如何构建输入的示例。我们将使用 llava-onevision-qwen2-7b-si-hf 以及文本和图像的对话历史记录。每个 content 字段都必须是字典列表,如下所示:
from transformers import AutoProcessor
processor = AutoProcessor.from_pretrained("llava-hf/llava-onevision-qwen2-7b-si-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)
'<|im_start|>user\n<image>What is shown in this image?<|im_end|>\n<|im_start|>assistant\nPage showing the list of options.<|im_end|>'
🚀 奖励: 如果您使用的是 transformers>=4.49.0
,您还可以从 apply_chat_template
获取向量化输出。请参阅下面的使用示例,详细了解如何使用它。
此模型由 RaushanTurganbay 贡献。 原始代码可以在这里找到。
使用示例
单图像推理
以下是如何加载模型并在半精度 (torch.float16
) 下执行推理:
from transformers import AutoProcessor, LlavaOnevisionForConditionalGeneration
import torch
processor = AutoProcessor.from_pretrained("llava-hf/llava-onevision-qwen2-7b-ov-hf")
model = LlavaOnevisionForConditionalGeneration.from_pretrained(
"llava-hf/llava-onevision-qwen2-7b-ov-hf",
torch_dtype=torch.float16,
low_cpu_mem_usage=True,
device_map="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"
conversation = [
{
"role": "user",
"content": [
{"type": "image", "url": url},
{"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")
inputs = inputs.to("cuda:0", torch.float16)
# autoregressively complete prompt
output = model.generate(**inputs, max_new_tokens=100)
print(processor.decode(output[0], skip_special_tokens=True))
'user\n\nWhat is shown in this image?\nassistant\nThe image shows a radar chart, also known as a spider chart or a star chart, which is used to compare multiple quantitative variables. Each axis represents a different variable, and the chart is filled with'
多图像推理
LLaVA-OneVision 可以使用多张图像作为输入执行推理,其中图像可以属于同一个提示词,也可以属于不同的提示词(在批量推理中)。为此,您必须使用带有 “ov” 后缀的检查点。以下是如何操作:
import requests
from PIL import Image
import torch
from transformers import AutoProcessor, LlavaOnevisionForConditionalGeneration
# Load the model in half-precision
model = LlavaOnevisionForConditionalGeneration.from_pretrained("llava-hf/llava-onevision-qwen2-7b-ov-hf", torch_dtype=torch.float16, device_map="auto")
processor = AutoProcessor.from_pretrained("llava-hf/llava-onevision-qwen2-7b-ov-hf")
# 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", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"},
{"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", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"},
{"type": "text", "text": "What about this image? How many cats do you see?"},
],
},
]
conversation_2 = [
{
"role": "user",
"content": [
{"type": "image", "url": "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.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, clean_up_tokenization_spaces=False)
['user\n\nWhat is shown in this image?\nassistant\nThere is a red stop sign in the image.\nuser\n\nWhat about this image? How many cats do you see?\nassistant\ntwo', 'user\n\nWhat is shown in this image?\nassistant\n']
视频推理
LLaVA-OneVision 还可以使用视频作为输入执行推理,其中视频帧被视为多张图像。以下是如何操作:
from huggingface_hub import hf_hub_download
import torch
from transformers import AutoProcessor, LlavaOnevisionForConditionalGeneration
# Load the model in half-precision
model = LlavaOnevisionForConditionalGeneration.from_pretrained("llava-hf/llava-onevision-qwen2-7b-ov-hf", torch_dtype=torch.float16, device_map="auto")
processor = AutoProcessor.from_pretrained("llava-hf/llava-onevision-qwen2-7b-ov-hf")
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": "video", "path": video_path},
{"type": "text", "text": "Why is this video funny?"},
],
},
]
inputs = processor.apply_chat_template(
conversation,
num_frames=8
add_generation_prompt=True,
tokenize=True,
return_dict=True,
return_tensors="pt"
).to(model.device, torch.float16)
out = model.generate(**inputs, max_new_tokens=60)
processor.batch_decode(out, skip_special_tokens=True, clean_up_tokenization_spaces=True)
["user\n\nWhy is this video funny?\nassistant\nThe video appears to be humorous because it shows a young child, who is wearing glasses and holding a book, seemingly reading with a serious and focused expression. The child's glasses are a bit oversized for their face, which adds a comical touch, as it's a common trope to see children wearing"]
模型优化
使用 bitsandbytes 进行量化
该模型可以加载为 8 位或 4 位,从而大大降低内存需求,同时保持原始模型的性能。首先,请确保安装 bitsandbytes,pip install bitsandbytes
,并确保可以访问该库支持的 GPU/加速器。
bitsandbytes 正在重构,以支持 CUDA 以外的多个后端。目前,ROCm (AMD GPU) 和 Intel CPU 实现已经成熟,Intel XPU 正在进行中,预计 Q4/Q1 将支持 Apple Silicon。有关安装说明和最新的后端更新,请访问此链接。
我们重视您的反馈,以帮助在全面发布之前识别错误!查看这些文档以获取更多详细信息和反馈链接。
只需将上面的代码片段更改为
from transformers import LlavaOnevisionForConditionalGeneration, 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 = LlavaOnevisionForConditionalGeneration.from_pretrained(model_id, quantization_config=quantization_config, device_map="auto")
使用 Flash-Attention 2 进一步加速生成
首先确保安装了 flash-attn。关于该软件包的安装,请参考 Flash Attention 的原始仓库。只需将上面的代码片段更改为
from transformers import LlavaOnevisionForConditionalGeneration
model = LlavaOnevisionForConditionalGeneration.from_pretrained(
model_id,
torch_dtype=torch.float16,
low_cpu_mem_usage=True,
use_flash_attention_2=True
).to(0)
LlavaOnevisionConfig
class transformers.LlavaOnevisionConfig
< 源文件 >( vision_config = None text_config = None image_token_index = 151646 video_token_index = 151647 projector_hidden_act = 'gelu' vision_feature_select_strategy = 'full' vision_feature_layer = -1 vision_aspect_ratio = 'anyres_max_9' image_grid_pinpoints = None tie_word_embeddings = False multimodal_projector_bias = True **kwargs )
参数
- vision_config (
Union[AutoConfig, dict]
, 可选, 默认为SiglipVisionConfig
) — 视觉骨干网络的配置对象或字典。 - text_config (
Union[AutoConfig, dict]
, 可选, 默认为Qwen2Config
) — 文本骨干网络的配置对象或字典。 - image_token_index (
int
, 可选, 默认为 151646) — 用于编码图像提示的图像 token 索引。 - video_token_index (
int
, 可选, 默认为 151647) — 用于编码视频提示的视频 token 索引。 - projector_hidden_act (
str
, 可选, 默认为"gelu"
) — 多模态投影器使用的激活函数。 - vision_feature_select_strategy (
str
, 可选, 默认为"full"
) — 用于从视觉骨干网络中选择视觉特征的特征选择策略。可以是"default"
或"full"
之一。如果为"default"
,则从视觉特征中移除 CLS token。如果为"full"
,则使用完整的视觉特征。 - vision_feature_layer (
Union[int, List[int]]
, 可选, 默认为 -1) — 选择视觉特征的层索引。如果提供多个索引,则会将相应索引的视觉特征连接起来以形成最终的视觉特征。 - vision_aspect_ratio (
str
, 可选, 默认为"anyres_max_9"
) — 处理图像特征时使用的宽高比。默认值为 “anyres_max_9”。 - image_grid_pinpoints (
List
, 可选) — 用于处理高分辨率图像的可能分辨率列表。列表中的每个项目应为(height, width)
形式的元组或列表。 - tie_word_embeddings (
bool
, 可选, 默认为False
) — 模型输入和输出词嵌入是否应该绑定。 - multimodal_projector_bias (
bool
, 可选, 默认为True
) — 是否在多模态投影器中使用偏置。
这是用于存储 LlavaOnevisionForConditionalGeneration 配置的配置类。它用于根据指定的参数实例化 Llava-NeXT 模型,定义模型架构。使用默认值实例化配置将产生与 llava-hf/llava-onevision-qwen2-7b-ov-hf 模型类似的配置。
配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PretrainedConfig 的文档。
示例
>>> from transformers import LlavaOnevisionForConditionalGeneration, LlavaOnevisionConfig, SiglipVisionConfig, Qwen2Config
>>> # Initializing a CLIP-vision config
>>> vision_config = SiglipVisionConfig()
>>> # Initializing a Llama config
>>> text_config = Qwen2Config()
>>> # Initializing a Llava-Next llava-hf/llava-onevision-qwen2-7b-ov-hf style configuration
>>> configuration = LlavaOnevisionConfig(vision_config, text_config)
>>> # Initializing a model from the llava-hf/llava-onevision-qwen2-7b-ov-hf style configuration
>>> model = LlavaOnevisionForConditionalGeneration(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
LlavaOnevisionProcessor
class transformers.LlavaOnevisionProcessor
< 源文件 >( image_processor = None tokenizer = None video_processor = None num_image_tokens = None vision_feature_select_strategy = None chat_template = None image_token = '<image>' video_token = '<video>' **kwargs )
参数
- image_processor (
LlavaOnevisionImageProcessor
, 可选) — 图像处理器是必需的输入。 - tokenizer (
LlamaTokenizerFast
, 可选) — 分词器是必需的输入。 - video_processor (
LlavaOnevisionVideoProcessor
, 可选) — 视频处理器是必需的输入。 - num_image_tokens (
int
, 可选) — 视觉塔将返回的单个图像的图像 token 数量。 - vision_feature_select_strategy (
str
, 可选) — 用于从视觉骨干网络中选择视觉特征的特征选择策略。应与模型配置中的相同 - chat_template (
str
, 可选) — Jinja 模板,用于将聊天中的消息列表转换为可标记化的字符串。 - image_token (
str
, 可选, 默认为"<image>"
) — 用于表示图像位置的特殊 token。 - video_token (
str
, 可选, 默认为"<video>"
) — 用于表示视频位置的特殊 token。
构建一个 LLaVa-Onevision 处理器,该处理器将 LLaVa-Onevision 视频处理器、LLaVa-NeXT 图像处理器和 LLaMa 分词器封装到一个处理器中。
LlavaNextProcessor 提供了 LlavaOnevisionVideoProcessor、LlavaOnevisionImageProcessor 和 LlamaTokenizerFast 的所有功能。有关更多信息,请参阅 call(), __call__()
和 decode()。
此方法将其所有参数转发给 LlamaTokenizerFast 的 batch_decode()。有关更多信息,请参阅此方法的文档字符串。
此方法将其所有参数转发给 LlamaTokenizerFast 的 decode()。有关更多信息,请参阅此方法的文档字符串。
LlavaOnevisionImageProcessor
class transformers.LlavaOnevisionImageProcessor
< source >( do_resize: bool = True size: typing.Dict[str, int] = None image_grid_pinpoints: typing.List = None resample: Resampling = <Resampling.BICUBIC: 3> 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_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_pad (
bool
, 可选, 默认为True
) — 是否填充图像。如果为True
,则会将批次中图像的 patch 维度填充到批次中最大的 patch 数量。填充将应用于底部和右侧,并使用零填充。 - do_convert_rgb (
bool
, 可选, 默认为True
) — 是否将图像转换为 RGB 格式。
构建 LLaVa-Onevision 图像处理器。基于 SiglipImageProcessor,并结合了处理每个视频帧的功能。
get_image_patches
< source >( image: <built-in function array> grid_pinpoints size: tuple patch_size: int resample: Resampling data_format: ChannelDimension input_data_format: ChannelDimension ) → List[np.array]
参数
- image (np.array) — 要处理的输入图像。
- grid_pinpoints (List) — 可能分辨率列表的字符串表示形式。
- size (
tuple
) — 调整原始图像大小的目标尺寸。 - patch_size (
int
) — 将图像分割成的 patch 的大小。 - resample (
PILImageResampling
) — 如果调整图像大小,则使用的重采样滤波器。 - data_format (
ChannelDimension
或str
) — 输出图像的通道维度格式。 - input_data_format (
ChannelDimension
或str
) — 输入图像的通道维度格式。
返回值
List[np.array]
包含已处理图像 patch 的 NumPy 数组列表。
通过将具有可变分辨率的图像划分为 patch 来处理图像。
pad
< source >( image: ndarray padding: typing.Union[int, typing.Tuple[int, int], typing.Iterable[typing.Tuple[int, int]]] mode: PaddingMode = <PaddingMode.CONSTANT: 'constant'> constant_values: typing.Union[float, typing.Iterable[float]] = 0.0 data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None ) → np.ndarray
参数
- image (
np.ndarray
) — 要填充的图像。 - padding (
int
或Tuple[int, int]
或Iterable[Tuple[int, int]]
) — 应用于高度、宽度轴边缘的填充。可以是以下三种格式之一:((before_height, after_height), (before_width, after_width))
:每个轴的唯一填充宽度。((before, after),)
:高度和宽度使用相同的前后填充。(pad,)
或 int:是 before = after = 所有轴的填充宽度的快捷方式。
- mode (
PaddingMode
) — 要使用的填充模式。可以是以下之一:"constant"
:用常数值填充。"reflect"
:用向量的反射值填充,向量在每个轴的第一个和最后一个值上镜像反射。"replicate"
:用数组每个轴边缘上最后一个值的复制值填充。"symmetric"
:用向量的反射值填充,向量沿着数组的边缘镜像反射。
- constant_values (
float
或Iterable[float]
, 可选) — 如果mode
为"constant"
,则用于填充的值。 - data_format (
str
或ChannelDimension
, 可选) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:图像格式为 (height, width, num_channels)。如果未设置,将使用与输入图像相同的格式。
- input_data_format (
str
或ChannelDimension
, 可选) — 输入图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:图像格式为 (height, width, num_channels)。如果未设置,将使用输入图像的推断格式。
返回值
np.ndarray
填充后的图像。
使用指定的 padding
和 mode
填充 image
。填充可以在 (height
, width
) 维度或 (num_patches
) 维度中进行。在第二种情况下,如果输入是元组的可迭代对象,则为预期输入。
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_resize: bool = None size: typing.Dict[str, int] = None image_grid_pinpoints: typing.List = None resample: Resampling = 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 (
PIL.Image.Image
,np.ndarray
,torch.Tensor
,List[PIL.Image.Image]
,List[np.ndarray]
,List[torch.Tensor]
) — 要准备的图像或图像批次。每个图像可以是 PIL 图像、NumPy 数组或 PyTorch 张量。支持通道优先和通道最后的格式。 - 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_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
,则将批次中图像的 patch 维度填充到批次中最大的 patch 数量。填充将应用于底部和右侧,并使用零值。 - 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) 的图像。
LlavaOnevisionImageProcessorFast
class transformers.LlavaOnevisionImageProcessorFast
< 源代码 >( **kwargs: typing_extensions.Unpack[transformers.models.llava_onevision.image_processing_llava_onevision_fast.LlavaOnevisionFastImageProcessorKwargs] )
参数
- do_resize (
bool
, 可选, 默认为self.do_resize
) — 是否将图像的 (高度, 宽度) 尺寸调整为指定的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
) — 处理图像的设备。如果未设置,则设备从输入图像中推断。 - image_grid_pinpoints (
List[List[int]]
, 可选) — 用于处理高分辨率图像的可能分辨率列表。最佳分辨率根据图像的原始大小选择。可以通过preprocess
方法中的image_grid_pinpoints
参数覆盖。不用于处理视频。 - do_pad (
bool
, 可选) — 是否填充图像。如果为True
,则会将批次中图像的补丁维度填充到批次中最大的补丁数量。填充将应用于底部和右侧,并用零填充。
构建一个快速的 ConvNeXT 图像处理器。基于 SiglipImageProcessor,并融入了处理每个视频帧的功能。
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_onevision.image_processing_llava_onevision_fast.LlavaOnevisionFastImageProcessorKwargs] )
参数
- 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
, optional, defaults toself.do_center_crop
) — 是否对图像进行中心裁剪。 - crop_size (
Dict[str, int]
, optional, defaults toself.crop_size
) — 应用center_crop
后输出图像的尺寸。 - do_rescale (
bool
, optional, defaults toself.do_rescale
) — 是否对图像进行缩放。 - rescale_factor (
float
, optional, defaults toself.rescale_factor
) — 如果do_rescale
设置为True
,则通过此缩放因子缩放图像。 - do_normalize (
bool
, optional, defaults toself.do_normalize
) — 是否对图像进行归一化。 - image_mean (
float
或List[float]
, optional, defaults toself.image_mean
) — 用于归一化的图像均值。仅当do_normalize
设置为True
时才生效。 - image_std (
float
或List[float]
, optional, defaults toself.image_std
) — 用于归一化的图像标准差。仅当do_normalize
设置为True
时才生效。 - do_convert_rgb (
bool
, optional, defaults toself.do_convert_rgb
) — 是否将图像转换为 RGB 格式。 - return_tensors (
str
或TensorType
, optional, defaults toself.return_tensors
) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。 - data_format (
ChannelDimension
或str
, optional, defaults toself.data_format
) — 仅支持ChannelDimension.FIRST
。为了与慢速处理器兼容而添加。 - input_data_format (
ChannelDimension
或str
, optional, defaults toself.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
, optional, defaults toself.device
) — 处理图像的设备。如果未设置,则设备从输入图像推断得出。 image_grid_pinpoints (List
, optional): 用于处理高分辨率图像的可能分辨率列表。列表中的每个项目都应为(height, width)
形式的元组或列表。 do_pad (bool
, optional): 是否填充图像。如果为True
,则会将批次中图像的 patch 维度填充为批次中最大的 patch 数量。填充将应用于底部和右侧,并使用零填充。
预处理单张图像或一批图像。
LlavaOnevisionVideoProcessor
class transformers.LlavaOnevisionVideoProcessor
< source >( do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling = <Resampling.BICUBIC: 3> 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 toTrue
) — 是否将图像的 (height, width) 尺寸调整为指定的size
。可以被preprocess
方法中的do_resize
参数覆盖。 - size (
Dict[str, int]
optional, defaults to{"shortest_edge" -- 224}
): 调整大小后图像的尺寸。图像的最短边将调整为 size[“shortest_edge”],最长边调整为保持输入宽高比。可以被preprocess
方法中的size
参数覆盖。 - resample (
PILImageResampling
, optional, defaults toResampling.BICUBIC
) — 如果调整图像大小,则使用的重采样滤波器。可以被preprocess
方法中的resample
参数覆盖。 - do_rescale (
bool
, optional, defaults toTrue
) — 是否通过指定的比例rescale_factor
缩放图像。可以被preprocess
方法中的do_rescale
参数覆盖。 - rescale_factor (
int
或float
, optional, defaults to1/255
) — 如果要缩放图像,则使用的缩放因子。可以被preprocess
方法中的rescale_factor
参数覆盖。 - do_normalize (
bool
, optional, defaults toTrue
) — 是否对图像进行归一化。可以被preprocess
方法中的do_normalize
参数覆盖。 - image_mean (
float
或List[float]
, optional, defaults to[0.48145466, 0.4578275, 0.40821073]
) — 如果要归一化图像,则使用的均值。这是一个浮点数或浮点数列表,其长度是图像中通道的数量。可以被preprocess
方法中的image_mean
参数覆盖。 - image_std (
float
或List[float]
, optional, defaults to[0.26862954, 0.26130258, 0.27577711]
) — 如果要归一化图像,则使用的标准差。这是一个浮点数或浮点数列表,其长度是图像中通道的数量。可以被preprocess
方法中的image_std
参数覆盖。可以被preprocess
方法中的image_std
参数覆盖。 - do_convert_rgb (
bool
, optional, defaults toTrue
) — 是否将图像转换为 RGB 格式。
构建 LLaVa-Onevisino-Video 视频处理器。基于 SiglipImageProcessor,并结合了处理每个视频帧的功能。
preprocess
< source >( videos: 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_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 )
参数
- videos (
np.ndarray
,torch.Tensor
,List[np.ndarray]
,List[torch.Tensor]
) — 要准备的图像或视频批次。每个视频可以是 4D NumPy 数组或 PyTorch - do_resize (
bool
, 可选, 默认为self.do_resize
) — 是否调整图像大小。 - size (
Dict[str, int]
, 可选, 默认为self.size
) — 调整大小后图像的尺寸。图像的最短边将被调整为 size[“shortest_edge”],最长边将被调整以保持输入宽高比。 - resample (
int
, 可选, 默认为self.resample
) — 如果调整图像大小,则使用的重采样滤波器。这可以是枚举PILImageResampling
之一。仅在do_resize
设置为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)。
LlavaOnevisionForConditionalGeneration
class transformers.LlavaOnevisionForConditionalGeneration
< source >( config: LlavaOnevisionConfig )
参数
- config (LlavaNextConfig 或
LlavaNextVisionConfig
) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
LLaVA-Onevision 模型由视觉骨干网络和语言模型组成。此模型继承自 PreTrainedModel。查看超类文档以获取库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
此模型也是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与常规用法和行为相关的所有事项。
forward
< source >( input_ids: LongTensor = None pixel_values: FloatTensor = None image_sizes: typing.Optional[torch.LongTensor] = None pixel_values_videos: FloatTensor = None image_sizes_videos: 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 vision_aspect_ratio: 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 )
参数
- input_ids (形状为
(batch_size, sequence_length)
的torch.LongTensor
) — 词汇表中输入序列标记的索引。如果您提供填充,默认情况下将被忽略。索引可以使用 AutoTokenizer 获得。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- pixel_values (形状为 `(batch_size, num_channels, image_size, image_size)` 的
torch.FloatTensor
) — 对应于输入图像的张量。像素值可以使用 AutoImageProcessor 获得。有关详细信息,请参阅 LlavaNextImageProcessor.call()。 LlavaProcessor 使用 LlavaNextImageProcessor 处理图像。 - image_sizes (形状为
(batch_size, 2)
的torch.LongTensor
, 可选) — 批次中图像的大小,每个图像为 (高度, 宽度)。 - pixel_values_videos (形状为
(batch_size, frames, num_channels, image_size, image_size))
的torch.FloatTensor
) -- 对应于输入视频的张量。像素值可以使用 [LlavaNextVideoProcessor](/docs/transformers/v4.50.0/en/model_doc/llava_next_video#transformers.LlavaNextVideoProcessor) 获得。有关详细信息,请参阅LlavaNextVideoProcessor.__call__()
。 LlavaProcessor 使用 LlavaNextVideoProcessor 处理视频。 - image_sizes_videos (形状为
(batch_size, frames, 2)
的torch.LongTensor
, 可选) — 批次中视频的大小,每个视频帧为 (高度, 宽度)。 - attention_mask (形状为
(batch_size, sequence_length)
的torch.Tensor
, 可选) — 掩码,用于避免对填充标记索引执行注意力机制。掩码值在[0, 1]
中选择:- 1 表示标记未被掩码,
- 0 表示标记被掩码。
索引可以使用 AutoTokenizer 获得。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
如果使用
past_key_values
,则可以选择仅输入最后一个decoder_input_ids
(请参阅past_key_values
)。如果您想更改填充行为,您应该阅读
modeling_opt._prepare_decoder_attention_mask
并根据您的需要进行修改。有关默认策略的更多信息,请参阅 论文 中的图 1。- 1 表示头未被掩码,
- 0 表示头被掩码。
- 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
时返回) —tuple(tuple(torch.FloatTensor))
的元组,长度为config.n_layers
,其中每个元组包含 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"
,则使用完整的视觉特征。 - vision_aspect_ratio (
str
, *可选的*,默认为"anyres_max_9"
) — 处理图像特征时使用的宽高比。默认值为 “anyres_max_9”。 - 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 (
torch.LongTensor
,形状为(sequence_length)
,*可选*) — 描述输入序列 token 在序列中位置的索引。与position_ids
相反,此张量不受 padding 的影响。它用于在正确的位置更新缓存并推断完整的序列长度。labels (
torch.LongTensor
,形状为(batch_size, sequence_length)
,*可选的*):用于计算掩码语言建模损失的标签。索引应在[0, ..., config.vocab_size]
或 -100 之间(请参阅input_ids
文档字符串)。索引设置为-100
的 token 将被忽略(掩码),损失仅针对标签在[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 格式(批次和序列长度的单个维度)时,这很有用。
示例
>>> from PIL import Image
>>> import requests
>>> import torch
>>> from transformers import LlavaOnevisionProcessor, LlavaOnevisionForConditionalGeneration
>>> model = LlavaOnevisionForConditionalGeneration.from_pretrained("llava-hf/llava-onevision-qwen2-7b-ov-hf", torch_dtype="float16", device_map="cuda:0")
>>> processor = LlavaOnevisionProcessor.from_pretrained("llava-hf/llava-onevision-qwen2-7b-ov-hf")
>>> conversation = [
... {
... "role": "user",
... "content": [
... {"type": "text", "text": "What is shown in this image?"},
... {"type": "image"},
... ],
... },
... ]
>>> prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
>>> image_file = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> raw_image = Image.open(requests.get(image_file, stream=True).raw)
>>> inputs = processor(text=prompt, images=raw_image, return_tensors='pt').to(0, torch.float16)
>>> output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
>>> processor.batch_decode(output, skip_special_tokens=True)[0]
"user\n\nWhat is shown in this image?\nassistant\ncat"