# 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