feat(models): add ERNIE-5.5-Flash (ernie5_5_moe) support

Abierto
#3,227 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
5/5
Tiempo estimado
Más de una semana
Aptitud para principiantes
8/100
Tipo de issue
Nueva funcionalidad
Claridad
Bastante claro
Estado de actividad
Activo
Stack tecnológico
rust

Línea de trabajo

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.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

arch:hybrid area:models modelsize:xlarge modeltype:text priority:medium status:blocked type:enhancement

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

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); then ffn_hc, ffn_norm, FFN, hc_expand. Final norm(hc_head(h)).
  • mHC difference from DeepSeek-V4: the mixing logits are (flat @ fn.T) / (sqrt(mean(flat^2)) + rms_norm_eps) with flat in f32, i.e. epsilon outside the square root. V4 (and mlxcel's HyperConnection, which applies fast_rms_norm_no_weight first, src/models/deepseek_v4_hyper.rs:131) puts it inside. The rest (_hc_split_sinkhorn_ops with scale, base, 20 Sinkhorn iterations, hc_expand) is V4's. hc_head is V4's HyperHead unchanged.
  • HCA layers (ratio 128): V4's CompressedAttention (wq_a, q_norm, wq_b, weightless per-head rms on q, wkv, kv_norm, interleaved RoPE, a RotatingKVCache(128) local window plus a pooling cache of compressed rows, learned per-head attn_sink, inverse RoPE on the output, grouped wo_a over o_groups, wo_b) with three ERNIE changes: (1) the compressor accumulates wkv and wgate projections and the softmax pooling in f32 even for a bf16 backbone (HCACompressor), (2) virtual heads mix the attention output across heads before wo_a: out = (I + V.f32 @ U.f32.T).astype(dtype) @ out over the head axis, with U, V [64, 16] (vha_postmix_U, vha_postmix_V), (3) the wo_b input is multiplied by sigmoid(o_gate(qr)) where qr = q_norm(wq_a(x)) and o_gate is q_lora_rank to o_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 at rope_theta on the 64-dim parts, absorbed embed_q / unembed_out from kv_b_proj (decode) or expanded K/V (prefill), additive mask on pe_scores with -inf, learned attn_sink, scale (192 + 64) ** -0.5, then virtual heads, * sigmoid(o_gate(qr)) (q_lora_rank to 64 * 256) and wo_b. Caches: latent KVCache and an indexer key KVCache.
  • 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 at rope_theta over the 64 rope dims. When the cached length S <= index_topk + sliding_window (2176) the indexer is a no-op. Otherwise score relu(q @ k.T).f32 weighted by weights_proj(x).f32 * (64 * 128) ** -0.5 and 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..42 LatentMoE: scores = sigmoid(x.f32 @ W.T) + sigmoid(x.f32 @ W1.T) (two routers, gate.weight and gate.weight_1, summed after the sigmoid); select top-10 by scores + e_score_correction_bias; weights from unbiased scores, divided by max(sum, 1e-20), then multiplied by routed_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), plus shared_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)^2 with multimax_ranges and multimax_ts ([4] each).
Weight layout and sanitize
  • Strip language_model.; drop every model.layers.N with N >= 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 K with a sibling K + "_scale_inv" is E4M3 with one F32 scale per 128x128 block (the config says scale_fmt ue8m0; the header stores the scales as F32, for example linear_q_up_proj.weight F8_E4M3 [32768, 1024] with weight_scale_inv F32 [256, 8]). Match on the _scale_inv suffix, not on .weight_scale_inv: self_attn.linear_o_group_proj is a bare tensor (F8_E4M3 [8192, 4096]) whose scale is linear_o_group_proj_scale_inv (F32 [64, 32]). Requantize to MLX mxfp8 through src/models/fp8_block.rs (requantize_block_fp8_weights, :418, and the config merge merge_fp8_block_quantization, :234), as the Qwen3.5 loaders do through src/models/fp8_checkpoint.rs, if that path accepts these tensors (including the bare-name pair and the 3-D reshape of linear_o_group_proj that 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, hc tensors, attn_sink, compressor.ape, MultiMax and lm_head unquantized (dequantize the FP8 ones to bf16) and keeps experts, shared experts and fc1/fc2_latent_proj in MXFP8; follow it.
  • Key renames: self_attention_hyper_connection to attn_hc and mlp_hyper_connection to ffn_hc, with mapping_proj.weight transposed into fn, bias to base, and alpha_pre, alpha_post, alpha_res concatenated into scale ([3]); model.mhc_contract.hc_head_{fn,base,scale} to model.hc_head.* with fn transposed; model.lm_head.multimax_* to multimax.*; input_layernorm to attn_norm, post_attention_layernorm to ffn_norm, block_sparse_moe and mlp to ffn, self_attn to attn, drop .core_attention.; linear_q_down_proj to wq_a, linear_q_up_proj to wq_b, linear_kv_proj to wkv, q_layernorm to q_norm, kv_layernorm to kv_norm, compressor.linear_wkv / linear_wgate to compressor.wkv / wgate, attn.gate_proj to attn.o_gate, attn.o_proj to attn.wo_b, vha_postmix_U / _V to vha.U / vha.V, softmax_offset to attn_sink; attn.linear_o_group_proj becomes wo_a.weight reshaped [o_groups, o_lora_rank, -1]; shared expert w1, w2, w3 to gate_proj, down_proj, up_proj; stack routed experts.E.{w1,w2,w3} into switch_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_moe arm in src/models/detection.rs. src/models/ernie4_5_moe.rs and ernie4_5_moe_vl.rs are unrelated architectures despite the name; do not extend them.
  • DeepSeek-V4 is the base to reuse, not copy: V4Attention with AttnKind::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) and V4LayerCache (src/models/deepseek_v4.rs:657). Add the ERNIE variations as explicit options on those types (an eps-outside-sqrt flag on HyperConnection, f32 accumulation on Compressor, an optional virtual-head mixer and output gate on the attention), so DeepSeek-V4's arithmetic stays bit-identical; run deepseek_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 from src/models/deepseek_v32_indexer.rs (it uses one sum_axis over heads; ERNIE also sums over heads but only past 2176 cached rows). Sinks via fast_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.rs SwitchGLU with 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:), possibly switch_layers.rs.

Implementation plan

  • src/models/ernie5_5_moe.rs (config with validation: compress_ratios truncated to the layer count and each entry -2 or a positive non-4 ratio, hidden_act == situ, o_groups divides 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. LanguageModel with last_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 in src/execution/memory_estimate.rs and src/distributed/tensor_parallel/inference.rs.
  • docs/supported-models.md: an entry with the large-model operational block from docs/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 arch lists ernie5_5_moe.
  • Tiny random model (4 layers with one MLA layer, 8 experts, hc_mult 4): logits match the mlx-vlm LanguageModel built 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 0 produces fluent continuation, and greedy 64-token output matches mlx_vlm.generate --temp 0 on the same weights.
  • mlxcel-server serves /v1/completions for 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 above r3; (5) indexer is a no-op at or below index_topk + sliding_window and always keeps the recent window above it; (6) sanitize renames, transposes, scale concatenation, wo_a reshape 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-server and mlxcel arch; docs/supported-models.md updated.

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.py and speculative/drafters/ernie5_5_mtp), and tensor parallel.
Lenguaje dominante
Rust
Estrellas
505
Forks
81
Merge medio
14 h 2 min
PR fusionados (30 d)
448

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de lablup/mlxcel

Todos los issues de lablup/mlxcel

Issues similares

Más issues de Rust

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.