Skip to content

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

Done

Description

@inureyes

Summary

The ERNIE-4.5 MoE text model (ernie4_5_moe) ignores the checkpoint's per-expert e_score_correction_bias, so it selects a different top-k set of experts than the reference on every routed token, and it computes the router in the activation dtype where the reference computes it in float32. ERNIE-4.5-MoE-VL already applies the bias; the text path does not.

Upstream reference

ml-explore/mlx-lm#1959 (a28cdd0), now in https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/ernie4_5_moe/layers.py and https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/ernie4_5_moe/checkpoint.py:

  • Routing: gates = gate_act(gate(x.astype(float32))) ("HF multiplies in fp32, so near-ties pick the same experts"); inds = argpartition(-(gates + e_score_correction_bias), kth=k-1)[..., :k]; scores = take_along_axis(gates, inds) from the unbiased gates; then scores / max(sum(scores), 1e-12). The bias only ranks experts.
  • Sanitize, per layer that has mlp.gate.weight (only MoE layers do; partial weight maps are allowed): pop mlp.moe_statics.e_score_correction_bias, falling back to an existing mlp.e_score_correction_bias, else zeros [E]; squeeze [1, E] to [E]; store as mlp.e_score_correction_bias. Sanitizing twice is idempotent.
  • cast_predicate keeps e_score_correction_bias and mlp.gate.weight out of dtype conversion, because the checkpoint stores them in float32.

Current mlxcel behavior

  • src/models/ernie4_5_moe.rs:474-482 MoEBlock has no bias field. MoEBlock::forward (:484) runs self.gate.forward(&x_flat) in the input dtype (:497), applies softmax or sigmoid in that dtype (:500-504), and selects with argpartition(-gates) (:510-515).
  • MoEBlock::from_weights (:858-890) loads gate, switch_mlp and shared experts and never reads e_score_correction_bias or moe_statics.*. The family loads through the config-backed route (src/model_metadata.rs:214, load_text_weights then Ernie45MoeModel::from_weights), so there is no model-specific sanitize to extend.
  • The pattern to copy is ExpertBank::route in src/models/ernie4_5_moe_vl.rs:588-614 (f32 logits, probs + correction_bias for selection only, scores from probs), tested by correction_bias_is_selection_only (:1463). Its load_bias closure (:649-655) errors when the key is missing; the text path must default to zeros instead, because existing converted checkpoints dropped the key.

What the checkpoints hold (safetensors headers): baidu/ERNIE-4.5-21B-A3B-PT stores model.layers.N.mlp.gate.weight F32 [64, 2560] and model.layers.N.mlp.moe_statics.e_score_correction_bias F32 [1, 64]. mlx-community/ERNIE-4.5-21B-A3B-PT-bf16 stores both as BF16 under the same names. mlx-community/ERNIE-4.5-21B-A3B-PT-4bit has no bias key (its converter dropped it) and a quantized gate.

Required changes

  1. src/models/ernie4_5_moe.rs:
    • Add e_score_correction_bias: UniquePtr<MlxArray> (float32 [E]) to MoEBlock.
    • In MoEBlock::from_weights, resolve it from {mlp}.e_score_correction_bias, then {mlp}.moe_statics.e_score_correction_bias; reshape [1, E] to [E]; accept [E]; any other shape, or E != args.moe_num_experts, is an error naming the key. Missing means zeros [E] f32, which keeps today's selection rule (no bias); the float32 router below can still move near-ties on a quantized checkpoint, which is intended. Cast to float32 after lookup.
    • In MoEBlock::forward, cast x_flat to float32 for the router only (gate.forward(&x_f32)), apply the activation in float32, select over gates + bias, take scores from the unbiased gates, normalize with the existing 1e-12 floor in float32, and pass the original x_flat to switch_mlp and the shared experts. moe_weighted_sum already casts the result to the activation dtype.
  2. Precision boundary: the F32 gate and bias in the baidu checkpoint are untouched by the bf16-to-f16 load conversion (it converts only bf16 tensors), and the router math widens per forward, so no exemption list is needed. For the BF16 community checkpoint the conversion turns the bias into f16 before the cast; check the loaded values against the file once on the real checkpoint, and if any nonzero entry falls below f16's normal range (6.1e-5), exempt keys ending in e_score_correction_bias from the conversion through the existing keep-predicate mechanism (convert_bf16_weights_with_keep, src/models/sanitize.rs) instead.
  3. Do not change ernie4_5_moe_vl.rs; reuse its routing shape, and if the selection code is factored into a shared helper, give it a // Used by: Ernie45MoeModel, Ernie45MoeVlTextModel comment.

Acceptance criteria

  • src/models/ernie4_5_moe_tests.rs: correction_bias_changes_selection_not_weights (3 experts, top-2, gate rows as in the VL test so raw probs order e0 > e1 > e2, bias [0, 0, 10]) asserts the selected set is {e0, e2} and the scores are the renormalized raw probs of e0 and e2. Fails today (selects {e0, e1}).
  • Same file: correction_bias_loads_from_moe_statics_and_squeezes builds a weight map with model.layers.1.mlp.moe_statics.e_score_correction_bias of shape [1, 4] and asserts the block holds [4] f32 with the same values; a second case with model.layers.1.mlp.e_score_correction_bias [4] loads too; a third with neither loads zeros; a [2, 4] bias is an error.
  • Same file: router_runs_in_f32 asserts that with an f16 input whose two expert logits differ only below f16 resolution, the selection matches the float32 reference (construct the gate so the f16 path ties and picks the lower index).
  • The existing ernie_native_batched_decode_matches_three_routed_rows and ernie45_moe_last_row_logits_match_the_full_forward keep passing (zero bias path).
  • Wired into the real flow: mlxcel generate, mlxcel-server and batched decode all go through MoEBlock::forward; no separate path is left on the old routing.

Validation

Checkpoint: mlx-community/ERNIE-4.5-21B-A3B-PT-bf16 (43.7 GB) or baidu/ERNIE-4.5-21B-A3B-PT, which carry the bias; the 4-bit community conversion has none and only confirms nothing regresses.

make verify-test
cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --check
cargo build --profile test-fast --features metal,accelerate --example logit_trace
./target/test-fast/examples/logit_trace models/ERNIE-4.5-21B-A3B-PT-bf16 docs/architecture.md 256 4 8 512 > fixed.tsv

Routing changes arithmetic, so follow CLAUDE.md "Changes that move the numbers": trace the same corpus on a build with the change reverted, compare with scripts/compare_logit_traces.py --decided 2, and compare both against an mlx-lm main reference on the same tokens (scripts/mlx_lm_logit_trace.py, same arguments as logit_trace). A pass is the fixed arm agreeing with the reference on decided positions where the reverted arm does not; report the numbers and perplexity in the PR body.

Related

#535 (ERNIE-4.5 MoE VL port, which already applies the bias), #2559 (batched MoE decode). Upstream: ml-explore/mlx-lm#1959.

Activity

  1. added
    status:ready
    type:bug
    priority:medium
    area:models
    modelsize:medium
    modeltype:text
    arch:moe
    on Nov 22, 2026
  2. added a commit that references this issue on Nov 26, 2026
    b00e1d3
  3. added
    status:done
    and removed
    status:ready
    on Nov 26, 2026
  4. added this to the 0.9 milestone on Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    arch:moearea:modelsmodelsize:mediummodeltype:textpriority:mediumstatus:donetype:bug

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions