Repository navigation
Description
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; thenscores / 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): popmlp.moe_statics.e_score_correction_bias, falling back to an existingmlp.e_score_correction_bias, else zeros[E]; squeeze[1, E]to[E]; store asmlp.e_score_correction_bias. Sanitizing twice is idempotent. cast_predicatekeepse_score_correction_biasandmlp.gate.weightout of dtype conversion, because the checkpoint stores them in float32.
Current mlxcel behavior
src/models/ernie4_5_moe.rs:474-482MoEBlockhas no bias field.MoEBlock::forward(:484) runsself.gate.forward(&x_flat)in the input dtype (:497), applies softmax or sigmoid in that dtype (:500-504), and selects withargpartition(-gates)(:510-515).MoEBlock::from_weights(:858-890) loadsgate,switch_mlpand shared experts and never readse_score_correction_biasormoe_statics.*. The family loads through the config-backed route (src/model_metadata.rs:214,load_text_weightsthenErnie45MoeModel::from_weights), so there is no model-specific sanitize to extend.- The pattern to copy is
ExpertBank::routeinsrc/models/ernie4_5_moe_vl.rs:588-614(f32 logits,probs + correction_biasfor selection only, scores fromprobs), tested bycorrection_bias_is_selection_only(:1463). Itsload_biasclosure (: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
src/models/ernie4_5_moe.rs:- Add
e_score_correction_bias: UniquePtr<MlxArray>(float32[E]) toMoEBlock. - 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, orE != 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, castx_flatto float32 for the router only (gate.forward(&x_f32)), apply the activation in float32, select overgates + bias, take scores from the unbiased gates, normalize with the existing1e-12floor in float32, and pass the originalx_flattoswitch_mlpand the shared experts.moe_weighted_sumalready casts the result to the activation dtype.
- Add
- 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_biasfrom the conversion through the existing keep-predicate mechanism (convert_bf16_weights_with_keep,src/models/sanitize.rs) instead. - 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, Ernie45MoeVlTextModelcomment.
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 ordere0 > 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_squeezesbuilds a weight map withmodel.layers.1.mlp.moe_statics.e_score_correction_biasof shape[1, 4]and asserts the block holds[4]f32 with the same values; a second case withmodel.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_f32asserts 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_rowsandernie45_moe_last_row_logits_match_the_full_forwardkeep passing (zero bias path). - Wired into the real flow:
mlxcel generate,mlxcel-serverand batched decode all go throughMoEBlock::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.tsvRouting 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
fix(models): apply ERNIE-4.5 MoE text correction bias in float32 rout…