feat(models): add LFM3-VL (lfm3_vl) vision-language support

Abierto
#3,208 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
5/5
Tiempo estimado
Más de una semana
Aptitud para principiantes
8/100
Tipo de issue
Nueva funcionalidad
Claridad
Bastante claro
Estado de actividad
Activo
Stack tecnológico
rust
Área
ai

Línea de trabajo

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.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

arch:hybrid area:models modelsize:small modeltype:vlm priority:medium status:blocked type:enhancement

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

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, then embedding_norm RMSNorm.
  • Frame-local loop: for each (t, h, w) in grid_thw, each of the t temporal groups is run through all 14 layers on its own h * w patches (no attention across frames or images), and the outputs are concatenated in order. A patch count that does not match grid_thw is 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_forward is the LFM3 SwiGLU (w1, w2, w3) at the vision widths.
  • VisionAttention: q/k/v/out projections without bias, q_layernorm / k_layernorm RMSNorm per head, GQA 16/8, scale 64 ** -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) with coords = (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 into b, c, v; b * v is reordered from merge-block order to a raster [1, h, w, 1024] grid, run through a depthwise Conv2d(1024, 1024, 3, padding=1, groups=1024, bias=False), reordered back to merge-block order, then out_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_ids are 0..L); there is no M-RoPE.
  • Sanitize: model.language_model.* to language_model.model.*, other model.* stripped, lm_head.* to language_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 when shape[1] == 1 (idempotent).
  • Processor: images through the Qwen3-VL image processor (smart resize to multiples of patch_size * merge_size = 32, min_pixels / max_pixels from processor_config.json image_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 to t * h * w / 4 copies. Videos are pre-sampled frames: count = int(total / src_fps * fps) clamped to [min_frames, min(max_frames, total)], indices linspace(0, total - 1, count).round(); an odd count is padded by repeating the last frame; frames resized with upstream's rule (round to 32 multiples, then shrink by sqrt(t * h * w / max_pixels) or grow by min_pixels, aspect ratio above 200 rejected, at least 2 frames). Each temporal group of a video expands to <{ts:.1f} seconds><|vision_start|> + <|video|> times h * w / 4 + <|vision_end|>, where ts = (idx_first / fps + idx_last / fps) / 2 with fps rounded 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:1068 knows lfm2_vl; there is no lfm3_vl arm.
  • 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_embeddings at :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, with with_pixel_bounds at :222, with_video_config at :229, with_resize_filter at :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 (tests lfm3_vl_tests.rs): Lfm3VlVisionTower with the patchifier, the frame-local loop, VisionAttention (axial RoPE computed once per (h, w)), VisionConv and the layer stack. Reuse the LFM3 SwiGLU MLP from src/models/lfm3.rs (make it pub(crate)) rather than writing another one.
  • src/vision/connectors/lfm3_vl.rs: the projector.
  • src/vision/processors/lfm3_vl.rs (tests beside it): wraps Qwen2VLProcessor for images with the LFM3 pixel bounds from processor_config.json (fall back to preprocessor_config.json), and implements the LFM3 video sampling, odd-count padding, resize rule and timestamp text on top of FrameSamplingPolicy. If the existing Qwen2VLProcessor resize 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 } with get_input_embeddings doing 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.rs plus src/loading/vlm.rs dispatch, "lfm3_vl" => Ok(ModelType::Lfm3VL) in src/models/detection.rs, LoadedModel::Lfm3VL in src/loaded_model.rs, VlmRuntimeRef::Lfm3Vl in src/loaded_model_capabilities.rs (image and video input true, audio false), src/model_metadata.rs (kind: Vlm), src/models/registry.rs.
  • d1 guard: when architectures contains D1Model (or auto_map.AutoModel ends with D1Model), 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), fps missing (24.0 default as upstream).
  • Error handling: shape and count mismatches are 400 on 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_positions order for a 4x6 grid; axial RoPE angles against a hand-computed table; VisionConv merge-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-2B in 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 32 reads the code; 32 greedy tokens match mlx-vlm on the same prompt.
  • mlxcel-server -m LiquidAI/LFM3-VL-2B-MLX-8bit answers a /v1/chat/completions request with one image_url part and one with a video_url part.
  • mlxcel generate -m LiquidAI/d1-2B -p hi fails with the d1 message before loading weights.
  • mlxcel arch and mlxcel arch --json list lfm3_vl; docs/supported-models.md has 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 D1Model routing pattern on the LFM2 generation.
Lenguaje dominante
Rust
Estrellas
505
Forks
81
Merge medio
14 h 2 min
PR fusionados (30 d)
448

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de lablup/mlxcel

Todos los issues de lablup/mlxcel

Issues similares

Más issues de Rust

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.