Skip to content

feat(models): port ERNIE-4.5 MoE VL (ViT + ERNIE-4.5 MoE text) #535

Closed

Description

@inureyes

Summary

Add support for ERNIE-4.5 MoE VL, Baidu's vision-language MoE. Checkpoints ship config.json with model_type: ernie4_5_moe_vl; mlxcel has no arm for it in src/models/detection.rs, so loading fails with "Unsupported model type".

The model pairs three parts:

  1. a "DFNRope" ViT vision encoder (Linear patch embedding, 2D vision RoPE, cu_seqlens-packed attention, quick_gelu MLP),
  2. a variable-resolution resampler that folds 2x2 spatial windows plus a temporal pair, then projects to the text hidden size,
  3. an ERNIE-4.5 MoE text decoder with 3D MRoPE (interleaved even/odd rotation) and modality-split expert banks: separate text and multimodal routers/experts selected per token by token type.

Current state in mlxcel

  • src/models/detection.rs maps ernie4_5 / ernie4_5_moe (lines 168-169) but not ernie4_5_moe_vl.
  • src/models/ernie4_5_moe.rs (Ernie45MoeModel): ERNIE-4.5 MoE text backbone with a single expert bank, softmax router without correction bias, scalar traditional RoPE via fast_rope, and hardcoded eos_token_ids() = vec![2]. The block structure, SwitchLinear/SwitchGLU expert-bank pattern, and DenseMLP are directly reusable; the router math, RoPE, and expert layout are not sufficient for VL (see Architecture).
  • src/models/ernie4_5.rs: dense ERNIE text backbone.
  • src/models/switch_layers.rs: shared MoE machinery (SwitchGLU::from_weights, moe_weighted_sum, gather/sort helpers).
  • src/models/dots1.rs and src/models/exaone_moe.rs: in-tree precedent for e_score_correction_bias that participates only in expert selection.
  • src/vision/encoders/qwen2_vl.rs: a nearly identical ViT skeleton (fused-QKV packed cu_seqlens attention, 2D rotary position embedding with tile-then-rotate-half application, quick_gelu MLP, LayerNorm blocks). Differences for ERNIE: the patch embedding weight is already 2-D (out_features, in_features) = (1280, 588) with no bias (the PatchEmbed in that file additionally handles a 5-D conv kernel reorder that ERNIE does not need), and there is no in-encoder PatchMerger; the tower ends with a plain LayerNorm (ln) and merging happens in an external resampler.
  • src/models/qwen2_vl.rs + src/models/qwen_mrope_state.rs: MRoPE position-id bookkeeping (prefill position_ids, per-sequence rope_deltas for decode). The state plumbing is reusable; the rotation math is not (ERNIE uses a different frequency-to-axis assignment and even/odd pairing, written out below).
  • src/vision/merge.rs: scatter of vision features into token embeddings.
  • src/vision/processors/qwen2_vl.rs: smart-resize implementation with the same resize factor and CLIP normalization constants ERNIE uses; the patch flattening differs (see Processor).
  • Canonical VLM port file set to mirror: the PaddleOCR-VL port (src/models/paddleocr_vl.rs, src/vision/paddleocr_vl.rs, src/vision/encoders/paddleocr_vl.rs, src/vision/connectors/paddleocr_vl.rs, src/vision/processors/paddleocr_vl.rs, src/loading/vlm_paddleocr.rs, tests/paddleocr_vl_parity.rs).

Architecture

config.json layout

Text parameters live at the config root (not nested under text_config), alongside a nested vision_config object. Some exports may additionally nest a text_config; prefer it when it carries hidden_size (same fallback logic as src/loading/vlm_paddleocr.rs).

Root / text keys (defaults apply when a key is absent; real checkpoints set the structural ones):

