feat(models): add LFM3-VL (lfm3_vl) vision-language support
メンテナーはふだん 1 日以内に返信
まだ誰も着手していません。
評価
調査の方向性
Start with the LFM2-VL wiring as the pattern: src/loading/vlm_lfm2_vl.rs (load_lfm2_vl) and src/vision/lfm2_vl.rs, plus the lfm3_vl dispatch point near src/models/detection.rs:1068. The issue is blocked by #3206 (the LFM3 text backbone), so confirm that lands first. Done means the acceptance-criteria tests pass: grid_positions order, axial RoPE angles, the VisionConv round trip, processor placeholder counts, and sanitize layouts.
索引モデルが issue の本文から書いたものです。
説明
Summary
Add LFM3-VL (model_type: lfm3_vl, Lfm3VlForConditionalGeneration): the LFM3 text backbone from #3206 plus a new vision tower (linear temporal patchifier, gated depthwise spatial convolutions, frame-local bidirectional attention with axial RoPE), a per-patch LayerNorm + GELU projector, and a Qwen3-VL-style image and pre-sampled video processor. Today mlxcel generate -m LiquidAI/LFM3-VL-2B --image x.png fails with Unsupported model type: lfm3_vl. This is the second PR of the LFM3 family and is blocked by #3206; it is kept separate because the tower, processor and VLM wiring are a different review surface from the text backbone and the text model must be validated first.
Upstream reference
- Blaizzy/mlx-vlm#2607 (merge
38fe39a3), https://github.com/Blaizzy/mlx-vlm/tree/main/mlx_vlm/models/lfm3_vl - Vision tower: https://github.com/Blaizzy/mlx-vlm/blob/main/mlx_vlm/models/lfm3_vl/vision.py (
grid_positions,VisionAttention,VisionConv,VisionLayer,VisionModel) - Wrapper, projector, merge, sanitize: https://github.com/Blaizzy/mlx-vlm/blob/main/mlx_vlm/models/lfm3_vl/lfm3_vl.py (
MultiModalProjector,Model._merge,Model.sanitize) - Config validation: https://github.com/Blaizzy/mlx-vlm/blob/main/mlx_vlm/models/lfm3_vl/config.py
- Processor: https://github.com/Blaizzy/mlx-vlm/blob/main/mlx_vlm/models/lfm3_vl/processing_lfm3_vl.py (
Lfm3VlProcessor,Lfm3VlVideoProcessor.sample_frames,_process_one,group_seconds), built on https://github.com/Blaizzy/mlx-vlm/blob/main/mlx_vlm/models/qwen3_vl/processing_qwen3_vl.py (Qwen3VLImageProcessor) - README with validation numbers: https://github.com/Blaizzy/mlx-vlm/blob/main/mlx_vlm/models/lfm3/README.md
Architecture (from upstream code and LiquidAI/LFM3-VL-2B/config.json)
Top level: downsample_factor 2 (must equal vision_config.spatial_merge_size), projector_hidden_size 4096, projector_hidden_act gelu (anything else is a load error), projector_bias true, projector_layer_norm_eps 1e-6, image_token_id 125030 (<|image|>), video_token_id 125029 (<|video|>), vision_start_token_id 125009, vision_end_token_id 125010, eos_token_id 124900. text_config is the LFM3 text config of #3206 (24 layers, hidden 2048, same layer pattern, max_position_embeddings 128000).
vision_config (model_type lfm3_vl_vision): hidden_size 1024, intermediate_size 2560, num_hidden_layers 14 with layer_types [conv, conv, full_attention, conv, full_attention, conv, full_attention, conv, full_attention, conv, full_attention, conv, full_attention, conv] (only conv and full_attention are valid), num_attention_heads 16, num_key_value_heads 8 (head_dim 64), in_channels 3, patch_size 16, temporal_patch_size 2, spatial_merge_size 2, conv_kernel_size 3, norm_eps 1e-5, rope_parameters {rope_type: axial, rope_theta: 1e6} (any other rope_type is a load error).
- Patchifier:
Linear(3 * 2 * 16 * 16 = 1536 -> 1024, bias=False)over the flattened patch rows, cast to the tower dtype, thenembedding_normRMSNorm. - Frame-local loop: for each
(t, h, w)ingrid_thw, each of thettemporal groups is run through all 14 layers on its ownh * wpatches (no attention across frames or images), and the outputs are concatenated in order. A patch count that does not matchgrid_thwis an error. - Patch order: rows arrive in merge-block order (
grid_positions: raster over(h/2, w/2)blocks, then the 2x2 positions inside each block). - Layer:
x = x + mixer(operator_norm(x)),x = x + feed_forward(ffn_norm(x)), no sandwich norm;feed_forwardis the LFM3 SwiGLU (w1,w2,w3) at the vision widths. - VisionAttention: q/k/v/out projections without bias,
q_layernorm/k_layernormRMSNorm per head, GQA 16/8, scale64 ** -0.5, bidirectional SDPA. Axial RoPE in f32:spatial_dim = 64 / 2 = 32,inv_freq = theta ** (-arange(0, 32, 2) / 32)(16 values),angles = (coords[..., None] * inv_freq).reshape(N, 32)withcoords = (row, col)per patch, duplicated to 64 and applied rotate-half over the whole head; q and k are cast to f32 for the rotation and back. - VisionConv:
in_proj: 1024 -> 3072(no bias) split intob, c, v;b * vis reordered from merge-block order to a raster[1, h, w, 1024]grid, run through a depthwiseConv2d(1024, 1024, 3, padding=1, groups=1024, bias=False), reordered back to merge-block order, thenout_proj(c * out). - Projector:
LayerNorm(1024, eps 1e-6)on each patch,reshape(-1, 4096)(four consecutive merge-ordered patches form one token),linear_1: 4096 -> 4096, exact GELU,linear_2: 4096 -> 2048, both with bias. - Merge: projected features are scattered into the
<|image|>(and<|video|>) positions in order; a count mismatch is an error naming both counts. Text positions stay plain 1D (position_idsare0..L); there is no M-RoPE. - Sanitize:
model.language_model.*tolanguage_model.model.*, othermodel.*stripped,lm_head.*tolanguage_model.lm_head.*(dropped when tied);*conv.conv.weight[C, 1, K]transposed to[C, K, 1]and*spatial_conv.weight[C, 1, 3, 3]transposed(0, 2, 3, 1), each only whenshape[1] == 1(idempotent). - Processor: images through the Qwen3-VL image processor (smart resize to multiples of
patch_size * merge_size = 32,min_pixels/max_pixelsfromprocessor_config.jsonimage_processor.size.shortest_edge/longest_edge, a single image duplicated to two temporal frames, rescale and mean/std normalize, Qwen2-VL patch flattening(t, h/2, w/2, 2, 2, C, temporal, 16, 16)). Each<|image|>placeholder expands tot * h * w / 4copies. Videos are pre-sampled frames:count = int(total / src_fps * fps)clamped to[min_frames, min(max_frames, total)], indiceslinspace(0, total - 1, count).round(); an odd count is padded by repeating the last frame; frames resized with upstream's rule (roundto 32 multiples, then shrink bysqrt(t * h * w / max_pixels)or grow bymin_pixels, aspect ratio above 200 rejected, at least 2 frames). Each temporal group of a video expands to<{ts:.1f} seconds><|vision_start|>+<|video|>timesh * w / 4+<|vision_end|>, wherets = (idx_first / fps + idx_last / fps) / 2withfpsrounded to 6 places.
Checkpoints and host
| Checkpoint | Size | Role |
|---|---|---|
LiquidAI/LFM3-VL-2B |
3.85 GB bf16 | Float reference for parity |
LiquidAI/LFM3-VL-2B-MLX-8bit |
2.23 GB | Validation target (backbone quantized, tower kept at source precision) |
LiquidAI/LFM3-VL-2B-MLX-4bit, -5bit, -6bit, -bf16 |
smaller | Load smoke tests |
LiquidAI/LFM3-VL-2B-FP8, -NVFP4 |
Out of scope; must fail at load with a named error, not load garbage |
Access as for #3206 (upstream README says gated; the Hub reported gated: false on 2026-11-23). The checkpoint is under 5 GB. LiquidAI/d1-2B shares model_type: lfm3_vl with architectures: ["D1Model"] and is a decision model, not a generator.
Current behavior
src/models/detection.rs:1068knowslfm2_vl; there is nolfm3_vlarm.- The closest in-tree VLM is LFM2-VL:
src/loading/vlm_lfm2_vl.rs:64(load_lfm2_vl),src/vision/lfm2_vl.rs:47(Lfm2VlModel,get_input_embeddingsat:72),src/multimodal/lfm2_vl_prompt.rs. Its SigLIP2 tower and pixel-unshuffle connector do not apply to LFM3-VL; only the wrapper, loader and prompt shape are the pattern. src/vision/processors/qwen2_vl.rs:30(Qwen2VLProcessor, withwith_pixel_boundsat:222,with_video_configat:229,with_resize_filterat:239) already implements the Qwen smart resize, temporal duplication and Qwen2-VL patch flattening;src/multimodal/video.rs:293(FrameSamplingPolicy) is the shared frame sampler.src/multimodal/qwen_vl.rs:1410(compute_qwen_vl_mrope_position_ids) is the Qwen M-RoPE position path; LFM3-VL must not take it.
Proposed solution
src/vision/encoders/lfm3_vl.rs(testslfm3_vl_tests.rs):Lfm3VlVisionTowerwith the patchifier, the frame-local loop,VisionAttention(axial RoPE computed once per(h, w)),VisionConvand the layer stack. Reuse the LFM3 SwiGLU MLP fromsrc/models/lfm3.rs(make itpub(crate)) rather than writing another one.src/vision/connectors/lfm3_vl.rs: the projector.src/vision/processors/lfm3_vl.rs(tests beside it): wrapsQwen2VLProcessorfor images with the LFM3 pixel bounds fromprocessor_config.json(fall back topreprocessor_config.json), and implements the LFM3 video sampling, odd-count padding, resize rule and timestamp text on top ofFrameSamplingPolicy. If the existingQwen2VLProcessorresize differs from upstream's NumPy/PIL bicubic by more than upstream's own stated tolerance (2 8-bit levels on natural images), add a filter option there instead of a second resize.src/vision/lfm3_vl.rs:Lfm3VlModel { tower, projector, text: Lfm3Model }withget_input_embeddingsdoing the ordered scatter for images then videos, and plain 1D positions.src/multimodal/lfm3_vl_prompt.rs: placeholder expansion for images and videos as described, applied to the chat-template output.src/loading/vlm_lfm3_vl.rsplussrc/loading/vlm.rsdispatch,"lfm3_vl" => Ok(ModelType::Lfm3VL)insrc/models/detection.rs,LoadedModel::Lfm3VLinsrc/loaded_model.rs,VlmRuntimeRef::Lfm3Vlinsrc/loaded_model_capabilities.rs(image and video input true, audio false),src/model_metadata.rs(kind: Vlm),src/models/registry.rs.- d1 guard: when
architecturescontainsD1Model(orauto_map.AutoModelends withD1Model), loading for generation fails with"<path> is a LiquidAI d1 decision checkpoint; it does not generate text". The decision path itself is #3218. - Quantization audit (adding-models VLM checklist item 8): the MLX conversions keep the tower at source precision; still route every learned tower parameter through the quantization-aware loader so a future quantized tower loads or fails by name.
Rejected alternative: reusing the Qwen-VL runtime (src/vision/qwen2_vl.rs) as a wrapper. Its M-RoPE positions and merger do not match LFM3-VL, and bending it would add LFM3 branches to the Qwen hot path.
Scope
In scope: the files above, multi-image prompts, pre-sampled video frames through --video, server image_url and video_url content parts, docs/supported-models.md LFM3-VL entry, NOTICE attribution.
Out of scope: FP8 and NVFP4 conversions (named load error), the d1 decision readout (#3218), video soundtrack audio, batched multi-row VLM prefill beyond the shared path.
Implementation notes
- Dtype policy: bf16 tower weights take the standard
load_vlm_weights()bf16 to f16 conversion; the RoPE rotation stays in f32 as upstream does. - Edge cases: image smaller than 32 px on a side (upscaled by the processor rule), extreme aspect ratios (rejected above 200), more placeholders than images and the reverse (error naming both counts), a video with one frame (rejected: at least 2), a video with an odd number of sampled frames (padded),
fpsmissing (24.0 default as upstream). - Error handling: shape and count mismatches are
400on the server and a CLI error naming the counts; a d1 checkpoint is refused before any weights load.
Acceptance criteria
- Unit tests (
src/vision/encoders/lfm3_vl_tests.rs):grid_positionsorder for a 4x6 grid; axial RoPE angles against a hand-computed table;VisionConvmerge-order to raster round trip is the identity; frame-local loop gives each temporal group the same output as running it alone. - Processor tests: placeholder counts and pixel shapes for three image sizes, the 200 aspect-ratio rejection, the video sampling indices and timestamp strings for a 30 fps 7-frame clip at 2 fps, odd-count padding; token ids for one image prompt and one video prompt match a committed upstream fixture.
- Sanitize tests: HF and MLX layouts load; both conv transposes are idempotent.
- Real-checkpoint parity against mlx-vlm on
LiquidAI/LFM3-VL-2Bin f32: committed fixture of tower output and projector output (relative error under 1e-4) and last-position logits for one image prompt and one 8-frame video prompt (relative error under 1e-4, same top-20). It fails on current code. -
mlxcel generate -m LiquidAI/LFM3-VL-2B-MLX-8bit --image <image with a red square and the text CODE 5739> -p "What code is written next to the red square?" -n 32reads the code; 32 greedy tokens match mlx-vlm on the same prompt. -
mlxcel-server -m LiquidAI/LFM3-VL-2B-MLX-8bitanswers a/v1/chat/completionsrequest with oneimage_urlpart and one with avideo_urlpart. -
mlxcel generate -m LiquidAI/d1-2B -p hifails with the d1 message before loading weights. -
mlxcel archandmlxcel arch --jsonlistlfm3_vl;docs/supported-models.mdhas the LFM3-VL entry with the tower, projector, processor and validated checkpoints.
Verification
cargo test --profile test-fast lfm3_vl
cargo test --profile test-fast lfm3_tests::
make verify-test
cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --check
./target/release/mlxcel generate -m models/LFM3-VL-2B-MLX-8bit --image tests/fixtures/<image>.png -p "Describe this image." -n 64
Related
- Blocked by #3206 (LFM3 text backbone).
- Followed by #3216 (LFM3-Omni, vision path reused) and #3218 (d1 LFM3 decision models).
- #2367 (d1-3B on LFM2-VL) shows the same
D1Modelrouting pattern on the LFM2 generation.
- 主要言語
- Rust
- スター
- 505
- フォーク
- 81
- 平均マージ
- 14時間 2分
- マージ済み PR(30日)
- 448
環境構築
- Dockerfile・Docker Compose ファイルなし
- プルリクエストのテンプレートあり
- コントリビューションガイドを読む
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
lablup/mlxcel のほかの issue
-
area:core priority:high status:ready type:security
難易度 2/5 1〜3時間 初心者へのやさしさ 82/100
メンテナーはふだん 1 日以内に返信
-
priority:medium status:ready type:security
難易度 4/5 3〜5日 初心者へのやさしさ 45/100
メンテナーはふだん 1 日以内に返信
-
area:models modeltype:text priority:medium status:in-progress type:bug
難易度 4/5 3〜5日 初心者へのやさしさ 57/100
メンテナーはふだん 1 日以内に返信
-
area:models priority:low status:ready type:test
難易度 4/5 3〜5日 初心者へのやさしさ 48/100
メンテナーはふだん 1 日以内に返信
-
area:models modeltype:omni priority:medium status:ready type:bug
難易度 4/5 3〜5日 初心者へのやさしさ 48/100
メンテナーはふだん 1 日以内に返信
似ている issue
-
TypeScript BM25 drops supplementary characters at the token length limit対応中かも @ErenAta16 が今日担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
chroma-core/chroma#8038 ·
メンテナーはふだん 1 日以内に返信
-
p3 ready
難易度 2/5 1〜3時間 初心者へのやさしさ 71/100
メンテナーはふだん 1 日以内に返信
-
area:ui effort:medium enhancement P7 source:agent
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
メンテナーはふだん 1 日以内に返信
-
marketing
難易度 2/5 1〜3時間 初心者へのやさしさ 85/100
メンテナーはふだん 1 日以内に返信
-
machine rename accepts a label already used by another machine, making --machine <label> ambiguousオープンmaintainer-needed p2 remote triaged
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
メンテナーはふだん 1 日以内に返信