Skip to content

Commit b2b8213

Browse files
justinchubyCopilot
andauthored
Add LFM2.5-VL multimodal support (#507)
## Summary Adds production Mobius support for [`LiquidAI/LFM2.5-VL-3B`](https://huggingface.co/LiquidAI/LFM2.5-VL-3B) (`model_type=lfm2_vl`) at immutable revision `5a414ead75d45db003906d06fb62bd5b6846cec0`. The implementation exports a standardized three-model package: - `vision_encoder`: SigLIP2 NaFlex patch embeddings, dynamic antialiased position interpolation, masked vision attention, pixel-unshuffle, and the LFM2-VL projector - `embedding`: token embedding plus image-feature substitution, including zero-image cached decode - `decoder`: existing LFM2 hybrid short-convolution/full-attention decoder with convolution and KV cache reuse It also pins revisions through configuration, weights, tokenizer/processor assets, CLI/runtime export, and golden generation; adds ORT GenAI metadata for hybrid cache names/layer types; and preserves the upstream adaptive-tiling processor contract. ## Architecture and integration checklist - [x] Extract composite LFM2-VL text, NaFlex vision, and projector configuration - [x] Register `lfm2_vl` with the `lfm2-vl` three-model task - [x] Use public Mobius components and `onnx_ir` only (no protobuf APIs) - [x] Route all decoder, vision, projector, tied LM-head, and embedding weights - [x] Emit standardized `decoder`, `vision_encoder`, and `embedding` keys - [x] Preserve `pixel_values`, `pixel_attention_mask`, and `spatial_shapes` processor inputs - [x] Emit hybrid `layer_types`, convolution cache names/size, image token ID, and `past_present_share_buffer=false` - [x] Add immutable `--revision` CLI plumbing across config, weights, assets, processor, and golden calls - [x] Add real nonzero-image L4/L5 goldens using `pipeline-cat-chonk.jpeg` - [x] Lower `CausalConvWithState` to its standard Conv function body only for CUDA-optimized exports; retain the portable local function for default/CPU ## Validation evidence Environment: Windows, NVIDIA RTX A1000 8 GB (driver 573.44), ONNX Runtime 1.26.0, ONNX Runtime GenAI 0.15.2, Transformers 5.14.1. ### L1 / weight alignment / L3 synthetic parity ```powershell $env:PYTHONPATH=(Resolve-Path src).Path python -m pytest src\mobius\models\lfm2_test.py src\mobius\models\lfm2_vl_test.py src\mobius\components\_siglip2_naflex_test.py tests\build_graph_test.py tests\weight_alignment_test.py -q -k "lfm2 or naflex" --tb=short ``` Result after rebase: **30 passed**. This includes ONNX graph/checker coverage, complete three-package Hugging Face weight alignment, NaFlex vision/projector full-tensor parity (`rtol=atol=1e-4`), embedding fusion, and full-logit LFM2 prefill plus cached-decode parity for both portable and CUDA-optimized decoder graphs (`rtol=atol=1e-4`). The CUDA structural regression also requires standard `Conv` and no remaining `CausalConvWithState` node. ### L2 / YAML schema ```powershell python -m pytest tests\yaml_schema_test.py -q --tb=short python -m pytest tests\yaml_schema_test.py tests\arch_validation_test.py -q -k "lfm2_5 or lfm2_vl" --tb=short ``` Results: **247 passed** schema tests; **2 passed** targeted schema/full pinned-config graph tests. ### L4 CUDA-specialized prefill (bf16) ```powershell $env:MOBIUS_TEST_DEVICE='cuda' $env:MOBIUS_TEST_BUILD_EP='cuda' python -m pytest tests\e2e_golden_test.py -m golden -k "lfm2_5-vl-3b" -v --tb=short -s ``` Result after rebase: **1 passed** in 250.79s. Executes real processor → CUDA-optimized ONNX NaFlex vision/projector → ONNX embedding fusion → CUDA-optimized ONNX hybrid decoder on CUDAExecutionProvider and matches the pinned upstream prefill golden. ### L5 CUDA-specialized cached deterministic generation (bf16) ```powershell $env:MOBIUS_TEST_DEVICE='cuda' $env:MOBIUS_TEST_BUILD_EP='cuda' python -m pytest tests\e2e_golden_test.py -m generation -k "lfm2_5-vl-3b" -v --tb=short -s ``` Result after rebase: **1 passed** in 288.64s. Exact 15-token cached decode: ```text [41, 10299, 5140, 355, 11759, 383, 278, 10409, 415, 267, 34204, 5097, 435, 22, 124900] ``` Decoded: `A brown cat is walking on the snow with a fence behind it.` ### Float16 CUDA parity The same L4 and L5 commands with the case dtype temporarily set to `float16` both passed (**244.35s** and **244.15s**) with the same exact 15-token sequence. The committed canonical golden case remains bf16. ### CLI and runtime metadata ```powershell python -m mobius build --model 'LiquidAI/LFM2.5-VL-3B' --revision '5a414ead75d45db003906d06fb62bd5b6846cec0' --dtype bf16 --ep cuda --runtime ort-genai <output-dir> ``` Result: successful export of `decoder/model.onnx`, `vision_encoder/model.onnx`, `embedding/model.onnx`, `genai_config.json`, pinned tokenizer/chat-template assets, and upstream `processor_config.json`. Intrinsic checks verified all referenced files, 30 hybrid layer types, convolution cache size 2, NaFlex input mapping, token IDs, and non-shared cache buffers. ### Formatting, lint, and broad regression ```powershell lintrunner format -r origin/main --output oneline lintrunner -a -r origin/main --output oneline python -m pytest tests\build_graph_test.py tests\cli_test.py src -q -k "not phi4mm and not apply_weights_unknown" --tb=short -n auto ``` Result after rebase: lint **passed with no findings**; broad regression **4059 passed, 58 skipped, 3 failed**. The three failures are unrelated existing numerical tests: one GGUF Q4_0 dequantization parity case and two decomposed softcap-attention parity cases. No LFM2-VL, revision, or runtime-metadata test failed. ## Explicit waivers / runtime notes - **ORT GenAI 0.15.2 model loading:** exported metadata is internally valid, but the released runtime rejects the required NaFlex `pixel_attention_mask` vision input as an unknown schema key. Current ORT GenAI cannot represent LFM2-VL adaptive patch masking; direct three-stage ONNX execution is fully covered by CUDA L4/L5. The upstream `processor_config.json` is intentionally preserved rather than emitting incorrect simplified transforms. - **Real fp32 CUDA checkpoint:** the 3B checkpoint requires over 12 GB for fp32 parameters before activations, exceeding the available 8 GB GPU. Full-tensor fp32 synthetic vision/projector and decoder prefill/cached-decode parity passes; real-checkpoint CUDA gates cover bf16 and fp16. ## Review - [x] Independent specialist review completed for the implementation - [x] Follow-up review completed for CUDA lowering, EP scoping, cached-decode parity, and post-rebase integration paths - [x] No high-confidence correctness, architecture, weight-routing, revision, cache, or metadata findings remained --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent 66e9c5e commit b2b8213

30 files changed

Lines changed: 3678 additions & 56 deletions

‎scripts/generate_golden.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,7 @@ def _generate_causal_lm(case: TestCase, json_path: Path, device: str) -> None:
263263
case.model_id,
264264
dtype=dtype_map[case.dtype],
265265
device=device,
266+
revision=case.revision,
266267
)
267268
else:
268269
model, tokenizer = load_torch_model(
@@ -471,7 +472,10 @@ def _generate_vision_language(case: TestCase, json_path: Path, device: str) -> N
471472
}
472473
torch_dtype = dtype_map.get(case.dtype, torch.float32)
473474
model, _tokenizer, processor = load_torch_multimodal_model(
474-
case.model_id, dtype=torch_dtype, device=device
475+
case.model_id,
476+
dtype=torch_dtype,
477+
device=device,
478+
revision=case.revision,
475479
)
476480