key default notes
hidden_size 3584 text hidden size, also the resampler output dim
intermediate_size 18944 dense-layer MLP size
num_hidden_layers 56
num_attention_heads 28
num_key_value_heads 4 null means equal to num_attention_heads
head_dim hidden_size / num_attention_heads
rms_norm_eps 1e-6
vocab_size required
rope_theta 1000000.0
max_position_embeddings 131072
use_bias false attention/MLP linear bias
tie_word_embeddings false
moe_num_experts 128 int, or 2-list [E_text, E_mm] on VL checkpoints
moe_intermediate_size 1408 int, or 2-list matching the two banks
moe_k 2 top-k
moe_layer_start_index 3 int or list (take the min)
moe_layer_end_index 53 int, list (take the max), or null (num_hidden_layers - 1)
moe_layer_interval 1
moe_num_shared_experts 0
moe_gate_act "softmax"
moe_norm_min 1e-12 score-normalization floor
moe_use_aux_free, moe_capacity, moe_norm_gate_logits, compression_ratio training-time fields, ignore for inference
rope_3d true
freq_allocation 20 temporal frequency count (mrope_section[2])
mrope_section [22, 22, 20] may also arrive as rope_scaling.mrope_section or rope_parameters.mrope_section; if absent derive [(head_dim/2 - freq_allocation)/2, same, freq_allocation]. rope_scaling.rope_type is an alias for rope_scaling.type
im_patch_id 100295 id of `<
image_start_token_id / image_end_token_id 101304 / 101305 `<
video_start_token_id / video_end_token_id 101306 / 101307
pixel_hidden_size 1280 equals vision embed_dim
spatial_conv_size 2 resampler spatial fold
temporal_conv_size 2 resampler temporal fold
use_temporal_conv true
eos_token_id optional list prefer over hardcoded ids; also honor generation_config.json

vision_config keys: model_type "DFNRope_vision_transformer", depth 32, embed_dim 1280 (hidden_size mirrors embed_dim), hidden_act "quick_gelu", mlp_ratio 4.0, num_heads 16, in_channels 3, patch_size 14, spatial_merge_size 2, layer_norm_eps 1e-6.

Vision encoder (DFNRope ViT)

  • Input: pixel_values with shape (total_patches, 588), where each row flattens (channels = 3, pixel_rows = 14, pixel_cols = 14) in that (channel-major) order, and grid_thw with shape (num_images, 3), each row (t, h, w) in patch units (t = 1 for images).
  • patch_embed.proj: Linear with weight (out_features = 1280, in_features = 588), no bias; output (total_patches, 1280). The in_features axis flattens (channels, pixel_rows, pixel_cols) in the same order the processor writes rows; no kernel reshape or axis permute is needed (unlike the conv-kernel reorders in src/vision/encoders/qwen2_vl.rs and src/vision/encoders/paddleocr_vl.rs).
  • 2D vision RoPE: per-head dim = 1280/16 = 80. A frequency table (max_grid_side, 20) with table[p, j] = p * 10000^(-2j/40), j in 0..20, indexed by per-patch (h_pos, w_pos). Patch positions are enumerated in merge-window order: position grids of shape (h, w) are reshaped to (h/2, 2, w/2, 2) (named (window_row, intra_row, window_col, intra_col)), transposed to (window_row, window_col, intra_row, intra_col), and flattened. Per patch, freqs = concat(table[h_pos], table[w_pos]) along the last axis, giving (total_patches, 40). Application: cos/sin of shape (total_patches, 40) are tiled (whole-block repeat, not per-element) along the last axis to (total_patches, 80), layout [f_0..f_39, f_0..f_39]; then out = x * cos + rotate_half(x) * sin computed in f32, where rotate_half splits the last axis (size 80) into two 40-wide halves (x1, x2) and returns concat(-x2, x1) along the last axis. This is exactly the concat-half rotation already implemented in src/vision/encoders/qwen2_vl.rs.
  • 32 pre-norm blocks: x += attn(norm1(x)); x += mlp(norm2(x)), all on (total_patches, 1280). Attention: fused qkv Linear with weight (3840, 1280) and bias (3840,); the output (seq, 3840) is reshaped to (seq, 3, num_heads = 16, head_dim = 80) and split along axis 1 into q/k/v of (seq, num_heads, head_dim) (the out_features axis stacks q, then k, then v, 1280 rows each). RoPE is applied on the last (head_dim) axis as above. Sequences are packed: q/k/v are transposed to (1, num_heads, seq, head_dim) and split along the sequence axis (axis 2) at cu_seqlens boundaries (cumulative t*h*w per image), scaled-dot-product attention runs per segment with scale 80^-0.5 and no mask, outputs are concatenated back along axis 2, transposed, and reshaped to (seq, 1280), then projected by proj with weight (1280, 1280) plus bias. MLP: fc1 weight (5120, 1280), quick_gelu (x * sigmoid(1.702 * x)), fc2 weight (1280, 5120), both biased. LayerNorms affine with bias, eps 1e-6.
  • Output: final LayerNorm ln, then (total_patches, 1280). No merger inside the tower.

