Repository navigation
Description
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:
- a "DFNRope" ViT vision encoder (Linear patch embedding, 2D vision RoPE,
cu_seqlens-packed attention, quick_gelu MLP), - a variable-resolution resampler that folds 2x2 spatial windows plus a temporal pair, then projects to the text hidden size,
- 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.rsmapsernie4_5/ernie4_5_moe(lines 168-169) but noternie4_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 viafast_rope, and hardcodedeos_token_ids() = vec![2]. The block structure,SwitchLinear/SwitchGLUexpert-bank pattern, andDenseMLPare 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.rsandsrc/models/exaone_moe.rs: in-tree precedent fore_score_correction_biasthat participates only in expert selection.src/vision/encoders/qwen2_vl.rs: a nearly identical ViT skeleton (fused-QKV packedcu_seqlensattention, 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 (thePatchEmbedin that file additionally handles a 5-D conv kernel reorder that ERNIE does not need), and there is no in-encoderPatchMerger; 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 (prefillposition_ids, per-sequencerope_deltasfor 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_valueswith shape(total_patches, 588), where each row flattens(channels = 3, pixel_rows = 14, pixel_cols = 14)in that (channel-major) order, andgrid_thwwith 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). Thein_featuresaxis 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 insrc/vision/encoders/qwen2_vl.rsandsrc/vision/encoders/paddleocr_vl.rs).- 2D vision RoPE: per-head dim = 1280/16 = 80. A frequency table
(max_grid_side, 20)withtable[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]; thenout = x * cos + rotate_half(x) * sincomputed in f32, whererotate_halfsplits the last axis (size 80) into two 40-wide halves(x1, x2)and returnsconcat(-x2, x1)along the last axis. This is exactly the concat-half rotation already implemented insrc/vision/encoders/qwen2_vl.rs. - 32 pre-norm blocks:
x += attn(norm1(x)); x += mlp(norm2(x)), all on(total_patches, 1280). Attention: fusedqkvLinear 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)(theout_featuresaxis 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) atcu_seqlensboundaries (cumulativet*h*wper image), scaled-dot-product attention runs per segment with scale80^-0.5and no mask, outputs are concatenated back along axis 2, transposed, and reshaped to(seq, 1280), then projected byprojwith weight(1280, 1280)plus bias. MLP:fc1weight(5120, 1280), quick_gelu (x * sigmoid(1.702 * x)),fc2weight(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:
- 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. Thenspatial_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 keysspatial_linear.0.*,spatial_linear.2.*,spatial_linear.3.*. - 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). Thentemporal_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. mlp: Linear with weight(out = hidden_size, in = 5120), thenafter_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_Hifi < hwand i is even;p_Wifi < hwand i is odd;p_Tifi >= 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_expertsis a 2-list, each MoE layer holds two independent banks: text (routergate: Linear with weight(E_text, hidden_size), bias-free; experts: SwitchGLU over E_text experts ofmoe_intermediate_size[0]) and multimodal (gate_1,switch_mlp_1with E_mm experts ofmoe_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 overprobs + bias(bias broadcast over axis 0); combination weights are the uncorrectedprobsgathered at the selected indices(n_tokens, k), normalized bymax(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 theMoEBlockinsrc/models/ernie4_5_moe.rs(no bias) and fromsrc/models/dots1.rs(sigmoid router); it needs its own block. - Dispatch:
token_type_ids(batch, seq)are 1 whereinput_idsequal 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 sizemoe_intermediate_size[0] * moe_num_shared_experts, added to the routed output for every token. Checkpoint keys are unindexed (mlp.shared_experts.gate_proj.weightetc.), unlike the indexedmlp.shared_experts.{i}.*layout consumed bysrc/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 exceedsmax_pixels, scale both sides by1/sqrt(h*w/max_pixels)and floor to the factor; if belowmin_pixels, scale up bysqrt(min_pixels/(h*w))and ceil to the factor. Same family assrc/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 thein_featuresordering ofpatch_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, andimage_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) witht*h*w / spatial_conv_size^2copies 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 intokenizer_config.json; some exports may not include atokenizer.json. Verify mlxcel's tokenizer path handles this family and add conversion/handling if not.
Implementation plan
src/models/detection.rs: add"ernie4_5_moe_vl" | "ernie4.5_moe_vl" => Ok(ModelType::Ernie45MoeVLM).src/models/mod.rs:ModelType::Ernie45MoeVLMvariant, entries in the supported-type arrays and the test enumeration, display-name arm("ERNIE 4.5 MoE VL", "ERNIE"), andpub usefor the new module.src/models/ernie4_5_moe_vl.rs(new; do not retrofiternie4_5_moe.rs): config structs parsing root-level keys including int-or-2-list MoE fields; the ERNIE MRoPE above; attention takingposition_ids; dual-bank MoE block with selection-only correction bias and token-type dispatch; per-sequence MRoPE state reusingsrc/models/qwen_mrope_state.rs;LanguageModelimpl so text-only prompts and decode work; eos ids from config/generation_config instead of a hardcoded value. Reusesrc/models/switch_layers.rsfor the expert banks.src/vision/encoders/ernie4_5_vl.rs: DFNRope ViT. Prefer extracting the shared packed-attention and 2D-RoPE helpers fromsrc/vision/encoders/qwen2_vl.rsover copying; register insrc/vision/encoders/mod.rs.src/vision/connectors/ernie4_5_vl.rs: the resampler (spatial fold, temporal pair fold with t = 1 duplication, mlp + RMSNorm); register insrc/vision/connectors/mod.rs.src/vision/processors/ernie4_5_vl.rs: smart resize, normalization, 588-wide merge-window patch extraction, grid computation, placeholder expansion helpers; register insrc/vision/processors/mod.rs.src/vision/ernie4_5_moe_vl.rs: VLM wrapper wiring tower -> resampler ->src/vision/merge.rsscatter, position-id/rope-delta computation, token-type-id construction, prompt info; register insrc/vision/mod.rs.src/loading/vlm_ernie4_5_vl.rs: loader followingsrc/loading/vlm_paddleocr.rs(root-level text config with nestedtext_configfallback,vision_configsubparse, quantizationgroup_size/bitspropagation, weight remap beforefrom_weights); wire the module intosrc/loading/vlm.rs(#[path]include + re-export) and theModelType::Ernie45MoeVLMdispatch insrc/loading/mod.rs.- Runtime integration:
LoadedModelvariant insrc/loaded_model.rs,VlmRuntimeRefarm insrc/loaded_model_capabilities.rs, dispatch insrc/multimodal/vlm_runtime.rs, and prompt handling (a model-specificsrc/multimodal/ernie4_5_vl_prompt.rsin the style ofsrc/multimodal/internvl_prompt.rs, or sharedsrc/multimodal/vlm_prompt.rsif the placeholder flow fits) plussrc/multimodal/mod.rsregistration. - Placeholder suppression: populate
MultimodalPlaceholderTokens(src/models/multimodal_placeholders.rs) withimage_token_id/video_token_id=im_patch_idand boi/eoi = image start/end ids so placeholders never leak into output. tests/ernie4_5_moe_vl_parity.rsplus co-located unit tests (see Validation).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.*andvision_model.*for the tower (rewrite the latter); strip a leadingmodel.frommodel.resampler_model.*->resampler_model.*. Text keys ship asmodel.embed_tokens.*,model.layers.{l}.*,model.norm.weight,lm_head.weight. - Vision tower keys:
patch_embed.proj.weight(1280, 588)(no bias;in_featuresflattens(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 theout_featuresaxis stacking q, k, v (1280 rows each, in that order) plusbias(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}; finalln.{weight,bias}. Drop any key containingposition_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; +.biaswhenuse_bias); dense layersmodel.layers.{l}.mlp.gate_proj.weight/up_proj.weight(intermediate_size, hidden_size)anddown_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 in0 .. E_text + E_mm; gate/up weights are(moe_intermediate_size, hidden_size), down is(hidden_size, moe_intermediate_size). Stack experts0..E_textin index order along a new leading axis 0 into the text bank, giving(E_text, out_features, in_features)per projection; stack expertsE_text..E_text+E_mmthe same way into the multimodal bank. Stackscales/biasesidentically for quantized exports. - Routers:
model.layers.{l}.mlp.gate.weightmay be stored transposed as(hidden_size, E_text); mlxcel needs the Linear layout(E_text, hidden_size), so transpose (swap axes 0 and 1) whenshape[0] > shape[1]. The multimodal router ships asmodel.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., ormtp_emb_norm.. - When
tie_word_embeddingsis true, droplm_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_sectionderivation fromfreq_allocation,rope_scaling/rope_parametersfallbacks); 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-embedin_featuresaxis assumes); the MRoPE text-only degeneracy (scalar positions must reproducefast_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 ontests/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_vlcheckpoint (baidu/ERNIE-4.5-VL-28B-A3B-Thinkingis 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, missingmrope_section), tokenizer/chat-template details (SentencePiecetokenizer.model, template intokenizer_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.mdupdated.
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
Ernie45Moepath or MoE kernel/perf work beyond the existingsrc/models/switch_layers.rspaths.
Activity