LLaVA-OneVision
概述
LLaVA-OneVision模型由
LLaVA-OneVision 是一个视觉-语言模型,能够根据一个或多个图像/视频生成文本。该模型由 SigLIP 视觉编码器和 Qwen2 语言主干组成。图像使用 anyres-9 技术进行处理,将图像分割为 9 个补丁,以更好地处理高分辨率图像并尽可能捕捉更多细节。然而,视频被池化为每帧 196 个标记的总序列长度,以实现更高效的内存计算。LLaVA-OneVision 提供三种规模:0.5B、7B 和 72B,并在基准评估中表现出色。
论文的摘要如下:
我们推出了LLaVA-OneVision,这是一个开放的大型多模态模型(LMMs)系列,通过整合我们在LLaVA-NeXT博客系列中对数据、模型和视觉表示的见解而开发。我们的实验结果表明,LLaVA-OneVision是第一个能够在三个重要的计算机视觉场景中同时推动开放LMMs性能边界的单一模型:单图像、多图像和视频场景。重要的是,LLaVA-OneVision的设计允许在不同模态/场景之间进行强大的迁移学习,从而产生新的新兴能力。特别是,通过从图像到视频的任务迁移,展示了强大的视频理解和跨场景能力。
![drawing](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/llava-ov-acrhitecture.png)
提示:
- 我们建议用户在计算批量生成时使用
padding_side="left"
,因为它会带来更准确的结果。只需确保在生成之前调用processor.tokenizer.padding_side = "left"
。
- Llava-OneVision 对图像使用不同数量的补丁,因此除了在处理输入时进行的填充外,还必须在建模代码内部对输入进行填充。如果模型处于
eval()
模式,则默认设置为“左填充”,否则为“右填充”。
- 请注意,模型应使用特定的提示格式,这是大型语言模型(LLM)训练时所使用的。你可以使用处理器的
apply_chat_template
来正确格式化你的提示。为此,你必须构建一个对话历史,传递一个纯字符串将不会格式化你的提示。聊天模板中的每条对话历史消息都是一个带有“role”和“content”键的字典。“content”应该是一个字典列表,用于“text”和“image”模式。
我们将使用 llava-onevision-qwen2-7b-si-hf 和一段包含文本和图像的对话历史。每个内容字段必须是一个字典列表,如下所示:
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|>"
该模型由RaushanTurganbay贡献。 原始代码可以在这里找到。
使用示例
单张图像推理
以下是如何以半精度(torch.float16
)加载模型并执行推理:
from transformers import AutoProcessor, LlavaOnevisionForConditionalGeneration
import torch
from PIL import Image
import requests
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)
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(images=image, text=prompt, return_tensors="pt").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")
# 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
inputs = processor(images=[image_stop, image_cats, image_snowman], text=prompts, 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 也可以使用视频作为输入进行推理,其中视频帧被视为多张图像。以下是您可以如何操作的方法:
import av
import numpy as np
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")
def read_video_pyav(container, indices):
'''
Decode the video with PyAV decoder.
Args:
container (`av.container.input.InputContainer`): PyAV container.
indices (`List[int]`): List of frame indices to decode.
Returns:
result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
'''
frames = []
container.seek(0)
start_index = indices[0]
end_index = indices[-1]
for i, frame in enumerate(container.decode(video=0)):
if i > end_index:
break
if i >= start_index and i in indices:
frames.append(frame)
return np.stack([x.to_ndarray(format="rgb24") for x in frames])
# Load the video as an np.array, sampling uniformly 8 frames (can sample more for longer videos, up to 32 frames)
video_path = hf_hub_download(repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset")
container = av.open(video_path)
total_frames = container.streams.video[0].frames
indices = np.arange(0, total_frames, total_frames / 8).astype(int)
video = read_video_pyav(container, indices)
# For videos we have to feed a "video" type instead of "image"
conversation = [
{
"role": "user",
"content": [
{"type": "video"},
{"type": "text", "text": "Why is this video funny?"},
],
},
]
prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
inputs = processor(videos=list(video), text=prompt, return_tensors="pt").to("cuda:0", 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
类 transformers.LlavaOnevisionConfig
< source >( vision_config = 无 text_config = 无 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 = 无 tie_word_embeddings = 假 **kwargs )
参数
- vision_config (
Union[AutoConfig, dict]
, optional, defaults toSiglipVisionConfig
) — 视觉骨干的配置对象或字典。 - text_config (
Union[AutoConfig, dict]
, 可选, 默认为Qwen2Config
) — 文本主干的配置对象或字典。 - image_token_index (
int
, optional, defaults to 151646) — 用于编码图像提示的图像令牌索引。 - video_token_index (
int
, optional, 默认为 151647) — 用于编码视频提示的视频令牌索引。 - projector_hidden_act (
str
, optional, defaults to"gelu"
) — 多模态投影器使用的激活函数。 - vision_feature_select_strategy (
str
, 可选, 默认为"full"
) — 用于从视觉骨干中选择视觉特征的特征选择策略。 可以是"default"
或"full"
之一。如果选择"default"
,则从视觉特征中移除 CLS 标记。 如果选择"full"
,则使用完整的视觉特征。 - vision_feature_layer (
int
, optional, defaults to -1) — 选择视觉特征的层的索引。 - vision_aspect_ratio (
str
, 可选, 默认为"anyres_max_9"
) — 处理图像特征时使用的宽高比。默认值为“anyres_max_9”。 - image_grid_pinpoints (
List
, 可选) — 用于处理高分辨率图像的可能的解析度列表。列表中的每个项目应该是形式为(height, width)
的元组或列表。 - tie_word_embeddings (
bool
, optional, defaults toFalse
) — 模型输入和输出的词嵌入是否应该绑定。
这是用于存储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
类 transformers.LlavaOnevisionProcessor
< source >( image_processor = 无 tokenizer = 无 video_processor = 无 num_image_tokens = 无 vision_feature_select_strategy = 无 chat_template = 无 image_token = '' video_token = ' **kwargs )
参数
- image_processor (LlavaOnevisionImageProcessor, optional) — 图像处理器是一个必需的输入。
- tokenizer (LlamaTokenizerFast, optional) — 分词器是一个必需的输入。
- video_processor (LlavaOnevisionVideoProcessor, optional) — 视频处理器是一个必需的输入。
- num_image_tokens (
int
, optional) — 由视觉塔返回的每张图像的图像令牌数量。 - vision_feature_select_strategy (
str
, optional) — 用于从视觉骨干中选择视觉特征的特征选择策略。 应与模型配置中的相同 - chat_template (
str
, optional) — 一个Jinja模板,用于将聊天中的消息列表转换为可标记的字符串。 - image_token (
str
, optional, defaults to"
) — 用于表示图像位置的特殊标记。"
- video_token (
str
, optional, defaults to"
) — 用于表示视频位置的特殊标记。
构建一个LLaVa-Onevision处理器,它将LLaVa-Onevision视频处理器、LLaVa-NeXT图像处理器和LLaMa分词器封装成一个单一的处理器。
LlavaNextProcessor 提供了 LlavaOnevisionVideoProcessor、LlavaOnevisionImageProcessor 和 LlamaTokenizerFast 的所有功能。有关更多信息,请参阅 call()、__call__()
和 decode()。
此方法将其所有参数转发给LlamaTokenizerFast的batch_decode()。请参考该方法的文档字符串以获取更多信息。
此方法将其所有参数转发给LlamaTokenizerFast的decode()。请参考该方法的文档字符串以获取更多信息。
LlavaOnevisionImageProcessor
类 transformers.LlavaOnevisionImageProcessor
< source >( do_resize: bool = True size: typing.Dict[str, int] = None image_grid_pinpoints: typing.List = None resample: Resampling =
参数
- 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
,将会将批次中图像的补丁维度填充到批次中最大的补丁数量。填充将使用零值应用于图像的底部和右侧。 - do_convert_rgb (
bool
, optional, defaults toTrue
) — 是否将图像转换为RGB.
构建一个LLaVa-Onevisino-Video视频处理器。基于SiglipImageProcessor,并加入了处理每一帧视频的功能。
get_image_patches
< source >( image: <内置函数 array> grid_pinpoints size: 元组 patch_size: 整数 resample: 重采样 data_format: 通道维度 input_data_format: 通道维度 ) → 列表[np.array]
参数
- image (np.array) — 要处理的输入图像。
- grid_pinpoints (List) — 一个表示可能分辨率列表的字符串表示形式。
- size (
tuple
) — 调整原始图像的大小到指定尺寸。 - patch_size (
int
) — 将图像分割成块的大小。 - resample (
PILImageResampling
) — 如果调整图像大小,则使用的重采样过滤器。 - data_format (
ChannelDimension
orstr
) — 输出图像的通道维度格式。 - input_data_format (
ChannelDimension
或str
) — 输入图像的通道维度格式。
返回
列表[np.array]
包含处理过的图像块的NumPy数组列表。
通过将图像分割成小块来处理具有可变分辨率的图像。
pad
< source >( image: ndarray padding: typing.Union[int, typing.Tuple[int, int], typing.Iterable[typing.Tuple[int, int]]] mode: PaddingMode = np.ndarray
参数
- 图像 (
np.ndarray
) — 要填充的图像。 - padding (
int
orTuple[int, int]
orIterable[Tuple[int, int]]
) — 应用于高度和宽度边缘的填充。可以是以下三种格式之一:((before_height, after_height), (before_width, after_width))
每个轴有独特的填充宽度。((before, after),)
高度和宽度的前后填充相同。(pad,)
或 int 是所有轴的前后填充宽度相同的快捷方式。
- 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
)维度进行。在第二种情况下,期望输入一个可迭代的元组。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('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] =
参数
- images (
PIL.Image.Image
,np.ndarray
,torch.Tensor
,List[PIL.Image.Image]
,List[np.ndarray]
,List[torch.Tensor]
) — 要准备的图像或图像批次。每个图像可以是PIL图像、NumPy数组或PyTorch张量。支持通道优先和通道最后的格式。 - do_resize (
bool
, optional, defaults toself.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
, optional, defaults toself.do_rescale
) — 是否对图像进行重新缩放. - rescale_factor (
float
, 可选, 默认为self.rescale_factor
) — 如果do_rescale
设置为True
,则用于重新缩放图像的重新缩放因子。 - do_normalize (
bool
, optional, defaults toself.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)。
LlavaOnevisionVideoProcessor
类 transformers.LlavaOnevisionVideoProcessor
< source >( do_resize: 布尔值 = 真 size: 字典[str, int] = 无 resample: 重采样 = <重采样.BICUBIC: 3> do_rescale: 布尔值 = 真 rescale_factor: 联合[int, float] = 0.00392156862745098 do_normalize: 布尔值 = 真 image_mean: 联合[float, 列表[float], 无类型] = 无 image_std: 联合[float, 列表[float], 无类型] = 无 do_convert_rgb: 布尔值 = 真 **kwargs )
参数
- 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_rescale (
bool
, 可选, 默认为True
) — 是否通过指定的比例rescale_factor
重新缩放图像。可以在preprocess
方法中被do_rescale
覆盖。 - rescale_factor (
int
或float
, 可选, 默认为1/255
) — 如果重新缩放图像,则使用的缩放因子。可以在preprocess
方法中通过rescale_factor
覆盖。 - do_normalize (
bool
, optional, defaults toTrue
) — 是否对图像进行归一化。可以在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
, optional, defaults toTrue
) — 是否将图像转换为RGB。
构建一个LLaVa-Onevisino-Video视频处理器。基于SiglipImageProcessor,并加入了处理每一帧视频的功能。
预处理
< source >( videos: typing.Union[typing.List[ForwardRef('PIL.Image.Image')], ForwardRef('np.ndarray'), ForwardRef('torch.Tensor'), typing.List[ForwardRef('np.ndarray')], typing.List[ForwardRef('torch.Tensor')], typing.List[typing.List[ForwardRef('PIL.Image.Image')]], typing.List[typing.List[ForwardRef('np.ndarrray')]], typing.List[typing.List[ForwardRef('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] =
参数
- 视频 (
np.ndarray
,torch.Tensor
,List[np.ndarray]
,List[torch.Tensor]
) — 要准备的图像或视频批次。每个视频可以是一个4D NumPy数组或PyTorch - do_resize (
bool
, optional, defaults toself.do_resize
) — 是否调整图像大小。 - size (
Dict[str, int]
, 可选, 默认为self.size
) — 调整大小后图像的尺寸。图像的最短边将调整为size[“shortest_edge”],最长边将调整以保持输入的宽高比。 - resample (
int
, 可选, 默认为self.resample
) — 如果调整图像大小,则使用的重采样过滤器。这可以是枚举PILImageResampling
中的一个。只有在do_resize
设置为True
时才会生效。 - do_rescale (
bool
, optional, defaults toself.do_rescale
) — 是否对图像进行重新缩放. - rescale_factor (
float
, 可选, 默认为self.rescale_factor
) — 如果do_rescale
设置为True
,则用于重新缩放图像的重新缩放因子。 - do_normalize (
bool
, optional, defaults toself.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
, optional, defaults toself.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)。
LlavaOnevisionForConditionalGeneration
类 transformers.LlavaOnevisionForConditionalGeneration
< source >( 配置: LlavaOnevisionConfig )
参数
- config (LlavaNextConfig 或
LlavaNextVisionConfig
) — 模型配置类,包含模型的所有参数。使用配置文件初始化时,不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
LLaVA-Onevision 模型由视觉主干和语言模型组成。 该模型继承自 PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< 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.Optional[int] = 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 num_logits_to_keep: int = 0 )
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- pixel_values (
torch.FloatTensor
of shape `(batch_size, num_channels, image_size, image_size)) — 对应于输入图像的张量。可以使用 AutoImageProcessor获取像素值。详情请参见LlavaNextImageProcessor.call()。LlavaProcessor使用 LlavaNextImageProcessor来处理图像。 - image_sizes (
torch.LongTensor
of shape(batch_size, 2)
, optional) — 批次中图像的大小,每张图像的大小为(高度,宽度)。 - pixel_values_videos (
torch.FloatTensor
of shape(batch_size, frames, num_channels, image_size, image_size)) -- 对应于输入视频的张量。像素值可以使用 [LlavaNextVideoProcessor](/docs/transformers/v4.47.1/en/model_doc/llava_next_video#transformers.LlavaNextVideoProcessor) 获取。详情请参阅
LlavaNextVideoProcessor.call()`。LlavaProcessor 使用 LlavaNextVideoProcessor 来处理视频。 - image_sizes_videos (
torch.LongTensor
of shape(batch_size, frames, 2)
, optional) — 批次中视频的大小,表示视频中每一帧的(高度,宽度)。 - attention_mask (
torch.Tensor
of shape(batch_size, sequence_length)
, optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]
:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
如果使用了
past_key_values
,则可以选择性地仅输入最后一个decoder_input_ids
(参见past_key_values
)。如果你想改变填充行为,你应该阅读
modeling_opt._prepare_decoder_attention_mask
并根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。- 1 indicates the head is not masked,
- 0 indicates the head is masked.
- position_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, 可选) — 每个输入序列标记在位置嵌入中的位置索引。选择范围在[0, config.n_positions - 1]
内。什么是位置ID? - past_key_values (
tuple(tuple(torch.FloatTensor))
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) — Tuple oftuple(torch.FloatTensor)
of lengthconfig.n_layers
, with each tuple having 2 tensors of shape(batch_size, num_heads, sequence_length, embed_size_per_head)
) and 2 additional tensors of shape(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
.包含预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),这些状态可用于(参见
past_key_values
输入)以加速顺序解码。如果使用了
past_key_values
,用户可以选择只输入形状为(batch_size, 1)
的最后一个decoder_input_ids
(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)
的所有decoder_input_ids
。 - inputs_embeds (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - vision_feature_layer (
int
, optional, defaults to -2) — 选择视觉特征的层的索引。 - vision_feature_select_strategy (
str
, 可选, 默认为"default"
) — 用于从视觉骨干中选择视觉特征的特征选择策略。 可以是"default"
或"full"
。如果选择"default"
,则从视觉特征中移除 CLS 标记。 如果选择"full"
,则使用完整的视觉特征。 - vision_aspect_ratio (
str
, 可选, 默认为"anyres_max_9"
) — 处理图像特征时使用的宽高比。默认值为“anyres_max_9”。 - use_cache (
bool
, 可选) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。 - cache_position (
torch.LongTensor
of shape(sequence_length)
, optional) — 表示输入序列标记在序列中的位置的索引。与position_ids
相反, 这个张量不受填充的影响。它用于在正确的位置更新缓存并推断 完整的序列长度。 - Args —
labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional): Labels for computing the masked language modeling loss. Indices should either be in[0, ..., config.vocab_size]
or -100 (seeinput_ids
docstring). Tokens with indices set to-100
are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size]
.num_logits_to_keep (
int
, 可选): 计算最后num_logits_to_keep
个token的logits。如果为0
,则计算所有input_ids
的logits(特殊情况)。生成时只需要最后一个token的logits,仅计算该token的logits可以节省内存,这对于长序列或大词汇量来说非常重要。
示例:
>>> 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"