Resampler (resampler_model)

Compresses the tower output (N, 1280) (rows in merge-window order) into text-embedding rows:

  1. Spatial fold: reshape (N, 1280) to (N/4, 5120), concatenating the features of each 4 consecutive rows (one 2x2 merge window; 4 = spatial_conv_size^2) along the last (feature) axis. Then spatial_linear: Linear (5120, 5120), exact (erf) GELU, Linear (5120, 5120), LayerNorm over the last axis (5120, eps 1e-6). The parameterized stages sit at sequential indices 0, 2, 3, hence weight keys spatial_linear.0.*, spatial_linear.2.*, spatial_linear.3.*.
  2. Temporal fold (when use_temporal_conv): per grid entry with T frames and S = hw/4 rows per frame, gather rows of even frame indices (t = 0, 2, ...) as A and odd frame indices (t = 1, 3, ...) as B; for T == 1 both A and B are the single frame (feature duplication). Concatenate A and B along the last (feature) axis: (rows, 5120) + (rows, 5120) -> (rows, 10240). Then temporal_linear: Linear with weight (out = 5120, in = 10240), GELU, Linear (5120, 5120), LayerNorm (5120, eps 1e-6). For a single image the row count stays hw/4.
  3. mlp: Linear with weight (out = hidden_size, in = 5120), then after_norm: RMSNorm over the last axis (hidden_size, eps 1e-5). Output (rows, hidden_size).

Result rows are scattered, in order, into the token-embedding tensor (batch, seq, hidden_size) at positions where input_ids (batch, seq) equals im_patch_id (fall back to the video token id when no image tokens are present); src/vision/merge.rs covers this pattern.

Text decoder

Standard pre-norm decoder: embed_tokens (vocab_size, hidden_size) -> per layer (input_layernorm RMSNorm -> GQA attention -> residual; post_attention_layernorm RMSNorm -> dense MLP or MoE -> residual) -> final RMSNorm -> lm_head (bias-free, weight (vocab_size, hidden_size)) or tied embedding. Layer l is MoE iff (l+1) % moe_layer_interval == 0 && moe_layer_start_index <= l <= moe_layer_end_index; other layers use a dense SwiGLU MLP with intermediate_size.

Attention shapes: from x (batch, seq, hidden_size), q is reshaped to (batch, seq, n_heads, head_dim) and transposed with axes (0, 2, 1, 3) to (batch, n_heads, seq, head_dim); k/v likewise with n_kv_heads. Scale head_dim^-0.5, causal mask, KV cache along the sequence axis (axis 2).

3D MRoPE (differs from the sectioned half-rotation in src/models/qwen2_vl.rs; implement exactly this):

Let D = head_dim, half = D/2 (64 for D = 128), hw = mrope_section[0] + mrope_section[1] (44). Each token carries position_ids of shape (batch, seq, 3), last axis ordered (p_T, p_H, p_W). For frequency-pair index i in 0..half:

  • frequency: f_i = rope_theta^(-2i/D)
  • position: p_H if i < hw and i is even; p_W if i < hw and i is odd; p_T if i >= hw
  • angle: theta_i = pos(i) * f_i

cos/sin are materialized as (batch, seq, head_dim) with each angle repeated twice at adjacent slots along the last axis ([c_0, c_0, c_1, c_1, ...]), broadcast over the heads axis by inserting axis 1 ((batch, 1, seq, head_dim)), and applied to q/k (batch, n_heads|n_kv_heads, seq, head_dim) by rotating adjacent (even, odd) element pairs of the last axis, in f32, cast back to the input dtype:

