Transformers 文档

VipLlava

VipLlava

概述

VipLlava模型由Mu Cai、Haotian Liu、Siva Karthik Mustikovela、Gregory P. Meyer、Yuning Chai、Dennis Park、Yong Jae Lee在Making Large Multimodal Models Understand Arbitrary Visual Prompts中提出。

VipLlava通过标记图像并在训练过程中使用“红色边界框”或“指向箭头”等自然提示与模型交互,增强了Llava的训练协议。

论文的摘要如下:

虽然现有的视觉-语言多模态模型专注于整体图像理解,但在实现区域特定理解方面存在显著差距。当前使用文本坐标或空间编码的方法通常无法提供用户友好的视觉提示界面。为了解决这一挑战,我们引入了一种能够解码任意视觉提示的新型多模态模型。这使得用户能够直观地标记图像,并使用“红色边界框”或“指向箭头”等自然提示与模型交互。我们的简单设计直接将视觉标记覆盖在RGB图像上,消除了复杂区域编码的需求,同时在区域理解任务(如Visual7W、PointQA和视觉常识推理基准)上实现了最先进的性能。此外,我们提出了ViP-Bench,这是一个全面的基准,用于评估模型在多个维度上理解视觉提示的能力,从而推动该领域的未来研究。代码、数据和模型均已公开。

原始代码可以在这里找到。

该模型由Younes Belkada贡献

使用提示:

  • 该架构与llava架构类似,不同之处在于多模态投影器接收一组连接的视觉隐藏状态,并且在该模块上有一个额外的layernorm层。

  • 我们建议用户在计算批量生成时使用padding_side="left",因为它可以带来更准确的结果。只需确保在生成之前调用processor.tokenizer.padding_side = "left"

  • 请注意,该模型并未经过明确训练以处理同一提示中的多张图像,尽管这在技术上是可行的,但您可能会遇到不准确的结果。

