Transformers documentation

FastVLM

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2024-12-17 在 HF papers 上发布,并于 2025-12-02 贡献至 Hugging Face Transformers。

FastVLM

FlashAttention SDPA

概述

FastVLM 是一款开源的视觉语言模型,其核心是一个名为 FastViTHD 的创新混合视觉编码器。通过采用可重参数化的卷积层、缩放后的输入分辨率以及精简的视觉 token 数量,FastVLM 在保持极高精度的同时实现了卓越的效率。其优化的架构使其能够部署在边缘设备上,在不牺牲性能的前提下实现极低的 TTFT(首 token 延迟)。

该模型由 Pavan Kumar Anasosalu Vasu、Fartash Faghri、Chun-Liang Li、Cem Koc、Nate True、Albert Antony、Gokul Santhanam、James Gabriel、Peter Grasch、Oncel Tuzel 和 Hadi Pouransari 在 FastVLM: Efficient Vision Encoding for Vision Language Models 中提出。

该论文的摘要如下:

提升输入图像的分辨率对于增强视觉语言模型(VLM)的性能至关重要,尤其是在文本丰富的图像理解任务中。然而,像 ViT 这样流行的视觉编码器在高分辨率下效率较低,因为 token 数量庞大且编码延迟较高。在不同的运行分辨率下,VLM 的视觉编码器可以沿两个维度进行优化:降低编码延迟,以及减少传递给 LLM 的视觉 token 数量,从而降低整体延迟。基于对图像分辨率、视觉延迟、token 数量和 LLM 规模之间相互作用的全面效率分析,我们提出了 FastVLM——一个在分辨率、延迟和准确性之间实现优化权衡的模型。FastVLM 集成了 FastViTHD,这是一种新颖的混合视觉编码器,旨在输出更少的 token,并显著降低高分辨率图像的编码时间。与以往方法不同,FastVLM 仅通过缩放输入图像即可在视觉 token 数量和图像分辨率之间实现最佳平衡,无需额外的 token 剪枝,从而简化了模型设计。在 LLaVA-1.5 设置中,FastVLM 在保持与先前工作相当的 VLM 基准性能的同时,将首 token 时间(TTFT)提升了 3.2 倍。与最高分辨率(1152×1152)下的 LLaVa-OneVision 相比,FastVLM 使用相同的 0.5B LLM,在 SeedBench、MMMU 和 DocVQA 等关键基准上取得了更好的性能,但 TTFT 快了 85 倍,且视觉编码器小了 3.4 倍。

该模型由 Kamila 贡献。 原始代码可在 此处 找到。

使用技巧

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

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

重要:

Hugging Face 模型默认使用 SDPA;不过,该模型的视觉骨干仅支持 eager attention,因此会自动回退到 "eager"。

如果您想在语言解码器中使用不同的注意力实现,请确保显式设置,例如:

model = FastVlmForConditionalGeneration.from_pretrained("KamilaMila/FastVLM-0.5B", attn_implementation={"text_config": "flash_attention_2"}, device_map="auto")

将其设置为整个模型,例如

model = FastVlmForConditionalGeneration.from_pretrained("KamilaMila/FastVLM-0.5B", attn_implementation="flash_attention_2", device_map="auto")

将导致错误。

使用聊天模板格式化提示

每个 checkpoint 都使用特定的提示格式进行训练,具体取决于底层的大语言模型骨干网络。为确保格式正确,请使用处理器的 apply_chat_template 方法。

重要:

  • 您必须构建对话历史——直接传入普通字符串将无法正常工作。
  • 每条消息应为一个字典,包含 "role" 和 "content" 键。
  • "content" 应为包含不同模态(如 "text" 和 "image")的字典列表。

使用示例

单输入推理

import torch

from transformers import AutoProcessor, FastVlmForConditionalGeneration


# Load the model in half-precision
model = FastVlmForConditionalGeneration.from_pretrained("KamilaMila/FastVLM-0.5B", device_map="auto")
processor = AutoProcessor.from_pretrained("KamilaMila/FastVLM-0.5B")

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.bfloat16)

