Skip to content

fix(models): load published ERNIE-4.5 text MoE expert layouts - #3333

Merged
inureyes merged 4 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/3323-ernie-moe-checkpoint-layout
Nov 26, 2026
Merged

inureyes merged 4 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/3323-ernie-moe-checkpoint-layout

Conversation

@Jaeyeong-CHOI

Copy link
Copy Markdown
Contributor

Summary

Closes #3323. Depends on #3322.

The ERNIE-4.5 text loader now accepts the expert layouts in the original Baidu checkpoint and both mlx-community exports. A GLU stored directly under mlp.shared_experts loads once at its stored width. A checkpoint with numbered shared GLUs still loads each configured module separately.

For numbered routed experts, the loader stacks each projection in numeric expert order with drain_numbered_expert_planes, including affine scales and biases when present. It checks that the expert planes cover the configured bank with matching shapes and materializes each projection before starting the next one. Already-stacked switch_mlp projections take their existing path. The loader drops the unused mtp_block, mtp_linear_proj, mtp_hidden_norm, and mtp_emb_norm components.

The directory loader and config-backed in-memory loader share this preparation. The public borrowed-weight constructor retains its signature. I checked the separate VL loader, which already reads a fused shared GLU and builds its modality-specific routed banks separately.

Original checkpoint verification

On Spark2 (NVIDIA GB10, CUDA 13.0), I ran the #3322 binary at d2cde7ea9 and the fix against the same download directories. Each run used mlxcel generate --no-chat-template --temp 0 -n 12 and one of three prompts: The capital of France is, Two plus two equals, or 海洋是. The patched runs used the original shards, index, config, and tokenizer files in each directory.

Checkpoint Hugging Face revision #3322 on original Fix on original vs. #3322 on its adapted copy
baidu/ERNIE-4.5-21B-A3B-PT 87db95487941cb39592ee0abca3b9155a6d19c5c 3/3 failed on missing switch_mlp.gate_proj.weight in layer 1 3/3 generated 12 tokens and matched byte-for-byte
mlx-community/ERNIE-4.5-21B-A3B-PT-bf16 6de3db650133247146f2feec80a94ae8d22de8d7 3/3 failed on missing shared_experts.0.gate_proj.weight in layer 1 3/3 generated 12 tokens and matched byte-for-byte
mlx-community/ERNIE-4.5-21B-A3B-PT-4bit 6a55392c9930d43543bfa0a8ac6b67985bf4bd1d 3/3 failed on the same shared expert key 3/3 generated 12 tokens and matched byte-for-byte

I compared the UTF-8 bytes printed between the generation marker and the timing footer, preserving whitespace. All nine fixed ERNIE runs had empty stderr. Both community downloads used their own SentencePiece file. The #3322 adapted copies had also included Baidu's tokenizer JSON.

The separate MoE control, mlx-community/LFM2-8B-A1B-4bit at 3266a85e9dabe5a6a711f889b8389cfa0c6b08d2, produced the same 68 output bytes on the France prompt with both binaries. Both emitted 22 quantization metadata warnings.

Teacher-forced logits

I ran the CUDA logit_trace example on the original Baidu checkpoint using the same docs/architecture.md corpus and 256 4 8 512 arguments as #3322. All 1,024 TSV data rows matched the saved #3322 adapted-checkpoint trace byte-for-byte, including target IDs, negative log-likelihoods, top-eight IDs, and their printed logits. Against the saved mlx-lm reference, the result reproduced 10/1,024 top-1 mismatches, 0/486 mismatches at a reference gap of at least 2, and perplexity 11.7712 (mlx-lm 11.7836).

Regression tests

Four new CUDA tests passed on the fix. Restoring every production change to #3322 while retaining the new tests made all four fail.

Fixture What the test checks Result on #3322
Fused shared GLU With two configured shared experts of width 6, one stored GLU projects from 8 to 12 and returns to 8. Missing numbered shared gate
Numbered routed experts All three projections load three distinct expert planes in numeric order. Missing stacked gate
Numbered affine 4-bit experts Packed uint32 weights, scales, and biases retain the expected values for each expert in all three projections. Missing stacked gate
Existing layout with MTP The config-backed loader accepts two numbered shared experts and three stacked routed experts, then leaves none of the four MTP keys in its map. The layout loaded, but the first MTP key remained

Test plan

Spark2 tested tree 2297640dcc1b8d6e8d53a7897903b844865da39e, the tree of e671e4fd98fc6b1b5e19f7cb578dd7d175a33283.

  • cargo fmt --all -- --check
  • cargo clippy --locked --workspace --all-targets --profile test-fast --features cuda -- -D warnings
  • Built the CUDA CLI and logit_trace example in the test-fast profile.
  • CUDA library tests filtered by ernie passed 79, with 5 ignored. The four new tests also passed in isolation and failed against the base implementation.
  • make verify-test-cuda completed 192 harnesses with 16,694 passed, 2 failed, 503 ignored using a private 0700 TMPDIR. The failed tests were models::deepseek_v32::rope_tests::prefill_and_decode_cache_yarn_rotated_keys_past_the_original_context and tests::family_order_is_exhaustive. The archived fix(models): apply ERNIE-4.5 MoE text correction bias in float32 routing #3322 gate had 16,690 passed, the same two failures, and 503 ignored.

Verification limits

Metal, ROCm, other ERNIE sizes, and real VL checkpoints were not verified. Numbered affine routed experts were tested with synthetic weights. The public 4-bit checkpoint supplies pre-stacked routed experts. The new teacher-forced trace covers Baidu only. The adapted generation and mlx-lm reference comparisons used saved #3322 evidence. Training and throughput were not measured.