[!注意] LLaVA模型在发布v4.46版本后,将会发出关于添加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将尝试推断每张图像所需的图像令牌数量,并使用尽可能多的占位符扩展文本。通常每张图像大约有500个令牌,因此请确保文本没有被截断,否则在合并嵌入时会出现失败。这些属性可以从模型配置中获取,如model.config.vision_config.patch_sizemodel.config.vision_feature_select_strategy。如果视觉骨干添加了CLS令牌,则num_additional_image_tokens应为1,如果没有向视觉补丁添加额外内容,则应为0`。

  • 为了获得更好的结果,我们建议用户使用处理器的apply_chat_template()方法来正确格式化您的提示。为此,您需要构建一个对话历史记录,传入纯字符串将无法格式化您的提示。聊天模板中的每条消息都是一个带有“role”和“content”键的字典。“content”应该是一个字典列表,用于“text”和“image”模式,如下所示:
from transformers import AutoProcessor

processor = AutoProcessor.from_pretrained("llava-hf/vip-llava-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)
>>> "###Human: <image>\nWhat’s shown in this image?###Assistant: This image shows a red stop sign.###Human: Describe the image in more details.###Assistant:"
  • 如果你想自己构建一个聊天提示,以下是VipLLaVa检查点接受的提示格式列表:
A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.###Human: <image>\n<prompt>###Assistant:

对于多轮对话:

A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.###Human: <image>\n<prompt1>###Assistant: <answer1>###Human: <prompt2>###Assistant:

VipLlavaConfig

transformers.VipLlavaConfig

< >

( vision_config = 无 text_config = 无 ignore_index = -100 image_token_index = 32000 projector_hidden_act = 'gelu' projector_layernorm_eps = 1e-05 vision_feature_layers = [-2, -5, -8, -11, 6] image_seq_length = 576 **kwargs )

参数

  • vision_config (VipLlavaVisionConfig, optional) — 自定义视觉配置或字典
  • text_config (Union[AutoConfig, dict], 可选) — 文本主干的配置对象。可以是 LlamaConfigMistralConfig 中的任意一个。
  • ignore_index (int, optional, defaults to -100) — 损失函数的忽略索引。
  • image_token_index (int, optional, defaults to 32000) — 用于编码图像提示的图像令牌索引。
  • projector_hidden_act (str, optional, defaults to "gelu") — 多模态投影器使用的激活函数。
  • projector_layernorm_eps (float, optional, 默认为 1e-05) — 投影器层归一化的层归一化 epsilon
  • vision_feature_layers (List[int], optional, defaults to [-2, -5, -8, -11, 6]) — 用于选择视觉特征的层列表。
  • image_seq_length (int, optional, defaults to 576) — 一张图片嵌入的序列长度。

这是用于存储VipLlavaForConditionalGeneration配置的配置类。它用于根据指定的参数实例化一个VipLlava模型,定义模型架构。使用默认值实例化配置将产生类似于VipLlava-9B的配置。

例如 ybelkada/vip-llava-7b-hf

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

示例:

>>> from transformers import VipLlavaForConditionalGeneration, VipLlavaConfig, CLIPVisionConfig, LlamaConfig

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

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

>>> # Initializing a VipLlava vipllava-7b style configuration
>>> configuration = VipLlavaConfig(vision_config, text_config)

>>> # Initializing a model from the vipllava-7b style configuration
>>> model = VipLlavaForConditionalGeneration(configuration)

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

VipLlavaForConditionalGeneration

transformers.VipLlavaForConditionalGeneration

< >

( config: VipLlavaConfig )

参数

  • config (VipLlavaConfigVipLlavaVisionConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化时不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。

VIPLLAVA模型由视觉骨干和语言模型组成。 该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头部等)。

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( 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_layers: typing.Optional[typing.List[int]] = 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 ) transformers.models.vipllava.modeling_vipllava.VipLlavaCausalLMOutputWithPasttuple(torch.FloatTensor)

参数

  • 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()

    什么是输入ID?

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, image_size, image_size)) -- 对应于输入图像的张量。可以使用 [AutoImageProcessor](/docs/transformers/v4.47.1/en/model_doc/auto#transformers.AutoImageProcessor) 获取像素值。有关详细信息,请参阅 [CLIPImageProcessor.__call__()](/docs/transformers/v4.47.1/en/model_doc/imagegpt#transformers.ImageGPTFeatureExtractor.__call__) ([]LlavaProcessor`] 使用 CLIPImageProcessor 处理图像)。
  • 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), optional) — 每个输入序列标记在位置嵌入中的位置索引。选择范围在 [0, config.n_positions - 1] 内。什么是位置ID?
  • past_key_values (tuple(tuple(torch.FloatTensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) — Tuple of tuple(torch.FloatTensor) of length config.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 索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • use_cache (bool, 可选) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的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 (see input_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可以节省内存,这对于长序列或大词汇量来说非常重要。

返回

transformers.models.vipllava.modeling_vipllava.VipLlavaCausalLMOutputWithPasttuple(torch.FloatTensor)

一个 transformers.models.vipllava.modeling_vipllava.VipLlavaCausalLMOutputWithPast 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(VipLlavaConfig)和输入。

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

  • logits (torch.FloatTensor 形状为 (batch_size, sequence_length, config.vocab_size)) — 语言建模头的预测分数(SoftMax 之前每个词汇令牌的分数)。

  • past_key_values (tuple(tuple(torch.FloatTensor))可选,当传递 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstuple(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。

VipLlavaForConditionalGeneration 的前向方法,重写了 __call__ 特殊方法。

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

示例:

>>> import torch
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, VipLlavaForConditionalGeneration

>>> model = VipLlavaForConditionalGeneration.from_pretrained("llava-hf/vip-llava-7b-hf", device_map="auto", torch_dtype=torch.float16)
>>> processor = AutoProcessor.from_pretrained("llava-hf/vip-llava-7b-hf")

>>> prompt = "A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.###Human: <image>\n{}###Assistant:"
>>> question = "Can you please describe this image?"
>>> prompt = prompt.format(question)
>>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/compel-neg.png"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> inputs = processor(text=text, images=image, return_tensors="pt").to(0, torch.float16)

>>> # Generate
>>> generate_ids = model.generate(**inputs, max_new_tokens=20)
>>> processor.decode(generate_ids[0][len(inputs["input_ids"][0]):], skip_special_tokens=True)
The image features a brown and white cat sitting on a green surface, with a red ball in its
< > Update on GitHub