# Generate
generate_ids = model.generate(**inputs, max_new_tokens=30)
processor.batch_decode(generate_ids, skip_special_tokens=True)

批量推理

FastVLM 也支持批量推理。以下是具体操作方式:

import torch

from transformers import AutoProcessor, FastVlmForConditionalGeneration


# Load the model in half-precision
model = FastVlmForConditionalGeneration.from_pretrained("KamilaMila/FastVLM-0.5B", device_map="auto")
processor = AutoProcessor.from_pretrained("KamilaMila/FastVLM-0.5B")


# 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.bfloat16)


# Generate
generate_ids = model.generate(**inputs, max_new_tokens=30)
processor.batch_decode(generate_ids, skip_special_tokens=True)

关于复现原始实现的说明

为了与原始实现的 logits 相匹配,需要使用 float32。在半精度下,由于 timm 中某些算子的实现存在细微差异,logits 之间的差异会更大。

使用 Flash Attention 2

Flash Attention 2 是上一版优化的进一步加速与优化版本,请参阅性能文档中的 Flash Attention 2 部分。

FastVlmConfig

class transformers.FastVlmConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneimage_token_index: int = 151646image_seq_length: int = 576projector_hidden_act: str = 'gelu'vision_feature_select_strategy: str = 'full'vision_feature_layer: int | list[int] = -1multimodal_projector_bias: bool = Truetie_word_embeddings: bool = False )

参数

  • vision_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 视觉骨干网络的配置对象或字典。
  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 文本骨干网络的配置对象或字典。
  • image_token_index (int,可选,默认为 151646) — 用作输入图像占位符的图像 token 索引。
  • image_seq_length (int,可选,默认为 576) — 单个图像嵌入的序列长度。
  • projector_hidden_act (str, 可选, 默认为 gelu) — 多模态投影器使用的激活函数。
  • vision_feature_select_strategy (str, 可选,默认为 full) — 用于从视觉主干网络中选择视觉特征的特征选择策略。
  • vision_feature_layer (Union[int, list[int]],可选,默认为 -1) — 用于选择视觉特征的层索引。如果提供了多个索引,则会将对应索引的视觉特征拼接起来,以形成视觉特征。
  • multimodal_projector_bias (bool,可选,默认为 True) — 是否在多模态投影器中使用偏置。
  • tie_word_embeddings (bool,可选,默认为 False) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。

这是用于存储 FastVlmModel 配置的类。它根据指定的参数实例化 Fast Vlm 模型,并定义模型架构。使用默认值实例化配置将得到与 KamilaMila/FastVLM-7B 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例:

>>> from transformers import FastVlmForConditionalGeneration, FastVlmConfig

>>> # Initializing a FastVLM-7B style configuration
>>> configuration = FastVlmConfig()

>>> # Initializing a model from the FastVLM-7B style configuration
>>> model = FastVlmForConditionalGeneration(configuration)

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

FastVlmModel

class transformers.FastVlmModel

< >

( config: FastVlmConfig )

参数

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

由视觉骨干网络和语言模型组成的 FastVlm 模型,不包含语言建模头。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonevision_feature_layer: int | list[int] | None = Nonevision_feature_select_strategy: str | None = Nonemm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → FastVlmModelOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是输入 ID?

  • pixel_values(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor,可选) — 与输入图像对应的张量。可以使用 image_processor_class 获取像素值。有关详细信息,请参阅 image_processor_class.__call__(processor_class 使用 image_processor_class 来处理图像)。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 past_key_values 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 past_key_values,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • vision_feature_layer (Union[int, list[int], NoneType], 可选) — 用于选择视觉特征的层索引。如果提供了多个索引,则会将对应索引的视觉特征拼接起来以形成视觉特征。目前仅支持 -1。
  • vision_feature_select_strategy (str, 可选) — 用于从视觉主干网络中选择视觉特征的特征选择策略。目前仅支持 “full”。
  • mm_encoder_outputs (dict[str, ~modeling_outputs.BaseModelOutputWithPooling], 可选) — 一个字典,其中键为支持的模态,值为该模态的编码输出。每个编码输出是一个元组,由 (pooler_output、可选:last_hidden_states、可选:hidden_states、可选:attentions) pooler_output,形状为 (batch_size, sequence_length, hidden_size),可选) 组成,它是编码器融合到文本嵌入中的多模态特征序列。

