Repository navigation
Fix ERNIE-4.5 MoE correction bias routing - #1959
Merged
Merged
Conversation
- 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>
Contributor
Author
michalk8
self-requested a review
October 20, 2026 11:09
michalk8
approved these changes
Oct 20, 2026
michalk8
left a comment
Collaborator
There was a problem hiding this comment.
I dropped the extra class you've added, otherwise LGTM, thanks!
Contributor
Author
|
Thanks @michalk8 for the review and merge. |
5 tasks
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Fix ERNIE-4.5 MoE correction bias routing
Fixes #1947
Summary
mlx-lmdropse_score_correction_biasduring sanitization, so ERNIE-4.5 MoE selects experts via the unbiased softmax probabilities. The Baidu and Hugging Face reference implementations select experts usingprobs + biasand 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 revision25a64672on July 18, 2025, butmlx-lmdid not follow that change.Changes
Add
Ernie4_5_MoeStaticswith 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_biasinsanitize(), 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.weightis 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_evalandrequestsdependencies and also occur on upstreammain.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
ernie_gist.pyernie_gist_branch.pyThis should be run on the PR branch; it needs the branch's implementation of
moe_staticsto 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.pyThis should be run with:
This trimmed benchmark compares only
mainand the fix branch and imports nothing frommlx_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-communityBF16 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)mlx0.32.3mlx-lm0.1.dev960+ga9bd8af5c (installed version string; the fix branch is based on upstreammainat9d8abd9)Python 3.12
transformers5.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
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.