Skip to content

Commit a2e0ab7

Browse files
justinchubyCopilot
andauthored
Add LiquidAI LFM2.5 hybrid model support (#462)
## Summary - add `lfm2` support for `LiquidAI/LFM2.5-230M` following upstream Transformers - implement mixed double-gated short-convolution and QK-normalized GQA layers - use native ONNX Swish, `com.microsoft::CausalConvWithState`, and residual `SkipSimplifiedLayerNormalization` fusions - wire hybrid KV/convolution cache, weight preprocessing, registry/config extraction, CLI export, and ORT GenAI - add representative L1, real-checkpoint L2, synthetic/real-weight L3, and pinned L4/L5 coverage Upstream references: - Transformers LFM2: https://github.com/huggingface/transformers/tree/e91f7ef4d3c2b6b96b3a75d6568df581e22a7b84/src/transformers/models/lfm2 - checkpoint revision: https://huggingface.co/LiquidAI/LFM2.5-230M/tree/13a53837c4906b4f7405932532ba85d182bb013b - ORT GenAI LFM2 cache: https://github.com/microsoft/onnxruntime-genai/blob/main/src/models/kv_cache.cpp ## Architecture fidelity - 14 decoder layers: 8 convolution + 6 full GQA - convolution: `B*x -> causal depthwise conv -> C*conv -> out_proj` - MLP: `w2(Swish(w1(x)) * w3(x))` - attention: per-head Q/K RMSNorm before RoPE, 16 query / 8 KV heads - tied token embedding / LM head - `RMSNormalization(stash_type=FLOAT)` matches Transformers exactly: normalize in fp32, cast normalized activations to input dtype, then apply gamma ## Fused graph Weighted optimized graph counts: | dtype / EP | nodes | Swish | CausalConvWithState | SkipSimplifiedLayerNormalization | GroupQueryAttention | plain Conv | |---|---:|---:|---:|---:|---:|---:| | fp32 / default | 305 | 14 | 8 | 28 | 0 | 0 | | fp16 / CUDA | 290 | 14 | 8 | 28 | 6 | 0 | The fused causal-conv op uses the exact K-1 recurrent history, supports prefill/decode, executes on CUDA, and produced 0 Memcpy events in profiling. Cache-slot counting is graph-derived as `max(past_key_values layer index)+1`, covering KV-sharing and hybrid recurrent-cache models without a model-type condition. ## Validation ```powershell lintrunner -a # no issues python -m pytest src/mobius/integrations/ort_genai/genai_config_test.py src/mobius/integrations/ort_genai/auto_export_test.py -q # 152 passed python -m pytest src/mobius/models/lfm2_test.py src/mobius/components/_short_conv_test.py tests/build_graph_test.py tests/synthetic_parity_test.py -k lfm2 -q # 10 passed python -m pytest tests/integration_test.py -m integration_fast -k 'lfm2.5-230m' -q # 3 passed python -m pytest tests/e2e_golden_test.py -m 'golden or generation' --models lfm2 -q # 2 passed python -m pytest tests/ort_genai_test.py -m integration_slow -k lfm2 -q # 1 passed $env:MOBIUS_TEST_DEVICE='cuda' python -m pytest tests/integration_test.py -m integration -k 'lfm2.5-230m' -q # 3 passed (CUDA prefill, cached decode, 20-token generation) ``` CUDA profile for the fused convolution: 8 `CausalConvWithState` events, all assigned to `CUDAExecutionProvider`, 0 Memcpy. Outputs were finite. ## Quality checklist - [x] architecture/config/weight mapping and hybrid cache behavior - [x] L1/L2/L3 and pinned L4/L5 - [x] real-weight prefill, cached decode, and deterministic generation - [x] fp32/fp16/bf16 and actual CUDA EP validation - [x] ORT GenAI load/generation - [x] full `lintrunner -a` - [x] graph simplicity/fusion audit - [x] no protobuf APIs ## Remaining infrastructure limitations - Foundry Local and Olive are not installed in this environment; those deployment/quantization smoke tests remain deferred. --------- Signed-off-by: Justin Chu <[email protected]> Signed-off-by: justinchuby <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent 0ea089b commit a2e0ab7

25 files changed

Lines changed: 869 additions & 61 deletions

‎scripts/detect_affected_models.py‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -58,17 +58,19 @@ def classify_file(path: str) -> str:
5858
"""Classify a changed file path.
5959
6060
Returns one of: 'model', 'traceable', 'shared_infra',
61-
'test', 'other'.
61+
'test_config', 'test', 'other'.
6262
"""
6363
normalized = path.replace("\\", "/")
6464

6565
if not normalized.startswith("src/mobius/"):
6666
# Test infrastructure files that affect all models
67-
if normalized in (
68-
"tests/conftest.py",
69-
"tests/_test_configs.py",
70-
):
67+
if normalized == "tests/conftest.py":
7168
return "shared_infra"
69+
if normalized == "tests/_test_configs.py":
70+
# A config-only change is broad, but new model implementations also
71+
# add an entry here. Defer the run-all decision until model files
72+
# have been collected so those PRs can use import-graph scoping.
73+
return "test_config"
7274
if normalized.endswith("_test.py") or normalized.startswith("tests/"):
7375
return "test"
7476
return "other"
@@ -427,6 +429,7 @@ def detect_affected_models(
427429
"""
428430
affected: set[str] = set()
429431
run_all = False
432+
test_config_changed = False
430433

431434
# Classify files
432435
model_files: list[str] = []
@@ -436,6 +439,8 @@ def detect_affected_models(
436439
if category == "shared_infra":
437440
run_all = True
438441
break
442+
elif category == "test_config":
443+
test_config_changed = True
439444
elif category == "model":
440445
# Deleted model files could break dependents — run all
441446
full_path = _PROJECT_ROOT / path
@@ -453,6 +458,9 @@ def detect_affected_models(
453458
if run_all:
454459
return {"affected": [], "run_all": True}
455460

461+
if test_config_changed and not model_files:
462+
return {"affected": [], "run_all": True}
463+
456464
if not model_files and not traceable_files:
457465
return {"affected": [], "run_all": False}
458466

‎scripts/detect_affected_models_test.py‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def test_test_infra_conftest(self):
7272
assert classify_file("tests/conftest.py") == "shared_infra"
7373

7474
def test_test_infra_configs(self):
75-
assert classify_file("tests/_test_configs.py") == "shared_infra"
75+
assert classify_file("tests/_test_configs.py") == "test_config"
7676

7777
def test_readme(self):
7878
assert classify_file("README.md") == "other"
@@ -200,6 +200,29 @@ def test_configs_change_no_run_all(self):
200200
assert result["run_all"] is False
201201
assert result["affected"] == []
202202

203+
def test_test_configs_only_runs_all(self):
204+
result = detect_affected_models(["tests/_test_configs.py"])
205+
assert result == {"affected": [], "run_all": True}
206+
207+
def test_test_configs_with_model_uses_model_scope(self):
208+
result = detect_affected_models(
209+
[
210+
"tests/_test_configs.py",
211+
"src/mobius/models/lfm2.py",
212+
]
213+
)
214+
assert result["run_all"] is False
215+
assert result["affected"] == ["lfm2"]
216+
217+
def test_test_configs_with_unmapped_task_still_runs_all(self):
218+
result = detect_affected_models(
219+
[
220+
"tests/_test_configs.py",
221+
"src/mobius/tasks/_causal_lm.py",
222+
]
223+
)
224+
assert result == {"affected": [], "run_all": True}
225+
203226
def test_unrelated_file_no_affected(self):
204227
result = detect_affected_models(["README.md"])
205228
assert result["run_all"] is False

‎src/mobius/_configs/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
GraniteMoeHybridConfig,
4040
JambaConfig,
4141
JetMoeConfig,
42+
Lfm2Config,
4243
LongcatFlashConfig,
4344
Mamba2Config,
4445
MambaConfig,
@@ -106,6 +107,7 @@
106107
"GraniteMoeHybridConfig",
107108
"JambaConfig",
108109
"JetMoeConfig",
110+
"Lfm2Config",
109111
"LongcatFlashConfig",
110112
"Mamba2Config",
111113
"MambaConfig",

‎src/mobius/_configs/_base.py‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ def _resolve_hidden_act(config, model_type: str) -> str | None:
6565
or getattr(config, "afn", None)
6666
# LLaDA/OLMo expose the activation as ``activation_type`` (e.g. "silu").
6767
or getattr(config, "activation_type", None)
68-
or ("silu" if model_type in ("qwen", "chatglm") else None)
68+
or ("silu" if model_type in ("qwen", "chatglm", "lfm2") else None)
6969
# gelu_activation is a boolean (XLM) — must be after all string
7070
# attrs so it cannot override an explicit hidden_act.
7171
or ("gelu" if getattr(config, "gelu_activation", False) else None)
@@ -411,6 +411,10 @@ class ArchitectureConfig(BaseModelConfig):
411411
linear_num_key_heads: int | None = None
412412
linear_num_value_heads: int | None = None
413413

414+
# Double-gated short-convolution config (LFM2-style hybrid layers).
415+
short_conv_kernel: int = 3
416+
short_conv_bias: bool = False
417+
414418
rms_norm_eps: float = 1e-6
415419

416420
# Rotary embedding config.
@@ -707,6 +711,8 @@ def from_transformers(cls, config, parent_config=None) -> ArchitectureConfig:
707711
linear_value_head_dim=(getattr(config, "linear_value_head_dim", None)),
708712
linear_num_key_heads=(getattr(config, "linear_num_key_heads", None)),
709713
linear_num_value_heads=(getattr(config, "linear_num_value_heads", None)),
714+
short_conv_kernel=getattr(config, "conv_L_cache", 3),
715+
short_conv_bias=getattr(config, "conv_bias", False),
710716
pad_token_id=(getattr(config, "pad_token_id", 0)),
711717
model_type=model_type,
712718
bos_token_id=getattr(config, "bos_token_id", None),
@@ -794,6 +800,7 @@ def from_transformers(cls, config, parent_config=None) -> ArchitectureConfig:
794800
"gemma3_text",
795801
"gemma3n",
796802
"gemma3n_text",
803+
"lfm2",
797804
"flex_olmo",
798805
"olmoe",
799806
"olmo2",
@@ -1313,6 +1320,38 @@ def from_transformers(cls, config, parent_config=None) -> MuseGlimmerConfig:
13131320
)
13141321

13151322

1323+
@dataclasses.dataclass
1324+
class Lfm2Config(CausalLMConfig):
1325+
"""Configuration for LFM2's automatically adjusted feed-forward width."""
1326+
1327+
block_multiple_of: int = 256
1328+
block_ffn_dim_multiplier: float | int | None = 1.0
1329+
block_auto_adjust_ff_dim: bool = True
1330+
1331+
@property
1332+
def effective_intermediate_size(self) -> int:
1333+
"""The MLP width constructed by HuggingFace's ``Lfm2MLP``."""
1334+
intermediate_size = self.intermediate_size
1335+
if self.block_auto_adjust_ff_dim:
1336+
intermediate_size = int(2 * intermediate_size / 3)
1337+
if self.block_ffn_dim_multiplier is not None:
1338+
intermediate_size = int(self.block_ffn_dim_multiplier * intermediate_size)
1339+
intermediate_size = self.block_multiple_of * (
1340+
(intermediate_size + self.block_multiple_of - 1) // self.block_multiple_of
1341+
)
1342+
return intermediate_size
1343+
1344+
@classmethod
1345+
def from_transformers(cls, config, parent_config=None) -> Lfm2Config:
1346+
base = ArchitectureConfig.from_transformers(config, parent_config)
1347+
return cls(
1348+
**_shallow_fields(base),
1349+
block_multiple_of=getattr(config, "block_multiple_of", 256),
1350+
block_ffn_dim_multiplier=getattr(config, "block_ffn_dim_multiplier", 1.0),
1351+
block_auto_adjust_ff_dim=getattr(config, "block_auto_adjust_ff_dim", True),
1352+
)
1353+
1354+
13161355
@dataclasses.dataclass
13171356
class DFlashConfig(CausalLMConfig):
13181357
"""Configuration for the DFlash speculative-decoding draft model.

‎src/mobius/_registry.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
Gemma3nMultiModalConfig,
2929
Gemma4AssistantConfig,
3030
Gemma4Config,
31+
Lfm2Config,
3132
MMSConfig,
3233
MuseGlimmerConfig,
3334
WhisperConfig,
@@ -70,6 +71,7 @@
7071
HunYuanVLMoTModel,
7172
InternLM2CausalLMModel,
7273
LayerNormCausalLMModel,
74+
Lfm2CausalLMModel,
7375
LLaDAModel,
7476
Llama4CausalLMModel,
7577
MoECausalLMModel,
@@ -472,6 +474,7 @@ def _detect_fallback_registration(hf_config) -> ModelRegistration | None:
472474
"hunyuan_v1_dense": ModelRegistration(HunYuanV1DenseCausalLMModel),
473475
"internlm2": ModelRegistration(InternLM2CausalLMModel),
474476
"llama4_text": ModelRegistration(Llama4CausalLMModel),
477+
"lfm2": ModelRegistration(Lfm2CausalLMModel, config_class=Lfm2Config),
475478
"llada": ModelRegistration(LLaDAModel, task="masked-diffusion"),
476479
"modernbert-decoder": ModelRegistration(ModernBertDecoderModel),
477480
"mpt": ModelRegistration(MPTCausalLMModel),
@@ -979,6 +982,7 @@ def _create_default_registry() -> ModelRegistry:
979982
# --- Hybrid SSM+Attention ---
980983
"jamba": "ai21labs/Jamba-v0.1",
981984
"bamba": "ibm-fms/Bamba-9B",
985+
"lfm2": "LiquidAI/LFM2.5-230M",
982986

983987
# --- Multimodal ---
984988
"qwen2_vl": "Qwen/Qwen2-VL-2B-Instruct",
@@ -1229,6 +1233,7 @@ def _create_default_registry() -> ModelRegistry:
12291233
"llama": "llama",
12301234
"code_llama": "llama",
12311235
"llama4_text": "llama",
1236+
"lfm2": "lfm",
12321237
"mllama": "llama",
12331238
"mistral": "mistral",
12341239
"mistral3": "mistral",
@@ -1300,6 +1305,7 @@ def _create_default_registry() -> ModelRegistry:
13001305
"falcon_mamba": "ssm",
13011306
"jamba": "hybrid-ssm+attn",
13021307
"bamba": "hybrid-mamba2+attn",
1308+
"lfm2": "hybrid-conv+attn",
13031309
"qwen3_next": "moe+linear-attn",
13041310
}
13051311

‎src/mobius/_testing/torch_reference.py‎

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -288,19 +288,21 @@ def torch_forward(
288288
input_ids: np.ndarray,
289289
attention_mask: np.ndarray,
290290
position_ids: np.ndarray,
291-
past_key_values: list[tuple[np.ndarray, np.ndarray]] | None = None,
292-
) -> tuple[np.ndarray, list[tuple[np.ndarray, np.ndarray]]]:
291+
past_key_values: object | None = None,
292+
) -> tuple[np.ndarray, object]:
293293
"""Run a single forward pass on a HuggingFace causal LM model.
294294
295295
Args:
296296
model: HuggingFace model in eval mode.
297297
input_ids: [batch, seq_len] int64 numpy array.
298298
attention_mask: [batch, total_seq_len] int64 numpy array.
299299
position_ids: [batch, seq_len] int64 numpy array.
300-
past_key_values: Optional list of (key, value) numpy array tuples.
300+
past_key_values: Optional list of (key, value) numpy array tuples, or
301+
an opaque HuggingFace Cache for hybrid recurrent models.
301302
302303
Returns:
303-
Tuple of (logits as numpy, list of (key, value) numpy tuples).
304+
Tuple of logits and either a list of KV numpy tuples or an opaque
305+
HuggingFace Cache when model-specific recurrent state must be retained.
304306
"""
305307
import inspect
306308

@@ -323,16 +325,21 @@ def torch_forward(
323325
kwargs["position_ids"] = pos_t
324326

325327
if past_key_values is not None:
326-
from transformers.cache_utils import DynamicCache
327-
328-
cache = DynamicCache()
329-
for layer_idx, (k, v) in enumerate(past_key_values):
330-
cache.update(
331-
torch.from_numpy(k).to(device=device, dtype=dtype),
332-
torch.from_numpy(v).to(device=device, dtype=dtype),
333-
layer_idx,
334-
)
335-
kwargs["past_key_values"] = cache
328+
from transformers.cache_utils import Cache, DynamicCache
329+
330+
if isinstance(past_key_values, Cache):
331+
# Hybrid caches carry model-specific recurrent state (for example
332+
# LFM2 conv windows) that cannot be reconstructed from KV pairs.
333+
kwargs["past_key_values"] = past_key_values
334+
else:
335+
cache = DynamicCache()
336+
for layer_idx, (k, v) in enumerate(past_key_values):
337+
cache.update(
338+
torch.from_numpy(k).to(device=device, dtype=dtype),
339+
torch.from_numpy(v).to(device=device, dtype=dtype),
340+
layer_idx,
341+
)
342+
kwargs["past_key_values"] = cache
336343

337344
try:
338345
outputs = model(**kwargs)
@@ -351,6 +358,10 @@ def torch_forward(
351358
# Extract KV cache if available (Mamba models don't have it)
352359
present_kv: list[tuple[np.ndarray, np.ndarray]] = []
353360
cache = getattr(outputs, "past_key_values", None)
361+
layer_types = getattr(model.config, "layer_types", None) or []
362+
if "conv" in layer_types:
363+
return logits, cache
364+
354365
if cache is not None and hasattr(cache, "layers"):
355366
for layer_idx in range(len(cache.layers)):
356367
layer_cache = cache.layers[layer_idx]

‎src/mobius/components/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
"GatedRMSNorm",
3535
"Gemma3nAudioEncoder",
3636
"Gemma3nMultimodalEmbedder",
37+
"GatedShortConv",
3738
"ClippableLinear",
3839
"GroupNorm",
3940
"GQAContext",
@@ -282,6 +283,7 @@
282283
from mobius.components._sanm_attention import (
283284
SANMEncoderLayer as SANMEncoderLayer,
284285
)
286+
from mobius.components._short_conv import GatedShortConv
285287
from mobius.components._ssm import (
286288
JambaSelectiveScan as JambaSelectiveScan,
287289
)

0 commit comments

Comments
 (0)