feat(vlm): add Muse Spark (muse_spark) image, video and audio input

Abierto
#3,223 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

Línea de trabajo

Start with the Glimmer vision tower in src/vision/encoders/muse_glimmer.rs and the Spark config notes, then run the comparison against trl-internal-testing/tiny-MuseSparkForConditionalGeneration that decides whether to reuse it. Video sampling belongs in src/multimodal/video.rs and audio decoding in src/audio/preprocessing_wav.rs. The issue is blocked by #3222, so the text decoder must land first. Done means the acceptance criteria pass for image, video and audio on the tiny checkpoint.

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

Descripción

arch:hybrid area:models modelsize:xlarge modeltype:omni priority:medium status:blocked type:enhancement

Summary

Add image, video and audio input to Muse Spark Open (model_type: muse_spark), on top of the text decoder from #3222, which blocks this issue. Upstream mlx-lm supports images; Blaizzy/mlx-vlm supports images, video and 24 kHz waveform audio, with multiple clips mixed in one prompt. This issue adds the three encoders, their processors and prompt expansion, and wires them through mlxcel generate and mlxcel-server, so that ModelType::MuseSparkVLM replaces the "media not supported yet" error #3222 leaves in place.

Implement image, video and audio in a single PR with one verification pass at the end, keeping pushes to a minimum. The three share one splice point and one normalization (perception_emb_norm), and the vision tower serves both images and video, so splitting them would mean three passes over the same loader and prompt code.

Dependency

Blocked by #3222 (set as a native blocked-by relation). Everything here assumes its MuseSparkArgs, sanitize, decoder and LanguageModel impl exist. The text model's input contract is: the decoder accepts pre-normalized input embeddings (embed(ids) is a weightless RMS norm of the token embedding), so the media rows are spliced into the normalized embeddings and must themselves be normalized by perception_emb_norm before the splice.

Upstream reference

Architecture

Vision tower (images and video)