返回值

FastVlmModelOutputWithPast 或 tuple(torch.Tensor)

FastVlmModelOutputWithPast 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(FastVlmConfig)和输入。

FastVlmModel 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor)— 模型最后一层输出的隐藏状态序列。

    如果使用了 past_key_values,则仅输出形状为 (batch_size, 1, hidden_size) 的序列的最后一个隐藏状态。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

  • image_hidden_states (torch.Tensor,可选) — 一个尺寸为 (batch_size, num_images, sequence_length, hidden_size) 的 torch.Tensor。 由视觉编码器生成的模型 image_hidden_states,并在投影最后一个隐藏状态之后得到。

get_image_features

< >

( pixel_values: Tensorvision_feature_layer: int | list[int] | None = Nonevision_feature_select_strategy: str | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, channels, height, width)) — 与输入图像对应的张量。
  • vision_feature_layer (Union[int, list[int]], 可选) — 用于选择视觉特征的层索引。仅支持 -1。
  • vision_feature_select_strategy (str, 可选) — 用于从视觉主干网络中选择视觉特征的特征选择策略。 目前仅支持 “full”。

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(FastVlmConfig)和输入。

从视觉塔获取图像的最后隐藏状态,并应用多模态投影。

  • last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor)— 模型最后一层输出的隐藏状态序列。

  • pooler_output (torch.Tensor,形状为 (batch_size, hidden_size)) — 序列中第一个 token(分类 token)的最后一层隐藏状态,经过用于辅助预训练任务的层进一步处理后得到。例如,对于 BERT 系列模型,这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重在预训练期间通过下一句预测(分类)目标进行训练。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

get_placeholder_mask

< >

( input_ids: LongTensorinputs_embeds: Tensorimage_features: Tensor )

从 input_ids 或 inputs_embeds 中获取多模态占位符掩码,并检查占位符 token 的数量是否等于多模态特征的长度。如果长度不一致,则会引发错误。

FastVlmForConditionalGeneration

class transformers.FastVlmForConditionalGeneration

< >

( config: FastVlmConfig )

参数

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

由视觉骨干网络和语言模型组成的 FastVlm 模型。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonevision_feature_layer: int | list[int] | None = Nonevision_feature_select_strategy: str | None = Nonelabels: typing.Optional[torch.LongTensor] = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → FastVlmCausalLMOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是输入 ID?

  • pixel_values(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor,可选) — 与输入图像对应的张量。可以使用 image_processor_class 获取像素值。有关详细信息,请参阅 image_processor_class.__call__(processor_class 使用 image_processor_class 来处理图像)。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 past_key_values 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 past_key_values,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • vision_feature_layer (Union[int, list[int], NoneType], 可选) — 用于选择视觉特征的层索引。如果提供了多个索引,则会将对应索引的视觉特征拼接起来以形成视觉特征。目前仅支持 -1。
  • vision_feature_select_strategy (str, 可选) — 用于从视觉主干网络中选择视觉特征的特征选择策略。目前仅支持 “full”。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引值应在 [0, ..., config.vocab_size] 范围内,或为 -100(参见 input_ids 的文档字符串)。索引值设为 -100 的 token 将被忽略(即被掩码),损失仅针对标签位于 [0, ..., config.vocab_size] 范围内的 token 进行计算。
  • logits_to_keep (Union[int, torch.Tensor], 可选,默认为 0) — 如果为 int,则计算最后 logits_to_keep 个 token 的 logits。如果为 0,则计算所有 input_ids 的 logits(特殊情况)。生成过程只需要最后一个 token 的 logits,仅针对该 token 进行计算可以节省内存,对于长序列或大词汇量而言,这种节省相当显著。 如果为 torch.Tensor,则必须是一维张量,对应于序列长度维度中需要保留的索引。 这在使用打包张量格式(将批次和序列长度合并为单一维度)时非常有用。
  • mm_encoder_outputs (dict[str, ~modeling_outputs.BaseModelOutputWithPooling], 可选) — 一个字典,其中键为支持的模态,值为该模态的编码输出。每个编码输出是一个元组,由 (pooler_output、可选:last_hidden_states、可选:hidden_states、可选:attentions) pooler_output,形状为 (batch_size, sequence_length, hidden_size),可选) 组成,它是编码器融合到文本嵌入中的多模态特征序列。