out[2i]   = x[2i]   * cos(theta_i) - x[2i+1] * sin(theta_i)
out[2i+1] = x[2i+1] * cos(theta_i) + x[2i]   * sin(theta_i)

Text-only degeneracy: when p_T = p_H = p_W = p (every text token), this reduces exactly to traditional interleaved RoPE with scalar positions, i.e. the same fast_rope(..., traditional=true, base=rope_theta) call used by src/models/ernie4_5_moe.rs. This equivalence is a required unit test.

Position-id construction: identical scheme to the Qwen2-VL family already implemented via src/models/qwen_mrope_state.rs: text runs share one scalar counter across all three axes; each vision block spans (t, h/merge, w/merge) index grids offset by the running counter (t index outermost, then h, then w; the block contributes t * (h/2) * (w/2) positions, matching the placeholder count for images); after a block the counter becomes max+1; rope_deltas = max_position + 1 - seq_len is carried per sequence so decode steps continue at cache_offset + delta with all three axes equal. Reuse the MRopeState plumbing and per-sequence binding.

Modality-split MoE (no in-tree equivalent, the core new work):

  • When moe_num_experts is a 2-list, each MoE layer holds two independent banks: text (router gate: Linear with weight (E_text, hidden_size), bias-free; experts: SwitchGLU over E_text experts of moe_intermediate_size[0]) and multimodal (gate_1, switch_mlp_1 with E_mm experts of moe_intermediate_size[1]), each with its own correction-bias vector of shape (E,).
  • Routing per bank, on tokens flattened to (n_tokens, hidden_size): logits (n_tokens, E); probs = softmax(logits, axis = -1) in f32; top-k selection along the last (expert) axis over probs + bias (bias broadcast over axis 0); combination weights are the uncorrected probs gathered at the selected indices (n_tokens, k), normalized by max(sum over axis -1, moe_norm_min). Expert outputs (n_tokens, k, hidden_size) are weighted by the scores (broadcast along the last axis) and summed over the k axis (axis 1). The bias influences which experts are picked, never the mixing weights. This differs from the MoEBlock in src/models/ernie4_5_moe.rs (no bias) and from src/models/dots1.rs (sigmoid router); it needs its own block.
  • Dispatch: token_type_ids (batch, seq) are 1 where input_ids equal the image/video placeholder id, else 0, and are only built when pixel values are present. Output per token = text-bank output where token type is 0, multimodal-bank output where 1 (select with the mask expanded to (batch, seq, 1) and broadcast along the hidden axis). Text-only calls and all decode steps (generated tokens are text) must take the text bank only and skip the multimodal bank entirely.
  • Shared experts (when moe_num_shared_experts > 0): one fused SwiGLU MLP with intermediate size moe_intermediate_size[0] * moe_num_shared_experts, added to the routed output for every token. Checkpoint keys are unindexed (mlp.shared_experts.gate_proj.weight etc.), unlike the indexed mlp.shared_experts.{i}.* layout consumed by src/models/ernie4_5_moe.rs; support the fused layout and key off which form is present.