Vision config (mlx-community/Muse-Spark-Open-816B-A42B-4bit): hidden_size 1536, intermediate_size 8960, 50 layers, 16 heads (head_dim 96), patch_size 14, patch_temporal 2, merge_size 2, pos_emb_height = pos_emb_width = 32 (non-square tables are rejected upstream), layer_norm_eps 1e-5, layer_types with full_attention on every fourth layer and the last layer and window_attention elsewhere, use_ij_pos_encoding (default false). Top level: out_hidden_size 6144 (= 1536 * 2 * 2), projector_hidden_size 4096, image_token_id 200092 (<|patch|>), video_token_id 200091.

  • Patchify: an image (C, H, W) with H, W multiples of patch_size * merge_size (28) is broadcast to patch_temporal copies and cut into gh * gw patches of t * C * p * p values (order: temporal, channel, row, column), then patch_embedder.patch_embedding (bias-free Linear).
  • Absolute position: the 32 x 32 position_embedding_table bilinearly sampled at the gh x gw grid (align_corners false, zero padding, torch.linspace semantics in the table dtype). With use_ij_pos_encoding false the legacy grid is transposed unless square; this is the H/W behavior Blaizzy/mlx-vlm#2746 fixed for Glimmer, so take the flag from the config and test a non-square grid both ways.
  • ln_pre (LayerNorm computed in f32, rounded once), then 50 pre-norm blocks: x + attn(norm1(x)), x + fc2(gelu_f32(fc1(norm2(x)))). Attention uses a fused qkv_proj with bias and proj with bias, and 2D RoPE (VisionRoPE2D, theta from vision_config.rope_parameters.rope_theta, default 10000). Window layers attend inside each 32 x 32 patch tile of the grid; full layers attend over the whole image. Then ln_post and a 2x2 pixel-shuffle downsample to (gh/2 * gw/2, 6144) with feature order channel, then row and column inside the block.
  • Adapter and projection: vision_adapter.fc1 (6144 to 4096, no bias), gelu in f32, fc2 (4096 to 4096), gelu in f32, then vision_projection (4096 to 8192, no bias), then perception_emb_norm (weightless RMS, eps text_config.rms_norm_eps).
  • Sanitize (HF layout): concatenate each block's attn.{q,k,v}_proj.{weight,bias} into attn.qkv_proj.* after reordering q and k rows with interleave_rope_rows(w, vision_head_dim), the same helper #3222 adds for the decoder.
  • Video (mlx-vlm video_processing.py): sample count = min(int(total * fps / source_fps), 600, total) frames (default fps 2, source fps 24 when unknown), round count down to a multiple of patch_temporal (minimum one group), and take source indices linspace(0, total - 1, count) truncated to integers; an explicit frame count or max-frames override replaces the defaults. Resize every frame (LANCZOS) to the largest grid with at most 256 merged tokens (max_video_frame_tokens), normalize with mean and std 0.5, pad an odd frame count by repeating the last frame, and pack patch_temporal adjacent frames per temporal group. Each group is encoded independently with the same tower. Timestamps are source_index / source_fps (or the metadata's explicit timestamps), and each group takes the timestamp of its first frame. The prompt expansion is <|vid_start|> + groups joined by <|vid_frame_separator|> + <|vid_end|>, each group written as Time: {timestamp:.2f}s followed by its video tokens.
Image processor

Least-distortion fit of the image to a token grid between min_num_image_tokens (1) and max_num_image_tokens (4096), read from processor_config.json when present; resize with LANCZOS (PIL Image.Resampling.LANCZOS, as upstream); scale to [0, 1], clip, normalize with mean and std 0.5; expand each <|patch|> in the rendered prompt to <|image_start|> + <|patch|> * n + <|image_end|> where n = (gh/2) * (gw/2). The count of <|patch|> markers must equal the number of images; a mismatch is a request error.

Audio encoder (mlx-vlm only)

Audio config: patch_sizes [16, 6, 5, 4] (product 1920 samples per token, 80 ms at 24 kHz), hidden_sizes [256, 512, 1024, 2048], depths [2, 2, 2, 2], conv_kernel_size 7, mlp_ratio 4.0, gelu, rms_norm_eps 1e-6, out_hidden_size 8192, audio_token_id 200038.

  • Four stages. Each stage: patch embedding (reshape to (B, L / p, p * C), Linear with bias, RMSNorm), then depth conv blocks: causal depthwise Conv1d(kernel 7) with left padding of 6, RMSNorm, MLP (fc1, gelu, fc2, with bias), residual add. Then norm, proj (2048 to 8192) and post_proj_norm, then perception_emb_norm. There is no vision-style projector for audio.
  • Input: mono f32 waveform at 24 kHz, right-padded to a multiple of 1920; each clip expands to <|soft_audio_start|> + <|audio|> * ceil(n / 1920) + <|soft_audio_end|>, counting the true (unpadded) length so padding adds no tokens, and only the first ceil(n / 1920) encoder rows per clip are spliced.
  • Checkpoints without model.audio_tower.* weights (every mlx-lm conversion, including the mlx-community repos) support images and video only; an audio request on them fails with a named error. Only meta-models/Muse-Spark-Open-816B-A42B-NVFP4 ships the audio tower among the reference checkpoints.

Current mlxcel state and reuse

  • Vision tower: src/vision/encoders/muse_glimmer.rs (MuseGlimmerPatchEmbedder, MuseGlimmerVisionTower), muse_glimmer_layers.rs (window/full layers), muse_glimmer_pos.rs (interpolate_position_table, muse_2d_rope) and MuseGlimmerVisionConfig (src/models/muse_glimmer_config.rs:111) have the same config surface (patch_temporal, merge_size, pos_emb_height/width, window and full layers). Decision rule: reuse the Glimmer tower if, on trl-internal-testing/tiny-MuseSparkForConditionalGeneration, its output for a 2-image batch with one non-square image matches the upstream mlx-lm VisionTower within 1e-3 max abs after the Spark sanitize; otherwise add src/vision/encoders/muse_spark.rs and share only the pieces that do match (position interpolation, tiling). Known differences to check first: Spark's adapter is two gelu Linears plus a separate vision_projection (not Glimmer's fusion module in src/vision/encoders/muse_glimmer_fusion.rs), RoPE row interleave in sanitize, f32 LayerNorm and gelu, and the use_ij_pos_encoding flag. Update // Used by: on every Glimmer helper reused.
  • Processor: src/vision/processors/muse_glimmer.rs uses smart_resize with pixel bounds; Spark's token-bounded least-distortion fit differs, so add a Spark processor that reuses the shared decode and normalize helpers rather than changing Glimmer's resize.
  • Video: src/multimodal/video.rs for frame decoding and sampling; Glimmer's runtime (src/multimodal/muse_glimmer_runtime.rs, muse_glimmer_prompt.rs) for prompt assembly patterns. docs/supported-models.md "Video on a model with no native video path" describes the fallback that must NOT apply here, since Spark has a native path.
  • Audio: src/audio/preprocessing_wav.rs for WAV decode, downmix and resampling to 24 kHz; Inkling's audio path (src/multimodal/inkling_audio.rs) as the pattern for splicing audio rows at a placeholder token.
  • Loader: src/loading/vlm_muse_glimmer.rs and its registration in try_load_vlm_model_from_dir() (src/loading/mod.rs) are the model for a src/loading/vlm_muse_spark.rs; VlmRuntimeRef in src/loaded_model_capabilities.rs for capability getters. Detection: the detect_text_or_vlm_by_weights branch the text issue adds for muse_spark returns MuseSparkVLM when vision weights exist.
  • Every learned vision and audio parameter needs the quantization-sidecar audit in docs/adding-models.md (VLM checklist item 8): the position table goes through vision::weights::load_dense_param.