477481
# Load real image/video media from testdata/.
@@ -883,7 +887,9 @@ def _load_speech_language_model(case: TestCase, device: str) -> tuple:
883887
)
884888

885889
model, _tokenizer, processor = load_torch_multimodal_model(
886-
case.model_id, device=device
890+
case.model_id,
891+
device=device,
892+
revision=case.revision,
887893
)
888894
forward_model = model
889895

‎src/mobius/__main__.py‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,7 @@ def _resolve_static_cache_task(model_type: str) -> ModelTask:
247247
else:
248248
static_cache_params = None
249249
trust_remote_code = args.trust_remote_code
250+
revision = args.revision
250251
output_dir = args.output_dir
251252
os.makedirs(output_dir, exist_ok=True)
252253
dtype_override = resolve_dtype(args.dtype)
@@ -259,7 +260,7 @@ def _resolve_static_cache_task(model_type: str) -> ModelTask:
259260
# central build() validation reject a diffusers/unsupported repo rather
260261
# than silently exporting a diffusion pipeline and ignoring the flag.
261262
if args.model and not args.config and not args.text_only:
262-
pipeline_index = _load_diffusers_pipeline_index(args.model)
263+
pipeline_index = _load_diffusers_pipeline_index(args.model, revision=revision)
263264
if pipeline_index is not None:
264265
print(
265266
f"Detected diffusers pipeline: {pipeline_index.get('_class_name', 'Unknown')}"
@@ -275,6 +276,7 @@ def _resolve_static_cache_task(model_type: str) -> ModelTask:
275276
pipeline_components = {max(roots, key=len)} if roots else {component_filter}
276277
pkg = build_diffusers_pipeline(
277278
args.model,
279+
revision=revision,
278280
dtype=dtype_override,
279281
load_weights=load_weights,
280282
components=pipeline_components,
@@ -342,7 +344,9 @@ def _resolve_static_cache_task(model_type: str) -> ModelTask:
342344
import transformers
343345

344346
hf_config = transformers.AutoConfig.from_pretrained(
345-
model_id_or_path, trust_remote_code=trust_remote_code
347+
model_id_or_path,
348+
trust_remote_code=trust_remote_code,
349+
revision=revision,
346350
)
347351
task = _resolve_static_cache_task(getattr(hf_config, "model_type", ""))
348352

@@ -351,6 +355,7 @@ def _resolve_static_cache_task(model_type: str) -> ModelTask:
351355
task=task,
352356
dtype=dtype_override,
353357
load_weights=load_weights,
358+
revision=revision,
354359
trust_remote_code=trust_remote_code,
355360
execution_provider=execution_provider,
356361
text_only=args.text_only,
@@ -424,6 +429,7 @@ def _save_package(
424429
ep=ep,
425430
local_config_dir=local_config_dir,
426431
trust_remote_code=getattr(args, "trust_remote_code", False),
432+
revision=getattr(args, "revision", None),
427433
)
428434
for name, path in artifacts.items():
429435
print(f" {name}: {path}")
@@ -730,6 +736,14 @@ def main(argv: list[str] | None = None) -> None:
730736
action="store_true",
731737
help="Trust remote code when loading the HuggingFace model config.",
732738
)
739+
build_parser.add_argument(
740+
"--revision",
741+
default=None,
742+
help=(
743+
"Immutable HuggingFace revision used for config, weights, tokenizer, "
744+
"and processor assets."
745+
),
746+
)
733747
build_parser.add_argument(
734748
"--dtype",
735749
choices=sorted(DTYPE_MAP),

‎src/mobius/_configs/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
JambaConfig,
4141
JetMoeConfig,
4242
Lfm2Config,
43+
Lfm2VlConfig,
4344
LongcatFlashConfig,
4445
Mamba2Config,
4546
MambaConfig,
@@ -112,6 +113,7 @@
112113
"JambaConfig",
113114
"JetMoeConfig",
114115
"Lfm2Config",
116+
"Lfm2VlConfig",
115117
"LongcatFlashConfig",
116118
"Mamba2Config",
117119
"MambaConfig",

‎src/mobius/_configs/_base.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1454,6 +1454,44 @@ def from_transformers(cls, config, parent_config=None) -> Lfm2Config:
14541454
)
14551455

14561456

1457+
@dataclasses.dataclass
1458+
class Lfm2VlConfig(Lfm2Config):
1459+
"""Configuration for LiquidAI LFM2-VL (SigLIP2 NaFlex + LFM2 decoder).
1460+
1461+
The HuggingFace ``Lfm2VlConfig`` is composite: the LFM2 decoder fields
1462+
live under ``text_config`` (which is what ``config`` refers to here) and
1463+
the projector knobs sit on the top-level composite, reachable through
1464+
``parent_config``. The SigLIP2 NaFlex geometry is extracted separately
1465+
into :attr:`ArchitectureConfig.vision`.
1466+
"""
1467+
1468+
downsample_factor: int = 2
1469+
projector_hidden_act: str = "gelu"
1470+
projector_hidden_size: int = 2048
1471+
projector_bias: bool = True
1472+
projector_use_layernorm: bool = False
1473+
1474+
@classmethod
1475+
def from_transformers(cls, config, parent_config=None) -> Lfm2VlConfig:
1476+
base = Lfm2Config.from_transformers(config, parent_config)
1477+
# Projector fields are top-level on the composite config.
1478+
source = parent_config if parent_config is not None else config
1479+
result = cls(
1480+
**_shallow_fields(base),
1481+
downsample_factor=getattr(source, "downsample_factor", 2),
1482+
projector_hidden_act=getattr(source, "projector_hidden_act", "gelu"),
1483+
projector_hidden_size=getattr(source, "projector_hidden_size", base.hidden_size),
1484+
projector_bias=getattr(source, "projector_bias", True),
1485+
projector_use_layernorm=getattr(source, "projector_use_layernorm", False),
1486+
)
1487+
# Preserve the composite identity; ``config`` is the nested LFM2 text
1488+
# config and would otherwise report ``model_type="lfm2"``.
1489+
result.model_type = "lfm2_vl"
1490+
if result.image_token_id is None:
1491+
result.image_token_id = getattr(source, "image_token_id", None)
1492+
return result
1493+
1494+
14571495
@dataclasses.dataclass
14581496
class DFlashConfig(CausalLMConfig):
14591497
"""Configuration for the DFlash speculative-decoding draft model.

‎src/mobius/_configs/per_model/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
_gemma4_unified_vision,
3232
_hunyuan_vl_mot_vision,
3333
_internvl_vision,
34+
_lfm2_vl_vision,
3435
_mage_vl_vision,
3536
_minicpmv4_6_vision,
3637
_muse_glimmer_vision,
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
4+
"""LiquidAI LFM2-VL vision extractor hook (SigLIP2 NaFlex tower)."""
5+
6+
from __future__ import annotations
7+
8+
import math
9+
10+
from mobius._configs._extractors import register_vision_hook
11+
12+
# SigLIP2 NaFlex checkpoints omit ``image_size`` because the tower accepts any
13+
# aspect ratio. The learned position table is still a square grid, so the
14+
# native training resolution is ``sqrt(num_patches) * patch_size``.
15+
_DEFAULT_NUM_PATCHES = 256
16+
17+
18+
@register_vision_hook("lfm2")
19+
def _lfm2_vl_vision(config, parent_config, model_type: str, fields: dict):
20+
"""Add the NaFlex-specific geometry the generic extractor cannot infer."""
21+
if getattr(parent_config, "model_type", None) != "lfm2_vl":
22+
return None
23+
24+
vision = getattr(parent_config, "vision_config", None)
25+
if vision is None:
26+
return None
27+
28+
num_patches = getattr(vision, "num_patches", None) or _DEFAULT_NUM_PATCHES
29+
patch_size = getattr(vision, "patch_size", 16)
30+
fields.update(
31+
# HF stores the position-table size as ``num_patches``; mobius keeps
32+
# learned 2D position grids under ``num_position_embeddings``.
33+
num_position_embeddings=num_patches,
34+
hidden_act=getattr(vision, "hidden_act", "gelu_pytorch_tanh"),
35+
image_size=patch_size * math.isqrt(num_patches),
36+
image_token_id=getattr(parent_config, "image_token_id", None),
37+
)
38+
return None

‎src/mobius/_optimizations.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -452,6 +452,16 @@ def _should_inline(func: ir.Function) -> bool:
452452
# ops like CausalConvWithState and LinearAttention registered per-model.
453453
if caps.name == "onnx-standard" and func.domain not in _STANDARD_ONNX_DOMAINS:
454454
return True
455+
# ORT's CUDA EP has no CausalConvWithState kernel. Keeping the local
456+
# function call causes TransformerMemcpy to inspect a node without a
457+
# provider assignment and abort session initialization. Inline its
458+
# standard Conv-based body so hybrid decoders run on CUDA.
459+
if (
460+
caps.name == "cuda"
461+
and func.domain == "com.microsoft"
462+
and func.name == "CausalConvWithState"
463+
):
464+
return True
455465
if func.domain == "com.microsoft" and func.name in (
456466
"SkipLayerNormalization",
457467
"SkipSimplifiedLayerNormalization",

‎src/mobius/_registry.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
Gemma4AssistantConfig,
3030
Gemma4Config,
3131
Lfm2Config,
32+
Lfm2VlConfig,
3233
MMSConfig,
3334
MoonshineConfig,
3435
MuseGlimmerConfig,
@@ -75,6 +76,7 @@
7576
InternLM2CausalLMModel,
7677
LayerNormCausalLMModel,
7778
Lfm2CausalLMModel,
79+
Lfm2VlForConditionalGeneration,
7880
LLaDAModel,
7981
Llama4CausalLMModel,
8082
MageVLForConditionalGeneration,
@@ -620,6 +622,11 @@ def _detect_fallback_registration(hf_config) -> ModelRegistration | None:
620622
"internvl": ModelRegistration(InternVL2Model, task="vision-language"),
621623
"internvl2": ModelRegistration(InternVL2Model, task="vision-language"),
622624
"internvl_chat": ModelRegistration(InternVL2Model, task="vision-language"),
625+
"lfm2_vl": ModelRegistration(
626+
Lfm2VlForConditionalGeneration,
627+
task="lfm2-vl",
628+
config_class=Lfm2VlConfig,
629+
),
623630
"mage_vl": ModelRegistration(MageVLForConditionalGeneration, task="mage-vl"),
624631
"janus": ModelRegistration(LLaVAModel, task="vision-language"),
625632
"llava": ModelRegistration(LLaVAModel, task="vision-language"),
@@ -1044,6 +1051,7 @@ def _create_default_registry() -> ModelRegistry:
10441051
"molmo": "allenai/MolmoE-1B-0924",
10451052
"mistral3": "mistralai/Ministral-3-3B-Instruct-2512",
10461053
"minicpmv4_6": "openbmb/MiniCPM-V-4.6",
1054+
"lfm2_vl": "LiquidAI/LFM2.5-VL-3B",
10471055
"aya_vision": "CohereForAI/aya-vision-8b",
10481056
"chameleon": "facebook/chameleon-7b",
10491057
"cohere2_vision": "CohereForAI/c4ai-command-r7b-12-2024",
@@ -1267,6 +1275,7 @@ def _create_default_registry() -> ModelRegistry:
12671275
"code_llama": "llama",
12681276
"llama4_text": "llama",
12691277
"lfm2": "lfm",
1278+
"lfm2_vl": "lfm",
12701279
"mllama": "llama",
12711280
"mistral": "mistral",
12721281
"mistral3": "mistral",
@@ -1339,6 +1348,7 @@ def _create_default_registry() -> ModelRegistry:
13391348
"jamba": "hybrid-ssm+attn",
13401349
"bamba": "hybrid-mamba2+attn",
13411350
"lfm2": "hybrid-conv+attn",
1351+
"lfm2_vl": "siglip2-naflex+hybrid-conv+attn",
13421352
"qwen3_next": "moe+linear-attn",
13431353
}
13441354

‎src/mobius/_testing/torch_reference.py‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,7 @@ def load_torch_multimodal_model(
252252
model_id: str,
253253
dtype: torch.dtype = torch.float32,
254254
device: str = "cpu",
255+
revision: str | None = None,
255256
):
256257
"""Load a HuggingFace multimodal model for reference inference.
257258
@@ -261,23 +262,29 @@ def load_torch_multimodal_model(
261262
model_id: HuggingFace model identifier.
262263
dtype: Model dtype (default float32 for numerical comparison).
263264
device: Device to load on.
265+
revision: Optional immutable HuggingFace revision used for tokenizer,
266+
processor, config, and weight loading.
264267
265268
Returns:
266269
Tuple of (model, tokenizer, image_processor).
267270
"""
268271
import transformers
269272

273+
hub_kwargs: dict[str, object] = {"trust_remote_code": True}
274+
if revision is not None:
275+
hub_kwargs["revision"] = revision
276+
270277
tokenizer = _load_mage_compatible(
271278
model_id,
272279
transformers.AutoTokenizer.from_pretrained,
273280
model_id,
274-
trust_remote_code=True,
281+
**hub_kwargs,
275282
)
276283
processor = _load_mage_compatible(
277284
model_id,
278285
transformers.AutoProcessor.from_pretrained,
279286
model_id,
280-
trust_remote_code=True,
287+
**hub_kwargs,
281288
)
282289

283290
# Shim: transformers 5.x removed DynamicCache.from_legacy_cache and
@@ -293,7 +300,7 @@ def load_torch_multimodal_model(
293300
model_id,
294301
transformers.AutoConfig.from_pretrained,
295302
model_id,
296-
trust_remote_code=True,
303+
**hub_kwargs,
297304
)
298305
config._attn_implementation = "eager"
299306

@@ -304,7 +311,7 @@ def load_torch_multimodal_model(
304311
# The weight-dtype keyword was renamed from ``torch_dtype`` to ``dtype`` in
305312
# transformers 5.x; support both so offline golden generation also works on
306313
# the older transformers (e.g. 4.43) required by 4.x-era remote-code models.
307-
base_kwargs = dict(config=config, device_map=device, trust_remote_code=True)
314+
base_kwargs = dict(config=config, device_map=device, **hub_kwargs)
308315

309316
def _load_from_pretrained(auto_cls):
310317
try:

‎src/mobius/components/__init__.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,8 @@
6969
"ScaleFreeRMSNorm",
7070
"SelectiveScan",
7171
"SiLU",
72+
"Siglip2NaFlexVisionEmbeddings",
73+
"Siglip2NaFlexVisionModel",
7274
"SigmoidTopKGate",
7375
"SnakeBeta",
7476
"SoftmaxTopKGate",
@@ -94,6 +96,7 @@
9496
"get_activation",
9597
"initialize_rope",
9698
"make_quantized_linear_factory",
99+
"siglip2_naflex_attention_mask",
97100
]
98101

99102
from mobius.components._activations import SiLU, get_activation
@@ -293,6 +296,11 @@
293296
SANMEncoderLayer as SANMEncoderLayer,
294297
)
295298
from mobius.components._short_conv import GatedShortConv
299+
from mobius.components._siglip2_naflex import (
300+
Siglip2NaFlexVisionEmbeddings,
301+
Siglip2NaFlexVisionModel,
302+
siglip2_naflex_attention_mask,
303+
)
296304
from mobius.components._ssm import (
297305
JambaSelectiveScan as JambaSelectiveScan,
298306
)

0 commit comments

Comments
 (0)