Processor

  • Smart resize: factor = patch_size * spatial_merge_size = 28, min_pixels = 5656 = 3136, max_pixels = 2828*1280 = 1003520, aspect-ratio clamp 200:1. Round each side to the nearest multiple of 28 (floor of at least 28); if the product exceeds max_pixels, scale both sides by 1/sqrt(h*w/max_pixels) and floor to the factor; if below min_pixels, scale up by sqrt(min_pixels/(h*w)) and ceil to the factor. Same family as src/vision/processors/qwen2_vl.rs.
  • Pixel pipeline: RGB, bicubic resize, scale 1/255, normalize with mean (0.48145466, 0.4578275, 0.40821073) and std (0.26862954, 0.26130258, 0.27577711).
  • Patch flattening: from the channel-first image (channels = 3, H, W) with grid (gh, gw) = (H/14, W/14), reshape to the 7-axis tensor (channels, gh/2, 2, 14, gw/2, 2, 14), named (channels, window_row, intra_row, pixel_row, window_col, intra_col, pixel_col); transpose with axes (1, 4, 2, 5, 0, 3, 6) to (window_row, window_col, intra_row, intra_col, channels, pixel_row, pixel_col); reshape to (gh*gw, 588). Rows are therefore ordered by merge window (row-major over windows, then the 2x2 intra-window patches row-major), and each row flattens (channels, pixel_row, pixel_col), matching the in_features ordering of patch_embed.proj.weight. Unlike the Qwen2-VL processor there is no temporal frame duplication and no temporal folding into the row: rows are 588 wide, not 1176, and image_grid_thw = [1, gh, gw] per image.
  • Placeholder expansion: the chat template yields <|IMAGE_START|><|image@placeholder|><|IMAGE_END|> per image; replace each <|image@placeholder|> (left to right) with t*h*w / spatial_conv_size^2 copies of <|IMAGE_PLACEHOLDER|> (h*w/4 for images). Token ids: <|IMAGE_PLACEHOLDER|> = im_patch_id (100295), <|IMAGE_START|> = 101304, <|IMAGE_END|> = 101305.
  • Tokenizer: checkpoints ship a SentencePiece tokenizer.model (bos <s>, eos </s>, pad/unk <unk>, cls <|begin_of_sentence|>, sep <|end_of_sentence|>) with the chat template in tokenizer_config.json; some exports may not include a tokenizer.json. Verify mlxcel's tokenizer path handles this family and add conversion/handling if not.

