Add LFM3-1.7B vLLM XPU plugin
Out-of-tree vLLM 0.32 plugin for LiquidAI LFM3 on Intel XPU: model, width-7 short-conv Triton kernels, Dockerfile, reference/API/bench tests, working notes and benchmark results. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
4e7a7ce903
26 files changed
+21423
No files matched your search
@@ -0,0 +1,29 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""Out-of-tree vLLM plugin for LiquidAI LFM3 (Lfm3ForCausalLM).
|
||||
|
||||
Loaded through the ``vllm.general_plugins`` entry point in every vLLM process
|
||||
(API server, EngineCore, workers).
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def register() -> None:
|
||||
from vllm import ModelRegistry
|
||||
|
||||
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")
|
||||
|
||||
# Lets transformers (and therefore vLLM) parse config.json with model_type "lfm3"
|
||||
# without --trust-remote-code.
|
||||
from transformers import AutoConfig
|
||||
|
||||
from .configuration_lfm3 import Lfm3Config
|
||||
|
||||
try:
|
||||
AutoConfig.register("lfm3", Lfm3Config)
|
||||
except ValueError:
|
||||
pass # already registered (e.g. a future transformers ships lfm3)
|
||||
@@ -0,0 +1,134 @@
|
||||
# Vendored verbatim from /models/LFM3-1.7B/configuration_lfm3.py (LiquidAI / HF, Apache-2.0)
|
||||
# so that config.json parses 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.utils import auto_docstring
|
||||
|
||||
|
||||
@auto_docstring(checkpoint="LiquidAI/LFM3-1.7B-Preview")
|
||||
@strict
|
||||
class Lfm3Config(PreTrainedConfig):
|
||||
r"""
|
||||
rope_parameters (`dict[str, RopeParameters]`, *optional*):
|
||||
RoPE parameters keyed by attention layer type, for example `{"full_attention": {"rope_type": "default",
|
||||
"rope_theta": 1000000.0, "partial_rotary_factor": 0.5}, "sliding_attention": {"rope_type": "default",
|
||||
"rope_theta": 10000.0}}`. `conv` layers do not use RoPE and have no entry. Full-attention layers rotate the
|
||||
first `partial_rotary_factor * head_dim` dimensions and leave the rest unrotated.
|
||||
conv_bias (`bool`, *optional*, defaults to `False`):
|
||||
Whether to use bias in the conv layers.
|
||||
conv_L_cache (`int`, *optional*, defaults to 7):
|
||||
L_cache dim in the conv layers.
|
||||
layer_types (`list[str]`, *optional*):
|
||||
Per-layer operator type, each one of `"full_attention"`, `"sliding_attention"` or `"conv"`. Defaults to the
|
||||
LFM3 pattern of a full-attention layer every fourth layer starting from the third, a sliding-attention layer
|
||||
in between, and gated short convolutions elsewhere.
|
||||
sliding_window (`int`, *optional*, defaults to 256):
|
||||
Sliding-window size of the `sliding_attention` layers.
|
||||
use_sandwich_norm (`bool`, *optional*, defaults to `True`):
|
||||
Whether to apply an RMSNorm to the operator and feed-forward outputs before they enter the residual stream.
|
||||
|
||||
```python
|
||||
>>> from transformers import Lfm3Model, Lfm3Config
|
||||
|
||||
>>> # Initializing a LFM3 model
|
||||
>>> configuration = Lfm3Config()
|
||||
|
||||
>>> # Initializing a model from the LFM3-1.7B style configuration
|
||||
>>> model = Lfm3Model(configuration)
|
||||
|
||||
>>> # Accessing the model configuration
|
||||
>>> configuration = model.config
|
||||
```
|
||||
"""
|
||||
|
||||
model_type = "lfm3"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
default_theta = 1000000.0
|
||||
|
||||
vocab_size: int = 128_000
|
||||
hidden_size: int = 2048
|
||||
intermediate_size: int = 7680
|
||||
num_hidden_layers: int = 24
|
||||
num_attention_heads: int = 16
|
||||
num_key_value_heads: int = 4
|
||||
max_position_embeddings: int = 128_000
|
||||
initializer_range: float = 0.02
|
||||
norm_eps: float = 0.00001
|
||||
use_cache: bool = True
|
||||
pad_token_id: int | None = 124_893
|
||||
bos_token_id: int | None = 124_894
|
||||
eos_token_id: int | list[int] | None = 124_900
|
||||
tie_word_embeddings: bool = True
|
||||
rope_parameters: dict | None = None
|
||||
conv_bias: bool = False
|
||||
conv_L_cache: int = 7
|
||||
layer_types: list[str] | None = None
|
||||
_attention_layer_types = ("full_attention", "sliding_attention")
|
||||
head_dim: int | None = None
|
||||
sliding_window: int | None = 256
|
||||
use_sandwich_norm: bool = True
|
||||
|
||||
def __post_init__(self, **kwargs):
|
||||
if self.head_dim is None:
|
||||
self.head_dim = self.hidden_size // self.num_attention_heads
|
||||
if self.rope_parameters is None:
|
||||
self.rope_parameters = {
|
||||
"full_attention": {"rope_type": "default", "rope_theta": 1_000_000.0, "partial_rotary_factor": 0.5},
|
||||
"sliding_attention": {"rope_type": "default", "rope_theta": 10_000.0},
|
||||
}
|
||||
if self.layer_types is None:
|
||||
self.layer_types = [
|
||||
"full_attention" if i % 4 == 2 else "sliding_attention" if i % 4 == 0 and i > 0 else "conv"
|
||||
for i in range(self.num_hidden_layers)
|
||||
]
|
||||
|
||||
self.tie_word_embeddings = kwargs.pop("tie_embedding", self.tie_word_embeddings)
|
||||
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 "sliding_attention" in self.layer_types and self.sliding_window is None:
|
||||
raise ValueError("`layer_types` has `sliding_attention` layers but `sliding_window` is None.")
|
||||
missing_rope = [
|
||||
layer_type
|
||||
for layer_type in self._attention_layer_types
|
||||
if layer_type in self.layer_types and layer_type not in self.rope_parameters
|
||||
]
|
||||
if missing_rope:
|
||||
raise ValueError(f"`rope_parameters` has no entry for the {missing_rope} layers in `layer_types`.")
|
||||
for layer_type, rope_params in self.rope_parameters.items():
|
||||
if not isinstance(rope_params, dict):
|
||||
continue
|
||||
if (
|
||||
rope_params.get("rope_type", "default") in ("dynamic", "longrope")
|
||||
and rope_params.get("partial_rotary_factor", 1.0) < 1
|
||||
):
|
||||
raise ValueError(
|
||||
f"`{rope_params['rope_type']}` RoPE recomputes its frequencies during the forward pass over the "
|
||||
f"rotated dimension only and cannot keep LFM3's partial rotation on `{layer_type}` layers."
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["Lfm3Config"]
|
||||
@@ -0,0 +1,343 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""Causal depthwise conv1d of arbitrary width for LFM3's short-conv layers.
|
||||
|
||||
vLLM's Triton ``causal_conv1d_fn`` / ``causal_conv1d_update`` are hand-unrolled for
|
||||
widths <= 4 / <= 6, and LFM3 uses width 7. This module provides:
|
||||
|
||||
* ``*_torch``: vectorized PyTorch implementations (no per-sequence Python loop, no
|
||||
host sync), used as reference and fallback;
|
||||
* ``*_triton``: Triton kernels (work on XPU through triton-xpu), the default.
|
||||
|
||||
Layouts (token-major, like vLLM's ShortConv after ``in_proj``):
|
||||
x (num_tokens, dim)
|
||||
weight (dim, width)
|
||||
conv_state (num_blocks, width - 1, dim) -- vLLM's "SD" conv state layout; any
|
||||
strides are accepted, so a transposed "DS" cache works as well.
|
||||
Row ``width - 2`` holds the most recent input.
|
||||
All accumulation is done in fp32.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import torch
|
||||
|
||||
try:
|
||||
import triton
|
||||
import triton.language as tl
|
||||
|
||||
HAS_TRITON = True
|
||||
except ImportError: # pragma: no cover
|
||||
HAS_TRITON = False
|
||||
|
||||
# LFM3_CONV_IMPL=torch forces the PyTorch path (debugging / kernel A/B tests).
|
||||
_IMPL = os.environ.get("LFM3_CONV_IMPL", "triton")
|
||||
|
||||
|
||||
def use_triton() -> bool:
|
||||
return HAS_TRITON and _IMPL == "triton"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# PyTorch implementations
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _prefill_source_indices(
|
||||
query_start_loc: torch.Tensor,
|
||||
num_tokens: int,
|
||||
state_len: int,
|
||||
width: int,
|
||||
):
|
||||
"""Per-token indices into ``cat([initial_states.flatten(0, 1), x])``.
|
||||
|
||||
Returns (tap_idx (num_tokens, width), new_state_idx (num_seqs, state_len)).
|
||||
"""
|
||||
device = query_start_loc.device
|
||||
qsl = query_start_loc.long()
|
||||
num_seqs = qsl.numel() - 1
|
||||
lens = qsl[1:] - qsl[:-1]
|
||||
seq_id = torch.repeat_interleave(
|
||||
torch.arange(num_seqs, device=device), lens, output_size=num_tokens
|
||||
)
|
||||
tok = torch.arange(num_tokens, device=device)
|
||||
pos = tok - qsl[seq_id]
|
||||
x_base = num_seqs * state_len
|
||||
|
||||
# tap k reads relative position p = pos + k - (width - 1)
|
||||
rel = torch.arange(width, device=device) - (width - 1)
|
||||
p = pos[:, None] + rel[None, :]
|
||||
tap_idx = torch.where(
|
||||
p >= 0,
|
||||
x_base + tok[:, None] + rel[None, :],
|
||||
seq_id[:, None] * state_len + state_len + p,
|
||||
)
|
||||
|
||||
# the new state is the last state_len inputs of (initial_state ++ x_seq)
|
||||
q = lens[:, None] - state_len + torch.arange(state_len, device=device)[None, :]
|
||||
seqs = torch.arange(num_seqs, device=device)[:, None]
|
||||
new_state_idx = torch.where(
|
||||
q >= 0, x_base + qsl[:-1, None] + q, seqs * state_len + state_len + q
|
||||
)
|
||||
return tap_idx, new_state_idx
|
||||
|
||||
|
||||
def causal_conv1d_prefill_torch(
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
bias: torch.Tensor | None,
|
||||
conv_state: torch.Tensor,
|
||||
query_start_loc: torch.Tensor,
|
||||
state_indices: torch.Tensor,
|
||||
has_initial_state: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
num_tokens, dim = x.shape
|
||||
width = weight.shape[1]
|
||||
state_len = width - 1
|
||||
num_seqs = query_start_loc.numel() - 1
|
||||
slots = state_indices.long()
|
||||
|
||||
init = conv_state[slots].to(x.dtype) # (S, L, D)
|
||||
init = init * has_initial_state.view(-1, 1, 1).to(init.dtype)
|
||||
src = torch.cat([init.reshape(num_seqs * state_len, dim), x], dim=0)
|
||||
|
||||
tap_idx, new_state_idx = _prefill_source_indices(
|
||||
query_start_loc, num_tokens, state_len, width
|
||||
)
|
||||
w = weight.float()
|
||||
out = torch.zeros(num_tokens, dim, dtype=torch.float32, device=x.device)
|
||||
for k in range(width):
|
||||
out += src[tap_idx[:, k]].float() * w[:, k]
|
||||
if bias is not None:
|
||||
out += bias.float()
|
||||
|
||||
conv_state[slots] = src[new_state_idx].to(conv_state.dtype)
|
||||
return out.to(x.dtype)
|
||||
|
||||
|
||||
def causal_conv1d_decode_torch(
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
bias: torch.Tensor | None,
|
||||
conv_state: torch.Tensor,
|
||||
state_indices: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
# padded rows (PAD_SLOT_ID = -1) are redirected to the null block 0
|
||||
slots = state_indices.long().clamp_min(0)
|
||||
window = torch.cat([conv_state[slots].to(x.dtype), x[:, None, :]], dim=1)
|
||||
out = torch.einsum("nkd,dk->nd", window.float(), weight.float())
|
||||
if bias is not None:
|
||||
out += bias.float()
|
||||
conv_state[slots] = window[:, 1:].to(conv_state.dtype)
|
||||
return out.to(x.dtype)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Triton implementations
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
if HAS_TRITON:
|
||||
|
||||
@triton.jit
|
||||
def _prefill_kernel(
|
||||
X, W, BIAS, STATE, SLOTS, HAS_INIT, QSL, SEQ_ID, Y,
|
||||
T, D,
|
||||
sx_t, sx_d,
|
||||
sw_d, sw_k,
|
||||
ss_b, ss_l, ss_d,
|
||||
sy_t, sy_d,
|
||||
K: tl.constexpr,
|
||||
HAS_BIAS: tl.constexpr,
|
||||
BLOCK_T: tl.constexpr,
|
||||
BLOCK_D: tl.constexpr,
|
||||
):
|
||||
t = tl.program_id(0) * BLOCK_T + tl.arange(0, BLOCK_T)
|
||||
d = tl.program_id(1) * BLOCK_D + tl.arange(0, BLOCK_D)
|
||||
tm = t < T
|
||||
dm = d < D
|
||||
seq = tl.load(SEQ_ID + t, mask=tm, other=0)
|
||||
start = tl.load(QSL + seq, mask=tm, other=0)
|
||||
pos = t - start
|
||||
slot = tl.load(SLOTS + seq, mask=tm, other=0).to(tl.int64)
|
||||
init = tl.load(HAS_INIT + seq, mask=tm, other=0) != 0
|
||||
|
||||
acc = tl.zeros((BLOCK_T, BLOCK_D), dtype=tl.float32)
|
||||
for k in tl.static_range(K):
|
||||
p = pos + (k - (K - 1))
|
||||
from_x = p >= 0
|
||||
from_s = (p < 0) & init
|
||||
xv = tl.load(
|
||||
X + (t + (k - (K - 1)))[:, None].to(tl.int64) * sx_t + d[None, :] * sx_d,
|
||||
mask=(tm & from_x)[:, None] & dm[None, :],
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
sv = tl.load(
|
||||
STATE + slot[:, None] * ss_b + (K - 1 + p)[:, None] * ss_l + d[None, :] * ss_d,
|
||||
mask=(tm & from_s)[:, None] & dm[None, :],
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
w = tl.load(W + d * sw_d + k * sw_k, mask=dm, other=0.0).to(tl.float32)
|
||||
acc += (xv + sv) * w[None, :]
|
||||
if HAS_BIAS:
|
||||
acc += tl.load(BIAS + d, mask=dm, other=0.0).to(tl.float32)[None, :]
|
||||
tl.store(
|
||||
Y + t[:, None].to(tl.int64) * sy_t + d[None, :] * sy_d,
|
||||
acc.to(Y.dtype.element_ty),
|
||||
mask=tm[:, None] & dm[None, :],
|
||||
)
|
||||
|
||||
@triton.jit
|
||||
def _prefill_state_kernel(
|
||||
X, STATE, SLOTS, HAS_INIT, QSL,
|
||||
D,
|
||||
sx_t, sx_d,
|
||||
ss_b, ss_l, ss_d,
|
||||
L: tl.constexpr,
|
||||
L_PAD: tl.constexpr,
|
||||
BLOCK_D: tl.constexpr,
|
||||
):
|
||||
s = tl.program_id(0)
|
||||
d = tl.program_id(1) * BLOCK_D + tl.arange(0, BLOCK_D)
|
||||
dm = d < D
|
||||
l = tl.arange(0, L_PAD)
|
||||
lm = l < L
|
||||
start = tl.load(QSL + s)
|
||||
length = tl.load(QSL + s + 1) - start
|
||||
slot = tl.load(SLOTS + s).to(tl.int64)
|
||||
init = tl.load(HAS_INIT + s) != 0
|
||||
# new row l holds relative position q = length - L + l
|
||||
q = length - L + l
|
||||
from_x = q >= 0
|
||||
xv = tl.load(
|
||||
X + (start + q)[:, None].to(tl.int64) * sx_t + d[None, :] * sx_d,
|
||||
mask=(lm & from_x)[:, None] & dm[None, :],
|
||||
other=0.0,
|
||||
)
|
||||
sv = tl.load(
|
||||
STATE + slot * ss_b + (L + q)[:, None] * ss_l + d[None, :] * ss_d,
|
||||
mask=(lm & (q < 0) & init)[:, None] & dm[None, :],
|
||||
other=0.0,
|
||||
)
|
||||
new = tl.where(from_x[:, None], xv, sv)
|
||||
# all loads above happen before the store: in-place update is safe
|
||||
tl.store(
|
||||
STATE + slot * ss_b + l[:, None] * ss_l + d[None, :] * ss_d,
|
||||
new.to(STATE.dtype.element_ty),
|
||||
mask=lm[:, None] & dm[None, :],
|
||||
)
|
||||
|
||||
@triton.jit
|
||||
def _decode_kernel(
|
||||
X, W, BIAS, STATE, SLOTS, Y,
|
||||
D,
|
||||
sx_n, sx_d,
|
||||
sw_d, sw_k,
|
||||
ss_b, ss_l, ss_d,
|
||||
sy_n, sy_d,
|
||||
L: tl.constexpr,
|
||||
L_PAD: tl.constexpr,
|
||||
HAS_BIAS: tl.constexpr,
|
||||
BLOCK_D: tl.constexpr,
|
||||
):
|
||||
n = tl.program_id(0)
|
||||
d = tl.program_id(1) * BLOCK_D + tl.arange(0, BLOCK_D)
|
||||
dm = d < D
|
||||
l = tl.arange(0, L_PAD)
|
||||
lm = l < L
|
||||
slot = tl.load(SLOTS + n).to(tl.int64)
|
||||
slot = tl.where(slot < 0, 0, slot) # PAD_SLOT_ID -> null block
|
||||
|
||||
base = STATE + slot * ss_b + d[None, :] * ss_d
|
||||
old = tl.load(base + l[:, None] * ss_l, mask=lm[:, None] & dm[None, :], other=0.0)
|
||||
nxt = tl.load(
|
||||
base + (l + 1)[:, None] * ss_l,
|
||||
mask=((l + 1) < L)[:, None] & dm[None, :],
|
||||
other=0.0,
|
||||
)
|
||||
x = tl.load(X + n * sx_n + d * sx_d, mask=dm, other=0.0)
|
||||
|
||||
w_state = tl.load(
|
||||
W + d[None, :] * sw_d + l[:, None] * sw_k,
|
||||
mask=lm[:, None] & dm[None, :],
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
w_last = tl.load(W + d * sw_d + L * sw_k, mask=dm, other=0.0).to(tl.float32)
|
||||
acc = tl.sum(old.to(tl.float32) * w_state, axis=0) + x.to(tl.float32) * w_last
|
||||
if HAS_BIAS:
|
||||
acc += tl.load(BIAS + d, mask=dm, other=0.0).to(tl.float32)
|
||||
|
||||
new = tl.where((l == L - 1)[:, None], x[None, :].to(old.dtype), nxt)
|
||||
tl.store(base + l[:, None] * ss_l, new, mask=lm[:, None] & dm[None, :])
|
||||
tl.store(Y + n * sy_n + d * sy_d, acc.to(Y.dtype.element_ty), mask=dm)
|
||||
|
||||
|
||||
def causal_conv1d_prefill_triton(
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
bias: torch.Tensor | None,
|
||||
conv_state: torch.Tensor,
|
||||
query_start_loc: torch.Tensor,
|
||||
state_indices: torch.Tensor,
|
||||
has_initial_state: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
num_tokens, dim = x.shape
|
||||
width = weight.shape[1]
|
||||
state_len = width - 1
|
||||
num_seqs = query_start_loc.numel() - 1
|
||||
lens = query_start_loc[1:] - query_start_loc[:-1]
|
||||
seq_id = torch.repeat_interleave(
|
||||
torch.arange(num_seqs, device=x.device, dtype=torch.int32),
|
||||
lens,
|
||||
output_size=num_tokens,
|
||||
)
|
||||
has_init = has_initial_state.to(torch.int8)
|
||||
out = torch.empty_like(x)
|
||||
BLOCK_T, BLOCK_D = 32, 64
|
||||
grid = (triton.cdiv(num_tokens, BLOCK_T), triton.cdiv(dim, BLOCK_D))
|
||||
_prefill_kernel[grid](
|
||||
x, weight, bias, conv_state, state_indices, has_init, query_start_loc,
|
||||
seq_id, out,
|
||||
num_tokens, dim,
|
||||
*x.stride(), *weight.stride(), *conv_state.stride(), *out.stride(),
|
||||
K=width, HAS_BIAS=bias is not None, BLOCK_T=BLOCK_T, BLOCK_D=BLOCK_D,
|
||||
)
|
||||
# the conv above read the old states; now overwrite them
|
||||
_prefill_state_kernel[(num_seqs, triton.cdiv(dim, 256))](
|
||||
x, conv_state, state_indices, has_init, query_start_loc,
|
||||
dim,
|
||||
*x.stride(), *conv_state.stride(),
|
||||
L=state_len, L_PAD=triton.next_power_of_2(state_len), BLOCK_D=256,
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def causal_conv1d_decode_triton(
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
bias: torch.Tensor | None,
|
||||
conv_state: torch.Tensor,
|
||||
state_indices: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
num_rows, dim = x.shape
|
||||
state_len = weight.shape[1] - 1
|
||||
out = torch.empty_like(x)
|
||||
BLOCK_D = 256
|
||||
_decode_kernel[(num_rows, triton.cdiv(dim, BLOCK_D))](
|
||||
x, weight, bias, conv_state, state_indices, out,
|
||||
dim,
|
||||
*x.stride(), *weight.stride(), *conv_state.stride(), *out.stride(),
|
||||
L=state_len, L_PAD=triton.next_power_of_2(state_len),
|
||||
HAS_BIAS=bias is not None, BLOCK_D=BLOCK_D,
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def causal_conv1d_prefill(*args, **kwargs) -> torch.Tensor:
|
||||
if use_triton():
|
||||
return causal_conv1d_prefill_triton(*args, **kwargs)
|
||||
return causal_conv1d_prefill_torch(*args, **kwargs)
|
||||
|
||||
|
||||
def causal_conv1d_decode(*args, **kwargs) -> torch.Tensor:
|
||||
if use_triton():
|
||||
return causal_conv1d_decode_triton(*args, **kwargs)
|
||||
return causal_conv1d_decode_torch(*args, **kwargs)
|
||||
@@ -0,0 +1,539 @@
|
||||
# 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.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
|
||||
missing = sorted({name for name, _ in self.named_parameters()} - loaded)
|
||||
if missing:
|
||||
raise ValueError(
|
||||
f"LFM3: {len(missing)} parameters not found in checkpoint: {missing[:20]}"
|
||||
)
|
||||
return loaded
|
||||
Reference in new issue
Block a user