Implementation plan

  • src/vision/encoders/muse_spark.rs (or reuse per the rule above), src/audio/encoders/muse_spark.rs or src/multimodal/muse_spark_audio.rs for the conv encoder, src/vision/processors/muse_spark.rs, src/multimodal/muse_spark_prompt.rs for image, video and audio placeholder expansion with timestamps, src/loading/vlm_muse_spark.rs, and ModelType::MuseSparkVLM / LoadedModel::MuseSparkVLM wiring in src/models/mod.rs, src/model_metadata.rs (Vlm kind), src/loaded_model.rs, src/loaded_model_capabilities.rs, src/models/registry.rs (modalities image, video, audio).
  • Server: accept image_url, video and input_audio content parts for this model, count media tokens in prompt-token accounting, and keep the ATEM and reasoning handling from #3222 unchanged.
  • docs/supported-models.md: move the Muse Spark entry to "Vision-language and multimodal variants" with the per-modality limits above (4096 image tokens, 256 tokens per video group, 2 fps and 600-frame defaults, 80 ms audio tokens, audio only on audio-inclusive checkpoints).

Acceptance criteria

  • Tiny checkpoint: vision features for a square and a non-square image match the mlx-lm encode_image output within 1e-3 max abs, and the spliced input embeddings match Model.embed_inputs.
  • Audio: on the audio tower of trl-internal-testing/tiny-MuseSparkForConditionalGeneration (it ships one: hidden_sizes [16, 16, 32, 32], patch_sizes [16, 6, 5, 4]), features match mlx-vlm encode_audio within 1e-3 max abs, and a 1.3 s clip produces ceil(31200 / 1920) = 17 tokens, padding does not change the token count, and a test fails if the causal left padding is replaced by symmetric padding.
  • Video: a 5 s, 30 fps clip (150 frames) at the default 2 fps samples 10 frames at source indices 0, 16, 33, 49, 66, 82, 99, 115, 132, 149, forms 5 temporal groups, and writes Time: 0.00s, Time: 1.10s, Time: 2.20s, Time: 3.30s, Time: 4.40s; a 4.5 s, 30 fps clip (135 frames) rounds 9 frames down to 8 (indices 0, 19, 38, 57, 76, 95, 114, 134; groups at 0.00, 1.27, 2.53, 3.80 s); explicitly supplied frames with an odd count repeat the last frame. The expected values come from upstream sample_frames and _timestamps; a test fails if timestamps are derived from the sampling fps instead of the source fps.
  • Prompt expansion: placeholder counts match the encoder row counts for every modality; a mismatch between <|patch|> markers and images is a request error.
  • On the 512 GiB host with mlx-community/Muse-Spark-Open-816B-A42B-3bit: mlxcel generate --image describes a test image correctly, a two-image prompt references both, and a short video is summarized; with the NVFP4 checkpoint, a spoken English clip is transcribed. Outputs are compared against mlx_vlm.generate --temp 0 on the same inputs.
  • mlxcel-server accepts image, video and audio content parts for this model; an audio request on a checkpoint without audio_tower weights returns the named error.
  • Integrated into mlxcel generate, mlxcel-server and mlxcel arch (modalities listed); docs/supported-models.md updated.

Verification

cargo build --release --features metal,accelerate
cargo test --profile test-fast --features metal,accelerate muse_spark muse_glimmer
make verify-test
cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --check
python3 scripts/ci/check_cross_repo_refs.py
./target/release/mlxcel generate -m models/tiny-MuseSparkForConditionalGeneration --image tests/fixtures/flux2/edit_reference.png -p "Describe this image." -n 16 --temp 0
# 512 GiB host only:
./target/release/mlxcel generate -m models/Muse-Spark-Open-816B-A42B-3bit --image tests/fixtures/flux2/edit_reference.png -p "Describe this image." -n 256 --temp 0

Related

  • Blocked by #3222. #1100 (Muse Glimmer), Blaizzy/mlx-vlm#2746 (Glimmer position-grid H/W swap, the same legacy-grid behavior).
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.