返回值

FastVlmCausalLMOutputWithPast 或 tuple(torch.Tensor)

FastVlmCausalLMOutputWithPast 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(FastVlmConfig)和输入。

FastVlmForConditionalGeneration 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

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

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

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • hidden_states (tuple[torch.Tensor],可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple[torch.Tensor],可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

  • image_hidden_states (torch.Tensor,可选) — 一个尺寸为 (batch_size, num_images, sequence_length, hidden_size) 的 torch.Tensor。 由视觉编码器生成的模型 image_hidden_states,并在投影最后一个隐藏状态之后得到。

示例:

>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import AutoProcessor, AutoModelForImageTextToText
>>> import torch

>>> device = "cuda" if torch.cuda.is_available() else "cpu"

>>> model = AutoModelForImageTextToText.from_pretrained("KamilaMila/FastVLM-0.5B").to(device)
>>> processor = AutoProcessor.from_pretrained("KamilaMila/FastVLM-0.5B")

>>> conversation = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "What are these?"},
                {"type": "image"}
            ]
        }
    ]

>>> prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> inputs = processor(images=image, text=prompt, return_tensors="pt").to(device)

>>> # Generate
>>> generated_ids = model.generate(**inputs, max_new_tokens=15)
>>> print(processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0])
system\n You are a helpful assistant.\n user\n What are these?\n assistant\n The image depicts a traditional Chinese street...

get_image_features

< >

( pixel_values: Tensorvision_feature_layer: int | list[int] | None = Nonevision_feature_select_strategy: str | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

  • pixel_values(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor)— 对应于输入图像的张量。可以使用 image_processor_class 获取像素值。有关详细信息,请参阅 image_processor_class.__call__(processor_class 使用 image_processor_class 来处理图像)。
  • vision_feature_layer (Union[int, list[int]], 可选) — 用于选择视觉特征的层索引。如果提供了多个索引,则会将对应索引的视觉特征拼接起来,以形成视觉特征。
  • vision_feature_select_strategy (str, 可选) — 用于从视觉主干网络中选择视觉特征的特征选择策略。 可以是 "default" 或 "full" 之一。

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(FastVlmConfig)和输入。

  • last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor)— 模型最后一层输出的隐藏状态序列。

  • pooler_output (torch.Tensor,形状为 (batch_size, hidden_size)) — 序列中第一个 token(分类 token)的最后一层隐藏状态,经过用于辅助预训练任务的层进一步处理后得到。例如,对于 BERT 系列模型,这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重在预训练期间通过下一句预测(分类)目标进行训练。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

示例:

>>> from PIL import Image
>>> from transformers import AutoProcessor, FastVlmForConditionalGeneration

>>> model = FastVlmForConditionalGeneration.from_pretrained("KamilaMila/FastVLM-7B")
>>> processor = AutoProcessor.from_pretrained("KamilaMila/FastVLM-7B")

>>> messages = [
...     {
...         "role": "user", "content": [
...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
...             {"type": "text", "text": "Where is the cat standing?"},
...         ]
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     return_dict=True,
...     return_tensors="pt",
...     add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]
Update on GitHub