Transformers documentation
LFM2-VL
This model was released on {release_date} and added to Hugging Face Transformers on 2025-09-18.
LFM2-VL
Overview
LFM2-VL first series of vision-language foundation models developed by Liquid AI. These multimodal models are designed for low-latency and device-aware deployment. LFM2-VL extends the LFM2 family of open-weight Liquid Foundation Models (LFMs) into the vision-language space, supporting both text and image inputs with variable resolutions.
Architecture
LFM2-VL consists of three main components: a language model backbone, a vision encoder, and a multimodal projector. LFM2-VL builds upon the LFM2 backbone, inheriting from either LFM2-1.2B (for LFM2-VL-1.6B) or LFM2-350M (for LFM2-VL-450M). For the vision tower, LFM2-VL uses SigLIP2 NaFlex encoders to convert input images into token sequences. Two variants are implemented:
- Shape-optimized (400M) for more fine-grained vision capabilities for LFM2-VL-1.6B
- Base (86M) for fast image processing for LFM2-VL-450M
The encoder processes images at their native resolution up to 512×512 pixels, efficiently handling smaller images without upscaling and supporting non-standard aspect ratios without distortion. Larger images are split into non-overlapping square patches of 512×512 each, preserving detail. In LFM2-VL-1.6B, the model also receives a thumbnail (a small, downscaled version of the original image capturing the overall scene) to enhance global context understanding and alignment. Special tokens mark each patch’s position and indicate the thumbnail’s start. The multimodal connector is a 2-layer MLP connector with pixel unshuffle to reduce image token count.
Example
The following example shows how to generate an answer using the AutoModelForImageTextToText
class.
from transformers import AutoProcessor, AutoModelForImageTextToText
\
# 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 snswer
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]
Lfm2VlImageProcessorFast
class transformers.Lfm2VlImageProcessorFast
< source >( **kwargs: typing_extensions.Unpack[transformers.models.lfm2_vl.image_processing_lfm2_vl_fast.Lfm2VlFastImageProcessorKwargs] )
Constructs a fast Lfm2 Vl image processor.
crop_image_to_patches
< source >( image: torch.Tensor min_tiles: int max_tiles: int tile_size: int use_thumbnail: bool thumbnail_size: tuple interpolation: F.InterpolationMode = None antialias: bool = True **kwargs )
Processes a high resolution image into patches. This method splits a high resolution image into a grid of smaller patches while trying to maintain the original aspect ratio. It finds the optimal grid configuration within the specified tile constraints.
smart_resize
< source >( height: int width: int downsample_factor: int min_image_tokens: int max_image_tokens: int encoder_patch_size: int )
Rescales the image so that the following conditions are met:
- Both dimensions (height and width) are divisible by ‘encoder_patch_size’ * ‘downsample_factor’. This ensures no padding is needed in the downsampling step.
- The total number of pixels is within the range [‘smart_resize_min_pixels’, ‘smart_resize_max_pixels’].
- The aspect ratio of the image is maintained as closely as possible.
Lfm2VlProcessor
class transformers.Lfm2VlProcessor
< source >( image_processor tokenizer chat_template: typing.Optional[str] = None use_image_special_tokens: typing.Optional[bool] = True **kwargs )
Parameters
- image_processor (
Lfm2VlImageProcessor
) — An instance ofLfm2VlImageProcessor
. The image processor is a required input. - tokenizer (
PreTrainedTokenizerBase
) — An instance of PreTrainedTokenizerBase. This should correspond with the model’s text model. The tokenizer is a required input. - chat_template (
str
, optional) — A Jinja template which will be used to convert lists of messages in a chat into a tokenizable string. - use_image_special_tokens (
bool
, optional, defaults toTrue
) — Whether to use image special tokens or not when processing.
Constructs a Lfm2Vl processor which wraps a Lfm2Tokenizer tokenizer and Lfm2VlImageProcessor into a single processor.
Lfm2VlProcessor offers all the functionalities of Lfm2ImageProcessor
and Lfm2Tokenizer
.
This method forwards all its arguments to LFM2Tokeniser’s batch_decode(). Please refer to the docstring of this method for more information.
This method forwards all its arguments to LFM2Tokeniser’s decode(). Please refer to the docstring of this method for more information.
Lfm2VlConfig
class transformers.Lfm2VlConfig
< source >( vision_config = None text_config = None image_token_id = 396 projector_hidden_act = 'gelu' projector_hidden_size = 2560 projector_bias = True downsample_factor = 2 **kwargs )
Parameters
- vision_config (
AutoConfig | dict
, optional, defaults toSiglip2ImageConfig
) — The config object or dictionary of the vision backbone. - text_config (
AutoConfig | dict
, optional, defaults toLfm2Config
) — The config object or dictionary of the text backbone. - image_token_id (
int
, optional, defaults to 396) — The image token index to encode the image prompt. - projector_hidden_act (
str
, optional, defaults to"gelu"
) — The activation function used by the multimodal projector. - projector_hidden_size (
int
, optional, defaults to 2560) — The hidden size of the multimodal projector. - projector_bias (
bool
, optional, defaults toTrue
) — Whether to use bias in the multimodal projector. - downsample_factor (
int
, optional, defaults to 2) — The downsample_factor factor of the vision backbone.
This is the configuration class to store the configuration of a Lfm2VlForConditionalGeneration. It is used to instantiate an Lfm2Vl model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the Lfm2-VL-1.6B.
Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.
Lfm2VlModel
class transformers.Lfm2VlModel
< source >( config: Lfm2VlConfig )
Parameters
- config (Lfm2VlConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
The Lfm2Vl model which consists of a vision backbone and a language model, without a language modeling head.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward
< source >( 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.FloatTensor] = None spatial_shapes: typing.Optional[torch.Tensor] = None pixel_attention_mask: typing.Optional[torch.Tensor] = None past_key_values: typing.Optional[transformers.cache_utils.Cache] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None use_cache: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → transformers.models.lfm2_vl.modeling_lfm2_vl.Lfm2VlModelOutputWithPast
or tuple(torch.FloatTensor)
Parameters
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- 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.
- position_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1]
. - pixel_values (
torch.FloatTensor
of shape(batch_size, num_channels, image_size, image_size)
, optional) — The tensors corresponding to the input images. Pixel values can be obtained usingimage_processor_class
. Seeimage_processor_class.__call__
for details (Lfm2VlProcessor usesimage_processor_class
for processing images). - spatial_shapes (
torch.Tensor
of shape(batch_size, 2)
, optional) — The spatial shapes of the input images. - pixel_attention_mask (
torch.Tensor
of shape(batch_size, height, width)
, optional) — The pixel attention mask of the input images. - past_key_values (
~cache_utils.Cache
, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in thepast_key_values
returned by the model at a previous stage of decoding, whenuse_cache=True
orconfig.use_cache=True
.Only Cache instance is allowed as input, see our kv cache guide. If no
past_key_values
are passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
past_key_values
are used, the user is expected to input only unprocessedinput_ids
(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)
instead of allinput_ids
of shape(batch_size, sequence_length)
. - inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_ids
indices into associated vectors than the model’s internal embedding lookup matrix. - use_cache (
bool
, optional) — If set toTrue
,past_key_values
key value states are returned and can be used to speed up decoding (seepast_key_values
). - cache_position (
torch.LongTensor
of shape(sequence_length)
, optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily toposition_ids
, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length.
Returns
transformers.models.lfm2_vl.modeling_lfm2_vl.Lfm2VlModelOutputWithPast
or tuple(torch.FloatTensor)
A transformers.models.lfm2_vl.modeling_lfm2_vl.Lfm2VlModelOutputWithPast
or a tuple of
torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various
elements depending on the configuration (Lfm2VlConfig) and inputs.
-
last_hidden_state (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — Sequence of hidden-states at the output of the last layer of the model. -
past_key_values (
Cache
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) — It is a Cache instance. For more details, see our kv cache guide.Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
past_key_values
input) to speed up sequential decoding. -
hidden_states (
tuple[torch.FloatTensor, ...]
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.FloatTensor
(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
-
attentions (
tuple[torch.FloatTensor, ...]
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
-
image_hidden_states (
torch.FloatTensor
, optional) — Atorch.FloatTensor
of size(batch_size, num_images, sequence_length, hidden_size)
. image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
The Lfm2VlModel forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Lfm2VlForConditionalGeneration
class transformers.Lfm2VlForConditionalGeneration
< source >( config: Lfm2VlConfig )
Parameters
- config (Lfm2VlConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
The LFM2_VL model which consists of a vision backbone and a language model.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = None pixel_values: typing.Optional[torch.FloatTensor] = 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: typing.Optional[transformers.cache_utils.Cache] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None logits_to_keep: typing.Union[int, torch.Tensor] = 0 **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] )
pixel_values (torch.FloatTensor
of shape (batch_size, channels, height, width)
, optional):
The input image tensors.
spatial_shapes (torch.Tensor
of shape (batch_size, 2)
, optional):
The spatial shapes of the input images.
pixel_attention_mask (torch.Tensor
of shape (batch_size, height, width)
, optional):
The pixel attention mask of the input images.
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]
.
Example:
>>> from PIL import Image
>>> import requests
>>> 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.'