Skip to content

Fix ERNIE-4.5 MoE correction bias routing - #1959

Merged
michalk8 merged 4 commits into
ml-explore:mainfrom
Knightkolla:fix-ernie-correction-bias
Oct 20, 2026
Merged

michalk8 merged 4 commits into
ml-explore:mainfrom
Knightkolla:fix-ernie-correction-bias

Conversation

@Knightkolla

Copy link
Copy Markdown
Contributor

Fix ERNIE-4.5 MoE correction bias routing

Fixes #1947

Summary

mlx-lm drops e_score_correction_bias during sanitization, so ERNIE-4.5 MoE selects experts via the unbiased softmax probabilities. The Baidu and Hugging Face reference implementations select experts using probs + bias and gather and renormalize weights from the original, unbiased probabilities.

When #267 (854b427) was merged on July 5, 2025, the implementation matched Baidu's Hub revision current at that time (3b57ea62), which did not make use of the correction bias. Baidu changed its routing in Hub revision 25a64672 on July 18, 2025, but mlx-lm did not follow that change.

Changes

  • Add Ernie4_5_MoeStatics with a zero-initialized correction-bias parameter whose path matches the checkpoint key.

  • Apply the bias only during expert selection; calculate routing weights from the unbiased gates.

  • Preserve e_score_correction_bias in sanitize(), squeeze [1, E] to [E] and default to zeros if the key is absent.

  • Safely handle partial or empty weight dictionaries by processing the bias only if mlp.gate.weight is present.

  • Keep the correction bias out of the conversion dtype cast, following the pattern used by other models.

  • Add tests for sanitization and routing behavior.

Validation

  • Both new tests pass on the fix branch and fail on upstream main.

  • Pre-commit checks pass with the repository's pinned hook versions.

  • The full suite reports 299 tests, 3 errors and 1 skip. The errors are due to missing datasets, lm_eval and requests dependencies and also occur on upstream main.

Routing comparison

The table compares routing behavior before and after the fix using the gate weights and correction bias from layers 1, 14 and 27 of baidu/ERNIE-4.5-21B-A3B-PT. It uses 4,000 random inputs and top-6 selection from 64 experts. The reference is a NumPy implementation of the Baidu/Hugging Face routing rule. Compared with the Hugging Face router, it differs by at most 2 of 4,000 tokens per layer (a 99.98%, 100.00% and 99.95% agreement for layers 1, 14 and 27, respectively).

Layer | Same expert set before | After | Mean experts differing before | After

--- | ---: | ---: | ---: | ---:

1 | 93.9% | 100.0% | 0.061 | 0.000

14 | 83.3% | 100.0% | 0.170 | 0.000

27 | 39.3% | 100.0% | 0.737 | 0.001

\ Two of 4,000 tokens in layer 27 still differ. Their 6th and 7th biased scores are equal in float32 (gap 0). This seems to be a tie-breaking difference, but the reason has not been confirmed.

Reproduction scripts

python ernie_gist.py


python ernie_gist_branch.py


This should be run on the PR branch; it needs the branch's implementation of moe_statics to load the correction bias.

Both scripts use random inputs, not real hidden states.

Performance benchmark

The router-only decode benchmark shows an increase of about 16% on the fix branch compared with main. Absolute timings vary with machine load, so individual microsecond values should not be treated as fixed. Prefill was approximately 1.6-3.5% slower in the latest run, within the observed run-to-run spread.

Benchmark script: ernie_bench_pr.py

This should be run with:

python ernie_bench_pr.py


This trimmed benchmark compares only main and the fix branch and imports nothing from mlx_lm. It reimplements the router operations inline rather than calling the model's router module. It measures 27 layers in one graph with a single token, takes the median of 60 timings and repeats the measurement across 9 interleaved runs.

End-to-end generation performance was not measured as the 21B model does not fit in the available 8 GB of memory.

Compatibility and existing conversions

  • Checkpoints without the correction-bias key will use a zero bias and retain their existing routing behavior. A [1, E] bias is squeezed to [E].

  • The mlx-community BF16 conversion contains the bias key, but in the inspected layers (1, 14, and 27) all 64 values collapse to the same BF16 value. The routing-relevant variation is therefore lost, and these conversions need to be regenerated from the original Baidu checkpoint for correct routing.

  • The 8-bit conversion also contains the key, but its bias values were not inspected.

  • The 4-bit conversion does not contain the key.

  • The conversion dtype behavior was checked on a small model using the same cast logic as convert.py; a real ERNIE checkpoint was not converted.

Environment

  • Apple M2, 8 GB RAM

  • macOS 27.0 (build 26A428)

  • mlx 0.32.3

  • mlx-lm 0.1.dev960+ga9bd8af5c (installed version string; the fix branch is based on upstream main at 9d8abd9)

  • Python 3.12

  • transformers 5.18.0 (used for the Hugging Face comparison)

Limitations

  • All routing inputs were random samples from N(0, 1) and not real hidden states.

  • No end-to-end perplexity or logits comparison against Hugging Face has been run.

  • No generation or conversion run has been performed on a real ERNIE checkpoint.

  • The sigmoid gate path (moe_gate_act) has not been compared against the reference.

  • Other ERNIE sizes and the VLM variant have not been checked.

  • Pipeline and tensor sharding are not supported by ERNIE currently; their behavior has not been evaluated.

☑️ I understand it is strictly prohibited to use AI to write PR description

  • AI usage disclosure:
    Claude Code assisted with investigating the routing implementation, preparing and running the routing comparison and benchmark scripts, implementing the fix, adding tests, reviewing the diff and fact-checking this PR description. I reviewed the drafts and the reported results during the development process.

Knightkolla and others added 2 commits October 9, 2026 20:42
- Add `Ernie4_5_MoeStatics` to preserve `e_score_correction_bias` from the checkpoint.
- Apply correction bias during top-k expert selection while keeping routing weights based on unbiased gates.
- Update sanitization to squeeze the bias from `[1, E]` to `[E]` and default to zeros when missing.
- Handle partial weight dictionaries safely and preserve float32 bias precision during conversion.
- Add tests for correction-bias sanitization and routing behavior.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Knightkolla <kartikeyadhavala2468@gmail.com>
@Knightkolla

Copy link
Copy Markdown
Contributor Author

@Goekdeniz-Guelmez

@michalk8
michalk8 self-requested a review October 20, 2026 11:09

@michalk8 michalk8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I dropped the extra class you've added, otherwise LGTM, thanks!

@michalk8
michalk8 merged commit a28cdd0 into ml-explore:main Oct 20, 2026
2 checks passed
@Knightkolla

Copy link
Copy Markdown
Contributor Author

Thanks @michalk8 for the review and merge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ernie4_5_moe: e_score_correction_bias is dropped, so expert selection differs from the reference

2 participants