@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 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
Main changed `drain_numbered_expert_planes` to return `Result` (lablup#3335), so the ERNIE text loader now propagates its error instead of discarding it, which would also fail `clippy -D warnings` on `unused_must_use`. A plane whose dtype differs from expert 0 now fails with the helper's message naming the expert key instead of a later `Weight not found` for the stacked projection.

Add a regression test covering the three malformed numbered-expert layouts the loader refuses: a dtype mismatch (reported by the shared helper), a missing expert, and an extra expert beyond `moe_num_experts`.
@inureyes

Copy link
Copy Markdown
Member

Hardening summary

Summary

Fixed and pushed. The loader changes are correct: the fused shared GLU loads once at its stored width, numbered routed experts stack in expert order (including affine sidecars), and the MTP tensors are dropped. Main had changed drain_numbered_expert_planes to return Result (#3335) after this branch was cut, so the branch discarded that error and would fail clippy -D warnings on unused_must_use once merged. I merged origin/main into the branch, propagated the error with ?, and added a regression test for the refused layouts.

This PR is stacked on #3322 (it carries d2cde7ea9 unchanged). Merge #3322 first. I simulated squash-merging #3322 onto main and then running git merge origin/main on this branch: it merges cleanly with no conflicts.

Reviewed (PR + issues)

Findings

  • MEDIUM (fixed): after main's fix(models): refuse mismatched experts in family-local MoE stacking #3335, drain_numbered_expert_planes(...) returns Result<(), String>, and the call here ignored it. A numbered expert plane whose dtype differs from expert 0 would then be silently dropped, and the load would fail later with an unrelated Weight not found: ...switch_mlp.gate_proj.weight. The ignored Result also trips unused_must_use under clippy -D warnings.
  • LOW (test gap, fixed): the loader's new refusals for a missing numbered expert and for more experts than moe_num_experts had no tests.

Fixes

  • 2356f8a93 Merge remote-tracking branch 'origin/main' into fix/3323-ernie-moe-checkpoint-layout
  • 0bdbf5b23 fix(models): surface ERNIE expert stacking errors after main merge. Propagates the helper's error with ? and adds checkpoint_layout_refuses_malformed_numbered_experts, which covers a dtype mismatch (the helper's message naming experts.2.gate_proj.weight), a missing expert, and an extra expert. With ? replaced by let _ =, the test fails with Weight not found: model.layers.1.mlp.switch_mlp.gate_proj.weight.

Security review

The numbered-expert path checks every plane's shape against expert 0, refuses gaps and surplus experts, and now also surfaces the shared helper's shape/dtype refusal before mlxcel_core::stack (which aborts the process on mismatch). The MTP filter matches whole key components only. No new file or network input.

Performance review

Stacking materializes one projection at a time (eval after each), so peak load memory grows by about one projection bank instead of all three. Borrowed-map loading clones handles, not tensor data. Inference paths are unchanged. No measurement was taken (policy: none needed).

Validation

Host: spark-101 (NVIDIA GB10, CUDA), test-fast profile, --features cuda, --test-threads=1, all GPU work under gpu-lock, on the pushed tree 0bdbf5b23.

  • cargo fmt --all -- --check: clean.
  • cargo clippy --locked --profile test-fast --features cuda --all-targets -p mlxcel -- -D warnings: clean.
  • CUDA lib tests filtered by ernie: 80 passed, 0 failed, 5 ignored. Filtered by switch_layers: 66 passed, 0 failed, 1 ignored.
  • Real checkpoints, loaded from the untouched downloads: baidu/ERNIE-4.5-21B-A3B-PT (87db954, numbered routed experts, fused shared GLU, F32 gate and bias, MTP tensors) and mlx-community/ERNIE-4.5-21B-A3B-PT-4bit (6a55392, stacked quantized experts, no bias). The mlx-community/ERNIE-4.5-21B-A3B-PT-bf16 layout was checked from the safetensors index and shard header: fused shared_experts.{gate,up}_proj.weight BF16 [3072, 2560] (2 x 1536), stacked switch_mlp [64, ...], BF16 moe_statics.e_score_correction_bias [1, 64], so it takes the same paths as the two checkpoints run here.
  • Greedy mlxcel generate --no-chat-template --temp 0 -n 24:
    • Baidu: The capital of France is Paris. Paris is known for its iconic landmarks such as the Eiffel Tower, the Louvre Museum, and; Two plus two equals four. That's a fundamental truth in mathematics. ...; 海洋是巨大的资源宝库,人类可以从海洋中获取多种物质。...
    • 4-bit: The capital of France is Paris. The Eiffel Tower is a famous landmark in Paris. ...; Two plus two equals four, but what about in the context of a quantum computer? ...; 海洋是地球上最广阔的水体,不可直接饮用,...
  • Teacher-forced logit_trace on Baidu (docs/architecture.md 256 4 8 512) against scripts/mlx_lm_logit_trace.py (mlx-lm main, MLX 0.32.5) with compare_logit_traces.py --decided 2: 14/1024 top-1 disagreements, 0/484 on decided positions, largest reference gap at a disagreement 0.188, perplexity 11.8461 reference vs 11.8534 mlxcel (+0.061%).
  • Router parity (the fix(models): apply ERNIE-4.5 MoE text correction bias in float32 routing #3322 change on this loader): on the Baidu checkpoint, MoEBlock::route matched mlx-lm's top-6 experts on 566/567 token/layer pairs (the miss is a 5.7e-6 near-tie on the BOS token at layer 21, where numpy float32 agrees with mlxcel), versus 400/567 with the bias removed.

Merge-order notes

@inureyes
inureyes merged commit fdecb27 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 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): ERNIE-4.5 text MoE cannot load the public ERNIE-4.5-21B-A3B checkpoints (fused shared expert and numbered routed experts)

2 participants