# SPDX-License-Identifier: Apache-2.0 """vLLM implementation of LiquidAI LFM3 (``Lfm3ForCausalLM``). Based on vLLM 0.32's ``lfm2.py``. Differences to LFM2 (see NOTES.md): * three layer types: ``conv`` (gated short conv, width 7), ``full_attention`` and ``sliding_attention`` (per-layer sliding window); * sandwich norm (``post_operator_norm`` / ``post_ffn_norm``); * attention with ``q_norm``/``k_norm``, a sigmoid output gate per head and RoPE per layer type, with LFM3's "zero-tail" partial rotation on full-attention layers; * plain SwiGLU MLP (no ff-dim auto adjustment), ``o_proj`` naming; * a width-7 causal conv1d (vLLM's Triton kernels stop at width 4/6). """ from collections.abc import Iterable from itertools import islice import torch import torch.nn as nn from vllm.compilation.decorators import support_torch_compile from vllm.config import CacheConfig, ModelConfig, VllmConfig from vllm.distributed import get_pp_group, get_tensor_model_parallel_world_size from vllm.model_executor.layers.activation import SiluAndMul from vllm.model_executor.layers.attention import Attention from vllm.model_executor.layers.layernorm import RMSNorm from vllm.model_executor.layers.linear import ( ColumnParallelLinear, MergedColumnParallelLinear, QKVParallelLinear, RowParallelLinear, ) from vllm.model_executor.layers.logits_processor import LogitsProcessor from vllm.model_executor.layers.mamba.mamba_utils import ( MambaStateCopyFunc, MambaStateCopyFuncCalculator, MambaStateDtypeCalculator, MambaStateShapeCalculator, is_conv_state_dim_first, ) from vllm.model_executor.layers.mamba.short_conv import ShortConv from vllm.model_executor.layers.quantization import QuantizationConfig from vllm.model_executor.layers.rotary_embedding.base import RotaryEmbedding from vllm.model_executor.layers.vocab_parallel_embedding import ( ParallelLMHead, VocabParallelEmbedding, ) from vllm.model_executor.models.interfaces import ( HasInnerState, IsHybrid, SupportsPP, SupportsQuant, ) from vllm.model_executor.models.utils import ( AutoWeightsLoader, PPMissingLayer, WeightsMapper, extract_layer_index, make_empty_intermediate_tensors_factory, make_layers, maybe_prefix, ) from vllm.forward_context import get_forward_context from vllm.sequence import IntermediateTensors from vllm.v1.attention.backends.short_conv_attn import ShortConvAttentionMetadata from .conv_ops import causal_conv1d_decode, causal_conv1d_prefill ATTENTION_LAYER_TYPES = ("full_attention", "sliding_attention") class Lfm3RotaryEmbedding(RotaryEmbedding): """Neox RoPE over the full head dim with LFM3's zero-tail partial rotation. The first ``partial_rotary_factor * head_dim // 2`` frequencies follow the progression of the *full* head dim, the rest are zero (cos=1, sin=0). This is not vLLM's ``partial_rotary_factor``, which rotates a prefix with its own progression. """ def __init__( self, head_size: int, max_position_embeddings: int, base: float, partial_rotary_factor: float, dtype: torch.dtype, ) -> None: self.partial_rotary_factor = partial_rotary_factor super().__init__( head_size=head_size, rotary_dim=head_size, max_position_embeddings=max_position_embeddings, base=base, is_neox_style=True, dtype=dtype, ) def _compute_inv_freq(self, base: float) -> torch.Tensor: dim = self.head_size rope_angles = int(self.partial_rotary_factor * dim) // 2 inv_freq = 1.0 / ( base ** (torch.arange(0, 2 * rope_angles, 2, dtype=torch.float) / dim) ) return torch.cat((inv_freq, torch.zeros(dim // 2 - rope_angles))) class Lfm3MLP(nn.Module): def __init__( self, hidden_size: int, intermediate_size: int, quant_config: QuantizationConfig | None = None, prefix: str = "", ): super().__init__() self.w13 = MergedColumnParallelLinear( input_size=hidden_size, output_sizes=[intermediate_size] * 2, bias=False, quant_config=quant_config, prefix=f"{prefix}.w13", ) self.w2 = RowParallelLinear( input_size=intermediate_size, output_size=hidden_size, bias=False, quant_config=quant_config, prefix=f"{prefix}.w2", ) self.act_fn = SiluAndMul() def forward(self, x: torch.Tensor) -> torch.Tensor: gate_up, _ = self.w13(x) x = self.act_fn(gate_up) x, _ = self.w2(x) return x class Lfm3Attention(nn.Module): def __init__( self, config, layer_idx: int, rotary_emb: Lfm3RotaryEmbedding, cache_config: CacheConfig | None = None, quant_config: QuantizationConfig | None = None, prefix: str = "", ) -> None: super().__init__() self.layer_idx = layer_idx self.hidden_size = config.hidden_size tp_size = get_tensor_model_parallel_world_size() self.total_num_heads = config.num_attention_heads assert self.total_num_heads % tp_size == 0 self.num_heads = self.total_num_heads // tp_size self.total_num_kv_heads = config.num_key_value_heads if self.total_num_kv_heads >= tp_size: assert self.total_num_kv_heads % tp_size == 0 else: assert tp_size % self.total_num_kv_heads == 0 self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size) self.head_dim = config.head_dim self.q_size = self.num_heads * self.head_dim self.kv_size = self.num_kv_heads * self.head_dim self.scaling = self.head_dim**-0.5 self.qkv_proj = QKVParallelLinear( hidden_size=self.hidden_size, head_size=self.head_dim, total_num_heads=self.total_num_heads, total_num_kv_heads=self.total_num_kv_heads, bias=False, quant_config=quant_config, prefix=f"{prefix}.qkv_proj", ) self.o_proj = RowParallelLinear( input_size=self.total_num_heads * self.head_dim, output_size=self.hidden_size, bias=False, quant_config=quant_config, prefix=f"{prefix}.o_proj", ) # one sigmoid gate per head; tiny, kept unquantized self.gate_proj = ColumnParallelLinear( input_size=self.hidden_size, output_size=self.total_num_heads, bias=False, gather_output=False, prefix=f"{prefix}.gate_proj", ) self.q_norm = RMSNorm(self.head_dim, eps=config.norm_eps) self.k_norm = RMSNorm(self.head_dim, eps=config.norm_eps) self.rotary_emb = rotary_emb is_sliding = config.layer_types[layer_idx] == "sliding_attention" self.attn = Attention( self.num_heads, self.head_dim, self.scaling, num_kv_heads=self.num_kv_heads, cache_config=cache_config, per_layer_sliding_window=config.sliding_window if is_sliding else None, prefix=f"{prefix}.attn", ) def forward(self, positions: torch.Tensor, hidden_states: torch.Tensor) -> torch.Tensor: n_tokens = hidden_states.shape[0] qkv, _ = self.qkv_proj(hidden_states) q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1) q = self.q_norm(q.view(n_tokens, self.num_heads, self.head_dim)) k = self.k_norm(k.view(n_tokens, self.num_kv_heads, self.head_dim)) q, k = self.rotary_emb(positions, q, k) attn_output = self.attn( q.reshape(n_tokens, self.q_size), k.reshape(n_tokens, self.kv_size), v ) gate, _ = self.gate_proj(hidden_states) attn_output = attn_output.view(n_tokens, self.num_heads, self.head_dim) attn_output = attn_output * torch.sigmoid(gate).unsqueeze(-1) output, _ = self.o_proj(attn_output.view(n_tokens, self.q_size)) return output class Lfm3ShortConv(ShortConv): """vLLM ShortConv with an arbitrary-width (here 7) causal conv. Only ``forward_cuda`` (used on every non-CPU platform, including XPU) is replaced; projections, state shape/dtype and metadata handling are inherited. """ def forward_cuda(self, hidden_states: torch.Tensor, output: torch.Tensor): attn_metadata = get_forward_context().attn_metadata if attn_metadata is not None: assert isinstance(attn_metadata, dict) attn_metadata = attn_metadata.get(self.prefix) BCx, _ = self.in_proj(hidden_states) B, C, x = BCx.chunk(3, dim=-1) if attn_metadata is None: # profile run: values don't matter, shapes do output[: hidden_states.shape[0]], _ = self.out_proj(C * (B * x)) return assert isinstance(attn_metadata, ShortConvAttentionMetadata) if attn_metadata.num_accepted_tokens is not None: raise NotImplementedError("LFM3 short conv: speculative decoding is not supported") # token-major view (num_blocks, width - 1, dim) of the conv state cache conv_state = self.kv_cache[0] if is_conv_state_dim_first(): conv_state = conv_state.transpose(-1, -2) conv_weights = self.conv.weight.view(self.conv.weight.size(0), self.conv.weight.size(2)) num_decodes = attn_metadata.num_decode_tokens num_prefill_tokens = attn_metadata.num_prefill_tokens num_actual_tokens = num_decodes + num_prefill_tokens Bx = B[:num_actual_tokens] * x[:num_actual_tokens] Bx_d, Bx_p = torch.split(Bx, [num_decodes, num_prefill_tokens], dim=0) conv_out = [] if num_decodes > 0: state_indices_d = attn_metadata.state_indices_tensor_d if state_indices_d.dim() > 1: state_indices_d = state_indices_d[:, 0] conv_out.append( causal_conv1d_decode( Bx_d, conv_weights, self.conv.bias, conv_state, state_indices_d[:num_decodes], ) ) if attn_metadata.num_prefills > 0: conv_out.append( causal_conv1d_prefill( Bx_p, conv_weights, self.conv.bias, conv_state, attn_metadata.query_start_loc_p, attn_metadata.state_indices_tensor_p, attn_metadata.has_initial_states_p, ) ) y = conv_out[0] if len(conv_out) == 1 else torch.cat(conv_out, dim=0) output[:num_actual_tokens], _ = self.out_proj(C[:num_actual_tokens] * y) class Lfm3DecoderLayer(nn.Module): def __init__( self, config, layer_idx: int, rotary_embs: dict[str, Lfm3RotaryEmbedding], model_config: ModelConfig | None = None, cache_config: CacheConfig | None = None, quant_config: QuantizationConfig | None = None, prefix: str = "", ) -> None: super().__init__() self.layer_idx = layer_idx self.layer_type = config.layer_types[layer_idx] self.is_attention_layer = self.layer_type in ATTENTION_LAYER_TYPES if self.is_attention_layer: self.self_attn = Lfm3Attention( config, layer_idx, rotary_embs[self.layer_type], cache_config=cache_config, quant_config=quant_config, prefix=f"{prefix}.self_attn", ) else: # HF's ".conv." is mapped to ".short_conv." (see hf_to_vllm_mapper) self.short_conv = Lfm3ShortConv( config=config, dim=config.hidden_size, layer_idx=layer_idx, model_config=model_config, cache_config=cache_config, quant_config=quant_config, prefix=f"{prefix}.short_conv", ) self.feed_forward = Lfm3MLP( config.hidden_size, config.intermediate_size, quant_config=quant_config, 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) self.use_sandwich_norm = config.use_sandwich_norm if self.use_sandwich_norm: self.post_operator_norm = RMSNorm(config.hidden_size, eps=config.norm_eps) self.post_ffn_norm = RMSNorm(config.hidden_size, eps=config.norm_eps) def forward( self, positions: torch.Tensor, hidden_states: torch.Tensor, residual: torch.Tensor | None, ) -> tuple[torch.Tensor, torch.Tensor]: # `hidden_states` is the previous layer's (post-normed) FFN output, not yet # added to `residual`; the fused add+norm performs the residual add. if residual is None: residual = hidden_states hidden_states = self.operator_norm(hidden_states) else: hidden_states, residual = self.operator_norm(hidden_states, residual) if self.is_attention_layer: hidden_states = self.self_attn(positions=positions, hidden_states=hidden_states) else: output = torch.empty_like(hidden_states) self.short_conv(hidden_states, output) hidden_states = output if self.use_sandwich_norm: hidden_states = self.post_operator_norm(hidden_states) hidden_states, residual = self.ffn_norm(hidden_states, residual) hidden_states = self.feed_forward(hidden_states) if self.use_sandwich_norm: hidden_states = self.post_ffn_norm(hidden_states) return hidden_states, residual @support_torch_compile class Lfm3Model(nn.Module): hf_to_vllm_mapper = WeightsMapper( orig_to_new_substr={".conv.": ".short_conv."}, orig_to_new_stacked={ ".q_proj": (".qkv_proj", "q"), ".k_proj": (".qkv_proj", "k"), ".v_proj": (".qkv_proj", "v"), ".w1": (".w13", 0), ".w3": (".w13", 1), }, ) def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): super().__init__() config = vllm_config.model_config.hf_config model_config = vllm_config.model_config cache_config = vllm_config.cache_config quant_config = vllm_config.quant_config self.config = config self.vocab_size = config.vocab_size for t in config.layer_types: if t not in (*ATTENTION_LAYER_TYPES, "conv"): raise ValueError(f"LFM3: unsupported layer type {t!r}") self.embed_tokens = VocabParallelEmbedding( self.vocab_size, config.hidden_size, org_num_embeddings=config.vocab_size ) # one RoPE (cos/sin cache) per attention layer type, shared by its layers rotary_embs: dict[str, Lfm3RotaryEmbedding] = {} for layer_type in sorted(set(config.layer_types) & set(ATTENTION_LAYER_TYPES)): rope = config.rope_parameters[layer_type] if rope.get("rope_type", "default") != "default": raise NotImplementedError(f"LFM3: rope_type {rope['rope_type']!r}") rotary_embs[layer_type] = Lfm3RotaryEmbedding( head_size=config.head_dim, max_position_embeddings=model_config.max_model_len, base=rope["rope_theta"], partial_rotary_factor=rope.get("partial_rotary_factor", 1.0), dtype=torch.get_default_dtype(), ) def get_layer(prefix: str): layer_idx = extract_layer_index(prefix) return Lfm3DecoderLayer( config, layer_idx, rotary_embs, model_config, cache_config, quant_config=quant_config, prefix=prefix, ) self.start_layer, self.end_layer, self.layers = make_layers( config.num_hidden_layers, get_layer, prefix=f"{prefix}.layers" ) self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory( ["hidden_states", "residual"], config.hidden_size ) # despite its name, LFM3's `embedding_norm` is the final norm after the last layer if get_pp_group().is_last_rank: self.embedding_norm = RMSNorm(config.hidden_size, eps=config.norm_eps) else: self.embedding_norm = PPMissingLayer() def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: return self.embed_tokens(input_ids) def forward( self, input_ids: torch.Tensor | None, positions: torch.Tensor, intermediate_tensors: IntermediateTensors | None = None, inputs_embeds: torch.Tensor | None = None, ) -> torch.Tensor | IntermediateTensors: if get_pp_group().is_first_rank: if inputs_embeds is not None: hidden_states = inputs_embeds else: hidden_states = self.embed_input_ids(input_ids) residual = None else: assert intermediate_tensors is not None hidden_states = intermediate_tensors["hidden_states"] residual = intermediate_tensors["residual"] for layer in islice(self.layers, self.start_layer, self.end_layer): hidden_states, residual = layer( positions=positions, hidden_states=hidden_states, residual=residual ) if not get_pp_group().is_last_rank: return IntermediateTensors({"hidden_states": hidden_states, "residual": residual}) hidden_states, _ = self.embedding_norm(hidden_states, residual) return hidden_states class Lfm3ForCausalLM(nn.Module, HasInnerState, SupportsPP, IsHybrid, SupportsQuant): packed_modules_mapping = { "qkv_proj": ["q_proj", "k_proj", "v_proj"], "w13": ["w1", "w3"], "in_proj": ["in_proj"], } hf_to_vllm_mapper = Lfm3Model.hf_to_vllm_mapper @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]]: hf_config = vllm_config.model_config.hf_config return MambaStateShapeCalculator.short_conv_state_shape( tp_world_size=vllm_config.parallel_config.tensor_parallel_size, intermediate_size=hf_config.hidden_size, conv_kernel=hf_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 = "") -> None: super().__init__() config = vllm_config.model_config.hf_config quant_config = vllm_config.quant_config self.config = config self.quant_config = quant_config self.model = Lfm3Model(vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")) if get_pp_group().is_last_rank: self.lm_head = ParallelLMHead( config.vocab_size, config.hidden_size, quant_config=quant_config, prefix=maybe_prefix(prefix, "lm_head"), ) if config.tie_word_embeddings: self.lm_head = self.lm_head.tie_weights(self.model.embed_tokens) else: self.lm_head = PPMissingLayer() self.logits_processor = LogitsProcessor(config.vocab_size) self.make_empty_intermediate_tensors = self.model.make_empty_intermediate_tensors def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: return self.model.embed_input_ids(input_ids) def forward( self, input_ids: torch.Tensor | None, positions: torch.Tensor, intermediate_tensors: IntermediateTensors | None = None, inputs_embeds: torch.Tensor | None = None, **kwargs, ) -> torch.Tensor | IntermediateTensors: return self.model(input_ids, positions, intermediate_tensors, inputs_embeds) def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor: return self.logits_processor(self.lm_head, hidden_states) def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: # Unknown checkpoint names make AutoWeightsLoader raise; missing ones are # checked below. `lm_head` is tied to `embed_tokens` and not in the checkpoint. loader = AutoWeightsLoader(self) loaded = loader.load_weights(weights, mapper=self.hf_to_vllm_mapper) # tied lm_head.weight is deduplicated into model.embed_tokens.weight here. # Quantized models get vLLM's own check instead (DefaultModelLoader), which knows # the parameters a checkpoint cannot carry (e.g. online-FP8 weight_scale). missing = sorted({name for name, _ in self.named_parameters()} - loaded) if missing and self.quant_config is None: raise ValueError( f"LFM3: {len(missing)} parameters not found in checkpoint: {missing[:20]}" ) return loaded