feat(models): load Mistral Medium 3.5 per-tensor FP8 checkpoints
メンテナーはふだん 1 日以内に返信
まだ誰も着手していません。
評価
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 初心者へのやさしさ
- 8/100
- issue の種類
- 機能追加
- 明瞭さ
- おおむね明確
- 活発さ
- 活発
- 技術スタック
- rust
調査の方向性
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.
索引モデルが issue の本文から書いたものです。
説明
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_invis renamed tooutput_scaleandactivation_scaledropped;_fp8_as_mxfp8views the E4M3 weight asuint32and writes unit E8M0 group scales (full(.., 127, uint8), i.e. 2^0);Fp8Linearis anmxfp8QuantizedLinear(group 32, 8 bits) that multiplies its output byoutput_scaleand casts back. The kernel has no slot for a per-tensor scale, so the output carries it._fusejoins q/k/v intoqkv_projand gate/up intogate_up_proj(FusedGLU) only for fp8 layers stored identically; a fused layer gets a per-rowoutput_scale(each part's scalar repeated over its rows).shard()shardslm_headall-to-sharded and gathers the last axis (gather_last_axis) when embeddings are untied; fused layers shard with segments; a scalaroutput_scaleis kept whole on every rank, a per-row one is split with the rows.mistral3.Model.shardforwards 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:1056sendsmistral3with vision weights toModelType::Mistral3VLM, loaded byload_mistral3_vlm(src/loading/vlm_pixtral.rs:367) throughbuild_pixtral_family_context(:193). Its text backbone isLlama3Model(:236-242, the non-MLA branch), notMinistral3Model; the text-only route (src/loading/mod.rs:436,load_mistral3_text_directory_variant) usesMinistral3Model::load_from_text_config. - Keys:
strip_language_model_prefix(src/loading/vlm.rs:514) strips onlylanguage_model., andsanitize_pixtral_weights(src/vision/encoders/pixtral.rs:642) rewritesvision_towertovision_tower.vision_modelinside the key, somodel.language_model.layers.*keeps its prefix andmodel.vision_tower.*becomesmodel.vision_tower.vision_model.*; neither matches whatLlama3Model::from_weightsandPixtralVisionModel::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); withweight_block_size: nullit would fail on the null too.UnifiedLinear::from_weightswould see a uint8 weight with noscalesand fail. - Reusable pieces:
QuantizedWeight.global_scale(src/lib/mlxcel-core/src/layers.rs:53) is a per-linear output multiplier thatquantized_linear_forward_global_scaleapplies 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'soutput_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 aglobal_scalesidecar (layers.rs:3524-3545, #2444). The tensor-parallel planner already offers a vocab-parallellm_head(ShardStrategy::VocabParallel,src/distributed/tensor_parallel/sharded_loading.rs:120) and mapsmistral3/ministral3tobuild_llama_plan(plan_generator.rs:88,:315); weights not in the plan, such as a{p}.global_scalescalar, replicate. - Precision boundary:
is_model_quantized(vlm.rs:475) reads onlyquantization, so on Apple Siliconfinish_vlm_weights_commonconverts every BF16 tensor to f16, theweight_scale_invscalars included.
Required changes
- 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 intext_config,fmtabsent or "e4m3", andweight_block_sizeabsent or null.pub(crate) fn rewrite_per_tensor_fp8(weights: &mut WeightMap) -> Result<usize, String>: for each{p}.weight_scale_invholding one element beside a one-byte{p}.weightof shape[out, in]within % 32 == 0, write{p}.weightasview(.., UINT32)[out, in/4], and split the scalesinto a power of two and a residual:e = floor(log2(s)),{p}.scales= uint8[out, in/32]filled with127 + e(clamped to 0..254),{p}.global_scale= float32[1]holdings / 2^e(in [1, 2)). Remove{p}.weight_scale_invand{p}.activation_scale. Error on a non-finite or non-positive scale, aninnot divisible by 32, or a non-scalarweight_scale_inv(that is a block layout forfp8_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.
- Precision boundary (CLAUDE.md Apple Silicon rules): when
per_tensor_fp8_declared, exempt keys ending in.weight_scale_invand.activation_scalefrom the bf16-to-f16 conversion withconvert_bf16_weights_with_keep(src/models/sanitize.rs:2819) in both funnels,finish_vlm_weights_common(vlm.rs:383) andload_text_weights(sanitize.rs:2390site), 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. - 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 explicitquantizationwins, as infp8_block::merge_fp8_block_quantization), soUnifiedLinearreads the planes asmxfp8. Unquantized modules have noscalesand stay regular linears. src/loading/vlm_pixtral.rsbuild_pixtral_family_context: beforestrip_language_model_prefix, remap the transformers-5 layout:model.language_model.tomodel.,model.vision_tower.tovision_tower.,model.multi_modal_projector.tomulti_modal_projector.;lm_head.unchanged. Then callrewrite_per_tensor_fp8when declared. Do the same rewrite inMinistral3Model::load_from_text_config(src/models/ministral3.rs:942) andMinistral3Model::load(:922) for the text-only route.- Backbone check: confirm with a unit test that the VLM route's
llama3::ModelArgsbuilt from thistext_configresolves YaRN (factor 64,original_max_position_embeddings4096,rope_theta1e6) and thatllama_4_scaling_beta: 0is a no-op. If either fails, route aministral3text_configtoMinistral3Modelinbuild_pixtral_family_context, mirroringis_ministral3_config(src/model_metadata.rs:329), rather than teachingLlama3Modelnew fields. - Fusion (measure-then-keep): extend
FusedQKVLinear::from_weights_separate_with_modeso that when all three planes are mxfp8 with[1]global_scalesidecars and equal input width, it concatenates weights and scales by rows and builds a[q + k + v]float32global_scalevector (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 indocs/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. - Tensor parallel: with TP active, do not fuse (each
global_scalestays a[1]scalar, which replicates correctly for column- and row-parallel planes). Check thatbuild_llama_planshards the new{p}.scales(uint8[out, in/32]) along the same axis as{p}.weight, and that--tp-lm-head-mode vocab_parallelshards the BF16lm_head.weightafter the key remap. Pipeline parallel is out of scope:src/distributed/pipeline/stage_executor/mistral.rs:38deliberately excludes Ministral3 and Mistral3.
Acceptance criteria
-
src/models/fp8_tensor_tests.rs:per_tensor_fp8_matches_dense_referencebuilds a[64, 64]E4M3 plane with scale 1.35e-4, rewrites it, loads aUnifiedLinear, and asserts the output on an f16 input matchesx @ (dequant(w) * s).Twithin 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_residualasserts scale 1.35e-4 gives E8M0 byte127 - 13 = 114and residual1.35e-4 * 2^13(about 1.106). - Same file:
per_tensor_fp8_declaredacceptsweight_block_size: nulland absence, rejects[128, 128];rewritedropsactivation_scaleand errors onin = 48. -
src/models/sanitize_tests.rs:per_tensor_fp8_scale_skips_bf16_to_f16asserts a BF16weight_scale_invof 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_mistral3maps the three prefixes above and leaveslm_head.weightalone; fails today. - The YaRN routing test from change 5.
- If fusion is kept: a
FusedQKVLineartest 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_paralleltests: the plan for a two-rankministral3FP8 layer shards{p}.scaleswith{p}.weightand replicates{p}.global_scale. - Wired into the real flow:
mlxcel generate,mlxcel generate --imageandmlxcel-serverload 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.
- 主要言語
- Rust
- スター
- 505
- フォーク
- 81
- 平均マージ
- 14時間 2分
- マージ済み PR(30日)
- 448
環境構築
- Dockerfile・Docker Compose ファイルなし
- プルリクエストのテンプレートあり
- コントリビューションガイドを読む
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
lablup/mlxcel のほかの issue
-
area:core priority:high status:ready type:security
難易度 2/5 1〜3時間 初心者へのやさしさ 82/100
メンテナーはふだん 1 日以内に返信
-
priority:medium status:ready type:security
難易度 4/5 3〜5日 初心者へのやさしさ 45/100
メンテナーはふだん 1 日以内に返信
-
area:models modeltype:text priority:medium status:in-progress type:bug
難易度 4/5 3〜5日 初心者へのやさしさ 57/100
メンテナーはふだん 1 日以内に返信
-
area:models priority:low status:ready type:test
難易度 4/5 3〜5日 初心者へのやさしさ 48/100
メンテナーはふだん 1 日以内に返信
-
area:models modeltype:omni priority:medium status:ready type:bug
難易度 4/5 3〜5日 初心者へのやさしさ 48/100
メンテナーはふだん 1 日以内に返信
似ている issue
-
TypeScript BM25 drops supplementary characters at the token length limit対応中かも @ErenAta16 が今日担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
chroma-core/chroma#8038 ·
メンテナーはふだん 1 日以内に返信
-
p3 ready
難易度 2/5 1〜3時間 初心者へのやさしさ 71/100
メンテナーはふだん 1 日以内に返信
-
area:ui effort:medium enhancement P7 source:agent
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
メンテナーはふだん 1 日以内に返信
-
marketing
難易度 2/5 1〜3時間 初心者へのやさしさ 85/100
メンテナーはふだん 1 日以内に返信
-
machine rename accepts a label already used by another machine, making --machine <label> ambiguousオープンmaintainer-needed p2 remote triaged
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
メンテナーはふだん 1 日以内に返信