feat(models): load Mistral Medium 3.5 per-tensor FP8 checkpoints

Đang mở
#3,239 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
Mức phù hợp với người mới
8/100
Loại issue
Tính năng
Độ rõ ràng
Khá rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
rust
Lĩnh vực
backend, machine-learning

Hướng nghiên cứu

Start with the key remap in src/loading/vlm_pixtral.rs (build_pixtral_family_context) and the FP8 config parser in src/models/fp8_block.rs, since the new src/models/fp8_tensor.rs builds on both. Done means the unit tests named in the acceptance criteria (fp8_tensor_tests.rs, sanitize_tests.rs, vlm_pixtral_tests.rs) pass and the Mistral Medium 3.5 checkpoint loads and generates. This is multi-subsystem design work, so pair with a maintainer before starting.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

arch:dense area:models modelsize:xlarge modeltype:vlm priority:medium status:ready type:enhancement

Summary

Load mistralai/Mistral-Medium-3.5-128B, Mistral's own FP8 release of Mistral Medium 3.5 (a mistral3 VLM: Pixtral tower plus an 88-layer dense ministral3 decoder, hidden 12288, 96 heads, 8 KV heads, YaRN factor 64). Its linears are per-tensor FP8: E4M3 weights with one BF16 weight_scale_inv scalar per tensor (weight_block_size: null) and a static activation_scale nobody consumes. mlxcel has no per-tensor FP8 path and does not read this checkpoint's transformers-5 key layout, so it fails to load. The work: per-tensor FP8 to MLX mxfp8 without dequantizing, the HF key remap for the Mistral 3 VLM loader, optional fused q/k/v and gate/up planes (kept only if measured faster), and tensor-parallel loading of the new sidecars with the vocab-parallel lm_head that already exists.

This is not #2401. #2401 is Mistral Large 3 (mistral_large3, 675B, DeepSeek-V3 MLA + MoE backbone, blocked on a 387 GB MLX conversion). This checkpoint is a dense ministral3 backbone, and its blocker is the FP8 format, not the architecture.

Upstream reference

