You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(models): apply ERNIE-4.5 MoE text correction bias in float32 routing - #3322
The ERNIE-4.5 text MoE router now projects the flattened input in float32. On CUDA, mixing BF16 and F32 ordinarily produces BF16. The text loader widens BF16 gate operands once, including affine scales and zero points, so both sides of the projection support float32 arithmetic. Both gate activations rank experts by the activated gates plus the checkpoint correction bias. Mixing weights come from the selected experts’ original gates and are normalized in float32 with the existing 1e-12 floor. Routed and shared experts still receive the original activation.
The loader prefers mlp.e_score_correction_bias, then checks mlp.moe_statics.e_score_correction_bias. It accepts [E] and [1, E], checks the configured expert count, and reports the offending key on a shape error. A missing key gives a float32 zero vector.
Regression tests
On a GB10 with CUDA 13, all four new tests passed. Restoring the old routing and ignoring the bias in the loader made all four fail.
Test
Fixed result
With the old behavior restored
Selection and mixing
Experts 0 and 2, with their renormalized raw scores, for both softmax and sigmoid
The softmax case selected 0 and 1
Bias loading
Both key names, converted-key precedence, f32 values, zero fallback, and invalid shapes passed
The stored vector loaded as zeros
Router precision
Both f16 and BF16 fixtures give dot products of 1 and 1 + 2⁻¹² in f32. Expert 1 wins
The f16 dot products tied. Expert 0 won
Quantized router precision
Affine 4-bit weights with BF16 scales select expert 1 on the same near-tie
Expert 0 won
On mlx-community/ERNIE-4.5-21B-A3B-PT-bf16, all 1,728 bias values matched the safetensors files after running the production loader with MLXCEL_CUDA_F16_NORMALIZE=1. None fell below the f16 normal range. In 26 of the 27 routed layers the exported bias is constant across experts. Layer 25 has two values, 28.625 and 28.75.
Checkpoint validation
The published checkpoints also expose a separate loader issue. The community exports use a fused shared GLU, while mlxcel looks for numbered shared experts. The original Baidu checkpoint additionally uses numbered routed experts, while mlxcel expects stacked planes.
For inference comparisons I created local copies in mlxcel’s expected layout. The existing fused shared GLU was named as expert 0 and its configured count set to one, retaining its full width. For Baidu I also stacked each routed projection’s original planes in expert order and omitted the unused MTP tensors. The repack copied the tensor bytes without dtype conversion. The community exports used Baidu’s tokenizer JSON after I checked that the SentencePiece files had identical SHA-256 hashes. The mlx-lm reference loaded the original tensor layout.
For The capital of France is Paris., I captured the seven input-token activations at every MoE layer from mlx-lm on the original Baidu weights. The Rust router selected the same six experts as float32 NumPy on 189/189 token/layer pairs. The unbiased NumPy calculation matched on 120/189. None of the corrected scores tied at the selection boundary. The fixed HTTP server returned 200 and generated 12 tokens on a completion request using the Baidu layout copy.
Teacher-forced logits
Spark2, NVIDIA GB10 (sm_121), CUDA 13.0. I traced docs/architecture.md with logit_trace ... 256 4 8 512 and compared each arm to mlx_lm_logit_trace.py with compare_logit_traces.py --decided 2. The reference used mlx-lm main 1bf8da05a and MLX 0.32.4 on the same GPU. Each trace scored 1,024 positions. A decided position has a reference top-two logit gap of at least 2.
Checkpoint
Top-1 mismatches, main → fix
Largest reference gap at a mismatch, main → fix
Decided mismatches, main → fix
Perplexity, reference / main / fix
Baidu, F32 router
26 → 10
0.250 → 0.125
0 → 0 of 486
11.7836 / 11.7490 / 11.7712
Community BF16
16 → 19
1.250 → 0.188
0 → 0 of 488
11.7327 / 11.7490 / 11.7484
The issue asks for a decided position where the fix recovers the reference token. Main already matched every decided position on this corpus, so that specific improvement was unobserved. The BF16 run had three more top-1 mismatches overall. On the separate seven-position Baidu prompt trace, the fix matched all seven reference top tokens and main matched six. Both matched the one decided token.
Greedy generation
mlxcel generate --no-chat-template --temp 0 -n 12. The three ERNIE prompts were The capital of France is, Two plus two equals, and 海洋是. All nine layout-adapted cases generated on both builds.
Hugging Face checkpoint
Revision
Same generated text on main and fix
baidu/ERNIE-4.5-21B-A3B-PT
87db95487941cb39592ee0abca3b9155a6d19c5c
0 of 3
mlx-community/ERNIE-4.5-21B-A3B-PT-bf16
6de3db650133247146f2feec80a94ae8d22de8d7
2 of 3. The France continuation changed
mlx-community/ERNIE-4.5-21B-A3B-PT-4bit
6a55392c9930d43543bfa0a8ac6b67985bf4bd1d
2 of 3. The arithmetic continuation changed with the zero-bias fallback
mlx-community/LFM2-8B-A1B-4bit, unmodified MoE control
3266a85e9dabe5a6a711f889b8389cfa0c6b08d2
1 of 1, byte-identical on the France prompt
Test plan
Run on tree f41b8fd74920c3d494e755a0ae948269f448fe14, based on main 251f08610.
Built mlxcel, mlxcel-server, and the logit_trace example with CUDA in the test-fast profile.
CUDA library tests filtered by ernie passed 75, with 5 ignored. This includes ernie_native_batched_decode_matches_three_routed_rows and ernie45_moe_last_row_logits_match_the_full_forward.
make verify-test-cuda completed on both trees. The fix had 16,690 passed, 2 failed, 503 ignored. Main had 16,686 passed, 2 failed, 503 ignored. Both failed models::deepseek_v32::rope_tests::prefill_and_decode_cache_yarn_rotated_keys_past_the_original_context and tests::family_order_is_exhaustive. An earlier run with a group-writable temporary directory had 12 additional CUDA cache failures. They cleared with the private temporary directory on both trees.
Verification limits
Metal, ROCm, other ERNIE sizes, training, and throughput were not verified. The real ERNIE runs used softmax. Sigmoid was unit-tested. Neither build generated directly from the three untouched ERNIE downloads. The full-model comparisons used the layout copies described above. No full-model reference trace was run for the 4-bit export.
Follow-up stacked on this branch: #3333 (Closes #3323, the published ERNIE-4.5-21B-A3B checkpoints do not load as downloaded) contains this commit plus one more and can be reviewed after this one.
Verified and merge-ready as-is; no commits pushed. The router now matches the mlx-lm ernie4_5_moe and HF transformers semantics: float32 projection, gate activation in float32, selection over gates + e_score_correction_bias, mixing weights from the unbiased gates, and normalization with the 1e-12 floor. This PR should merge before #3333, which is stacked on it and carries this commit unchanged.
Issue fix(models): route ERNIE-4.5 MoE text experts with correction bias #3237 acceptance criteria: the three named tests exist and pass (correction_bias_changes_selection_not_weights, correction_bias_loads_from_moe_statics_and_squeezes, router_runs_in_f32), plus a quantized-gate variant. The zero-bias regression tests (ernie_native_batched_decode_matches_three_routed_rows, ernie45_moe_last_row_logits_match_the_full_forward) still pass. MoEBlock::forward is the only routing site for the text model, so generate, server and batched decode all go through MoEBlock::route.
Cross-checked against mlx-lm main mlx_lm/models/ernie4_5_moe/layers.py (Ernie4_5_MoeMLP.__call__).
Findings
None blocking. Notes:
The Baidu gate and bias are F32 and stay F32. The community BF16 bias and gate are widened at load; the BF16 bias values in the 21B-A3B export are about 28.6, well inside f16's normal range, so the bf16-to-f16 load conversion does not need an exemption.
The bias shape is validated against moe_num_experts ([E] or [1, E]) and a mismatch returns an error naming the key, so a malformed checkpoint cannot reach the add broadcast with the wrong width. No new input parsing or unbounded allocation.
Performance review
The extra work per MoE layer is one f32 cast of x_flat for the router, a [T, E] add, and a one-time widening of BF16 gate operands at load (64 x 2560 per layer). Routed and shared experts still receive the original activation dtype. No measurement was taken (policy: none needed for this change).
Validation
Host: spark-101 (NVIDIA GB10, CUDA), test-fast profile, --features cuda, --test-threads=1, all GPU work under gpu-lock. Run on the #3333 tree merged with main 36129ebb3, which includes this commit.
CUDA lib tests filtered by ernie: 80 passed, 0 failed, 6 ignored.
Router parity on baidu/ERNIE-4.5-21B-A3B-PT (87db954): captured each MoE layer's input activations from mlx-lm main (MLX 0.32.5) for a 21-token mixed English/Chinese prompt, then ran MoEBlock::route on the same activations. mlxcel matched mlx-lm's top-6 set on 566/567 token/layer pairs; an independent numpy float32 computation from the safetensors gate and bias also matched 566/567. With the bias removed, mlxcel matched 400/567 (numpy without bias: 400/567). The one disagreement is the BOS token at layer 21, where the 6th and 7th corrected scores differ by 5.7e-6 (about 3 f32 ulps at 25.66); numpy and mlxcel agree with each other there and mlx-lm picks the other expert.
Teacher-forced logit_trace on Baidu, docs/architecture.md 256 4 8 512, against scripts/mlx_lm_logit_trace.py with the same arguments: 14/1024 top-1 disagreements, 0/484 on decided positions (gap >= 2), largest reference gap at a disagreement 0.188; perplexity reference 11.8461, mlxcel 11.8534 (+0.061%).
Greedy generation (mlxcel generate --no-chat-template --temp 0 -n 24) on Baidu BF16/F32 and mlx-community/ERNIE-4.5-21B-A3B-PT-4bit (6a55392, zero-bias fallback): coherent on The capital of France is, Two plus two equals, and 海洋是 for both checkpoints.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes #3237.
The ERNIE-4.5 text MoE router now projects the flattened input in float32. On CUDA, mixing BF16 and F32 ordinarily produces BF16. The text loader widens BF16 gate operands once, including affine scales and zero points, so both sides of the projection support float32 arithmetic. Both gate activations rank experts by the activated gates plus the checkpoint correction bias. Mixing weights come from the selected experts’ original gates and are normalized in float32 with the existing
1e-12floor. Routed and shared experts still receive the original activation.The loader prefers
mlp.e_score_correction_bias, then checksmlp.moe_statics.e_score_correction_bias. It accepts[E]and[1, E], checks the configured expert count, and reports the offending key on a shape error. A missing key gives a float32 zero vector.Regression tests
On a GB10 with CUDA 13, all four new tests passed. Restoring the old routing and ignoring the bias in the loader made all four fail.
On
mlx-community/ERNIE-4.5-21B-A3B-PT-bf16, all 1,728 bias values matched the safetensors files after running the production loader withMLXCEL_CUDA_F16_NORMALIZE=1. None fell below the f16 normal range. In 26 of the 27 routed layers the exported bias is constant across experts. Layer 25 has two values, 28.625 and 28.75.Checkpoint validation
The published checkpoints also expose a separate loader issue. The community exports use a fused shared GLU, while mlxcel looks for numbered shared experts. The original Baidu checkpoint additionally uses numbered routed experts, while mlxcel expects stacked planes.
For inference comparisons I created local copies in mlxcel’s expected layout. The existing fused shared GLU was named as expert 0 and its configured count set to one, retaining its full width. For Baidu I also stacked each routed projection’s original planes in expert order and omitted the unused MTP tensors. The repack copied the tensor bytes without dtype conversion. The community exports used Baidu’s tokenizer JSON after I checked that the SentencePiece files had identical SHA-256 hashes. The mlx-lm reference loaded the original tensor layout.
For
The capital of France is Paris., I captured the seven input-token activations at every MoE layer from mlx-lm on the original Baidu weights. The Rust router selected the same six experts as float32 NumPy on 189/189 token/layer pairs. The unbiased NumPy calculation matched on 120/189. None of the corrected scores tied at the selection boundary. The fixed HTTP server returned 200 and generated 12 tokens on a completion request using the Baidu layout copy.Teacher-forced logits
Spark2, NVIDIA GB10 (sm_121), CUDA 13.0. I traced
docs/architecture.mdwithlogit_trace ... 256 4 8 512and compared each arm tomlx_lm_logit_trace.pywithcompare_logit_traces.py --decided 2. The reference used mlx-lm main1bf8da05aand MLX 0.32.4 on the same GPU. Each trace scored 1,024 positions. A decided position has a reference top-two logit gap of at least 2.The issue asks for a decided position where the fix recovers the reference token. Main already matched every decided position on this corpus, so that specific improvement was unobserved. The BF16 run had three more top-1 mismatches overall. On the separate seven-position Baidu prompt trace, the fix matched all seven reference top tokens and main matched six. Both matched the one decided token.
Greedy generation
mlxcel generate --no-chat-template --temp 0 -n 12. The three ERNIE prompts wereThe capital of France is,Two plus two equals, and海洋是. All nine layout-adapted cases generated on both builds.baidu/ERNIE-4.5-21B-A3B-PT87db95487941cb39592ee0abca3b9155a6d19c5cmlx-community/ERNIE-4.5-21B-A3B-PT-bf166de3db650133247146f2feec80a94ae8d22de8d7mlx-community/ERNIE-4.5-21B-A3B-PT-4bit6a55392c9930d43543bfa0a8ac6b67985bf4bd1dmlx-community/LFM2-8B-A1B-4bit, unmodified MoE control3266a85e9dabe5a6a711f889b8389cfa0c6b08d2Test plan
Run on tree
f41b8fd74920c3d494e755a0ae948269f448fe14, based on main251f08610.cargo fmt --all -- --checkcargo clippy --locked --workspace --all-targets --profile test-fast --features cuda -- -D warningsmlxcel,mlxcel-server, and thelogit_traceexample with CUDA in the test-fast profile.erniepassed 75, with 5 ignored. This includesernie_native_batched_decode_matches_three_routed_rowsandernie45_moe_last_row_logits_match_the_full_forward.make verify-test-cudacompleted on both trees. The fix had 16,690 passed, 2 failed, 503 ignored. Main had 16,686 passed, 2 failed, 503 ignored. Both failedmodels::deepseek_v32::rope_tests::prefill_and_decode_cache_yarn_rotated_keys_past_the_original_contextandtests::family_order_is_exhaustive. An earlier run with a group-writable temporary directory had 12 additional CUDA cache failures. They cleared with the private temporary directory on both trees.Verification limits
Metal, ROCm, other ERNIE sizes, training, and throughput were not verified. The real ERNIE runs used softmax. Sigmoid was unit-tested. Neither build generated directly from the three untouched ERNIE downloads. The full-model comparisons used the layout copies described above. No full-model reference trace was run for the 4-bit export.