feat(vlm): add Muse Spark (muse_spark) image, video and audio input
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
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
- mlx-lm: https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/muse_spark/vision.py (tower, adapter), https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/muse_spark/processor.py and
Model.embed_inputs/encode_imagein https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/muse_spark/model.py, from ml-explore/mlx-lm#1976 and ml-explore/mlx-lm#1981. - mlx-vlm (Blaizzy/mlx-vlm#2542, merge
f1a9b7ba): https://github.com/Blaizzy/mlx-vlm/tree/main/mlx_vlm/models/muse_spark (vision.py,audio.py,image_processing.py,video_processing.py,processing_muse_spark.py,muse_spark.py,sanitize.py) and its testsmlx_vlm/tests/test_muse_spark.py,test_muse_spark_video.py.
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)withH, Wmultiples ofpatch_size * merge_size(28) is broadcast topatch_temporalcopies and cut intogh * gwpatches oft * C * p * pvalues (order: temporal, channel, row, column), thenpatch_embedder.patch_embedding(bias-free Linear). - Absolute position: the
32 x 32position_embedding_tablebilinearly sampled at thegh x gwgrid (align_corners false, zero padding, torch.linspace semantics in the table dtype). Withuse_ij_pos_encoding falsethe 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 fusedqkv_projwith bias andprojwith bias, and 2D RoPE (VisionRoPE2D, theta fromvision_config.rope_parameters.rope_theta, default 10000). Window layers attend inside each32 x 32patch tile of the grid; full layers attend over the whole image. Thenln_postand 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, thenvision_projection(4096 to 8192, no bias), thenperception_emb_norm(weightless RMS, epstext_config.rms_norm_eps). - Sanitize (HF layout): concatenate each block's
attn.{q,k,v}_proj.{weight,bias}intoattn.qkv_proj.*after reordering q and k rows withinterleave_rope_rows(w, vision_head_dim), the same helper #3222 adds for the decoder. - Video (mlx-vlm
video_processing.py): samplecount = min(int(total * fps / source_fps), 600, total)frames (default fps 2, source fps 24 when unknown), roundcountdown to a multiple ofpatch_temporal(minimum one group), and take source indiceslinspace(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 packpatch_temporaladjacent frames per temporal group. Each group is encoded independently with the same tower. Timestamps aresource_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 asTime: {timestamp:.2f}sfollowed 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), thendepthconv blocks: causal depthwiseConv1d(kernel 7)with left padding of 6, RMSNorm, MLP (fc1, gelu,fc2, with bias), residual add. Thennorm,proj(2048 to 8192) andpost_proj_norm, thenperception_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 firstceil(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. Onlymeta-models/Muse-Spark-Open-816B-A42B-NVFP4ships 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) andMuseGlimmerVisionConfig(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, ontrl-internal-testing/tiny-MuseSparkForConditionalGeneration, its output for a 2-image batch with one non-square image matches the upstream mlx-lmVisionTowerwithin 1e-3 max abs after the Spark sanitize; otherwise addsrc/vision/encoders/muse_spark.rsand share only the pieces that do match (position interpolation, tiling). Known differences to check first: Spark's adapter is two gelu Linears plus a separatevision_projection(not Glimmer's fusion module insrc/vision/encoders/muse_glimmer_fusion.rs), RoPE row interleave in sanitize, f32 LayerNorm and gelu, and theuse_ij_pos_encodingflag. Update// Used by:on every Glimmer helper reused. - Processor:
src/vision/processors/muse_glimmer.rsusessmart_resizewith 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.rsfor 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.rsfor 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.rsand its registration intry_load_vlm_model_from_dir()(src/loading/mod.rs) are the model for asrc/loading/vlm_muse_spark.rs;VlmRuntimeRefinsrc/loaded_model_capabilities.rsfor capability getters. Detection: thedetect_text_or_vlm_by_weightsbranch the text issue adds formuse_sparkreturnsMuseSparkVLMwhen 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 throughvision::weights::load_dense_param.
Implementation plan
src/vision/encoders/muse_spark.rs(or reuse per the rule above),src/audio/encoders/muse_spark.rsorsrc/multimodal/muse_spark_audio.rsfor the conv encoder,src/vision/processors/muse_spark.rs,src/multimodal/muse_spark_prompt.rsfor image, video and audio placeholder expansion with timestamps,src/loading/vlm_muse_spark.rs, andModelType::MuseSparkVLM/LoadedModel::MuseSparkVLMwiring insrc/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 andinput_audiocontent 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_imageoutput within 1e-3 max abs, and the spliced input embeddings matchModel.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-vlmencode_audiowithin 1e-3 max abs, and a 1.3 s clip producesceil(31200 / 1920) = 17tokens, 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 upstreamsample_framesand_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 --imagedescribes 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 againstmlx_vlm.generate --temp 0on the same inputs. -
mlxcel-serveraccepts image, video and audio content parts for this model; an audio request on a checkpoint withoutaudio_towerweights returns the named error. - Integrated into
mlxcel generate,mlxcel-serverandmlxcel arch(modalities listed);docs/supported-models.mdupdated.
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
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de lablup/mlxcel
-
area:core priority:high status:ready type:security
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
Los mantenedores suelen responder en 1 día
-
priority:medium status:ready type:security
Dificultad 4/5 3-5 días Aptitud para principiantes 45/100
Los mantenedores suelen responder en 1 día
-
area:models modeltype:text priority:medium status:in-progress type:bug
Dificultad 4/5 3-5 días Aptitud para principiantes 57/100
Los mantenedores suelen responder en 1 día
-
area:models priority:low status:ready type:test
Dificultad 4/5 3-5 días Aptitud para principiantes 48/100
Los mantenedores suelen responder en 1 día
-
area:models modeltype:omni priority:medium status:ready type:bug
Dificultad 4/5 3-5 días Aptitud para principiantes 48/100
Los mantenedores suelen responder en 1 día
Todos los issues de lablup/mlxcel
Issues similares
-
TypeScript BM25 drops supplementary characters at the token length limitPosiblemente ocupada @ErenAta16 la tomó hoy. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
chroma-core/chroma#8038 ·
Los mantenedores suelen responder en 1 día
-
p3 ready
Dificultad 2/5 1-3 horas Aptitud para principiantes 71/100
Los mantenedores suelen responder en 1 día
-
area:ui effort:medium enhancement P7 source:agent
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 1 día
-
marketing
Dificultad 2/5 1-3 horas Aptitud para principiantes 85/100
Los mantenedores suelen responder en 1 día
-
machine rename accepts a label already used by another machine, making --machine <label> ambiguousAbiertomaintainer-needed p2 remote triaged
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
Los mantenedores suelen responder en 1 día