Implementation plan

  1. src/models/detection.rs: add "ernie4_5_moe_vl" | "ernie4.5_moe_vl" => Ok(ModelType::Ernie45MoeVLM).
  2. src/models/mod.rs: ModelType::Ernie45MoeVLM variant, entries in the supported-type arrays and the test enumeration, display-name arm ("ERNIE 4.5 MoE VL", "ERNIE"), and pub use for the new module.
  3. src/models/ernie4_5_moe_vl.rs (new; do not retrofit ernie4_5_moe.rs): config structs parsing root-level keys including int-or-2-list MoE fields; the ERNIE MRoPE above; attention taking position_ids; dual-bank MoE block with selection-only correction bias and token-type dispatch; per-sequence MRoPE state reusing src/models/qwen_mrope_state.rs; LanguageModel impl so text-only prompts and decode work; eos ids from config/generation_config instead of a hardcoded value. Reuse src/models/switch_layers.rs for the expert banks.
  4. src/vision/encoders/ernie4_5_vl.rs: DFNRope ViT. Prefer extracting the shared packed-attention and 2D-RoPE helpers from src/vision/encoders/qwen2_vl.rs over copying; register in src/vision/encoders/mod.rs.
  5. src/vision/connectors/ernie4_5_vl.rs: the resampler (spatial fold, temporal pair fold with t = 1 duplication, mlp + RMSNorm); register in src/vision/connectors/mod.rs.
  6. src/vision/processors/ernie4_5_vl.rs: smart resize, normalization, 588-wide merge-window patch extraction, grid computation, placeholder expansion helpers; register in src/vision/processors/mod.rs.
  7. src/vision/ernie4_5_moe_vl.rs: VLM wrapper wiring tower -> resampler -> src/vision/merge.rs scatter, position-id/rope-delta computation, token-type-id construction, prompt info; register in src/vision/mod.rs.
  8. src/loading/vlm_ernie4_5_vl.rs: loader following src/loading/vlm_paddleocr.rs (root-level text config with nested text_config fallback, vision_config subparse, quantization group_size/bits propagation, weight remap before from_weights); wire the module into src/loading/vlm.rs (#[path] include + re-export) and the ModelType::Ernie45MoeVLM dispatch in src/loading/mod.rs.
  9. Runtime integration: LoadedModel variant in src/loaded_model.rs, VlmRuntimeRef arm in src/loaded_model_capabilities.rs, dispatch in src/multimodal/vlm_runtime.rs, and prompt handling (a model-specific src/multimodal/ernie4_5_vl_prompt.rs in the style of src/multimodal/internvl_prompt.rs, or shared src/multimodal/vlm_prompt.rs if the placeholder flow fits) plus src/multimodal/mod.rs registration.
  10. Placeholder suppression: populate MultimodalPlaceholderTokens (src/models/multimodal_placeholders.rs) with image_token_id/video_token_id = im_patch_id and boi/eoi = image start/end ids so placeholders never leak into output.
  11. tests/ernie4_5_moe_vl_parity.rs plus co-located unit tests (see Validation).
  12. docs/supported-models.md: one entry in the VLM section describing the pairing, in the style of the PaddleOCR-VL entry.

Weight loading and sanitize

Layout note: every learned matrix in this model is a Linear stored as (out_features, in_features), which is exactly what mlxcel's UnifiedLinear::from_weights and the SwitchLinear banks consume; there are no conv kernels anywhere, so no channels-last permutes are required (contrast the 5-D reorder in src/vision/encoders/qwen2_vl.rs::PatchEmbed and the 4-D reorder in src/vision/encoders/paddleocr_vl.rs). The only shape fix-ups are the router transposes and expert stacking below.

Safetensors keys and the transforms the loader must perform (per-model sanitize fn in the loader module, consistent with src/models/sanitize.rs conventions):

  • Prefix normalization: accept both vision_tower.* and vision_model.* for the tower (rewrite the latter); strip a leading model. from model.resampler_model.* -> resampler_model.*. Text keys ship as model.embed_tokens.*, model.layers.{l}.*, model.norm.weight, lm_head.weight.
  • Vision tower keys: patch_embed.proj.weight (1280, 588) (no bias; in_features flattens (channels = 3, pixel_row = 14, pixel_col = 14)); per block i: blocks.{i}.norm1.{weight,bias} (1280,), blocks.{i}.attn.qkv.weight (3840, 1280) with the out_features axis stacking q, k, v (1280 rows each, in that order) plus bias (3840,), blocks.{i}.attn.proj.{weight (1280, 1280), bias}, blocks.{i}.norm2.{weight,bias}, blocks.{i}.mlp.fc1.{weight (5120, 1280), bias}, blocks.{i}.mlp.fc2.{weight (1280, 5120), bias}; final ln.{weight,bias}. Drop any key containing position_ids.
  • Resampler keys: resampler_model.spatial_linear.0.{weight (5120, 5120), bias}, resampler_model.spatial_linear.2.{weight (5120, 5120), bias}, resampler_model.spatial_linear.3.{weight,bias} (LayerNorm, (5120,)), resampler_model.temporal_linear.0.{weight (5120, 10240), bias}, resampler_model.temporal_linear.2.{weight (5120, 5120), bias}, resampler_model.temporal_linear.3.{weight,bias}, resampler_model.mlp.{weight (hidden_size, 5120), bias}, resampler_model.after_norm.weight (hidden_size,).
  • Text keys: model.embed_tokens.weight (vocab_size, hidden_size); model.layers.{l}.self_attn.{q,k,v,o}_proj.weight ((n_heads*head_dim, hidden_size) for q, (n_kv_heads*head_dim, hidden_size) for k/v, (hidden_size, n_heads*head_dim) for o; + .bias when use_bias); dense layers model.layers.{l}.mlp.gate_proj.weight / up_proj.weight (intermediate_size, hidden_size) and down_proj.weight (hidden_size, intermediate_size); input_layernorm.weight, post_attention_layernorm.weight (hidden_size,); lm_head.weight (vocab_size, hidden_size).
  • Expert stacking (MoE layers): per-expert keys model.layers.{l}.mlp.experts.{e}.{gate,up,down}_proj.{weight,scales,biases} with e in 0 .. E_text + E_mm; gate/up weights are (moe_intermediate_size, hidden_size), down is (hidden_size, moe_intermediate_size). Stack experts 0..E_text in index order along a new leading axis 0 into the text bank, giving (E_text, out_features, in_features) per projection; stack experts E_text..E_text+E_mm the same way into the multimodal bank. Stack scales/biases identically for quantized exports.
  • Routers: model.layers.{l}.mlp.gate.weight may be stored transposed as (hidden_size, E_text); mlxcel needs the Linear layout (E_text, hidden_size), so transpose (swap axes 0 and 1) when shape[0] > shape[1]. The multimodal router ships as model.layers.{l}.mlp.gate.weight_1; split it into its own tensor with the same transpose rule, target (E_mm, hidden_size).
  • Correction bias: model.layers.{l}.mlp.moe_statics.e_score_correction_bias, shape (2, E): split along axis 0 into row 0 = text-bank bias (E_text,) and row 1 = multimodal-bank bias (E_mm,). A 1-D (E,) form means text bank only (squeeze extra axes if present).
  • Shared experts (when configured): unindexed model.layers.{l}.mlp.shared_experts.{gate,up,down}_proj.weight (single fused MLP; gate/up (moe_intermediate_size[0] * moe_num_shared_experts, hidden_size)).
  • Drop multi-token-prediction training heads: any key containing mtp_block., mtp_linear_proj., mtp_hidden_norm., or mtp_emb_norm..
  • When tie_word_embeddings is true, drop lm_head.weight.

Validation and acceptance criteria

  • Co-located unit tests (in the new modules): config parsing (int vs 2-list moe_num_experts/moe_intermediate_size, mrope_section derivation from freq_allocation, rope_scaling/rope_parameters fallbacks); smart-resize/grid values against the formula; patch-extraction row ordering (window order and the (channels, pixel_row, pixel_col) row layout that the patch-embed in_features axis assumes); the MRoPE text-only degeneracy (scalar positions must reproduce fast_rope(traditional=true) numerics); router semantics (bias changes selection but not mixing weights; normalization floor; router-weight transpose rule); resampler shapes including the t = 1 temporal duplication; placeholder expansion counts.
  • Synthetic parity test tests/ernie4_5_moe_vl_parity.rs, modeled on tests/paddleocr_vl_parity.rs: construct the full stack from synthetic weights and run processor -> tower -> resampler -> embedding merge -> text forward (prefill + a few decode steps), covering both a text-only prompt (text bank only) and an image prompt (dual-bank dispatch), asserting shapes, finiteness, and determinism.
  • Real-checkpoint smoke test: load a real ernie4_5_moe_vl checkpoint (baidu/ERNIE-4.5-VL-28B-A3B-Thinking is a known public one; a quantized export is acceptable) and generate through mlxcel's server/CLI runtime with an image prompt and with a text-only prompt, producing coherent output with no placeholder tokens leaking.
  • Known failure mode: synthetic parity can pass while real checkpoints break on weight-key layout (prefix variants, gate.weight_1, moe_statics, transposed routers), config defaults (list-typed MoE fields, missing mrope_section), tokenizer/chat-template details (SentencePiece tokenizer.model, template in tokenizer_config.json), and MoE fusion/stacking. Real-checkpoint load + generate is therefore the completion bar, not the parity test.
  • Completion requires integration into the working runtime (detection, loader dispatch, LoadedModel/VlmRuntimeRef, prompt path, server/CLI generation), not standalone modules.
  • docs/supported-models.md updated.

Out of scope

  • Video generation end to end. The resampler and grid handling should accept general grid_thw, but video placeholder expansion, frame sampling, and video position-id wiring are a follow-up (note: with temporal folding, video feature counts differ from image-style placeholder counts, so this needs its own design pass).
  • Multi-token-prediction heads (dropped in sanitize).
  • Training-only MoE fields (moe_capacity, moe_use_aux_free, aux-free load balancing).
  • Changes to the existing text-only Ernie45Moe path or MoE kernel/perf work beyond the existing src/models/switch_layers.rs paths.

Effort: high

Activity

  1. added
    status:ready
    type:enhancement
    priority:low
    area:models
    on Jul 1, 2026
  2. self-assigned this
    on Aug 31, 2026
  3. added
    status:done
    and removed
    status:ready
    on Sep 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area:modelspriority:lowstatus:donetype:enhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions