# LFM2-VL

## 概述

[LFM2-VL](https://www.liquid.ai/blog/lfm2-vl-efficient-vision-language-models) 是 [Liquid AI](https://liquid.ai/) 推出的首个视觉-语言基础模型系列。这些多模态模型专为低延迟和设备感知部署而设计。LFM2-VL 将 LFM2 系列开放权重 Liquid Foundation Models (LFMs) 扩展至视觉-语言领域，支持可变分辨率的文本和图像输入。

## 架构

LFM2-VL 由三个主要组件构成：语言模型主干、视觉编码器以及多模态投影器。LFM2-VL 基于 LFM2 主干构建，继承自 LFM2-1.2B（用于 LFM2-VL-1.6B）或 LFM2-350M（用于 LFM2-VL-450M）。在视觉塔方面，LFM2-VL 使用 SigLIP2 NaFlex 编码器将输入图像转换为 token 序列。实现了两种变体：

* 针对 LFM2-VL-1.6B 进行形状优化（400M），以实现更细粒度的视觉能力
* Base (86M) 用于 LFM2-VL-450M 的快速图像处理

编码器以原生分辨率处理图像，最大支持 512×512 像素，能够高效处理较小的图像而无需放大，并支持非标准宽高比而不产生失真。较大的图像会被分割为互不重叠的 512×512 方形块，以保留细节。在 LFM2-VL-1.6B 中，模型还会接收一张缩略图（原始图像的小型下采样版本，用于捕捉整体场景），以增强对全局上下文的理解和对齐。特殊标记用于指示每个图像块的位置以及缩略图的起始位置。多模态连接器是一个 2 层 MLP 连接器，采用像素反交错（pixel unshuffle）来减少图像标记的数量。

## 示例

以下示例展示了如何使用 `AutoModelForImageTextToText` 类生成答案。

```python
from transformers import AutoModelForImageTextToText, AutoProcessor

\
# Load model and processor
model_id = "LiquidAI/LFM2-VL-1.6B"
model = AutoModelForImageTextToText.from_pretrained(
    model_id,
    device_map="auto",
    dtype="bfloat16",
)
processor = AutoProcessor.from_pretrained(model_id)

# Load image and create conversation
conversation = [
    {
        "role": "user",
        "content": [
            {"type": "image", "image": "https://www.ilankelman.org/stopsigns/australia.jpg"},
            {"type": "text", "text": "What is in this image?"},
        ],
    },
]

# Generate answer
inputs = processor.apply_chat_template(
    conversation,
    add_generation_prompt=True,
    return_tensors="pt",
    return_dict=True,
    tokenize=True,
).to(model.device)

outputs = model.generate(**inputs, max_new_tokens=64)
processor.batch_decode(outputs, skip_special_tokens=True)[0]
```

## Lfm2VlImageProcessor[[transformers.Lfm2VlImageProcessor]]

#### transformers.Lfm2VlImageProcessor[[transformers.Lfm2VlImageProcessor]]

```python
transformers.Lfm2VlImageProcessor(**kwargs: *<class 'transformers.models.lfm2_vl.image_processing_lfm2_vl.Lfm2VlImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/lfm2_vl/image_processing_lfm2_vl.py#L218)

**参数：**

do_convert_rgb (`bool`, *kwargs*, *可选*) : 是否将图像转换为 RGB。

do_resize (`bool`, *kwargs*, *可选*, 默认为 `True`) : 是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'height' : 512, 'width': 512}`)：描述输入到模型的最大尺寸。

default_to_square (`bool`，*kwargs*，*可选*，默认为 `True`)：当 size 为整数时，是否在调整大小时默认使用正方形图像。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 应用 `center_crop` 后输出图像的尺寸。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*，默认为 `2`) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

do_rescale (`bool`, *kwargs*, *可选*，默认为 `True`)：是否对图像进行重新缩放。

rescale_factor (`float`, *kwargs*, *可选*，默认为 `0.00392156862745098`) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行缩放的缩放因子。

do_normalize (`bool`，*kwargs*，*可选*，默认为 `True`)：是否对图像进行归一化。

image_mean (`Union[float, list[float], tuple[float, ...]]`，*kwargs*，*可选*，默认为 `[0.5, 0.5, 0.5]`)：用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.5, 0.5, 0.5]`) : 用于归一化的图像标准差。仅当 `do_normalize` 设置为 `True` 时生效。

do_pad (`bool`, *kwargs*，默认为 `True`) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 用于将图像填充到的尺寸，格式为 `{"height": int, "width" int}`。该尺寸必须大于预处理中提供的任何图像尺寸。如果未提供 `pad_size`，图像将被填充到批次中最大的高度和宽度。仅在 `do_pad=True.` 时应用。

do_center_crop (`bool`, *kwargs*, *可选*) : 是否对图像进行居中裁剪。

data_format (`Union[str, ~image_utils.ChannelDimension]`，*kwargs*，*可选*)：仅支持 `ChannelDimension.FIRST`。为兼容旧版处理器而添加。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *可选*) : 输入图像的通道维度格式。如果未设置，则从输入图像中推断通道维度格式。可以是以下之一： - `"channels_first"` 或 `ChannelDimension.FIRST`：图像为 (num_channels, height, width) 格式。 - `"channels_last"` 或 `ChannelDimension.LAST`：图像为 (height, width, num_channels) 格式。 - `"none"` 或 `ChannelDimension.NONE`：图像为 (height, width) 格式。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*)：用于处理视频的设备。如果未设置，则从输入视频中推断设备。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

downsample_factor (`int`, *kwargs*, *可选*，默认为 `2`) : 调整图像大小时使用的图像下采样因子。

do_image_splitting (`bool`, *kwargs*, *optional*, 默认为 `True`) : 是否将大图像分割为较小的图块网格。启用后，超出最大 token 限制的图像将根据 `min_tiles` 和 `max_tiles` 约束被划分为多个图块。

min_tiles (`int`, *kwargs*, *可选*，默认为 `2`) : 将图像分割为网格时使用的最小瓦片数量（宽 × 高）。网格配置的选择旨在保持原始宽高比，同时保持在 `min_tiles` 和 `max_tiles` 范围内。

max_tiles (`int`, *kwargs*, *可选*，默认为 `10`) : 将图像分割为网格时使用的最大瓦片数（宽 × 高）。网格配置的选择旨在保持原始宽高比，同时保持在 `min_tiles` 和 `max_tiles` 范围内。

use_thumbnail (`bool`, *kwargs*, *可选*，默认为 `True`) : 在将图像分割为瓦片时，是否包含图像的缩略图版本。该缩略图提供整个图像的低分辨率概览，并在网格包含多个瓦片时作为额外的补丁添加。

min_image_tokens (`int`, *kwargs*, *可选*，默认为 `64`)：为图像生成的最小图像 token（patch）数量。小于此阈值的图像将被放大，以满足最小 token 要求。

max_image_tokens (`int`, *kwargs*, *可选*，默认值为 `256`)：单张图像允许的最大图像 token（patch）数量。超过此限制的图像将被拆分为多个图块或相应地缩小。

encoder_patch_size (`int`, *kwargs*, *可选*，默认为 `16`) : 视觉编码器使用的 patch 大小。图像将被划分为该大小的 patch，且高度和宽度都必须能被该值整除（在考虑下采样因子之后）。

tile_size (`int`, *kwargs*, *可选*，默认为 `512`) : 将大图像分割为网格时，每个图块的大小。每个图块在处理为补丁之前，都会被调整为此尺寸。

max_pixels_tolerance (`float`, *kwargs*, *可选*，默认为 `2.0`) : 用于判断图像是否过大的容差因子。如果图像的像素数超过 `max_image_tokens * encoder_patch_size^2 * downsample_factor^2 * max_pixels_tolerance`，则视为过大。

return_row_col_info (`bool`, *kwargs*, *可选*，默认为 `False`) : 是否返回批次中每张图片的行和列信息。启用后，输出将包含 `image_rows`、`image_cols` 和 `image_sizes` 字段，指示处理后图像的网格布局和尺寸。

构建一个 Lfm2VlImageProcessor 图像处理器。

#### preprocess[[transformers.Lfm2VlImageProcessor.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], *args, image_like_kwargs: dict[str, typing.Any] | None = None, **kwargs: *<class 'transformers.processing_utils.ImagesKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/image_processing_utils.py#L382)

**参数：**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`) : 要预处理的图像。期望输入单张或一批像素值在 0 到 255 之间的图像。如果传入的图像像素值在 0 到 1 之间，请设置 `do_rescale=False`。

image_like_kwargs (`dict[str, Any]`，*可选*)：用于额外图像类输入的开发者标志，这些输入也将被预处理。仅在以关键字参数传递输入不起作用时使用此标志。例如，`preprocess(images, masks=masks)` 是首选方式，但对于某些模型会导致参数优先级问题。在这种情况下，可以改用 `preprocess(images, image_like_inputs={"masks": masks})`。

do_convert_rgb (`bool`, *kwargs*, *可选*) : 是否将图像转换为 RGB。

do_resize (`bool`，*kwargs*，*可选*)：是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*)：描述模型的最大输入维度。

default_to_square (`bool`, *kwargs*, *可选*) : 当 size 为 int 时，是否在调整大小时默认使用正方形图像。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 应用 `center_crop` 后输出图像的尺寸。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

do_rescale (`bool`, *kwargs*, *可选*) : 是否对图像进行重新缩放。

rescale_factor (`float`, *kwargs*, *可选*) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行缩放的缩放因子。

do_normalize (`bool`, *kwargs*, *可选*) : 是否对图像进行归一化。

image_mean (`Union[float, list[float], tuple[float, ...]]`，*kwargs*，*可选*)：用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*) : 用于归一化的图像标准差。仅当 `do_normalize` 设置为 `True` 时生效。

do_pad (`bool`, *kwargs*, *可选*) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 用于将图像填充到的尺寸，格式为 `{"height": int, "width" int}`。该尺寸必须大于预处理中提供的任何图像尺寸。如果未提供 `pad_size`，图像将被填充到批次中最大的高度和宽度。仅在 `do_pad=True.` 时应用。

do_center_crop (`bool`, *kwargs*, *可选*) : 是否对图像进行居中裁剪。

data_format (`Union[str, ~image_utils.ChannelDimension]`，*kwargs*，*可选*)：仅支持 `ChannelDimension.FIRST`。为兼容旧版处理器而添加。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *可选*) : 输入图像的通道维度格式。如果未设置，则从输入图像中推断通道维度格式。可以是以下之一： - `"channels_first"` 或 `ChannelDimension.FIRST`：图像为 (num_channels, height, width) 格式。 - `"channels_last"` 或 `ChannelDimension.LAST`：图像为 (height, width, num_channels) 格式。 - `"none"` 或 `ChannelDimension.NONE`：图像为 (height, width) 格式。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*)：用于处理视频的设备。如果未设置，则从输入视频中推断设备。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

