Skip to content

fix(models): apply ERNIE-4.5 MoE text correction bias in float32 routing - #3322

Merged
inureyes merged 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:fix/3237-ernie-moe-correction-bias
Nov 26, 2026
Merged

inureyes merged 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:fix/3237-ernie-moe-correction-bias

Conversation

@Jaeyeong-CHOI

Copy link
Copy Markdown
Contributor

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-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.

  • cargo fmt --all -- --check
  • cargo clippy --locked --workspace --all-targets --profile test-fast --features cuda -- -D warnings
  • 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.

@Jaeyeong-CHOI

Jaeyeong-CHOI commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

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.

@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:medium Medium priority area:models Model architectures, weights, loading, metadata modelsize:medium 4-bit checkpoint 10-50GB; comfortable on a 128GB dev box modeltype:text Text-only language model arch:moe Sparse mixture-of-experts decoder labels Nov 24, 2026
@inureyes inureyes self-assigned this Nov 24, 2026
@inureyes

Copy link
Copy Markdown
Member

Hardening summary

Summary

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.

Reviewed (PR + issues)

  • PR fix(models): apply ERNIE-4.5 MoE text correction bias in float32 routing #3322 at d2cde7ea9 (src/models/ernie4_5_moe.rs, src/models/ernie4_5_moe_tests.rs).
  • 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:

Fixes

None.

Security review

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.
  • git merge origin/main into this branch is clean.

@inureyes
inureyes merged commit b00e1d3 into lablup:main Nov 26, 2026
33 checks passed
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 26, 2026
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

arch:moe Sparse mixture-of-experts decoder area:models Model architectures, weights, loading, metadata modelsize:medium 4-bit checkpoint 10-50GB; comfortable on a 128GB dev box modeltype:text Text-only language model priority:medium Medium priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(models): route ERNIE-4.5 MoE text experts with correction bias

2 participants