diff --git a/lfm3/Dockerfile b/lfm3/Dockerfile index 8134a2e..e6c7c3f 100644 --- a/lfm3/Dockerfile +++ b/lfm3/Dockerfile @@ -1,4 +1,4 @@ -# vLLM 0.32.0 XPU + LFM3 plugin +# vLLM 0.32.0 XPU + LFM3 / LFM3-VL plugin FROM vllm/vllm-openai-xpu:latest COPY pyproject.toml /opt/vllm-lfm3/pyproject.toml COPY vllm_lfm3 /opt/vllm-lfm3/vllm_lfm3 diff --git a/lfm3/pyproject.toml b/lfm3/pyproject.toml index 186c4fe..c3e6fa0 100644 --- a/lfm3/pyproject.toml +++ b/lfm3/pyproject.toml @@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta" [project] name = "vllm-lfm3" version = "0.1.0" -description = "Out-of-tree vLLM plugin: LiquidAI LFM3 (Lfm3ForCausalLM) with width-7 short-conv kernels" +description = "Out-of-tree vLLM plugin: LiquidAI LFM3 (Lfm3ForCausalLM, width-7 short-conv kernels) and LFM3-VL (Lfm3VlForConditionalGeneration, images)" requires-python = ">=3.10" license = { text = "Apache-2.0" } diff --git a/lfm3/vllm_lfm3/__init__.py b/lfm3/vllm_lfm3/__init__.py index 78d25ec..1e94fdc 100644 --- a/lfm3/vllm_lfm3/__init__.py +++ b/lfm3/vllm_lfm3/__init__.py @@ -1,5 +1,6 @@ # SPDX-License-Identifier: Apache-2.0 -"""Out-of-tree vLLM plugin for LiquidAI LFM3 (Lfm3ForCausalLM). +"""Out-of-tree vLLM plugin for LiquidAI LFM3 (Lfm3ForCausalLM) and LFM3-VL +(Lfm3VlForConditionalGeneration). Loaded through the ``vllm.general_plugins`` entry point in every vLLM process (API server, EngineCore, workers). @@ -16,6 +17,10 @@ def register() -> None: if "Lfm3ForCausalLM" not in ModelRegistry.get_supported_archs(): # lazy "module:class" form: the model module is only imported when used ModelRegistry.register_model("Lfm3ForCausalLM", "vllm_lfm3.model:Lfm3ForCausalLM") + if "Lfm3VlForConditionalGeneration" not in ModelRegistry.get_supported_archs(): + ModelRegistry.register_model( + "Lfm3VlForConditionalGeneration", "vllm_lfm3.model_vl:Lfm3VlForConditionalGeneration" + ) # Lets transformers (and therefore vLLM) parse config.json with model_type "lfm3" # without --trust-remote-code. @@ -27,3 +32,28 @@ def register() -> None: AutoConfig.register("lfm3", Lfm3Config) except ValueError: pass # already registered (e.g. a future transformers ships lfm3) + + _register_vl() + + +def _register_vl() -> None: + """Same for LFM3-VL: config (``lfm3_vl`` / ``lfm3_vl_vision``) and Liquid's processor, + image and video processor classes, so AutoProcessor finds them locally.""" + from transformers import AutoConfig, AutoImageProcessor, AutoProcessor, AutoVideoProcessor + + from .configuration_lfm3_vl import Lfm3VlConfig, Lfm3VlVisionConfig + from .image_processing_lfm3_vl import Lfm3VlImageProcessor + from .processing_lfm3_vl import Lfm3VlProcessor + from .video_processing_lfm3_vl import Lfm3VlVideoProcessor + + for register in ( + lambda: AutoConfig.register("lfm3_vl", Lfm3VlConfig), + lambda: AutoConfig.register("lfm3_vl_vision", Lfm3VlVisionConfig), + lambda: AutoImageProcessor.register(Lfm3VlConfig, fast_image_processor_class=Lfm3VlImageProcessor), + lambda: AutoVideoProcessor.register(Lfm3VlConfig, Lfm3VlVideoProcessor), + lambda: AutoProcessor.register(Lfm3VlConfig, Lfm3VlProcessor), + ): + try: + register() + except ValueError: + pass # already registered diff --git a/lfm3/vllm_lfm3/configuration_lfm3_vl.py b/lfm3/vllm_lfm3/configuration_lfm3_vl.py new file mode 100644 index 0000000..3e449a6 --- /dev/null +++ b/lfm3/vllm_lfm3/configuration_lfm3_vl.py @@ -0,0 +1,213 @@ +# Vendored verbatim from LFM3-VL-2B/configuration_lfm3_vl.py (LiquidAI / HF, Apache-2.0) +# so that the VL checkpoint loads without --trust-remote-code. +# Copyright 2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from huggingface_hub.dataclasses import strict + +from transformers.configuration_utils import PreTrainedConfig +from transformers.models.auto import CONFIG_MAPPING, AutoConfig +from transformers.utils import auto_docstring + +from .configuration_lfm3 import Lfm3Config + + +def _config_class(model_type): + # the LFM3 configs ship with the checkpoint instead of the transformers registry + remote = {"lfm3": Lfm3Config, "lfm3_vl_vision": Lfm3VlVisionConfig} + return remote.get(model_type) or CONFIG_MAPPING[model_type] + + +@auto_docstring(checkpoint="LiquidAI/LFM3-VL-2B") +@strict +class Lfm3VlVisionConfig(PreTrainedConfig): + r""" + layer_types (`list[str]`, *optional*): + Per-layer operator type, each one of `"full_attention"` or `"conv"`. Defaults to two gated convolution + layers followed by alternating attention and convolution layers. + patch_size (`int`, *optional*, defaults to 16): + The spatial size of each image patch. + temporal_patch_size (`int`, *optional*, defaults to 2): + The number of video frames packed into one patch. + spatial_merge_size (`int`, *optional*, defaults to 2): + The side of the square block of patches merged into one language token. + conv_kernel_size (`int`, *optional*, defaults to 3): + The kernel size of the depthwise 2D convolution layers. + norm_eps (`float`, *optional*, defaults to 1e-05): + The epsilon used by the RMS normalization layers. + """ + + model_type = "lfm3_vl_vision" + base_config_key = "vision_config" + default_theta = 1_000_000.0 + default_rope_type = "axial" + _attention_layer_types = ("full_attention",) + + hidden_size: int = 1024 + intermediate_size: int = 2560 + num_hidden_layers: int = 14 + num_attention_heads: int = 16 + num_key_value_heads: int = 8 + layer_types: list[str] | None = None + patch_size: int = 16 + temporal_patch_size: int = 2 + in_channels: int = 3 + spatial_merge_size: int = 2 + conv_kernel_size: int = 3 + norm_eps: float = 1e-5 + initializer_range: float = 0.02 + rope_parameters: dict | None = None + + def __post_init__(self, **kwargs): + if self.layer_types is None: + self.layer_types = ["conv" if i < 2 or i % 2 else "full_attention" for i in range(self.num_hidden_layers)] + super().__post_init__(**kwargs) + + def validate_architecture(self): + """Part of ``@strict``-powered validation.""" + if len(self.layer_types) != self.num_hidden_layers: + raise ValueError( + f"`layer_types` has {len(self.layer_types)} entries but `num_hidden_layers` is {self.num_hidden_layers}." + ) + allowed_layer_types = (*self._attention_layer_types, "conv") + invalid_layer_types = [layer_type for layer_type in self.layer_types if layer_type not in allowed_layer_types] + if invalid_layer_types: + raise ValueError(f"`layer_types` entries must be one of {allowed_layer_types}; got {invalid_layer_types}.") + if self.hidden_size % self.num_attention_heads: + raise ValueError("`hidden_size` must be a multiple of `num_attention_heads`.") + + +# The first checkpoints spell every text and `vision_*` field at the top level of the config +_LEGACY_TEXT_KEYS = ( + "vocab_size", + "hidden_size", + "intermediate_size", + "num_hidden_layers", + "num_attention_heads", + "num_key_value_heads", + "head_dim", + "layer_types", + "conv_bias", + "conv_L_cache", + "sliding_window", + "max_position_embeddings", + "use_sandwich_norm", + "use_cache", +) +_LEGACY_VISION_KEYS = { + "vision_hidden_size": "hidden_size", + "vision_intermediate_size": "intermediate_size", + "vision_num_hidden_layers": "num_hidden_layers", + "vision_num_attention_heads": "num_attention_heads", + "vision_num_key_value_heads": "num_key_value_heads", + "vision_layer_types": "layer_types", + "vision_patch_size": "patch_size", + "vision_temporal_patch_size": "temporal_patch_size", + "vision_num_channels": "in_channels", + "vision_spatial_merge_size": "spatial_merge_size", +} +_LEGACY_DROPPED_KEYS = ("vision_patch_dim", "vision_max_position_embeddings") + + +@auto_docstring(checkpoint="LiquidAI/LFM3-VL-2B") +@strict +class Lfm3VlConfig(PreTrainedConfig): + r""" + video_token_id (`int`, *optional*, defaults to 125029): + The id of the placeholder token for video patches. + vision_start_token_id (`int`, *optional*, defaults to 125009): + The id of the token opening an image or a video frame. + vision_end_token_id (`int`, *optional*, defaults to 125010): + The id of the token closing an image or a video frame. + projector_layer_norm_eps (`float`, *optional*, defaults to 1e-06): + The epsilon of the layer normalization applied to the vision features before projection. + downsample_factor (`int`, *optional*, defaults to 2): + The side of the square block of vision tokens merged by the projector, equal to the vision encoder's + `spatial_merge_size`. + """ + + model_type = "lfm3_vl" + sub_configs = {"text_config": AutoConfig, "vision_config": Lfm3VlVisionConfig} + + text_config: dict | PreTrainedConfig | None = None + vision_config: dict | PreTrainedConfig | None = None + image_token_id: int = 125_030 + video_token_id: int = 125_029 + vision_start_token_id: int = 125_009 + vision_end_token_id: int = 125_010 + projector_hidden_act: str = "gelu" + projector_hidden_size: int = 4096 + projector_bias: bool = True + projector_layer_norm_eps: float = 1e-6 + downsample_factor: int = 2 + tie_word_embeddings: bool = True + + def __post_init__(self, **kwargs): + if "vision_hidden_size" in kwargs: + kwargs = self._convert_legacy_flat_config(kwargs) + + if isinstance(self.vision_config, dict): + self.vision_config = self.sub_configs["vision_config"](**self.vision_config) + elif self.vision_config is None: + self.vision_config = self.sub_configs["vision_config"]() + + if isinstance(self.text_config, dict): + self.text_config = {"model_type": "lfm3", **self.text_config} + self.text_config = _config_class(self.text_config["model_type"])(**self.text_config) + elif self.text_config is None: + self.text_config = _config_class("lfm3")() + self.validate_vision_fields() + + super().__post_init__(**kwargs) + + def validate_vision_fields(self): + """Part of `@strict`-powered validation, so `validate()` and `save_pretrained` refuse later edits too.""" + if self.downsample_factor != self.vision_config.spatial_merge_size: + raise ValueError("downsample_factor must match vision_config.spatial_merge_size") + # an `inputs_embeds` forward embeds both placeholder ids to find them + vocab_size = self.text_config.vocab_size + for name in ("image_token_id", "video_token_id"): + if not 0 <= getattr(self, name) < vocab_size: + raise ValueError(f"{name}={getattr(self, name)} must lie in [0, text_config.vocab_size={vocab_size})") + + def _convert_legacy_flat_config(self, kwargs: dict) -> dict: + text_config = {key: kwargs.pop(key) for key in _LEGACY_TEXT_KEYS if key in kwargs} + text_config["norm_eps"] = kwargs.pop("rms_norm_eps", 1e-5) + text_config["rope_parameters"] = { + "full_attention": { + "rope_type": "default", + "rope_theta": kwargs.pop("full_attention_rope_theta", 1_000_000.0), + "partial_rotary_factor": kwargs.pop("partial_rotary_factor", 0.5), + }, + "sliding_attention": { + "rope_type": "default", + "rope_theta": kwargs.pop("sliding_attention_rope_theta", 10_000.0), + }, + } + for key in ("pad_token_id", "bos_token_id", "eos_token_id"): + if kwargs.get(key) is not None: + text_config[key] = kwargs[key] + text_config["tie_word_embeddings"] = self.tie_word_embeddings + + vision_config = {new: kwargs.pop(old) for old, new in _LEGACY_VISION_KEYS.items() if old in kwargs} + vision_config["norm_eps"] = text_config["norm_eps"] + vision_config["rope_parameters"] = {"rope_type": "axial", "rope_theta": kwargs.pop("vision_rope_theta", 1e6)} + for key in _LEGACY_DROPPED_KEYS: + kwargs.pop(key, None) + + self.text_config = text_config + self.vision_config = vision_config + return kwargs + + +__all__ = ["Lfm3VlConfig", "Lfm3VlVisionConfig"] diff --git a/lfm3/vllm_lfm3/image_processing_lfm3_vl.py b/lfm3/vllm_lfm3/image_processing_lfm3_vl.py new file mode 100644 index 0000000..9c5c966 --- /dev/null +++ b/lfm3/vllm_lfm3/image_processing_lfm3_vl.py @@ -0,0 +1,295 @@ +# Vendored verbatim from LFM3-VL-2B/image_processing_lfm3_vl.py (LiquidAI / HF, Apache-2.0) +# so that the VL checkpoint loads without --trust-remote-code. +# Copyright 2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import math +import warnings +from collections.abc import Iterable + +import torch +from torchvision.transforms.v2 import functional as tvF + +from transformers.image_processing_backends import TorchvisionBackend +from transformers.image_processing_utils import BatchFeature +from transformers.image_transforms import group_images_by_shape, reorder_images +from transformers.image_utils import ImageInput, PILImageResampling, SizeDict +from transformers.processing_utils import ImagesKwargs, Unpack +from transformers.utils import TensorType, auto_docstring + + +class Lfm3VlImageProcessorKwargs(ImagesKwargs, total=False): + r""" + min_pixels (`int`, *optional*, defaults to `56 * 56`): + The min pixels of the image to resize the image. + max_pixels (`int`, *optional*, defaults to `28 * 28 * 1280`): + The max pixels of the image to resize the image. + patch_size (`int`, *optional*, defaults to 14): + The spatial patch size of the vision encoder. + temporal_patch_size (`int`, *optional*, defaults to 2): + The temporal patch size of the vision encoder. + merge_size (`int`, *optional*, defaults to 2): + The merge size of the vision encoder to llm encoder. + """ + + min_pixels: int + max_pixels: int + patch_size: int + temporal_patch_size: int + merge_size: int + + +def smart_resize( + height: int, width: int, factor: int = 28, min_pixels: int = 56 * 56, max_pixels: int = 14 * 14 * 4 * 1280 +): + """Rescales the image so that the following conditions are met: + + 1. Both dimensions (height and width) are divisible by 'factor'. + + 2. The total number of pixels is within the range ['min_pixels', 'max_pixels']. + + 3. The aspect ratio of the image is maintained as closely as possible. + + """ + if max(height, width) / min(height, width) > 200: + raise ValueError( + f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}" + ) + h_bar = round(height / factor) * factor + w_bar = round(width / factor) * factor + if h_bar * w_bar > max_pixels: + beta = math.sqrt((height * width) / max_pixels) + h_bar = max(factor, math.floor(height / beta / factor) * factor) + w_bar = max(factor, math.floor(width / beta / factor) * factor) + elif h_bar * w_bar < min_pixels: + beta = math.sqrt(min_pixels / (height * width)) + h_bar = math.ceil(height * beta / factor) * factor + w_bar = math.ceil(width * beta / factor) * factor + return h_bar, w_bar + + +@auto_docstring +class Lfm3VlImageProcessor(TorchvisionBackend): + do_resize = True + resample = PILImageResampling.BICUBIC + size = {"shortest_edge": 65_536, "longest_edge": 16_777_216} + default_to_square = False + do_rescale = True + do_normalize = True + image_mean = [0.5, 0.5, 0.5] + image_std = [0.5, 0.5, 0.5] + do_convert_rgb = True + patch_size = 16 + temporal_patch_size = 2 + merge_size = 2 + valid_kwargs = Lfm3VlImageProcessorKwargs + model_input_names = ["pixel_values", "image_grid_thw"] + + def __init__(self, **kwargs: Unpack[Lfm3VlImageProcessorKwargs]): + # backward compatibility: override size with min_pixels and max_pixels if they are provided + size = kwargs.pop("size", None) + size = dict(self.size) if size is None else size + if (min_pixels := kwargs.pop("min_pixels", None)) is not None: + size["shortest_edge"] = min_pixels + size.pop("min_pixels", None) + if (max_pixels := kwargs.pop("max_pixels", None)) is not None: + size["longest_edge"] = max_pixels + size.pop("max_pixels", None) + super().__init__(size=size, **kwargs) + + def _standardize_kwargs( + self, + size: int | Iterable[int] | dict[str, int] | SizeDict | None = None, + min_pixels: int | None = None, + max_pixels: int | None = None, + **kwargs, + ) -> dict: + if min_pixels is not None or max_pixels is not None: + warnings.warn( + "Passing `min_pixels` and `max_pixels` to a processor call is deprecated and will be removed in v5.23. " + "Pass in `size={'longest_edge': xxx, 'shortest_edge': xxx} to override the target size.`", + FutureWarning, + ) + + size_dict = dict(size) if isinstance(size, (dict, SizeDict)) else {} + if min_pixels is not None: + size_dict["shortest_edge"] = min_pixels + if max_pixels is not None: + size_dict["longest_edge"] = max_pixels + size = SizeDict(**size_dict) + return super()._standardize_kwargs(size=size, **kwargs) + + @auto_docstring + def preprocess( + self, + images: ImageInput, + **kwargs: Unpack[Lfm3VlImageProcessorKwargs], + ) -> BatchFeature: + return super().preprocess(images, **kwargs) + + def resize( + self, + images: "torch.Tensor", + size: SizeDict, + resample: "PILImageResampling | tvF.InterpolationMode | int | None", + factor: int, + **kwargs, + ) -> "torch.Tensor": + """Resize dynamically based on input image aspect ratio.""" + if not size.shortest_edge or not size.longest_edge: + raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") + + height, width = images.shape[-2:] + resized_height, resized_width = smart_resize( + height, + width, + factor=factor, + min_pixels=size.shortest_edge, + max_pixels=size.longest_edge, + ) + return super().resize( + image=images, + size=SizeDict(height=resized_height, width=resized_width), + resample=resample, + ) + + def patchify( + self, + images: "torch.Tensor", + patch_size: int, + merge_size: int, + temporal_patch_size: int, + ) -> tuple["torch.Tensor", int, int]: + """Patchifies each image into flat layout of shape (`seq_len`, `patch_dim`) so we can concat dynamically shaped pixels.""" + batch_size, channel, resized_height, resized_width = images.shape + grid_h, grid_w = resized_height // patch_size, resized_width // patch_size + patches = images.reshape( + batch_size, + channel, + grid_h // merge_size, + merge_size, + patch_size, + grid_w // merge_size, + merge_size, + patch_size, + ) + # Reorder dimensions to group grid and patch information for subsequent flattening. + # [batch, grid_h/merge, grid_w/merge, merge, merge, channel, patch, patch] + patches = patches.permute(0, 2, 5, 3, 6, 1, 4, 7) + + flatten_patches = ( + patches.unsqueeze(6) + .expand(-1, -1, -1, -1, -1, -1, temporal_patch_size, -1, -1) + .reshape( + batch_size, + grid_h * grid_w, + channel * temporal_patch_size * patch_size * patch_size, + ) + ) + return flatten_patches, grid_h, grid_w + + def _preprocess( + self, + images: list["torch.Tensor"], + do_resize: bool, + size: SizeDict, + resample: "PILImageResampling | tvF.InterpolationMode | int | None", + do_rescale: bool, + rescale_factor: float, + do_normalize: bool, + image_mean: float | list[float] | None, + image_std: float | list[float] | None, + patch_size: int, + temporal_patch_size: int, + merge_size: int, + disable_grouping: bool | None, + return_tensors: str | TensorType | None, + **kwargs, + ) -> BatchFeature: + grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) + resized_images_grouped = {} + for shape, stacked_images in grouped_images.items(): + if do_resize: + stacked_images = self.resize( + images=stacked_images, + size=size, + resample=resample, + factor=patch_size * merge_size, + ) + resized_images_grouped[shape] = stacked_images + resized_images = reorder_images(resized_images_grouped, grouped_images_index) + + grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping) + processed_images_grouped = {} + processed_grids = {} + for shape, stacked_images in grouped_images.items(): + stacked_images = self.rescale_and_normalize( + stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std + ) + patches, grid_h, grid_w = self.patchify( + stacked_images, + patch_size=patch_size, + merge_size=merge_size, + temporal_patch_size=temporal_patch_size, + ) + + processed_images_grouped[shape] = patches + processed_grids[shape] = [[1, grid_h, grid_w]] * len(stacked_images) + + processed_images = reorder_images(processed_images_grouped, grouped_images_index) + processed_grids_ordered = reorder_images(processed_grids, grouped_images_index) + pixel_values = processed_images[0] if len(processed_images) == 1 else torch.cat(processed_images, dim=0) + image_grid_thw = torch.tensor(processed_grids_ordered, dtype=torch.long) + + return BatchFeature( + data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors + ) + + def get_number_of_image_patches(self, height: int, width: int, images_kwargs: dict | None = None) -> int: + """ + A utility that returns number of image patches for a given image size. + + Note: Do not remove this method! It is used by vLLM to infer the number of patches and placeholders + without an image input. + + Args: + height (`int`): + Height of the input image. + width (`int`): + Width of the input image. + images_kwargs (`dict`, *optional*) + Any kwargs to override defaults of the image processor. + Returns: + `int`: Number of image patches per image. + """ + # `size` is the supported override (`min_pixels` / `max_pixels` are deprecated): count with the budget the + # preprocessing applies + images_kwargs = dict(images_kwargs or {}) + size = images_kwargs.pop("size", None) or self.size + images_kwargs.setdefault("min_pixels", size["shortest_edge"]) + images_kwargs.setdefault("max_pixels", size["longest_edge"]) + images_kwargs = images_kwargs or {} + min_pixels = images_kwargs["min_pixels"] if "min_pixels" in images_kwargs else self.size["shortest_edge"] + max_pixels = images_kwargs["max_pixels"] if "max_pixels" in images_kwargs else self.size["longest_edge"] + patch_size = images_kwargs.get("patch_size", self.patch_size) + merge_size = images_kwargs.get("merge_size", self.merge_size) + + factor = patch_size * merge_size + resized_height, resized_width = smart_resize( + height, width, factor, min_pixels=min_pixels, max_pixels=max_pixels + ) + grid_h, grid_w = resized_height // patch_size, resized_width // patch_size + return grid_h * grid_w + + +__all__ = ["Lfm3VlImageProcessor"] diff --git a/lfm3/vllm_lfm3/model_vl.py b/lfm3/vllm_lfm3/model_vl.py new file mode 100644 index 0000000..7dff0a1 --- /dev/null +++ b/lfm3/vllm_lfm3/model_vl.py @@ -0,0 +1,593 @@ +# SPDX-License-Identifier: Apache-2.0 +"""vLLM implementation of LiquidAI LFM3-VL (``Lfm3VlForConditionalGeneration``), images only. + +Structure (SupportsMultiModal + IsHybrid shell, weight mapper) follows vLLM 0.32's ``lfm2_vl.py``; +the multimodal processing (flat ``pixel_values`` + ``image_grid_thw``) follows ``qwen2_vl.py``, +because LFM3-VL's image processor is Qwen2-VL-style ``smart_resize`` without tiling. The vision +encoder and projector follow Liquid's ``modeling_lfm3_vl.py`` (see NOTES.md, "LFM3-VL"): + * linear patchifier (3·2·16·16 -> 1024) + RMSNorm; + * 14 layers alternating a gated depthwise 3x3 conv over each frame's patch grid and + bidirectional GQA attention (16 q / 8 kv heads, q/k RMSNorm, 2D axial RoPE), each followed + by a SwiGLU MLP, pre-norm, no final norm; + * projector: LayerNorm per vision token, 2x2 merge block -> 4096, Linear-GELU-Linear -> 2048. +The language model is our ``Lfm3ForCausalLM`` (``model.py``), built on ``text_config``. +""" + +from collections.abc import Iterable, Mapping, Sequence +from typing import Any + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from transformers import BatchFeature + +from vllm.config import VllmConfig +from vllm.config.multimodal import MultiModalDummyOptions +from vllm.inputs import MultiModalDataDict +from vllm.model_executor.layers.attention import MMEncoderAttention +from vllm.model_executor.layers.layernorm import RMSNorm +from vllm.model_executor.layers.linear import QKVParallelLinear, ReplicatedLinear +from vllm.model_executor.layers.mamba.mamba_utils import ( + MambaStateCopyFunc, + MambaStateCopyFuncCalculator, + MambaStateDtypeCalculator, + MambaStateShapeCalculator, +) +from vllm.model_executor.model_loader.weight_utils import default_weight_loader +from vllm.model_executor.models.interfaces import ( + IsHybrid, + MultiModalEmbeddings, + SupportsMultiModal, + SupportsPP, +) +from vllm.model_executor.models.utils import ( + AutoWeightsLoader, + WeightsMapper, + init_vllm_registered_model, + maybe_prefix, +) +from vllm.multimodal import MULTIMODAL_REGISTRY +from vllm.multimodal.inputs import MultiModalFieldConfig, MultiModalKwargsItems +from vllm.multimodal.parse import ImageSize, MultiModalDataItems +from vllm.multimodal.processing import ( + BaseDummyInputsBuilder, + BaseMultiModalProcessor, + BaseProcessingInfo, + PromptReplacement, + PromptUpdate, +) +from vllm.renderers import TokenizeParams +from vllm.sequence import IntermediateTensors + +from .configuration_lfm3_vl import Lfm3VlConfig, Lfm3VlVisionConfig +from .image_processing_lfm3_vl import smart_resize +from .model import Lfm3MLP +from .processing_lfm3_vl import Lfm3VlProcessor + + +# --------------------------------------------------------------------------- processing + + +class Lfm3VlProcessingInfo(BaseProcessingInfo): + def get_hf_config(self) -> Lfm3VlConfig: + return self.ctx.get_hf_config(Lfm3VlConfig) + + def get_hf_processor(self, **kwargs: object) -> Lfm3VlProcessor: + return self.ctx.get_hf_processor(Lfm3VlProcessor, **kwargs) + + def get_default_tok_params(self) -> TokenizeParams: + # the chat template already starts with <|startoftext|> + return super().get_default_tok_params().with_kwargs(add_special_tokens=False) + + def get_supported_mm_limits(self) -> Mapping[str, int | None]: + # video is phase 2: without a "video" entry vLLM rejects video inputs + return {"image": None} + + def _get_pixel_limits(self, mm_kwargs: Mapping[str, object]) -> tuple[int, int]: + """(min_pixels, max_pixels) as the image processor resolves them: ``size`` dict, or the + ``min_pixels`` / ``max_pixels`` aliases, over the checkpoint defaults.""" + image_processor = self.get_hf_processor().image_processor + resolved = self._merge_and_resolve_mm_processor_kwargs(mm_kwargs) + # flat keys may have been routed into the images_kwargs scope + merged = {**resolved, **(resolved.get("images_kwargs") or {})} + size = dict(merged.get("size") or image_processor.size) + if merged.get("min_pixels") is not None: + size["shortest_edge"] = merged["min_pixels"] + if merged.get("max_pixels") is not None: + size["longest_edge"] = merged["max_pixels"] + return int(size["shortest_edge"]), int(size["longest_edge"]) + + def get_num_image_tokens( + self, *, image_width: int, image_height: int, mm_kwargs: Mapping[str, object] + ) -> int: + vision_config = self.get_hf_config().vision_config + merge = vision_config.spatial_merge_size + min_pixels, max_pixels = self._get_pixel_limits(mm_kwargs) + height, width = smart_resize( + image_height, + image_width, + factor=vision_config.patch_size * merge, + min_pixels=min_pixels, + max_pixels=max_pixels, + ) + return (height // vision_config.patch_size) * (width // vision_config.patch_size) // merge**2 + + def get_image_size_with_most_features(self) -> ImageSize: + # As qwen2_vl: factorize the maximum number of merged patches into an allowed aspect + # ratio (<= 200) instead of resizing one huge square image. + vision_config = self.get_hf_config().vision_config + unit = vision_config.patch_size * vision_config.spatial_merge_size + _, max_pixels = self._get_pixel_limits({}) + max_tokens = max_pixels // (unit * unit) + for n in range(max_tokens, 0, -1): + h = next(d for d in range(int(n**0.5), 0, -1) if n % d == 0) + if (n // h) / h <= 200: + return ImageSize(width=unit * (n // h), height=unit * h) + return ImageSize(width=unit, height=unit) + + def get_mm_max_tokens_per_item( + self, seq_len: int, mm_counts: Mapping[str, int] + ) -> Mapping[str, int]: + size = self.get_image_size_with_most_features() + return { + "image": self.get_num_image_tokens( + image_width=size.width, image_height=size.height, mm_kwargs={} + ) + } + + +class Lfm3VlDummyInputsBuilder(BaseDummyInputsBuilder[Lfm3VlProcessingInfo]): + def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str: + processor = self.info.get_hf_processor() + image = processor.vision_start_token + processor.image_token + processor.vision_end_token + return image * mm_counts.get("image", 0) + + def get_dummy_mm_data( + self, + seq_len: int, + mm_counts: Mapping[str, int], + mm_options: MultiModalDummyOptions, + ) -> MultiModalDataDict: + size = self.info.get_image_size_with_most_features() + return { + "image": self._get_dummy_images( + width=size.width, + height=size.height, + num_images=mm_counts.get("image", 0), + overrides=mm_options.get("image"), + ) + } + + +class Lfm3VlMultiModalProcessor(BaseMultiModalProcessor[Lfm3VlProcessingInfo]): + def _get_mm_fields_config( + self, + hf_inputs: BatchFeature, + hf_processor_mm_kwargs: Mapping[str, object], + ) -> Mapping[str, MultiModalFieldConfig]: + image_grid_thw = hf_inputs.get("image_grid_thw", torch.empty((0, 3))) + return dict( + pixel_values=MultiModalFieldConfig.flat_from_sizes("image", image_grid_thw.prod(-1)), + image_grid_thw=MultiModalFieldConfig.batched("image", keep_on_cpu=True), + ) + + def _get_prompt_updates( + self, + mm_items: MultiModalDataItems, + hf_processor_mm_kwargs: Mapping[str, Any], + out_mm_kwargs: MultiModalKwargsItems, + ) -> Sequence[PromptUpdate]: + image_token_id = self.info.get_hf_config().image_token_id + merge = self.info.get_hf_config().vision_config.spatial_merge_size + + # the template's single <|image|> (between <|vision_start|> and <|vision_end|>) + # becomes one <|image|> per merged 2x2 patch block, as in Lfm3VlProcessor + def get_replacement(item_idx: int): + grid_thw = out_mm_kwargs["image"][item_idx]["image_grid_thw"].data + return [image_token_id] * (int(grid_thw.prod()) // merge**2) + + return [ + PromptReplacement(modality="image", target=[image_token_id], replacement=get_replacement) + ] + + +# --------------------------------------------------------------------------- vision encoder + + +def vision_position_ids(grid_thw: list[list[int]], merge: int) -> torch.Tensor: + """(h, w) patch coordinates in merge-block order (Transformers ``get_vision_position_ids``).""" + pos = [] + for t, h, w in grid_thw: + hpos, wpos = torch.meshgrid(torch.arange(h), torch.arange(w), indexing="ij") + block = (h // merge, merge, w // merge, merge) + hpos = hpos.reshape(block).transpose(1, 2).flatten() + wpos = wpos.reshape(block).transpose(1, 2).flatten() + pos.append(torch.stack([hpos, wpos], dim=-1).repeat(t, 1)) + return torch.cat(pos, dim=0) + + +def rotate_half(x: torch.Tensor) -> torch.Tensor: + x1, x2 = x.chunk(2, dim=-1) + return torch.cat((-x2, x1), dim=-1) + + +class Lfm3VlVisionRotaryEmbedding(nn.Module): + """Axial 2D RoPE: the same head_dim/4 frequencies for the h and the w coordinate, angles + [h·f, w·f] concatenated and duplicated over the full head_dim (rotate_half style).""" + + def __init__(self, config: Lfm3VlVisionConfig): + super().__init__() + rope = config.rope_parameters + if rope["rope_type"] != "axial": + raise NotImplementedError(f"LFM3-VL vision: rope_type {rope['rope_type']!r}") + spatial_dim = config.hidden_size // config.num_attention_heads // 2 + inv_freq = 1.0 / ( + rope["rope_theta"] ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim) + ) + self.register_buffer("inv_freq", inv_freq, persistent=False) + + def forward(self, position_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + # position_ids: (N, 2) -> cos, sin: (N, head_dim), fp32 + freqs = position_ids[..., None].float() * self.inv_freq.float() # (N, 2, head_dim/4) + freqs = freqs.flatten(1) + freqs = torch.cat([freqs, freqs], dim=-1) + return freqs.cos(), freqs.sin() + + +class Lfm3VlVisionAttention(nn.Module): + def __init__(self, config: Lfm3VlVisionConfig, prefix: str = ""): + super().__init__() + self.num_heads = config.num_attention_heads + self.num_kv_heads = config.num_key_value_heads + self.head_dim = config.hidden_size // config.num_attention_heads + self.qkv_proj = QKVParallelLinear( + config.hidden_size, + self.head_dim, + self.num_heads, + self.num_kv_heads, + bias=False, + prefix=f"{prefix}.qkv_proj", + disable_tp=True, + ) + self.out_proj = ReplicatedLinear( + self.num_heads * self.head_dim, + config.hidden_size, + bias=False, + prefix=f"{prefix}.out_proj", + ) + self.q_layernorm = RMSNorm(self.head_dim, eps=config.norm_eps) + self.k_layernorm = RMSNorm(self.head_dim, eps=config.norm_eps) + self.attn = MMEncoderAttention( + num_heads=self.num_heads, + head_size=self.head_dim, + scale=self.head_dim**-0.5, + num_kv_heads=self.num_kv_heads, + prefix=f"{prefix}.attn", + ) + + def forward( + self, + x: torch.Tensor, + cos: torch.Tensor, + sin: torch.Tensor, + cu_seqlens: torch.Tensor, + max_seqlen: torch.Tensor, + ) -> torch.Tensor: + n = x.shape[0] + qkv, _ = self.qkv_proj(x) + kv_size = self.num_kv_heads * self.head_dim + q, k, v = qkv.split([self.num_heads * self.head_dim, kv_size, kv_size], dim=-1) + q = self.q_layernorm(q.reshape(n, self.num_heads, self.head_dim)) + k = self.k_layernorm(k.reshape(n, self.num_kv_heads, self.head_dim)) + v = v.reshape(n, self.num_kv_heads, self.head_dim) + # RoPE in fp32, as the reference + cos, sin = cos.unsqueeze(-2), sin.unsqueeze(-2) + qf, kf = q.float(), k.float() + q = (qf * cos + rotate_half(qf) * sin).to(v.dtype) + k = (kf * cos + rotate_half(kf) * sin).to(v.dtype) + out = self.attn( + q.unsqueeze(0), k.unsqueeze(0), v.unsqueeze(0), + cu_seqlens=cu_seqlens, max_seqlen=max_seqlen, + ) + out, _ = self.out_proj(out.reshape(n, -1)) + return out + + +class Lfm3VlVisionConv2d(nn.Module): + """Gated depthwise 3x3 conv over each frame's patch grid: in_proj -> (B, C, x), + out_proj(C · conv(B · x)). Tokens come in merge-block order and are convolved in raster order.""" + + def __init__(self, config: Lfm3VlVisionConfig, prefix: str = ""): + super().__init__() + self.merge = config.spatial_merge_size + self.padding = config.conv_kernel_size // 2 + self.in_proj = ReplicatedLinear( + config.hidden_size, 3 * config.hidden_size, bias=False, prefix=f"{prefix}.in_proj" + ) + # nn.Conv2d(hidden, hidden, k, groups=hidden, bias=False) weight: (hidden, 1, k, k) + self.spatial_conv = nn.Module() + self.spatial_conv.weight = nn.Parameter( + torch.empty(config.hidden_size, 1, config.conv_kernel_size, config.conv_kernel_size) + ) + self.out_proj = ReplicatedLinear( + config.hidden_size, config.hidden_size, bias=False, prefix=f"{prefix}.out_proj" + ) + + def _conv(self, frames: torch.Tensor) -> torch.Tensor: + w = self.spatial_conv.weight + return F.conv2d(frames, w, padding=self.padding, groups=w.shape[0]) + + def forward(self, x: torch.Tensor, frame_shapes: list[tuple[int, int]]) -> torch.Tensor: + proj, _ = self.in_proj(x) + b, c, xx = proj.chunk(3, dim=-1) + gated = b * xx + m = self.merge + if len(set(frame_shapes)) == 1: + # equal-size frames convolve as one batch + h, w = frame_shapes[0] + nf = len(frame_shapes) + frames = gated.view(nf, h // m, w // m, m, m, -1) + frames = frames.permute(0, 5, 1, 3, 2, 4).reshape(nf, -1, h, w) + frames = self._conv(frames) + frames = frames.view(nf, -1, h // m, m, w // m, m).permute(0, 2, 4, 3, 5, 1) + conv = frames.reshape(gated.shape[0], -1) + else: + outs = [] + for frame, (h, w) in zip(gated.split([h * w for h, w in frame_shapes]), frame_shapes): + frame = frame.view(h // m, w // m, m, m, -1).permute(4, 0, 2, 1, 3).reshape(1, -1, h, w) + frame = self._conv(frame) + frame = frame.view(-1, h // m, m, w // m, m).permute(1, 3, 2, 4, 0) + outs.append(frame.reshape(h * w, -1)) + conv = torch.cat(outs, dim=0) + out, _ = self.out_proj(c * conv) + return out + + +class Lfm3VlVisionLayer(nn.Module): + def __init__(self, config: Lfm3VlVisionConfig, layer_idx: int, prefix: str = ""): + super().__init__() + layer_type = config.layer_types[layer_idx] + if layer_type not in ("conv", "full_attention"): + raise ValueError(f"LFM3-VL vision: unsupported layer type {layer_type!r}") + self.is_attention_layer = layer_type == "full_attention" + if self.is_attention_layer: + self.self_attn = Lfm3VlVisionAttention(config, prefix=f"{prefix}.self_attn") + else: + self.conv = Lfm3VlVisionConv2d(config, prefix=f"{prefix}.conv") + self.feed_forward = Lfm3MLP( + config.hidden_size, config.intermediate_size, prefix=f"{prefix}.feed_forward" + ) + self.operator_norm = RMSNorm(config.hidden_size, eps=config.norm_eps) + self.ffn_norm = RMSNorm(config.hidden_size, eps=config.norm_eps) + + def forward(self, x: torch.Tensor, ctx: dict) -> torch.Tensor: + h = self.operator_norm(x) + if self.is_attention_layer: + h = self.self_attn(h, ctx["cos"], ctx["sin"], ctx["cu_seqlens"], ctx["max_seqlen"]) + else: + h = self.conv(h, ctx["frame_shapes"]) + x = x + h + return x + self.feed_forward(self.ffn_norm(x)) + + +class Lfm3VlVisionModel(nn.Module): + def __init__(self, config: Lfm3VlVisionConfig, prefix: str = ""): + super().__init__() + self.config = config + self.spatial_merge_size = config.spatial_merge_size + patch_dim = config.in_channels * config.temporal_patch_size * config.patch_size**2 + self.patchifier = ReplicatedLinear( + patch_dim, config.hidden_size, bias=False, prefix=f"{prefix}.patchifier" + ) + self.embedding_norm = RMSNorm(config.hidden_size, eps=config.norm_eps) + self.rotary_pos_emb = Lfm3VlVisionRotaryEmbedding(config) + self.layers = nn.ModuleList( + [ + Lfm3VlVisionLayer(config, i, prefix=f"{prefix}.layers.{i}") + for i in range(config.num_hidden_layers) + ] + ) + + @property + def dtype(self) -> torch.dtype: + return self.patchifier.weight.dtype + + def forward(self, pixel_values: torch.Tensor, grid_thw: list[list[int]]) -> torch.Tensor: + device = pixel_values.device + frame_shapes = [(h, w) for t, h, w in grid_thw for _ in range(t)] + lengths = np.array([h * w for h, w in frame_shapes], dtype=np.int32) + cu_seqlens = np.concatenate([np.zeros(1, dtype=np.int32), lengths.cumsum(dtype=np.int32)]) + cos, sin = self.rotary_pos_emb( + vision_position_ids(grid_thw, self.spatial_merge_size).to(device) + ) + ctx = { + "frame_shapes": frame_shapes, + "cos": cos, + "sin": sin, + "cu_seqlens": torch.from_numpy(cu_seqlens).to(device, non_blocking=True), + "max_seqlen": torch.tensor(int(lengths.max()), dtype=torch.int32), + } + x, _ = self.patchifier(pixel_values.to(self.dtype)) + x = self.embedding_norm(x) + for layer in self.layers: + x = layer(x, ctx) + return x + + def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: + stacked = [ + # (param, checkpoint, shard) + ("qkv_proj", "q_proj", "q"), + ("qkv_proj", "k_proj", "k"), + ("qkv_proj", "v_proj", "v"), + ("w13", "w1", 0), + ("w13", "w3", 1), + ] + params = dict(self.named_parameters()) + loaded: set[str] = set() + for name, weight in weights: + for param_name, ckpt_name, shard in stacked: + if f".{ckpt_name}." not in name: + continue + name = name.replace(f".{ckpt_name}.", f".{param_name}.") + param = params[name] + param.weight_loader(param, weight, shard) + break + else: + if name not in params: + raise ValueError(f"LFM3-VL: unexpected vision weight {name!r}") + param = params[name] + getattr(param, "weight_loader", default_weight_loader)(param, weight) + loaded.add(name) + return loaded + + +class Lfm3VlMultiModalProjector(nn.Module): + def __init__(self, config: Lfm3VlConfig, prefix: str = ""): + super().__init__() + vision_hidden = config.vision_config.hidden_size + if config.projector_hidden_act != "gelu": + raise NotImplementedError(f"LFM3-VL: projector act {config.projector_hidden_act!r}") + self.layer_norm = nn.LayerNorm(vision_hidden, eps=config.projector_layer_norm_eps) + self.linear_1 = ReplicatedLinear( + vision_hidden * config.downsample_factor**2, + config.projector_hidden_size, + bias=config.projector_bias, + prefix=f"{prefix}.linear_1", + ) + self.linear_2 = ReplicatedLinear( + config.projector_hidden_size, + config.text_config.hidden_size, + bias=config.projector_bias, + prefix=f"{prefix}.linear_2", + ) + + def forward(self, vision_features: torch.Tensor) -> torch.Tensor: + # merge-block order: each 2x2 block is 4 consecutive tokens + x = self.layer_norm(vision_features).reshape(-1, self.linear_1.input_size) + x, _ = self.linear_1(x) + x, _ = self.linear_2(F.gelu(x)) + return x + + +# --------------------------------------------------------------------------- model + + +@MULTIMODAL_REGISTRY.register_processor( + Lfm3VlMultiModalProcessor, + info=Lfm3VlProcessingInfo, + dummy_inputs=Lfm3VlDummyInputsBuilder, +) +class Lfm3VlForConditionalGeneration(nn.Module, SupportsMultiModal, SupportsPP, IsHybrid): + merge_by_field_config = True + + hf_to_vllm_mapper = WeightsMapper( + orig_to_new_prefix={ + "lm_head.": "language_model.lm_head.", + "model.language_model.": "language_model.model.", + "model.vision_tower.": "vision_tower.", + "model.multi_modal_projector.": "multi_modal_projector.", + } + ) + + @classmethod + def get_placeholder_str(cls, modality: str, i: int) -> str | None: + if modality.startswith("image"): + return "<|vision_start|><|image|><|vision_end|>" + raise ValueError(f"LFM3-VL: only image input is supported, not {modality!r}") + + @classmethod + def get_mamba_state_dtype_from_config(cls, vllm_config: VllmConfig) -> tuple[torch.dtype, ...]: + return MambaStateDtypeCalculator.short_conv_state_dtype( + vllm_config.model_config.dtype, + vllm_config.cache_config.mamba_cache_dtype, + ) + + @classmethod + def get_mamba_state_shape_from_config(cls, vllm_config: VllmConfig) -> tuple[tuple[int, int]]: + text_config = vllm_config.model_config.hf_config.text_config + return MambaStateShapeCalculator.short_conv_state_shape( + tp_world_size=vllm_config.parallel_config.tensor_parallel_size, + intermediate_size=text_config.hidden_size, + conv_kernel=text_config.conv_L_cache, + ) + + @classmethod + def get_mamba_state_copy_func(cls) -> tuple[MambaStateCopyFunc]: + return MambaStateCopyFuncCalculator.short_conv_state_copy_func() + + def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): + super().__init__() + config: Lfm3VlConfig = vllm_config.model_config.hf_config + self.config = config + self.quant_config = vllm_config.quant_config + + # vision tower and projector stay unquantized (BF16) + with self._mark_tower_model(vllm_config, "image"): + self.vision_tower = Lfm3VlVisionModel( + config.vision_config, prefix=maybe_prefix(prefix, "vision_tower") + ) + self.multi_modal_projector = Lfm3VlMultiModalProjector( + config, prefix=maybe_prefix(prefix, "multi_modal_projector") + ) + + with self._mark_language_model(vllm_config): + self.language_model = init_vllm_registered_model( + vllm_config=vllm_config, + hf_config=config.text_config, + prefix=maybe_prefix(prefix, "language_model"), + architectures=["Lfm3ForCausalLM"], + ) + + self.make_empty_intermediate_tensors = self.language_model.make_empty_intermediate_tensors + + def embed_multimodal(self, **kwargs: object) -> MultiModalEmbeddings: + for key in ("pixel_values_videos", "video_grid_thw", "image_embeds"): + if kwargs.get(key) is not None: + raise ValueError(f"LFM3-VL: {key} is not supported (images as pixels only)") + pixel_values = kwargs.get("pixel_values") + if pixel_values is None: + return [] + grid_thw = kwargs["image_grid_thw"] + if isinstance(grid_thw, list): + grid_thw = torch.stack(grid_thw) + grid_list = grid_thw.tolist() + if isinstance(pixel_values, list): + pixel_values = torch.cat(pixel_values) + + features = self.vision_tower(pixel_values, grid_list) + embeds = self.multi_modal_projector(features) + merge = self.config.vision_config.spatial_merge_size + return embeds.split([t * h * w // merge**2 for t, h, w in grid_list]) + + def forward( + self, + input_ids: torch.Tensor | None, + positions: torch.Tensor, + intermediate_tensors: IntermediateTensors | None = None, + inputs_embeds: torch.Tensor | None = None, + **kwargs: object, + ) -> torch.Tensor | IntermediateTensors: + if intermediate_tensors is not None: + inputs_embeds = None + return self.language_model( + input_ids=input_ids, + positions=positions, + intermediate_tensors=intermediate_tensors, + inputs_embeds=inputs_embeds, + ) + + def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor | None: + return self.language_model.compute_logits(hidden_states) + + def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: + # Unknown names raise (AutoWeightsLoader / vision load_weights); the language model + # checks its own missing parameters; here the whole model is checked once more. + loader = AutoWeightsLoader(self) + loaded = loader.load_weights(weights, mapper=self.hf_to_vllm_mapper) + missing = sorted({name for name, _ in self.named_parameters()} - loaded) + if missing and self.quant_config is None: + raise ValueError( + f"LFM3-VL: {len(missing)} parameters not found in checkpoint: {missing[:20]}" + ) + return loaded diff --git a/lfm3/vllm_lfm3/processing_lfm3_vl.py b/lfm3/vllm_lfm3/processing_lfm3_vl.py new file mode 100644 index 0000000..f485bd6 --- /dev/null +++ b/lfm3/vllm_lfm3/processing_lfm3_vl.py @@ -0,0 +1,250 @@ +# Vendored verbatim from LFM3-VL-2B/processing_lfm3_vl.py (LiquidAI / HF, Apache-2.0) +# so that the VL checkpoint loads without --trust-remote-code. +# Copyright 2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import math + +import numpy as np + +from transformers.image_utils import is_pil_image, is_valid_image, make_flat_list_of_images +from transformers.processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin +from transformers.utils import auto_docstring, is_numpy_array, is_torch_tensor, logging +from transformers.video_utils import VideoMetadata, is_valid_video, make_batched_videos + + +logger = logging.get_logger(__name__) + + +class Lfm3VlProcessorKwargs(ProcessingKwargs, total=False): + _defaults = { + "text_kwargs": { + "padding": False, + "return_token_type_ids": False, + "return_mm_token_type_ids": False, + }, + "videos_kwargs": {"return_metadata": True}, + } + + +def _check_video_fps(metadata: VideoMetadata) -> None: + if metadata.fps is not None and not (math.isfinite(metadata.fps) and metadata.fps > 0): + raise ValueError(f"`video_metadata.fps` must be a positive number, got {metadata.fps}") + + +def _media_per_prompt(media, is_item) -> list[int] | None: + # rows name the prompt that owns them while the expansion consumes media in flat order; a row is a list of whole + # items or one stacked batch, and a list of single frames is one video, not a row + if not isinstance(media, (list, tuple)): + return None + counts = [] + for row in media: + if isinstance(row, (list, tuple)) and all(is_item(item) for item in row): + counts.append(len(row)) + elif (is_numpy_array(row) or is_torch_tensor(row)) and row.ndim == 4 and (len(row) == 0 or is_item(row[0])): + counts.append(len(row)) + else: + return None + return counts + + +def _check_vision_placeholder_counts(processor, prompts, images, videos) -> None: + for name, token, media, flatten, is_item in ( + ( + "images", + processor.image_token, + images, + make_flat_list_of_images, + lambda item: is_valid_image(item) and (is_pil_image(item) or item.ndim == 3), + ), + ( + "videos", + processor.video_token, + videos, + make_batched_videos, + lambda item: isinstance(item, str) or (not is_pil_image(item) and is_valid_video(item)), + ), + ): + num_placeholders = sum(prompt.count(token) for prompt in prompts) + num_media = 0 if media is None else len(flatten(media)) + if num_placeholders != num_media: + raise ValueError(f"Found {num_placeholders} {token} tokens in the text but received {num_media} {name}") + # one prompt cannot take another's media + per_prompt = _media_per_prompt(media, is_item) if len(prompts) > 1 else None + in_text = [prompt.count(token) for prompt in prompts] + if per_prompt is not None and per_prompt != in_text: + raise ValueError(f"Found {in_text} {token} tokens per prompt but received {per_prompt} {name} per prompt") + + +@auto_docstring +class Lfm3VlProcessor(ProcessorMixin): + valid_processor_kwargs = Lfm3VlProcessorKwargs + + def __init__(self, image_processor=None, tokenizer=None, video_processor=None, chat_template=None, **kwargs): + self.image_token = getattr(tokenizer, "image_token", "<|image|>") + self.video_token = getattr(tokenizer, "video_token", "<|video|>") + self.vision_start_token = getattr(tokenizer, "vision_start_token", "<|vision_start|>") + self.vision_end_token = getattr(tokenizer, "vision_end_token", "<|vision_end|>") + self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token) + self.video_token_id = tokenizer.convert_tokens_to_ids(self.video_token) + self.vision_start_token_id = tokenizer.convert_tokens_to_ids(self.vision_start_token) + self.vision_end_token_id = tokenizer.convert_tokens_to_ids(self.vision_end_token) + super().__init__(image_processor, tokenizer, video_processor, chat_template=chat_template) + + def replace_image_token(self, image_inputs: dict, image_idx: int, **kwargs) -> str: + merge_length = self.image_processor.merge_size**2 + num_image_tokens = image_inputs["image_grid_thw"][image_idx].prod() // merge_length + return self.image_token * num_image_tokens + + def replace_video_token(self, video_inputs: dict, video_idx: int, **kwargs) -> str: + metadata = video_inputs["video_metadata"][video_idx] + if metadata.frames_indices is None: + raise ValueError("Frame timestamps need the sampled frame indices in `video_metadata`") + _check_video_fps(metadata) + merge_length = self.video_processor.merge_size**2 + num_frames = video_inputs["video_grid_thw"][video_idx][0] + frame_seqlen = video_inputs["video_grid_thw"][video_idx][1:].prod() // merge_length + metadata = video_inputs["video_metadata"][video_idx] + video_placeholder = "" + + if metadata.fps is None: + logger.warning_once( + "Lfm3Vl requires frame timestamps to construct prompts, but the `fps` of the input video could not be inferred. " + "Probably `video_metadata` was missing from inputs and you passed pre-sampled frames. " + "Defaulting to `fps=24`. Please provide `video_metadata` for more accurate results." + ) + # a released transformers reads torchcodec's scanned average fps, which carries float noise + # (30.000000000000004) where the fork reads the container header + metadata.fps = 24 if metadata.fps is None else round(metadata.fps, 6) + + # if timestamps are not provided, calculate them + curr_timestamp = self._calculate_timestamps( + metadata.frames_indices, + metadata.fps, + self.video_processor.temporal_patch_size, + ) + + for frame_idx in range(num_frames): + curr_time = curr_timestamp[frame_idx] + video_placeholder += f"<{curr_time:.1f} seconds>" + video_placeholder += self.vision_start_token + self.video_token * frame_seqlen + self.vision_end_token + return video_placeholder + + def _get_num_multimodal_tokens(self, image_sizes=None, video_sizes=None, **kwargs): + """ + Computes the number of placeholder tokens needed for multimodal inputs with the given sizes. + + Args: + image_sizes (`list[list[int]]`, *optional*): + The input sizes formatted as (height, width) per each image. + video_sizes (`list[list[int]]`, *optional*): + The input sizes formatted as (num_frames, height, width) per each video. + + Returns: + `MultiModalData`: the number of tokens per provided modality. + """ + vision_data = {} + if image_sizes is not None: + # copy: `update` on the class-level defaults would leak kwargs into every later call + images_kwargs = dict(Lfm3VlProcessorKwargs._defaults.get("images_kwargs", {})) + images_kwargs.update(kwargs) + merge_size = images_kwargs.get("merge_size") or self.image_processor.merge_size + + num_image_patches = [ + self.image_processor.get_number_of_image_patches(*image_size, images_kwargs) + for image_size in image_sizes + ] + num_image_tokens = [(num_patches // merge_size**2) for num_patches in num_image_patches] + vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches}) + + if video_sizes is not None: + videos_kwargs = dict(Lfm3VlProcessorKwargs._defaults.get("videos_kwargs", {})) + videos_kwargs.update(kwargs) + merge_size = videos_kwargs.get("merge_size") or self.video_processor.merge_size + num_video_patches = [ + self.video_processor.get_num_of_video_patches(*video_size, videos_kwargs) for video_size in video_sizes + ] + num_video_tokens = [(num_patches // merge_size**2) for num_patches in num_video_patches] + vision_data["num_video_tokens"] = num_video_tokens + + return MultiModalData(**vision_data) + + def post_process_image_text_to_text( + self, generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False, **kwargs + ): + """ + Post-process the output of the model to decode the text. + + Args: + generated_outputs (`torch.Tensor` or `np.ndarray`): + The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)` + or `(sequence_length,)`. + skip_special_tokens (`bool`, *optional*, defaults to `True`): + Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method. + clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`): + Whether or not to clean up the tokenization spaces. Argument passed to the tokenizer's `batch_decode` method. + **kwargs: + Additional arguments to be passed to the tokenizer's `batch_decode method`. + + Returns: + `list[str]`: The decoded text. + """ + return self.tokenizer.batch_decode( + generated_outputs, + skip_special_tokens=skip_special_tokens, + clean_up_tokenization_spaces=clean_up_tokenization_spaces, + **kwargs, + ) + + @property + def model_input_names(self): + return list( + dict.fromkeys( + self.tokenizer.model_input_names + + self.image_processor.model_input_names + + self.video_processor.model_input_names + ) + ) + + def _calculate_timestamps(self, indices: list[int] | np.ndarray, video_fps: float, merge_size: int = 2): + if not isinstance(indices, list): + indices = indices.tolist() + if len(indices) % merge_size != 0: + indices.extend(indices[-1] for _ in range(merge_size - len(indices) % merge_size)) + timestamps = [idx / video_fps for idx in indices] + # @JJJYmmm frames are merged by self.merge_size, \ + # so we need to average the timestamps between the first/last frame within the temporal patch + timestamps = [ + (timestamps[i] + timestamps[i + merge_size - 1]) / 2 for i in range(0, len(timestamps), merge_size) + ] + return timestamps + + def prepare_inputs_layout(self, images=None, text=None, videos=None, audio=None, **kwargs): + for name, media in (("images", images), ("videos", videos)): + if isinstance(media, (list, tuple)) and len(media) == 0: + raise ValueError(f"`{name}` must hold at least one item; pass `{name}=None` for prompts without one") + return super().prepare_inputs_layout(images=images, text=text, videos=videos, audio=audio, **kwargs) + + def validate_inputs(self, images=None, text=None, videos=None, audio=None, **kwargs): + super().validate_inputs(images=images, text=text, videos=videos, audio=audio, **kwargs) + if text is not None: + _check_vision_placeholder_counts(self, [text] if isinstance(text, str) else text, images, videos) + + def _process_videos(self, videos, **kwargs): + # the frame timestamps need the metadata whatever the caller's `return_metadata`; `__call__` drops it from + # the output unless it was asked for + kwargs["return_metadata"] = True + return super()._process_videos(videos, **kwargs) + + +__all__ = ["Lfm3VlProcessor"] diff --git a/lfm3/vllm_lfm3/video_processing_lfm3_vl.py b/lfm3/vllm_lfm3/video_processing_lfm3_vl.py new file mode 100644 index 0000000..870cc6a --- /dev/null +++ b/lfm3/vllm_lfm3/video_processing_lfm3_vl.py @@ -0,0 +1,398 @@ +# Vendored verbatim from LFM3-VL-2B/video_processing_lfm3_vl.py (LiquidAI / HF, Apache-2.0) +# so that the VL checkpoint loads without --trust-remote-code. +# Copyright 2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import math + +import numpy as np +import torch +from torchvision.transforms.v2 import functional as tvF + +from transformers.image_processing_utils import BatchFeature +from transformers.image_utils import PILImageResampling, SizeDict +from transformers.processing_utils import Unpack, VideosKwargs +from transformers.utils import TensorType, auto_docstring, logging +from transformers.video_processing_utils import BaseVideoProcessor +from transformers.video_utils import ( + VideoMetadata, + group_videos_by_shape, + make_batched_metadata, + make_batched_videos, + reorder_videos, +) + + +logger = logging.get_logger(__name__) + + +class Lfm3VlVideoProcessorInitKwargs(VideosKwargs, total=False): + r""" + patch_size (`int`, *optional*, defaults to 16): + The spatial patch size of the vision encoder. + temporal_patch_size (`int`, *optional*, defaults to 2): + The temporal patch size of the vision encoder. + merge_size (`int`, *optional*, defaults to 2): + The merge size of the vision encoder to llm encoder. + min_frames (`int`, *optional*, defaults to 4): + The minimum number of frames to sample from video. + max_frames (`int`, *optional*, defaults to 768): + The maximum number of frames to sample from video. + cap_pixels_per_frame (`bool`, *optional*): + Whether to cap each frame's pixel cost the way the reference implementation (qwen-vl-utils) does: + per-frame pixels are limited to `min(max_video_tokens * factor**2, size["longest_edge"] / num_frames)` + and floored at `1.05 * size["shortest_edge"]`, so token cost scales with clip duration. Without the + cap, videos that sample few frames spend the whole `size["longest_edge"]` budget on those frames and + keep near-native per-frame resolution, so a short clip can cost almost as many tokens as a long + video. If unset, the current uncapped behavior is kept and a warning is emitted: the default will + change to `True` in v5.22, after which the argument will be removed. + max_video_tokens (`int`, *optional*, defaults to 768): + The per-frame token ceiling applied by `cap_pixels_per_frame`, in vision tokens per frame + (qwen-vl-utils' `VIDEO_MAX_TOKEN_NUM`). + """ + + patch_size: int + temporal_patch_size: int + merge_size: int + min_frames: int + max_frames: int + cap_pixels_per_frame: bool + max_video_tokens: int + + +def smart_resize( + num_frames: int, + height: int, + width: int, + temporal_factor: int = 2, + factor: int = 28, + min_pixels: int = 112 * 112, + max_pixels: int = 14 * 14 * 2 * 2 * 2 * 6144, +): + if num_frames < temporal_factor: + raise ValueError(f"t:{num_frames} must be larger than temporal_factor:{temporal_factor}") + if height < factor or width < factor: + scale = max(factor / height, factor / width) + height = int(height * scale) + width = int(width * scale) + + if max(height, width) / min(height, width) > 200: + raise ValueError( + f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}" + ) + h_bar = round(height / factor) * factor + w_bar = round(width / factor) * factor + t_bar = round(num_frames / temporal_factor) * temporal_factor + + if t_bar * h_bar * w_bar > max_pixels: + beta = math.sqrt((num_frames * height * width) / max_pixels) + h_bar = max(factor, math.floor(height / beta / factor) * factor) + w_bar = max(factor, math.floor(width / beta / factor) * factor) + elif t_bar * h_bar * w_bar < min_pixels: + beta = math.sqrt(min_pixels / (num_frames * height * width)) + h_bar = math.ceil(height * beta / factor) * factor + w_bar = math.ceil(width * beta / factor) * factor + + return h_bar, w_bar + + +def _check_video_fps(metadata: VideoMetadata) -> None: + if metadata.fps is not None and not (math.isfinite(metadata.fps) and metadata.fps > 0): + raise ValueError(f"`video_metadata.fps` must be a positive number, got {metadata.fps}") + + +def _check_video_metadata_count(videos, video_metadata) -> None: + # the shared sampler pairs clips with metadata by `zip`, which drops the clips past the last entry + if video_metadata is None: + return + videos = make_batched_videos(videos) + entries = make_batched_metadata(videos, video_metadata) if video_metadata != [] else [] + if len(entries) != len(videos): + raise ValueError( + f"Received {len(videos)} videos but {len(entries)} `video_metadata` entries; pass one entry per video" + ) + + +@auto_docstring +class Lfm3VlVideoProcessor(BaseVideoProcessor): + resample = PILImageResampling.BICUBIC + size = {"shortest_edge": 4_096, "longest_edge": 25_165_824} + image_mean = [0.5, 0.5, 0.5] + image_std = [0.5, 0.5, 0.5] + do_resize = True + do_rescale = True + do_normalize = True + do_convert_rgb = True + patch_size = 16 + temporal_patch_size = 2 + merge_size = 2 + min_frames = 4 + max_frames = 768 + do_sample_frames = True + cap_pixels_per_frame = False + max_video_tokens = 768 + valid_kwargs = Lfm3VlVideoProcessorInitKwargs + model_input_names = ["pixel_values_videos", "video_grid_thw"] + max_image_size = {"longest_edge": 28 * 28 * 2 * 30000} + max_duration = None + num_frames = None + fps = 2.0 + + def __init__(self, **kwargs: Unpack[Lfm3VlVideoProcessorInitKwargs]): + super().__init__(**kwargs) + + def sample_frames( + self, metadata: VideoMetadata, num_frames: int | None = None, fps: int | float | None = None, **kwargs + ): + """Decoded frames whose metadata carries no fps are sampled and timestamped at the 24 fps the shared sampler + assumes (with a warning); pass `video_metadata` with the clip's fps for accurate timestamps.""" + _check_video_fps(metadata) + if fps is not None and not (math.isfinite(fps) and fps > 0): + raise ValueError(f"`fps` must be a positive number, got {fps}") + if fps is not None and num_frames is not None: + raise ValueError("`num_frames` and `fps` are mutually exclusive arguments, please use only one!") + + total_num_frames = metadata.total_num_frames + fps = fps if fps is not None else self.fps + + # If num_frames is not given but fps is, calculate num_frames from fps + if num_frames is None and fps is not None: + if metadata.fps is None: + metadata.fps = 24 + logger.warning_once( + "Asked to sample `fps` frames per second but no video metadata was provided which is required when sampling with `fps`. " + "Defaulting to `fps=24`. Please provide `video_metadata` for more accurate results." + ) + num_frames = int(total_num_frames / metadata.fps * fps) + num_frames = min(max(num_frames, self.min_frames), self.max_frames, total_num_frames) + + if num_frames is None: + num_frames = min(max(total_num_frames, self.min_frames), self.max_frames) + + indices = np.linspace(0, total_num_frames - 1, num_frames).round().astype(int) + + return indices + + def resize( + self, + videos: "torch.Tensor", + size: SizeDict, + resample: "PILImageResampling | tvF.InterpolationMode | int | None", + factor: int, + temporal_factor: int, + cap_pixels_per_frame: bool | None = None, + **kwargs, + ) -> "torch.Tensor": + """Resize dynamically based on input video aspect ratio.""" + if not size.shortest_edge or not size.longest_edge: + raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") + + num_frames = videos.shape[1] + max_pixels = size.longest_edge + if cap_pixels_per_frame: + # per-frame pixels are capped at `max_video_tokens` patches or the budget's even share per frame + frame_cap = self.max_video_tokens * factor * factor + pixels_per_frame = max(min(frame_cap, size.longest_edge // num_frames), int(size.shortest_edge * 1.05)) + max_pixels = pixels_per_frame * num_frames + + height, width = videos.shape[-2:] + resized_height, resized_width = smart_resize( + height=height, + width=width, + num_frames=num_frames, + factor=factor, + temporal_factor=temporal_factor, + min_pixels=size.shortest_edge, + max_pixels=max_pixels, + ) + return super().resize( + image=videos, + size=SizeDict(height=resized_height, width=resized_width), + resample=resample, + ) + + def patchify( + self, + videos: "torch.Tensor", + patch_size: int, + merge_size: int, + temporal_patch_size: int, + ) -> tuple["torch.Tensor", int, int]: + "Patchifies each video into flat layout of shape (`seq_len`, `patch_dim`) so we can concat dynamically shaped pixels." + batch_size, num_frames, channel, resized_height, resized_width = videos.shape + + # Check that videos have `num_frames` divisible by `temporal_patch_size` + if pad := -num_frames % temporal_patch_size: + repeats = videos[:, -1:].expand(-1, pad, -1, -1, -1) + videos = torch.cat((videos, repeats), dim=1) + num_frames += pad + + grid_t = num_frames // temporal_patch_size + grid_h, grid_w = resized_height // patch_size, resized_width // patch_size + + patches = videos.view( + batch_size, + grid_t, + temporal_patch_size, + channel, + grid_h // merge_size, + merge_size, + patch_size, + grid_w // merge_size, + merge_size, + patch_size, + ) + patches = patches.permute(0, 1, 4, 7, 5, 8, 3, 2, 6, 9) + flatten_patches = patches.reshape( + batch_size, + grid_t * grid_h * grid_w, + channel * temporal_patch_size * patch_size * patch_size, + ) + + return flatten_patches, grid_t, grid_h, grid_w + + def _preprocess( + self, + videos: list["torch.Tensor"], + do_resize: bool, + size: SizeDict, + resample: "PILImageResampling | tvF.InterpolationMode | int | None", + do_rescale: bool, + rescale_factor: float, + do_normalize: bool, + image_mean: float | list[float] | None, + image_std: float | list[float] | None, + patch_size: int | None = None, + temporal_patch_size: int | None = None, + merge_size: int | None = None, + cap_pixels_per_frame: bool | None = None, + return_tensors: str | TensorType | None = None, + **kwargs, + ): + if cap_pixels_per_frame is None: + logger.warning_once( + "Lfm3Vl video processing does not apply the per-frame pixel cap the reference " + "implementation (qwen-vl-utils) applies, so some videos cost far more tokens than they " + "would there. In v5.22 the capped behavior will become the default and " + "`cap_pixels_per_frame` will be removed. Pass `cap_pixels_per_frame=True` to adopt the " + "reference behavior now, or `False` to keep the current behavior and silence this " + "warning." + ) + cap_pixels_per_frame = False + # Group videos by size for batched resizing + grouped_videos, grouped_videos_index = group_videos_by_shape(videos) + resized_videos_grouped = {} + for shape, stacked_videos in grouped_videos.items(): + if do_resize: + stacked_videos = self.resize( + videos=stacked_videos, + size=size, + resample=resample, + factor=patch_size * merge_size, + temporal_factor=temporal_patch_size, + cap_pixels_per_frame=cap_pixels_per_frame, + ) + resized_videos_grouped[shape] = stacked_videos + resized_videos = reorder_videos(resized_videos_grouped, grouped_videos_index) + + # Group videos by size for further processing + # Needed in case do_resize is False, or resize returns videos with different sizes + grouped_videos, grouped_videos_index = group_videos_by_shape(resized_videos) + processed_videos_grouped = {} + processed_grids = {} + for shape, stacked_videos in grouped_videos.items(): + # Fused rescale and normalize + stacked_videos = self.rescale_and_normalize( + stacked_videos, do_rescale, rescale_factor, do_normalize, image_mean, image_std + ) + patches, grid_t, grid_h, grid_w = self.patchify( + stacked_videos, + patch_size=patch_size, + merge_size=merge_size, + temporal_patch_size=temporal_patch_size, + ) + + processed_videos_grouped[shape] = patches + processed_grids[shape] = [[grid_t, grid_h, grid_w]] * len(stacked_videos) + + processed_videos = reorder_videos(processed_videos_grouped, grouped_videos_index) + processed_grids = reorder_videos(processed_grids, grouped_videos_index) + pixel_values_videos = torch.cat(processed_videos, dim=0) + video_grid_thw = torch.tensor(processed_grids) + + return BatchFeature( + data={"pixel_values_videos": pixel_values_videos, "video_grid_thw": video_grid_thw}, + tensor_type=return_tensors, + ) + + def get_num_of_video_patches(self, num_frames: int, height: int, width: int, videos_kwargs=None): + """ + A utility that returns number of video patches a given video size. + + Args: + num_frames (`int`): + Number of frames in the input video. + height (`int`): + Height of the input video. + width (`int`): + Width of the input video. + videos_kwargs (`dict`, *optional*) + Any kwargs to override defaults of the video processor. + Returns: + `int`: Number of video patches per video. + """ + videos_kwargs = videos_kwargs if videos_kwargs is not None else {} + size = videos_kwargs.get("size", None) or self.size + min_pixels = size["shortest_edge"] + max_pixels = size["longest_edge"] + patch_size = videos_kwargs.get("patch_size", None) or self.patch_size + merge_size = videos_kwargs.get("merge_size", None) or self.merge_size + temporal_patch_size = videos_kwargs.get("temporal_patch_size", None) or self.temporal_patch_size + cap_pixels_per_frame = videos_kwargs.get("cap_pixels_per_frame", None) or self.cap_pixels_per_frame + + factor = patch_size * merge_size + if cap_pixels_per_frame: + # Keep the count in sync with `resize` when the per-frame cap is active. + frame_cap = self.max_video_tokens * factor * factor + pixels_per_frame = max(min(frame_cap, max_pixels // num_frames), int(min_pixels * 1.05)) + max_pixels = pixels_per_frame * num_frames + + resized_height, resized_width = smart_resize( + num_frames, + height, + width, + temporal_factor=temporal_patch_size, + factor=factor, + min_pixels=min_pixels, + max_pixels=max_pixels, + ) + grid_h, grid_w = resized_height // patch_size, resized_width // patch_size + grid_t = (num_frames + -num_frames % temporal_patch_size) // temporal_patch_size + return grid_t * grid_h * grid_w + + def preprocess(self, videos, **kwargs): + _check_video_metadata_count(videos, kwargs.get("video_metadata")) + # the shared `preprocess` fills every unset option from the instance before `sample_frames` runs, so the + # caller's options are told apart from the instance ones here: a caller option beats an instance one, and a + # configured `num_frames` beats the default fps + num_frames, fps = kwargs.get("num_frames"), kwargs.get("fps") + if num_frames is not None and fps is not None: + raise ValueError("`num_frames` and `fps` are mutually exclusive arguments, please use only one!") + if num_frames is not None or (fps is None and self.num_frames is not None): + kwargs["fps"] = None + elif fps is not None: + kwargs["num_frames"] = None + return super().preprocess(videos, **kwargs) + + +__all__ = ["Lfm3VlVideoProcessor"]