**返回：** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- 由 __call__ 方法返回的列表/数组/张量字典（例如 'pixel_values'）。
- **tensor_type** (`Union[None, str, TensorType]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

预处理一张图像或一批图像。

## Lfm2VlProcessor[[transformers.Lfm2VlProcessor]]

#### transformers.Lfm2VlProcessor[[transformers.Lfm2VlProcessor]]

```python
transformers.Lfm2VlProcessor(image_processor, tokenizer, chat_template: str | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/lfm2_vl/processing_lfm2_vl.py#L57)

**参数：**

image_processor (`Lfm2VlImageProcessor`)：图像处理器是必需的输入。

tokenizer (`tokenizer_class`)：分词器是必需的输入。

chat_template (`str`, *可选*) : 用于将聊天中的消息列表转换为可分词字符串的 Jinja 模板。

构建一个 Lfm2VlProcessor，它将图像处理器和分词器封装为单一处理器。

[Lfm2VlProcessor](/docs/transformers/v5.23.0/zh/model_doc/lfm2_vl#transformers.Lfm2VlProcessor) 提供了 [Lfm2VlImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/lfm2_vl#transformers.Lfm2VlImageProcessor) 和 `tokenizer_class` 的所有功能。有关更多信息，请参阅 [~Lfm2VlImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/lfm2_vl#transformers.Lfm2VlImageProcessor) 和 `~tokenizer_class`。

#### __调用__[[transformers.Lfm2VlProcessor.__call__]]

```python
__call__(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, text: str | list[str] | list[list[str]] | None = None, **kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/lfm2_vl/processing_lfm2_vl.py#L86)

**参数：**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`, *可选*) : 要预处理的图像。期望输入单张图像或一批图像，其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间，请设置 `do_rescale=False`。

text (`Union[str, list[str], list[list[str]]]`，*可选*)：要编码的序列或序列批次。每个序列可以是字符串或字符串列表（预分词字符串）。如果传入预分词输入，请设置 `is_split_into_words=True` 以避免与批量输入产生歧义。

return_mm_token_type_ids (`bool`, *kwargs*) : 是否返回多模态 token 类型 ID，以指示多模态占位符 token 的位置。

return_text_replacement_offsets (`bool`, *kwargs*) : 是否返回每个多模态占位符及其替换项的字符偏移量。

return_tensors (`str` 或 [TensorType](/docs/transformers/v5.23.0/zh/internal/file_utils#transformers.TensorType)，*可选*)：如果设置，将返回特定框架的张量。可接受的值为： - `'pt'`：返回 PyTorch `torch.Tensor` 对象。 - `'np'`：返回 NumPy `np.ndarray` 对象。

- ****kwargs** ([ProcessingKwargs](/docs/transformers/v5.23.0/zh/main_classes/processors#transformers.ProcessingKwargs), *可选*) : 针对每种模态（文本、图像、视频、音频）的额外处理选项。模型特定参数已在上方列出；有关支持参数的完整列表，请参阅 TypedDict 类。

## Lfm2VlConfig[[transformers.Lfm2VlConfig]]

#### transformers.Lfm2VlConfig[[transformers.Lfm2VlConfig]]

```python
transformers.Lfm2VlConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, image_token_id: int = 396, projector_hidden_act: str = 'gelu', projector_hidden_size: int = 2560, projector_bias: bool = True, projector_use_layernorm: bool = True, downsample_factor: int = 2, tie_word_embeddings: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/lfm2_vl/configuration_lfm2_vl.py#L25)

**参数：**

vision_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：视觉骨干网络的配置对象或字典。

text_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：文本骨干网络的配置对象或字典。

image_token_id (`int`，*可选*，默认为 `396`)：用作输入图像占位符的图像标记索引。

projector_hidden_act (`str`，*可选*，默认为 `gelu`)：多模态投影器所使用的激活函数。

projector_hidden_size (`int`，*可选*，默认为 `2560`)：文本和视觉投影层的维度。

projector_bias (`bool`，*可选*，默认为 `True`)：是否在多模态投影器中使用偏置。

projector_use_layernorm (`bool`, *可选*, 默认为 `True`) : 是否在多模态投影器中使用层归一化。

downsample_factor (`int`, *可选*，默认为 2)：视觉骨干网络的 downsample_factor 因子。

tie_word_embeddings (`bool`，*可选*，默认为 `True`)：是否根据模型的 `tied_weights_keys` 映射来绑定权重嵌入。

这是用于存储 Lfm2VlModel 配置的类。它根据指定的参数实例化 Lfm2 Vl 模型，并定义模型架构。使用默认值实例化配置将得到与 [LiquidAI/LFM2-VL-1.6B](https://huggingface.co/LiquidAI/LFM2-VL-1.6B) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

## Lfm2VlModel[[transformers.Lfm2VlModel]]

#### transformers.Lfm2VlModel[[transformers.Lfm2VlModel]]

```python
transformers.Lfm2VlModel(config: Lfm2VlConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/lfm2_vl/modeling_lfm2_vl.py#L147)

**参数：**

config ([Lfm2VlConfig](/docs/transformers/v5.23.0/zh/model_doc/lfm2_vl#transformers.Lfm2VlConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

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

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.Lfm2VlModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, pixel_values: typing.Optional[torch.Tensor] = None, spatial_shapes: typing.Optional[torch.Tensor] = None, pixel_attention_mask: typing.Optional[torch.Tensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, use_cache: bool | None = None, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/lfm2_vl/modeling_lfm2_vl.py#L230)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/v5.23.0/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*)：与输入图像对应的张量。可以使用 [Lfm2VlImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/lfm2_vl#transformers.Lfm2VlImageProcessor) 获取像素值。有关详细信息，请参阅 [Lfm2VlProcessor.__call__()](/docs/transformers/v5.23.0/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（[Lfm2VlProcessor](/docs/transformers/v5.23.0/zh/model_doc/lfm2_vl#transformers.Lfm2VlProcessor) 使用 [Lfm2VlImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/lfm2_vl#transformers.Lfm2VlImageProcessor) 处理图像）。

spatial_shapes (`torch.Tensor`，形状为 `(batch_size, 2)`，*可选*)：输入图像的空间形状。

pixel_attention_mask (`torch.Tensor`，形状为 `(batch_size, height, width)`，*可选*)：输入图像的像素注意力掩码。

past_key_values (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常由模型在解码的先前阶段返回的 `past_key_values` 组成，前提是 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `past_key_values`，则默认初始化 [DynamicCache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入相同的缓存格式。 如果使用 `past_key_values`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是传入 `input_ids`。如果你希望比模型内部的嵌入查找矩阵更精细地控制如何将 `input_ids` 索引转换为对应的向量，这将非常有用。

use_cache (`bool`，*可选*)：如果设置为 `True`，则会返回 `past_key_values` 键值状态，可用于加速解码（参见 `past_key_values`）。

mm_encoder_outputs (`dict[str, ~modeling_outputs.BaseModelOutputWithPooling]`, *可选*) : 一个字典，其中键为支持的模态，值为该模态的编码输出。每个编码输出是一个元组，由 (`pooler_output`, *可选*: `last_hidden_states`, *可选*: `hidden_states`, *可选*: `attentions`) 组成，其中 `pooler_output` 的形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)，表示编码器生成的多模态特征序列，并已融合到文本嵌入中。

**返回：** `Lfm2VlModelOutputWithPast` 或 `tuple(torch.Tensor)`

`Lfm2VlModelOutputWithPast` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Lfm2VlConfig](/docs/transformers/v5.23.0/zh/model_doc/lfm2_vl#transformers.Lfm2VlConfig)）和输入。

[Lfm2VlModel](/docs/transformers/v5.23.0/zh/model_doc/lfm2_vl#transformers.Lfm2VlModel) 的 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](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/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[[transformers.Lfm2VlModel.get_image_features]]

```python
get_image_features(pixel_values: Tensor, spatial_shapes: Tensor, pixel_attention_mask: Tensor, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/lfm2_vl/modeling_lfm2_vl.py#L156)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, channels, height, width)`)：与输入图像对应的张量。

spatial_shapes (`torch.Tensor`，形状为 `(batch_size, 2)`)：输入图像的空间形状。

pixel_attention_mask (`torch.Tensor`，形状为 `(batch_size, height, width)`)：输入图像的像素注意力掩码。

**返回：** [BaseModelOutputWithPooling](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `tuple(torch.Tensor)`

一个 [BaseModelOutputWithPooling](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Lfm2VlConfig](/docs/transformers/v5.23.0/zh/model_doc/lfm2_vl#transformers.Lfm2VlConfig)）和输入。

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

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.Tensor`）-- 序列中第一个 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 后的注意力权重，用于在自注意力头中计算加权平均值。

## Lfm2VlForConditionalGeneration[[transformers.Lfm2VlForConditionalGeneration]]

#### transformers.Lfm2VlForConditionalGeneration[[transformers.Lfm2VlForConditionalGeneration]]

```python
transformers.Lfm2VlForConditionalGeneration(config: Lfm2VlConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/lfm2_vl/modeling_lfm2_vl.py#L305)

**参数：**

config ([Lfm2VlConfig](/docs/transformers/v5.23.0/zh/model_doc/lfm2_vl#transformers.Lfm2VlConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

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

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.Lfm2VlForConditionalGeneration.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, pixel_values: typing.Optional[torch.Tensor] = None, spatial_shapes: typing.Optional[torch.Tensor] = None, pixel_attention_mask: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = None, logits_to_keep: typing.Union[int, torch.Tensor] = 0, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/lfm2_vl/modeling_lfm2_vl.py#L341)

pixel_values (`torch.Tensor`，形状为 `(batch_size, channels, height, width)`，*可选*)：输入图像张量。spatial_shapes (`torch.Tensor`，形状为 `(batch_size, 2)`，*可选*)：输入图像的空间形状。pixel_attention_mask (`torch.Tensor`，形状为 `(batch_size, height, width)`，*可选*)：输入图像的像素注意力掩码。labels (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于计算掩码语言建模损失的标签。索引应在 `[0, ..., config.vocab_size]` 范围内，或为 -100（参见 `input_ids` 的文档字符串）。索引设置为 `-100` 的令牌将被忽略（掩码），损失仅针对标签在 `[0, ..., config.vocab_size]` 范围内的令牌进行计算。

示例：

```python
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import AutoProcessor, AutoModelForImageTextToText
>>> from transformers.image_utils import load_image

>>> model = AutoModelForImageTextToText.from_pretrained(
...     "LiquidAI/LFM2-VL-1.6B",
... )
>>> processor = AutoProcessor.from_pretrained(
...     "LiquidAI/LFM2-VL-1.6B",
... )

>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> image = load_image(url)

>>> conversation = [
...     {
...         "role": "user",
...         "content": [
...             {"type": "image", "image": image},
...             {"type": "text", "text": "What is in this image?"},
...         ],
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     conversation,
...     add_generation_prompt=True,
...     tokenize=True,
...     return_dict=True,
...     return_tensors="pt"
... )

>>> # Generate
>>> outputs = model.generate(**inputs, max_new_tokens=45)
>>> processor.batch_decode(outputs, skip_special_tokens=True)[0]
'This image depicts a vibrant street scene in what appears to be a Chinatown or similar cultural area. The focal point is a large red stop sign with white lettering, mounted on a pole.'
```

#### get_image_features[[transformers.Lfm2VlForConditionalGeneration.get_image_features]]

```python
get_image_features(pixel_values: Tensor, spatial_shapes: Tensor, pixel_attention_mask: Tensor, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/lfm2_vl/modeling_lfm2_vl.py#L318)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, channels, height, width)`)：与输入图像对应的张量。

spatial_shapes (`torch.Tensor`，形状为 `(batch_size, 2)`)：输入图像的空间形状。

pixel_attention_mask (`torch.Tensor`，形状为 `(batch_size, height, width)`)：输入图像的像素注意力掩码。

**返回：** [BaseModelOutputWithPooling](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `tuple(torch.Tensor)`

一个 [BaseModelOutputWithPooling](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Lfm2VlConfig](/docs/transformers/v5.23.0/zh/model_doc/lfm2_vl#transformers.Lfm2VlConfig)）和输入。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.Tensor`）-- 序列中第一个 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 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

```python
>>> from PIL import Image
>>> from transformers import AutoProcessor, Lfm2VlForConditionalGeneration

>>> model = Lfm2VlForConditionalGeneration.from_pretrained("LiquidAI/LFM2-VL-1.6B")
>>> processor = AutoProcessor.from_pretrained("LiquidAI/LFM2-VL-1.6B")

>>> 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]
```

