feat(vlm): add Mistral Large 4 (mistral_large4) support
I maintainer di solito rispondono entro 1 giorno
Nessuno ha ancora preso questa issue.
Valutazione
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Idoneità per principianti
- 12/100
- Tipo di issue
- Funzionalità
- Chiarezza
- Specificata chiaramente
- Stato di attività
- Attiva
- Stack tecnologico
- rust
- Ambito
- machine-learning
Direzione di ricerca
Start with the model routing in src/models/detection.rs (around line 1056, where mistral3 and mistral4 are matched) and the Mistral 3 VLM loader in src/loading/vlm_pixtral.rs (load_mistral3_vlm). The DSA code in src/models/deepseek_v32.rs and deepseek_v32_indexer.rs is the base the new layers extend. Done means a mistral_large4 arm plus unit tests for config validation and the sanitize remap, since the real-checkpoint gate is blocked on hardware. The issue is labelled status:blocked and is not a newcomer task.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
Summary
Add Mistral Large 4 (model_type: mistral_large4, MistralLarge4ForConditionalGeneration, 1T total / 52B active): the Mistral 3 VLM shell with a Pixtral vision tower and projector, in front of a 72-layer MLA MoE decoder with DeepSeek Sparse Attention (DSA) indexers. Compared with mlxcel's DeepSeek-V3.2 / GLM-5 DSA families it adds cross-layer KV sharing (kv_source_layers), cross-layer indexer sharing (indexer_types: shared reuse the previous layer's top-k), NoPE layers (every fourth), LeRoPE (YaRN-style frequencies with a learned per-frequency alpha), SSMax (per-head learned log-position query scaling, in attention and in the indexer), softmax routing, and a final logit softcap of 30. The vision side and the Mistral-native weight names are close to Mistral Large 3 (#2401).
Blocked on hardware
Public checkpoints exist, but none fits the available hardware: the native FP8 release is 1060.55 GB, the native NVFP4 release 610.04 GB, and the only MLX-labelled conversion (inferencerlabs/Mistral-Large-4-1T-A52B-MLX-Q3i, 459.02 GB) uses Inferencer's own "INF" quantization and model.inf metadata rather than an mlx-lm/mlx-vlm layout, so it is not a target for mlxcel either. Upstream's README documents running it across two or three Macs with expert parallelism (experts split 64/64 or 42/43/43). The port can be written and unit-tested now; the real-checkpoint gate needs either a single host with enough memory for a standard MLX conversion (the 610 GB NVFP4 release is the smallest standard-format source; a 4-bit MLX conversion of the full model is an estimated 500-600 GB and would itself need converting) or distributed expert parallelism, which mlxcel does not have. Labelled status:blocked for the same reason as #2401.
Upstream reference
- Port: Blaizzy/mlx-vlm#2629 (the
mistral_large4model, its kernels and DSpark verifier). Follow-ups: Blaizzy/mlx-vlm#2717 (commit 633757c8,params.jsonfallback and the MLX Mistral processor for Large 4), Blaizzy/mlx-vlm#2736 (commit 43477877, normalize native Large 4 checkpoint metadata,config_from_params, native 128x128 block-FP8 viaqscale_weight), Blaizzy/mlx-vlm#2659 (DSpark decode stability), Blaizzy/mlx-vlm#2664 (trailing-logit projection). - Code: https://github.com/Blaizzy/mlx-vlm/tree/main/mlx_vlm/models/mistral_large4 (
config.pyTextConfigvalidation andModelConfig.__post_init__native normalization,language.pyLeRoPE,SoftmaxScaling,Indexer,PackedIndexer,Attention,MoE,LatentCache,mistral_large4.pysanitizeandshard,mla_kernel.py/block_mla_kernel.pyfused sparse-MLA decode kernels,speculative_verifier.py). Test casemistral_large4in https://github.com/Blaizzy/mlx-vlm/blob/main/mlx_vlm/tests/model_cases.json (8 layers,kv_source_layers [0, 1, 2, 3, 4, 5, 6, 3],indexer_types [full, full, shared, full, full, shared, full, shared],index_topk 4, chunkedforward_cache [2, 3, 3]).
Checkpoints
| HF id | Revision | Format | Safetensors size |
|---|---|---|---|
mistralai/Mistral-Large-4-1T-A52B |
af26e7869af601441d5cdf75a1272469ddc3d059 |
native FP8 E4M3 128x128 blocks (quantization_config.quant_method: fp8), 54 consolidated-*.safetensors shards with consolidated.safetensors.index.json, Mistral-native tensor names, bundled BF16 DSpark head (about 4.2 GB) |
1060.55 GB |
mistralai/Mistral-Large-4-1T-A52B-NVFP4 |
bb6d00fe249b0e876f0cffc6b85014be02de3e68 |
native NVFP4 experts, params.json only (no config.json) |
610.04 GB |
inferencerlabs/Mistral-Large-4-1T-A52B-MLX-Q3i |
06c416e2bdd09ad82bca9fc6cdf3954abdd05e24 |
Inferencer INF Q3 (not loadable by mlx-vlm conventions) | 459.02 GB |
Architecture (from the upstream code and the FP8 release's config.json)
Config. text_config (mistral_large4_text): hidden 6144, 72 layers, 64 heads (num_key_value_heads 64), kv_lora_rank 512, qk_nope_head_dim 64, qk_rope_head_dim 64, v_head_dim 128, intermediate_size 24576 (dense layer 0), moe_intermediate_size 6144, n_routed_experts 128, n_shared_experts 1, num_experts_per_tok 4, first_k_dense_replace 1, n_group 1, topk_group 1, routed_scaling_factor 1.0, index_topk 2048, index_head_dim 128, index_n_heads 32, final_logit_softcapping 30.0, rms_norm_eps 1e-5, vocab 204800, max_position_embeddings 1048576, rope_parameters {rope_type: yarn, rope_theta 1e4, factor 2048, original_max_position_embeddings 512, beta_fast 32, beta_slow 1, attention_factor 1.0}, no_rope_layers (1 = RoPE, 0 = NoPE despite the name; every fourth layer is NoPE), kv_source_layers (layers 39, 43, 47, ... 71 read layer 35's latent KV), indexer_types (full for layers 0-16, then a repeating shared, shared, full, full pattern), tie_word_embeddings false. vision_config (pixtral): hidden 2048, 30 layers, 16 heads, head_dim 128, intermediate 6144, image_size 1540, patch_size 14, axial 2D RoPE theta 1e4. Top level: image_token_index 10, spatial_merge_size 2, multimodal_projector_bias false, projector_hidden_act gelu, vision_feature_layer -1. quantization_config.modules_to_not_convert lists the vision tower, projector, lm_head, kv_b_proj, indexer.wk, indexer.weights_proj, kv_a_proj_with_mqa (these stay BF16).
Config validation (upstream TextConfig.__post_init__): no_rope_layers, kv_source_layers and indexer_types must have num_hidden_layers entries; for every layer i, 0 <= kv_source_layers[i] <= i, the source must be its own source, and the source must have the same RoPE/NoPE layout as i; 0 <= expert_start < expert_end <= n_routed_experts.
Native metadata (Blaizzy/mlx-vlm#2736, params.json): Mistral names dim, n_layers, hidden_dim, n_heads, n_kv_heads, norm_eps, softmax_tanh_gating, moe.{num_experts, num_shared_experts, expert_hidden_dim, num_experts_per_tok, num_expert_groups, num_expert_groups_per_tok, routed_scale, first_k_dense_replace}, dsa.{topk, head_dim, n_heads, sharing}, nope (a comma pattern of rope/nope repeated to n_layers), kv_sharing.source_layers_str, yarn.{factor, original_max_position_embeddings, beta, alpha} map to the fields above (beta -> beta_fast, alpha -> beta_slow); quantization.qformat_weight: fp8_e4m3 with qscheme_weight: BLOCK and 128x128 blocks means native block FP8 whose scale key is qscale_weight; vision_encoder holds the Pixtral config with image_token_id and adapter_bias.
LeRoPE. inv = theta^(-arange(0, 64, 2)/64); YaRN ramp with low = max(floor(corr(beta_fast)), 0), high = min(ceil(corr(beta_slow)), 63), corr(r) = 64 * ln(orig / (r * 2 pi)) / (2 ln theta), ramp = clip((arange(32) - low) / max(high - low, 0.001), 0, 1), inv_freq = inv * ((1 - ramp) + ramp / factor); angles pos * inv_freq * exp(alpha) in float32 with a learned alpha [32] (lerope.alpha); no attention scaling (attention_factor 1.0). Rotation takes interleaved input pairs and writes a half-split output: concat(a*cos - b*sin, b*cos + a*sin) with a = x[..., ::2], b = x[..., 1::2].
SSMax (SoftmaxScaling): per-head s (init 0) and b (init 1); q *= s * log(pos + 1) + b with absolute positions, applied to the attention query and, with its own parameters, to the indexer query.
Attention (one decoder layer i): wq [h -> 64 * head_dim] with head_dim = 128 on RoPE layers (64 nope + 64 rope) and 128 nope on NoPE layers; RoPE on the last 64 dims of q on RoPE layers. If kv_source_layers[i] == i: kv = wkv_a_with_mqa(x) ([h -> 512 + rope_dim]), latent kv_a_norm(kv[..., :512]) (RMSNorm), k_rope = kv[..., 512:] rotated on RoPE layers, both appended to this layer's latent cache and published for sharing; otherwise the layer reads the source layer's (latent, k_rope) for this step and owns no KV projection or cache of its own. wkv_b [512 -> 64 * (nope + 128)] expands latent keys and values; wo [64 * 128 -> h]. Prefill: dense SDPA over expanded keys concat(k_nope, k_rope) with scale head_dim^-0.5 and the causal mask intersected with the DSA selection. Decode: absorbed attention (fold wkv_b's key half into q, attend over the selected latents with an fp32 core, then apply the value half).
DSA indexer (Indexer, present when indexer_types[i] == full): k = k_norm(wk(x)) (LayerNorm eps 1e-6, [h -> 128]), rotated on its first 64 dims on RoPE layers and appended to the indexer cache; when the cached length is at most index_topk, return no selection (all causal tokens attend); else q = wq_b(q_input_norm(x)) (LayerNorm eps 1e-6 on x, not on a q-lora latent; [h -> 32 * 128]), SSMax-scaled and rotated, weights = weights_proj(x) * 32^-0.5 in float32, scores = sum_heads(relu(q . k * 128^-0.5) * weights) masked to causal positions, top-index_topk by argpartition. A shared layer reuses the previous layer's top-k indices. A sanitize-time packing fuses wk and weights_proj into wk_weights_proj when both are dense floating point.
MoE (MoE.route): scores = softmax(router_logits(x, gate.weight)) in precise float32; optional group limiting (n_group > 1, off here); top-4 by argpartition, sorted ascending (the reference scatter order); weights normalized by their sum (+1e-20) times routed_scaling_factor; experts w1/w3/w2 SwiGLU; outputs combined in float32 then cast; plus one shared expert MLP (moe_intermediate_size * n_shared_experts). Layer 0 is a dense MLP. A sanitize-time packing fuses dense w1/w3 into gate_up_proj when both are floating point with equal shapes.
Logits. lm_head (untied), tanh(logits / 30) * 30.
Weights and sanitize (mistral_large4.py): drop mtp* and *.input_scale; layers.N.{experts,shared_experts,gate}.* gain a feed_forward. prefix; layers.N.* -> language_model.model.layers.N.* (attention names attention.{wq, wkv_a_with_mqa, kv_a_norm, wkv_b, wo, indexer.*}, attention_norm, ffn_norm keep their Mistral names inside the model); tok_embeddings.weight -> language_model.model.embed_tokens.weight; norm.weight -> language_model.model.norm.weight; lerope.alpha -> language_model.model.rotary_emb.alpha; output.weight -> language_model.lm_head.weight; pre_mm_projector_norm.weight -> multi_modal_projector.norm.weight; patch_merger.merging_layer.weight -> multi_modal_projector.patch_merger.merging_layer.weight; vision_language_adapter.w_in/w_out -> multi_modal_projector.linear_1/linear_2; vision_encoder.* -> vision_tower.vision_model.* with .wq/.wk/.wv/.wo -> .q_proj/.k_proj/.v_proj/.o_proj, .w1/.w2/.w3 -> .gate_proj/.down_proj/.up_proj, and patch_conv.weight transposed (0, 2, 3, 1); per-expert experts.E.{w1,w2,w3}.{weight, scales, biases, weight_scale_2} stacked for E in [expert_start, expert_end).
Current mlxcel state
src/models/detection.rs:1056routesmistral3and:1061mistral4;mistral_large4has no arm. Mistral Large 3 (#2401, open) plansmistral_large3and the same Mistral-native remap for the vision side andtok_embeddings/output/norm.src/loading/vlm_pixtral.rs:367(load_mistral3_vlm) builds the Pixtral encoder (src/vision/encoders/pixtral.rs),Mistral3Projector(src/vision/connectors/mistral3.rs) and the Pixtral processor over a text backbone, and already hosts the Mistral 4 MLA+MoE backbone (docs/supported-models.md).- DSA:
src/models/deepseek_v32.rs(apply_sparse_prefill_maskat line 803, masked dense prefill),src/models/deepseek_v32_indexer.rs(the lightning indexer, shared withsrc/models/glm_moe_dsa.rs),src/models/deepseek_v32_latent.rs(quantized MLA latent option, #3163). None of these has KV sharing, indexer sharing, NoPE layers, SSMax or LeRoPE. GLM-5.2 IndexShare (#2964, open) adds cross-layer indexer sharing to the GLM DSA family; reuse its mechanism rather than writing a second one. - FP8:
src/models/fp8_block.rsreconstructs 128x128 block FP8 withweight_scale_invand requantizes tomxfp8; the native release names the scaleqscale_weight(per Blaizzy/mlx-vlm#2736). - Weights:
mlxcel_core::weightsreadsmodel.safetensors.index.json(src/lib/mlxcel-core/src/weights.rs:96) and otherwise globs shards; the native release shipsconsolidated.safetensors.index.jsonandconsolidated-NNNNN-of-00054.safetensors, andweights.rs:508skips a singleconsolidated.safetensorsbeside real shards. Confirm the glob picks up the numbered consolidated shards and that the DSpark head tensors are dropped by sanitize rather than loaded. - No expert parallelism:
docs/distributed.mdcovers tensor and pipeline parallel only.
Proposed solution
- Detection and registry.
"mistral_large4" => Ok(ModelType::MistralLarge4VLM);ModelType,src/models/registry.rs,src/model_metadata.rsentries. A directory with onlyparams.jsonis accepted when it parses as the native schema (normalized as in Blaizzy/mlx-vlm#2736), else refused with a message naming the missing fields. - Config.
src/models/mistral_large4/config.rsaccepting bothconfig.json(text_config/vision_config) and nativeparams.json, with the validation above. - Text model. New
src/models/mistral_large4.rs(withsrc/models/mistral_large4/{attention, indexer, moe, rope}.rs). Reuse the MLA attention core and absorbed-decode path fromdeepseek_v32.rsand the indexer scoring and top-k fromdeepseek_v32_indexer.rswhere the math matches, parameterizing them for: LayerNorm on the indexer q input, SSMax, the interleaved-in / half-split-out rotation, NoPE layers (rope_dim = 0, nope dim 128), shared KV sources (a layer without its own KV owns no latent cache; caches are per source layer), shared indexers (the previous layer's indices), and the softmax router with a shared expert. LeRoPE is a new rope variant insrc/models/rope_utils.rswith the learnedalpha. Prefill uses masked dense DSA (the current DeepSeek-V3.2 approach); fused sparse-MLA kernels are out of scope. Implementlast_row_logitswith the softcap. - Loader.
src/loading/vlm_mistral_large4.rs: the sanitize table above, expert stacking, thewk_weights_projandgate_up_projdense packing (or keep them separate if the shared linear path makes packing pointless; decide by measurement, not by default), native block-FP8 reconstruction withqscale_weightthroughsrc/models/fp8_block.rs, NVFP4 experts withweight_scale_2throughswitch_layers, and the Pixtral vision side by factoring the shared part ofload_mistral3_vlminto a helper (coordinate with #2401, which needs the same helper). WireLoadedModel,delegate_language_model!andVlmRuntimeRef. Register the directory entry point intry_load_vlm_model_from_dir()(src/loading/mod.rs:337) and the family route insrc/loading/vlm.rs, perdocs/adding-models.md(VLM checklist item 5). - Docs.
docs/supported-models.mdentry with checkpoint sizes, hardware requirement and refused paths.
Scope
In scope: config.json and native params.json metadata; native FP8 and NVFP4 weights and standard MLX conversions of them; text and image prompts; CLI and server; single host.
Out of scope: expert parallelism and the upstream shard / rank-local expert-range loading (mlxcel has no EP), the fused sparse-MLA Metal kernels (mla_kernel.py, block_mla_kernel.py), DSA sparse prefill that gathers only the top-k keys (track with the DeepSeek-V3.2 DSA work, not here), the DSpark drafter and speculative verifier, FP8 activation or KV quantization, the Inferencer Q3i format.
Implementation notes
- Precision rule.
load_vlm_weights()does bf16 -> f16 for non-quantized weights on Apple Silicon; this checkpoint is quantized (FP8 or NVFP4), so dense BF16 tensors listed inmodules_to_not_convertkeep their dtype, and quantized planes keep their scales (FP32 global scales for NVFP4). LeRoPE angles, SSMax log terms, indexer scores and routing run in float32. - Edge cases. Context at or below
index_topk(2048) runs dense attention with no indexer selection; a shared indexer layer at position 0 of a pattern must have a preceding full layer (validated at load); prefill chunking must keep shared latents and indices consistent across chunks (the upstream case uses chunks[2, 3, 3]). - Shared hotspots. Changes to
deepseek_v32.rs/deepseek_v32_indexer.rs/rope_utils.rsaffect DeepSeek-V3.2 and GLM-5 DSA; update// Used by:comments and keep their outputs bit-identical. - Attribution. Derived from mlx-vlm (MIT). Add per-file derivation lines and a
NOTICEentry per the "Third-party attribution" rule in the repository development guidelines.
Acceptance criteria
-
mlxcel archlistsmistral_large4; detection tests on the FP8 release'sconfig.jsonand on a nativeparams.json; config validation rejects a KV source that is not its own source, a source with a different RoPE layout, and wrong-length per-layer lists, naming the field. -
params.jsonnormalization test: a native fixture produces the sameTextConfigas upstreamconfig_from_params(fixture committed with the upstream commit noted). - Sanitize test in
src/loading/vlm_mistral_large4_tests.rs: a synthetic native key set (dense layer 0, one MoE layer with three experts, vision, projector,lerope.alpha,mtp_dspark.*,*.input_scale) maps to exactly the expected names, stacks experts in order, transposespatch_conv, drops the draft and input-scale tensors, and is a no-op on converted keys. - LeRoPE and SSMax unit tests match upstream values for the release's
rope_parametersand a seededalpha,s,b. - Tiny random-weight test with the upstream
mistral_large4case shape (8 layers, the listedkv_source_layersandindexer_types,index_topk 4, small Pixtral): chunked prefill[2, 3, 3]equals a single prefill, decode after prefill equals a full forward, a shared-KV layer allocates no cache of its own, and an image placeholder's features reach the merged embeddings. - Regression: DeepSeek-V3.2 and GLM-5 DSA tests pass unchanged.
- Real checkpoint, once hardware allows:
mlxcel generatewith a text prompt and with--imageon a standard MLX conversion ofmistralai/Mistral-Large-4-1T-A52Bmatchesmlx_vlm.generate, and the same throughmlxcel-server. - Integrated in
mlxcel generate --image,mlxcel-serverchat completions with images andmlxcel arch;docs/supported-models.md,NOTICE, derivation lines.
Verification
cargo build --release --features metal,accelerate
cargo test --profile test-fast --features metal,accelerate mistral_large4
cargo test --profile test-fast --features metal,accelerate deepseek_v32
make verify-test
cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --check
Related
- Mistral Large 3 (shares the Mistral-native remap and the Pixtral helper): #2401.
- DSA families and their open work: GLM-5.2 IndexShare #2964, DeepSeek-V3.2 long-context fp16 #3178, MLA latent quantization #3163.
- Lingua principale
- Rust
- Stelle
- 505
- Fork
- 81
- Merge medio
- 14h 2m
- PR unite (30g)
- 448
Preparare l'ambiente
- Nessun Dockerfile né file Docker Compose
- Ha un modello di pull request
- Leggi la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di lablup/mlxcel
-
area:core priority:high status:ready type:security
Difficoltà 2/5 1-3 ore Idoneità per principianti 82/100
I maintainer di solito rispondono entro 1 giorno
-
priority:medium status:ready type:security
Difficoltà 4/5 3-5 giorni Idoneità per principianti 45/100
I maintainer di solito rispondono entro 1 giorno
-
area:models modeltype:text priority:medium status:in-progress type:bug
Difficoltà 4/5 3-5 giorni Idoneità per principianti 57/100
I maintainer di solito rispondono entro 1 giorno
-
area:models priority:low status:ready type:test
Difficoltà 4/5 3-5 giorni Idoneità per principianti 48/100
I maintainer di solito rispondono entro 1 giorno
-
area:models modeltype:omni priority:medium status:ready type:bug
Difficoltà 4/5 3-5 giorni Idoneità per principianti 48/100
I maintainer di solito rispondono entro 1 giorno
Tutte le issue di lablup/mlxcel
Issue simili
-
area:ui effort:medium enhancement P7 source:agent
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
I maintainer di solito rispondono entro 1 giorno
-
marketing
Difficoltà 2/5 1-3 ore Idoneità per principianti 85/100
I maintainer di solito rispondono entro 1 giorno
-
machine rename accepts a label already used by another machine, making --machine <label> ambiguousApertamaintainer-needed p2 remote triaged
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
I maintainer di solito rispondono entro 1 giorno
-
bug help wanted ui
Difficoltà 2/5 1-3 ore Idoneità per principianti 82/100
userFRM/egui-charts#4605 ·
I maintainer di solito rispondono entro 1 giorno
-
bug
Difficoltà 2/5 1-3 ore Idoneità per principianti 84/100
I maintainer di solito rispondono entro 1 giorno