feat(models): add ERNIE-5.5-Flash (ernie5_5_moe) support
I maintainer di solito rispondono entro 1 giorno
Nessuno ha ancora preso questa issue.
Valutazione
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Idoneità per principianti
- 8/100
- Tipo di issue
- Funzionalità
- Chiarezza
- Abbastanza chiara
- Stato di attività
- Attiva
- Stack tecnologico
- rust
- Ambito
- ai, machine-learning
Direzione di ricerca
Start with the existing DeepSeek-V4 code: src/models/deepseek_v4_attention.rs (V4Attention, AttnKind::Compressed), src/models/deepseek_v4_compress.rs (Compressor), and src/models/deepseek_v4_hyper.rs (HyperConnection, HyperHead). Add ERNIE behaviour as opt-in flags so deepseek_v4_tests:: still passes unchanged. Done means a tiny random ERNIE config loads and produces logits, with the blocked full checkpoint left out of scope. The issue is blocked on checkpoint hosting, so it is not a good first pick.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
Summary
Add Baidu ERNIE-5.5-Flash-Base (model_type: ernie5_5_moe, Ernie5_5_MoeForCausalLM), a text completion base model in the DeepSeek-V4 lineage: 43 decoder layers that are mostly heavily compressed attention (HCA, DeepSeek-V4's ratio-128 pooled attention plus a 128-token local window) with an MLA layer every seventh position that uses a DSA-style indexer, four-way hyper-connection (mHC) residual streams with Sinkhorn mixing, a latent MoE with two summed routers and learned per-expert scaling, a SiTU activation, virtual-head output mixing, and a MultiMax logit transform. The checkpoint also carries ECHO, a draft layer that reuses the final decoder layer for speculative decoding.
This issue covers the next-token backbone only. ECHO decoding is a follow-up, because it needs this backbone, the MTP/speculative plumbing, and a fresh-cache full-prompt-prefill contract of its own.
Upstream reference
- Blaizzy/mlx-vlm#2708 (commit
b9d55c92, 2026-11-15), https://github.com/Blaizzy/mlx-vlm/tree/main/mlx_vlm/models/ernie5_5_moe (config.py,language.py,echo.py,ernie5_5_moe.py) and the ECHO drafter in https://github.com/Blaizzy/mlx-vlm/tree/main/mlx_vlm/speculative/drafters/ernie5_5_mtp. It importsCompressedAttention,Compressor,HyperHead,_hc_split_sinkhorn_opsandhc_expandfrom https://github.com/Blaizzy/mlx-vlm/tree/main/mlx_vlm/models/deepseek_v4. Vendor reference: https://github.com/baidu/vLLM-ERNIE/tree/main/src/vllm_ernie/models/ernie5_5. There is no mlx-lm port. - Text only; use plain completion prompts, the checkpoint ships no chat template.
Architecture (from upstream code and the published config)
Config of baidu/ERNIE-5.5-Flash-Base (028544b2): hidden_size 4096, num_hidden_layers 43, vocab_size 201216, rms_norm_eps 1e-6, max_position_embeddings 1048576, tie_word_embeddings false, bos 1, eos 2, pad 0. HCA attention: num_attention_heads 64, num_key_value_heads 1, head_dim 512, q_lora_rank 1024, qk_rope_head_dim 64, o_groups 8, o_lora_rank 1024, sliding_window 128, rope_theta 8000000, compress_rope_theta 160000, rope_scaling {type yarn, factor 16, original_max_position_embeddings 65536, beta_fast 32, beta_slow 1}, hca_rope_type yarn. compress_ratios has 44 entries (one extra for the ECHO layer; truncate to 43): -2 (MLA) at layers 7, 14, 21, 28, 35, 42 and 128 elsewhere, layer 0 included. MLA: hybrid_mla_num_attention_heads 64, hybrid_mla_q_lora_rank 1024, hybrid_mla_kv_lora_rank 512, hybrid_mla_qk_nope_head_dim 192, hybrid_mla_qk_rope_head_dim 64, hybrid_mla_v_head_dim 256, index_n_heads 64, index_head_dim 128, index_topk 2048. mHC: hc_mult 4, hc_sinkhorn_iters 20, hc_eps 1e-6. MoE: first_k_dense_replace 1, intermediate_size 14336, n_routed_experts 512, num_experts_per_tok 10, n_shared_experts 1, moe_intermediate_size 2048, moe_latent_size 2048, routed_scaling_factor 3.0 (learnable per expert), norm_topk_prob true, scoring_func sigmoid, hidden_act situ, activation_situ_beta 4.0, activation_situ_linear_beta 25.0. vha_rank 16 (upstream default; the config enables use_vha_attention). Quantization: {quant_method fp8, fmt e4m3, scale_fmt ue8m0, weight_block_size [128, 128]}.
- Residual streams:
h = broadcast(embed_tokens(ids), [B, L, 4, D]). Per layer:x, post, comb = attn_hc(h);h = hc_expand(attn(attn_norm(x)), h, post, comb); thenffn_hc,ffn_norm, FFN,hc_expand. Finalnorm(hc_head(h)). - mHC difference from DeepSeek-V4: the mixing logits are
(flat @ fn.T) / (sqrt(mean(flat^2)) + rms_norm_eps)withflatin f32, i.e. epsilon outside the square root. V4 (and mlxcel'sHyperConnection, which appliesfast_rms_norm_no_weightfirst,src/models/deepseek_v4_hyper.rs:131) puts it inside. The rest (_hc_split_sinkhorn_opswithscale,base, 20 Sinkhorn iterations,hc_expand) is V4's.hc_headis V4'sHyperHeadunchanged. - HCA layers (ratio 128): V4's
CompressedAttention(wq_a,q_norm,wq_b, weightless per-head rms on q,wkv,kv_norm, interleaved RoPE, aRotatingKVCache(128)local window plus a pooling cache of compressed rows, learned per-headattn_sink, inverse RoPE on the output, groupedwo_aovero_groups,wo_b) with three ERNIE changes: (1) the compressor accumulateswkvandwgateprojections and the softmax pooling in f32 even for a bf16 backbone (HCACompressor), (2) virtual heads mix the attention output across heads beforewo_a:out = (I + V.f32 @ U.f32.T).astype(dtype) @ outover the head axis, withU,V[64, 16](vha_postmix_U,vha_postmix_V), (3) thewo_binput is multiplied bysigmoid(o_gate(qr))whereqr = q_norm(wq_a(x))ando_gateisq_lora_ranktoo_groups * o_lora_rank. - MLA layers (ratio -2):
q_a_proj,q_a_layernorm,q_b_proj(192 nope + 64 rope per head),kv_a_proj_with_mqa(512 latent + 64),kv_a_layernorm, interleaved RoPE atrope_thetaon the 64-dim parts, absorbedembed_q/unembed_outfromkv_b_proj(decode) or expanded K/V (prefill), additive mask onpe_scoreswith-inf, learnedattn_sink, scale(192 + 64) ** -0.5, then virtual heads,* sigmoid(o_gate(qr))(q_lora_rankto64 * 256) andwo_b. Caches: latentKVCacheand an indexer keyKVCache. - MLA indexer (DSA-style):
q = wq_b(qr)([64, 128]heads),k = LayerNorm(wk(x))(one 128-dim key, LayerNorm with bias, eps 1e-6), both with non-traditional RoPE atrope_thetaover the 64 rope dims. When the cached lengthS <= index_topk + sliding_window(2176) the indexer is a no-op. Otherwise scorerelu(q @ k.T).f32weighted byweights_proj(x).f32 * (64 * 128) ** -0.5and summed over heads; always keep the most recent 128 positions; select the top 2048 among older positions; at decode (L == 1) gather the selected latent rows, and at prefill apply the selection as a boolean mask. The orthonormal Hadamard of the release is a no-op for full-precision dot products and is not implemented. - FFN: layer 0 dense
MLP(intermediate_size)with SiTU (gate = 4 * tanh(gate / 4) * sigmoid(gate),up = 25 * tanh(up / 25), product in f32, rounded once). Layers 1..42LatentMoE:scores = sigmoid(x.f32 @ W.T) + sigmoid(x.f32 @ W1.T)(two routers,gate.weightandgate.weight_1, summed after the sigmoid); select top-10 byscores + e_score_correction_bias; weights from unbiasedscores, divided bymax(sum, 1e-20), then multiplied byrouted_scaling_factor_param[ids](a learned[512]vector, initialized to 3.0). Experts run in a latent space:latent = fc1_latent_proj(x)(4096 to 2048),SwitchGLU(2048, 2048)with SiTU, f32 weighted sum,latent_norm,fc2_latent_proj(2048 to 4096), plusshared_experts(x)(SiTU MLP of width 2048). - Head:
logits = lm_head(h.f32), then MultiMax in f32:l + t0 * relu(r0 - l) + t1 * relu(l - r1) + t2 * relu(r2 - l)^2 + t3 * relu(l - r3)^2withmultimax_rangesandmultimax_ts([4]each).
Weight layout and sanitize
- Strip
language_model.; drop everymodel.layers.NwithN >= 43(the ECHO layer:e_proj,h_proj,enorm,hnorm,shared_head.norm,hc_head_*,transformer_layer.*); keep them out of the backbone but do not error on them. - Block FP8: every tensor
Kwith a siblingK + "_scale_inv"is E4M3 with one F32 scale per 128x128 block (the config saysscale_fmt ue8m0; the header stores the scales as F32, for examplelinear_q_up_proj.weightF8_E4M3[32768, 1024]withweight_scale_invF32[256, 8]). Match on the_scale_invsuffix, not on.weight_scale_inv:self_attn.linear_o_group_projis a bare tensor (F8_E4M3[8192, 4096]) whose scale islinear_o_group_proj_scale_inv(F32[64, 32]). Requantize to MLXmxfp8throughsrc/models/fp8_block.rs(requantize_block_fp8_weights,:418, and the config mergemerge_fp8_block_quantization,:234), as the Qwen3.5 loaders do throughsrc/models/fp8_checkpoint.rs, if that path accepts these tensors (including the bare-name pair and the 3-D reshape oflinear_o_group_projthat follows) without new code; if it does not, extend it with a test for each new case rather than adding an ERNIE-local FP8 decoder. A scale without its tensor, or a uint8 tensor without a scale, is a load error. The upstream quantization policy keeps the dense attention, norms, routers,hctensors,attn_sink,compressor.ape, MultiMax andlm_headunquantized (dequantize the FP8 ones to bf16) and keeps experts, shared experts andfc1/fc2_latent_projin MXFP8; follow it. - Key renames:
self_attention_hyper_connectiontoattn_hcandmlp_hyper_connectiontoffn_hc, withmapping_proj.weighttransposed intofn,biastobase, andalpha_pre,alpha_post,alpha_resconcatenated intoscale([3]);model.mhc_contract.hc_head_{fn,base,scale}tomodel.hc_head.*withfntransposed;model.lm_head.multimax_*tomultimax.*;input_layernormtoattn_norm,post_attention_layernormtoffn_norm,block_sparse_moeandmlptoffn,self_attntoattn, drop.core_attention.;linear_q_down_projtowq_a,linear_q_up_projtowq_b,linear_kv_projtowkv,q_layernormtoq_norm,kv_layernormtokv_norm,compressor.linear_wkv/linear_wgatetocompressor.wkv/wgate,attn.gate_projtoattn.o_gate,attn.o_projtoattn.wo_b,vha_postmix_U/_Vtovha.U/vha.V,softmax_offsettoattn_sink;attn.linear_o_group_projbecomeswo_a.weightreshaped[o_groups, o_lora_rank, -1]; shared expertw1,w2,w3togate_proj,down_proj,up_proj; stack routedexperts.E.{w1,w2,w3}intoswitch_mlp.{gate,down,up}_proj. - MLA
kv_b_proj: dequantize first if it is quantized (FP8 or MXFP8 after requantization), reshape[64, 192 + 256, 512],embed_q = k.swapaxes(-1, -2),unembed_out = v.
Checkpoints and hosts
| Checkpoint | Revision | Format | Size |
|---|---|---|---|
baidu/ERNIE-5.5-Flash-Base |
028544b2 |
block FP8 E4M3, 128x128 | 288.4 GB |
baidu/ERNIE-5.5-Flash-Base-BF16 |
dfab899d |
BF16 | 572.9 GB |
No public MLX conversion exists below 288 GB: orcarouter/ERNIE-5.5-Flash-Base-abliterated-MLX is a 299.8 GB derivative, and qwegnai/ERNIE-5.5-Flash-Base-hq8g32-shvq15g64-shvq3g64 is an 87.6 GB custom model.qwp container, not safetensors, which mlxcel will not load. The routed experts are about 270B of the parameters (512 experts of three 2048x2048 matrices over 42 layers), so an mlx_vlm.convert -q --q-bits 4 conversion of the experts should land near 150 GB; that is an estimate, not a measured size. This issue is status:blocked: the FP8 original needs a 512 GiB host, and the 256 GB route needs that 4-bit conversion produced and published (or produced locally) first. Implementation and unit tests can start now on tiny random configs built from this config with the layer counts reduced.
Current mlxcel state and reuse
- No
ernie5_5_moearm insrc/models/detection.rs.src/models/ernie4_5_moe.rsandernie4_5_moe_vl.rsare unrelated architectures despite the name; do not extend them. - DeepSeek-V4 is the base to reuse, not copy:
V4AttentionwithAttnKind::Compressed(src/models/deepseek_v4_attention.rs:51-110),Compressor,PoolingCache,align_local_mask,extend_mask(src/models/deepseek_v4_compress.rs:59-367),HyperConnection,hc_expand,HyperHead(src/models/deepseek_v4_hyper.rs:50-245),V4Rope(src/models/deepseek_v4_rope.rs:55) andV4LayerCache(src/models/deepseek_v4.rs:657). Add the ERNIE variations as explicit options on those types (an eps-outside-sqrt flag onHyperConnection, f32 accumulation onCompressor, an optional virtual-head mixer and output gate on the attention), so DeepSeek-V4's arithmetic stays bit-identical; rundeepseek_v4_tests::to prove it. Update every// Used by:comment on the V4 items reused. - MLA plus indexer: absorbed MLA from
src/models/deepseek_v3.rs(DeepSeekV3Attention,:201), indexer pattern fromsrc/models/deepseek_v32_indexer.rs(it uses onesum_axisover heads; ERNIE also sums over heads but only past 2176 cached rows). Sinks viafast_scaled_dot_product_attention_with_sinks. - SiTU: Raon-1-mini (#3225) uses the same function; whichever lands first adds a shared
situ(gate, up, beta, linear_beta)helper and the other reuses it. - Experts:
src/models/switch_layers.rsSwitchGLUwith a SiTU activation; MXFP8 expert planes through the shared loader. - Shared hotspots touched:
deepseek_v4_hyper.rs,deepseek_v4_compress.rs,deepseek_v4_attention.rs(options plus// Used by:), possiblyswitch_layers.rs.
Implementation plan
src/models/ernie5_5_moe.rs(config with validation:compress_ratiostruncated to the layer count and each entry-2or a positive non-4 ratio,hidden_act == situ,o_groupsdivides heads,0 < num_experts_per_tok <= n_routed_experts),ernie5_5_moe_layers.rs(MLA plus indexer, LatentMoE, MultiRouter, virtual heads, MultiMax),ernie5_5_moe_sanitize.rs,ernie5_5_moe_tests.rs.LanguageModelwithlast_row_logits(hc_head, norm, f32 head and MultiMax on the sampled row only).- Registration:
src/models/mod.rs(ModelType::Ernie5_5Moe),src/models/detection.rs,src/model_metadata.rs,src/loaded_model.rs,src/models/registry.rs, and the per-family tables insrc/execution/memory_estimate.rsandsrc/distributed/tensor_parallel/inference.rs. docs/supported-models.md: an entry with the large-model operational block fromdocs/adding-models.md(checkpoint identity, memory class, 1048576 declared context with a 128-token window, pooled and MLA caches, base model with no chat template, ECHO, TP and PP unsupported).
Acceptance criteria
-
mlxcel archlistsernie5_5_moe. - Tiny random model (4 layers with one MLA layer, 8 experts,
hc_mult 4): logits match the mlx-vlmLanguageModelbuilt from the same random weights within 1e-3 max abs for one prefill longer than the indexer threshold scaled to the tiny config, and for chunked prefill plus decode. - On the large host:
mlxcel generate -m models/ERNIE-5.5-Flash-Base -p "Large language models are" -n 128 --temp 0produces fluent continuation, and greedy 64-token output matchesmlx_vlm.generate --temp 0on the same weights. -
mlxcel-serverserves/v1/completionsfor this model. - Unit tests: (1) eps-outside-sqrt mHC differs from the V4 form on a constructed input and matches the hand computation, while V4's path is unchanged; (2) two-router scoring, selection bias and learned per-expert scaling on a hand-built score row; (3) virtual-head mixing equals an explicit loop over heads; (4) MultiMax piecewise terms at points below
r0, between, and abover3; (5) indexer is a no-op at or belowindex_topk + sliding_windowand always keeps the recent window above it; (6) sanitize renames, transposes,scaleconcatenation,wo_areshape and the ECHO-layer drop; (7) FP8 block requantization keeps experts in MXFP8 and dequantizes the attention projections; (8)last_row_case!. -
deepseek_v4_tests::still pass unchanged. - Integrated into
mlxcel generate,mlxcel-serverandmlxcel arch;docs/supported-models.mdupdated.
Verification
cargo build --release --features metal,accelerate
cargo test --profile test-fast --features metal,accelerate ernie5_5_moe_tests:: deepseek_v4_tests:: deepseek_v32
make verify-test
cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --check
python3 scripts/ci/check_cross_repo_refs.py
# 512 GiB host only (FP8 original):
./target/release/mlxcel generate -m models/ERNIE-5.5-Flash-Base -p "Large language models are" -n 128 --temp 0
Related
- DeepSeek-V4 lineage: #2386 (DeepSeek-V4.1 text) and #3205 (DeepSeek-V4 DSML tool calls) touch the same V4 modules; coordinate if they are in flight at the same time.
- Follow-up after this lands: ECHO decoding from the bundled layer 43 (upstream
echo.pyandspeculative/drafters/ernie5_5_mtp), and tensor parallel.
- Lingua principale
- Rust
- Stelle
- 505
- Fork
- 81
- Merge medio
- 14h 2m
- PR unite (30g)
- 448
Preparare l'ambiente
- Nessun Dockerfile né file Docker Compose
- Ha un modello di pull request
- Leggi la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di lablup/mlxcel
-
area:core priority:high status:ready type:security
Difficoltà 2/5 1-3 ore Idoneità per principianti 82/100
I maintainer di solito rispondono entro 1 giorno
-
priority:medium status:ready type:security
Difficoltà 4/5 3-5 giorni Idoneità per principianti 45/100
I maintainer di solito rispondono entro 1 giorno
-
area:models modeltype:text priority:medium status:in-progress type:bug
Difficoltà 4/5 3-5 giorni Idoneità per principianti 57/100
I maintainer di solito rispondono entro 1 giorno
-
area:models priority:low status:ready type:test
Difficoltà 4/5 3-5 giorni Idoneità per principianti 48/100
I maintainer di solito rispondono entro 1 giorno
-
area:models modeltype:omni priority:medium status:ready type:bug
Difficoltà 4/5 3-5 giorni Idoneità per principianti 48/100
I maintainer di solito rispondono entro 1 giorno
Tutte le issue di lablup/mlxcel
Issue simili
-
area:ui effort:medium enhancement P7 source:agent
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
I maintainer di solito rispondono entro 1 giorno
-
marketing
Difficoltà 2/5 1-3 ore Idoneità per principianti 85/100
I maintainer di solito rispondono entro 1 giorno
-
machine rename accepts a label already used by another machine, making --machine <label> ambiguousApertamaintainer-needed p2 remote triaged
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
I maintainer di solito rispondono entro 1 giorno
-
bug help wanted ui
Difficoltà 2/5 1-3 ore Idoneità per principianti 82/100
userFRM/egui-charts#4605 ·
I maintainer di solito rispondono entro 1 giorno
-
bug
Difficoltà 2/5 1-3 ore Idoneità per principianti 84/100
I maintainer di solito rispondono entro 1 giorno