ml-explore/mlx-lm#1986 (0d4d3d0), now in https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/ministral3/layers.py, https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/ministral3/checkpoint.py, https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/ministral3/model.py and https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/mistral3/model.py:

  • weight_scale_inv is renamed to output_scale and activation_scale dropped; _fp8_as_mxfp8 views the E4M3 weight as uint32 and writes unit E8M0 group scales (full(.., 127, uint8), i.e. 2^0); Fp8Linear is an mxfp8 QuantizedLinear (group 32, 8 bits) that multiplies its output by output_scale and casts back. The kernel has no slot for a per-tensor scale, so the output carries it.
  • _fuse joins q/k/v into qkv_proj and gate/up into gate_up_proj (FusedGLU) only for fp8 layers stored identically; a fused layer gets a per-row output_scale (each part's scalar repeated over its rows).
  • shard() shards lm_head all-to-sharded and gathers the last axis (gather_last_axis) when embeddings are untied; fused layers shard with segments; a scalar output_scale is kept whole on every rank, a per-row one is split with the rows. mistral3.Model.shard forwards to the language model.

What the checkpoint holds

Hub API and safetensors headers, 2026-11-23: 121.8 G F8_E4M3 elements and 5.9 G BF16 (about 134 GB). quantization_config: {"quant_method": "fp8", "activation_scheme": "static", "weight_block_size": null, "dequantize": false, "modules_to_not_convert": ["model.vision_tower", "model.multi_modal_projector", "lm_head"]}. Keys: model.language_model.layers.N.{self_attn.{q,k,v,o}_proj, mlp.{gate,up,down}_proj}.{weight (F8_E4M3), weight_scale_inv (BF16 []), activation_scale (BF16 [])}, model.language_model.{embed_tokens,norm}.weight, lm_head.weight, model.vision_tower.*, model.multi_modal_projector.*. Sampled weight_scale_inv values in layer 0 run from 1.35e-4 to 4.8e-4. The repo also carries consolidated-*.safetensors (Mistral-native layout); mlxcel reads shards from model.safetensors.index.json, so those files are ignored and need not be downloaded.

Current mlxcel behavior

  • Detection: src/models/detection.rs:1056 sends mistral3 with vision weights to ModelType::Mistral3VLM, loaded by load_mistral3_vlm (src/loading/vlm_pixtral.rs:367) through build_pixtral_family_context (:193). Its text backbone is Llama3Model (:236-242, the non-MLA branch), not Ministral3Model; the text-only route (src/loading/mod.rs:436, load_mistral3_text_directory_variant) uses Ministral3Model::load_from_text_config.
  • Keys: strip_language_model_prefix (src/loading/vlm.rs:514) strips only language_model., and sanitize_pixtral_weights (src/vision/encoders/pixtral.rs:642) rewrites vision_tower to vision_tower.vision_model inside the key, so model.language_model.layers.* keeps its prefix and model.vision_tower.* becomes model.vision_tower.vision_model.*; neither matches what Llama3Model::from_weights and PixtralVisionModel::from_weights(.., "vision_tower.vision_model") read.
  • FP8: no Mistral loader reads weight_scale_inv. The one FP8 config parser, qwen_fp8_block_quantization (src/models/fp8_block.rs:148), is Qwen-only and rejects a missing block size (:183-190); with weight_block_size: null it would fail on the null too. UnifiedLinear::from_weights would see a uint8 weight with no scales and fail.
  • Reusable pieces: QuantizedWeight.global_scale (src/lib/mlxcel-core/src/layers.rs:53) is a per-linear output multiplier that quantized_linear_forward_global_scale applies after the matmul and casts back (src/lib/mlxcel-core/cpp/mlx_cxx_bridge.cpp:1749), loaded from {prefix}.global_scale (layers.rs:2821). It is the equivalent of upstream's output_scale, and its multiply broadcasts a [out] vector as well as a [1] scalar. FusedQKVLinear (layers.rs:3403) already fuses q/k/v at load for Llama3 but deliberately loads split when any plane has a global_scale sidecar (layers.rs:3524-3545, #2444). The tensor-parallel planner already offers a vocab-parallel lm_head (ShardStrategy::VocabParallel, src/distributed/tensor_parallel/sharded_loading.rs:120) and maps mistral3 / ministral3 to build_llama_plan (plan_generator.rs:88, :315); weights not in the plan, such as a {p}.global_scale scalar, replicate.
  • Precision boundary: is_model_quantized (vlm.rs:475) reads only quantization, so on Apple Silicon finish_vlm_weights_common converts every BF16 tensor to f16, the weight_scale_inv scalars included.

Required changes

  1. New src/models/fp8_tensor.rs:
    • pub(crate) fn per_tensor_fp8_declared(config: &Value) -> bool: quant_method "fp8" (case-insensitive) at the top level or in text_config, fmt absent or "e4m3", and weight_block_size absent or null.
    • pub(crate) fn rewrite_per_tensor_fp8(weights: &mut WeightMap) -> Result<usize, String>: for each {p}.weight_scale_inv holding one element beside a one-byte {p}.weight of shape [out, in] with in % 32 == 0, write {p}.weight as view(.., UINT32) [out, in/4], and split the scale s into a power of two and a residual: e = floor(log2(s)), {p}.scales = uint8 [out, in/32] filled with 127 + e (clamped to 0..254), {p}.global_scale = float32 [1] holding s / 2^e (in [1, 2)). Remove {p}.weight_scale_inv and {p}.activation_scale. Error on a non-finite or non-positive scale, an in not divisible by 32, or a non-scalar weight_scale_inv (that is a block layout for fp8_block), naming the key.
    • Why not upstream's unit scales: upstream runs the matmul in bf16, where an output 1/s times too large (about 7400x here) is harmless. mlxcel runs f16 activations on Apple Silicon, where it would overflow f16's 65504 ceiling. Moving the power-of-two part into the E8M0 group scale is exact and leaves the f16 matmul output within 2x of its true value. Dequantizing to f16 was also rejected: about 256 GB of weights.
  2. Precision boundary (CLAUDE.md Apple Silicon rules): when per_tensor_fp8_declared, exempt keys ending in .weight_scale_inv and .activation_scale from the bf16-to-f16 conversion with convert_bf16_weights_with_keep (src/models/sanitize.rs:2819) in both funnels, finish_vlm_weights_common (vlm.rs:383) and load_text_weights (sanitize.rs:2390 site), so the scale is read from its BF16 value and never through an f16 subnormal. Embeddings, norms, lm_head, the vision tower and the projector stay unquantized and keep converting to f16 like any non-quantized weight. There are no bf16 group scales or biases in this checkpoint for the "quantized scales stay bf16" rule to cover; the new E8M0 scales are uint8.
  3. Config: when declared, insert quantization: {"group_size": 32, "bits": 8, "mode": "mxfp8"} into the text config and the top level before args are parsed (an explicit quantization wins, as in fp8_block::merge_fp8_block_quantization), so UnifiedLinear reads the planes as mxfp8. Unquantized modules have no scales and stay regular linears.
  4. src/loading/vlm_pixtral.rs build_pixtral_family_context: before strip_language_model_prefix, remap the transformers-5 layout: model.language_model. to model., model.vision_tower. to vision_tower., model.multi_modal_projector. to multi_modal_projector.; lm_head. unchanged. Then call rewrite_per_tensor_fp8 when declared. Do the same rewrite in Ministral3Model::load_from_text_config (src/models/ministral3.rs:942) and Ministral3Model::load (:922) for the text-only route.
  5. Backbone check: confirm with a unit test that the VLM route's llama3::ModelArgs built from this text_config resolves YaRN (factor 64, original_max_position_embeddings 4096, rope_theta 1e6) and that llama_4_scaling_beta: 0 is a no-op. If either fails, route a ministral3 text_config to Ministral3Model in build_pixtral_family_context, mirroring is_ministral3_config (src/model_metadata.rs:329), rather than teaching Llama3Model new fields.
  6. Fusion (measure-then-keep): extend FusedQKVLinear::from_weights_separate_with_mode so that when all three planes are mxfp8 with [1] global_scale sidecars and equal input width, it concatenates weights and scales by rows and builds a [q + k + v] float32 global_scale vector (each part's residual repeated over its rows), used only by the plain fused forward (the fused-rope kernels take no scale and must keep refusing it). Add the equivalent gate/up fusion in the backbone MLP that runs this checkpoint. Keep both only if decode and prefill tok/s on the real checkpoint improve by at least 3% over split planes, per the gate in docs/benchmarks.md ("Fused decode kernels: the measure-then-keep gate"); otherwise leave the split planes, which are already correct, and record the numbers. Update the // Used by: comment on any shared function touched.
  7. Tensor parallel: with TP active, do not fuse (each global_scale stays a [1] scalar, which replicates correctly for column- and row-parallel planes). Check that build_llama_plan shards the new {p}.scales (uint8 [out, in/32]) along the same axis as {p}.weight, and that --tp-lm-head-mode vocab_parallel shards the BF16 lm_head.weight after the key remap. Pipeline parallel is out of scope: src/distributed/pipeline/stage_executor/mistral.rs:38 deliberately excludes Ministral3 and Mistral3.

Acceptance criteria

  • src/models/fp8_tensor_tests.rs: per_tensor_fp8_matches_dense_reference builds a [64, 64] E4M3 plane with scale 1.35e-4, rewrites it, loads a UnifiedLinear, and asserts the output on an f16 input matches x @ (dequant(w) * s).T within 1e-3 relative and contains no inf. A variant with upstream's unit scales must overflow on the same input, which the test asserts to prove discrimination.
  • Same file: scale_splits_into_exponent_and_residual asserts scale 1.35e-4 gives E8M0 byte 127 - 13 = 114 and residual 1.35e-4 * 2^13 (about 1.106).
  • Same file: per_tensor_fp8_declared accepts weight_block_size: null and absence, rejects [128, 128]; rewrite drops activation_scale and errors on in = 48.
  • src/models/sanitize_tests.rs: per_tensor_fp8_scale_skips_bf16_to_f16 asserts a BF16 weight_scale_inv of 1.0e-6 reaches the rewrite with its BF16 value (through f16 it would be a subnormal, off by more than 1%).
  • src/loading/vlm_pixtral_tests.rs: hf_layout_keys_remap_for_mistral3 maps the three prefixes above and leaves lm_head.weight alone; fails today.
  • The YaRN routing test from change 5.
  • If fusion is kept: a FusedQKVLinear test that the fused per-row-scale plane equals the three split planes within 1e-3. Either way, the measured tok/s numbers go in the PR body.
  • src/distributed/tensor_parallel tests: the plan for a two-rank ministral3 FP8 layer shards {p}.scales with {p}.weight and replicates {p}.global_scale.
  • Wired into the real flow: mlxcel generate, mlxcel generate --image and mlxcel-server load the checkpoint with no flag.

Validation

Checkpoint: mistralai/Mistral-Medium-3.5-128B, about 134 GB, so it runs on the 256 GB+ host. Download model-*.safetensors, model.safetensors.index.json and the configs only. mlx-community/Mistral-Medium-3.5-128B-4bit (affine) is the no-regression check.

make verify-test
cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --check
./target/release/mlxcel generate -m models/Mistral-Medium-3.5-128B -p "Summarize the causes of the 1929 stock market crash." -n 256
./target/release/mlxcel generate -m models/Mistral-Medium-3.5-128B --image tests/fixtures/test_image_shapes.png -p "Describe the image." -n 128
cargo build --profile test-fast --features metal,accelerate --example logit_trace
./target/test-fast/examples/logit_trace models/Mistral-Medium-3.5-128B docs/architecture.md 256 4 8 512 > fp8.tsv

Per CLAUDE.md "Changes that move the numbers": compare the FP8 trace against an mlx-lm main reference on the same tokens (scripts/mlx_lm_logit_trace.py models/Mistral-Medium-3.5-128B docs/architecture.md 256 4 8 512 > ref.tsv) with scripts/compare_logit_traces.py --decided 2, and for the fusion step trace fused against split at decode width 1 and at the prefill width, reporting the decided-position disagreement and tok/s of each arm.

Related

#2401 (Mistral Large 3, different architecture), #2444 (global-scale sidecar keeps fused q/k/v split), #1361 and #2411 (block and compressed-tensors FP8 requantized to mxfp8), #3201 (ModelOpt mixed NVFP4 + FP8), #3070 and #3081 (prefill lm_head projection). Upstream: ml-explore/mlx-lm#1986.

Ngôn ngữ chính
Rust
Star
505
Fork
81
Merge trung bình
14 giờ 2 phút
Pull request đã merge (30 ngày)
448

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của lablup/mlxcel

Tất cả issue của lablup/mlxcel

Issue tương tự

Thêm issue về Rust

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.