Skip to content

feat(models): port Step-3 (step3p7) (newer StepFun multimodal) #543

Closed

Description

@inureyes

Summary

Add Step-3 (step3p7) support to mlxcel. Checkpoints ship config.json with model_type: "step3p7". mlxcel currently has no arm for it in src/models/detection.rs, so a step3p7 checkpoint fails with "Unsupported model type".

Step-3.7 is a StepFun multimodal model. Its text decoder is the Step-3.5 architecture that mlxcel already implements in src/models/step3p5.rs (the checkpoint's nested text_config.model_type is literally "step3p5"). What is new is everything around it: a nested VLM config layout, a 47-layer ViT vision tower (vision_config.model_type: "perception_encoder"), two stride-2 conv downsamplers plus a linear projector into the text hidden size, an image patcher/processor with a base-image pass and a tiled-patch pass, and token scatter into <im_patch> placeholder positions.

Recommendation (based on the actual delta, detailed below): do NOT fork a step3p7 text model. The text-side delta vs src/models/step3p5.rs is config parsing only (nested config, one field that can be a JSON array, three default values). Extend src/models/step3p5.rs config-gated and reuse Step3p5Model as the backbone; add the vision stack as new files following the canonical VLM file set (the paddleocr_vl port is the closest structural template).

Shape notation used throughout this issue: every tensor shape is written with named dimensions in explicit order, e.g. (batch, seq, n_heads, head_dim). Axis numbers are 0-based and always refer to the shape as written at that point.

Current state in mlxcel

Verified against the tree:

  • src/models/step3p5.rs + src/models/step3p5_tests.rs: text-only Step-3.5. Implements per-layer sliding/full attention, per-head q/k RMSNorm, optional head-wise attention gate (g_proj), clamped SwiGLU with per-layer limits, sigmoid MoE gate with router_bias, SwitchGLU experts + shared expert, per-layer rope_theta and partial_rotary_factors. It implements LanguageModel with internal RefCell caches and supports_batching() == false.
  • src/models/detection.rs:215: "step3p5" => Ok(ModelType::Step3p5). No step3p7 arm anywhere (grep -rn step3p7 src/ is empty).
  • src/model_metadata.rs:210: Step3p5 is registered as kind: Text, directory: ConfigBacked with dir_loader: models::Step3p5Model::load.
  • There are no Step files under src/vision/, src/vision/encoders/, src/vision/connectors/, or src/vision/processors/. Step support today is text-only.
  • docs/supported-models.md lists "Step 3.5" in the text-model families line only.
  • Canonical VLM port file set exists and is verifiable via 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, loader src/loading/vlm_paddleocr.rs wired into src/loading/vlm.rs (#[path] module + pub(crate) use) and src/loading/mod.rs:187, runtime variant in src/loaded_model.rs:84 and src/loaded_model_capabilities.rs (VlmRuntimeRef::PaddleOcr), preparation branch in src/multimodal/vlm_runtime.rs:315, parity test tests/paddleocr_vl_parity.rs, docs entry.

Architecture

config.json, top level

key type / default notes
model_type "step3p7" detection key
text_config object nested Step-3.5 text config, its own model_type defaults to "step3p5"
vision_config object model_type: "perception_encoder"
understand_projector_stride int, 2 stride of each of the two downsampler convs (total 4x per axis)
projector_bias bool, false bias on vit_large_projector
image_token_id int, 128001 id of <im_patch>
image_token_index optional int, defaults to image_token_id scatter target id
vocab_size int, 128896
eos_token_id optional int or list; falls back to text_config.eos_token_id
quantization / quantization_config optional objects per-tensor entries may use pre-remap key names, see sanitize section

text_config (nested)

Same field set the flat Step-3.5 config uses, with these defaults: hidden_size 4096, intermediate_size 11264, num_attention_heads 64, num_attention_groups 8 (KV heads), num_hidden_layers 45, vocab_size 128896, rms_norm_eps 1e-5, head_dim 128, max_position_embeddings 262144, rope_theta 10000.0 (scalar or per-layer list), rope_scaling optional (a rope_type key is an accepted alias for type), layer_types optional list of "sliding_attention"/"full_attention" (fallback when absent: even layers sliding), sliding_window optional (no default), attention_other_setting optional {num_attention_heads, num_attention_groups} override for sliding layers, use_head_wise_attn_gate false, partial_rotary_factors optional per-layer list, yarn_only_types optional list, moe_num_experts 288, moe_top_k 8, moe_intermediate_size 1280, share_expert_dim 1280 (alias share_expert_dims), norm_expert_weight true, moe_router_scaling_factor 1.0, moe_layers_enum comma-separated string or JSON int array, default layers 3 through 44 inclusive, swiglu_limits / swiglu_limits_shared optional per-layer lists with nullable entries, tie_word_embeddings false, pad_token_id 1. Keys use_moe_router_bias, moe_router_activation, need_fp32_gate, use_rope_layers, max_seq_len, attention_dropout may appear in checkpoints but do not change the compute path: routing is always the sigmoid-plus-bias scheme below, and gate scoring is done in float32.

vision_config (nested, perception_encoder)

key default notes
width 1536 hidden size; head_dim = width/heads = 96
layers 47 transformer blocks
heads 16
num_channels 3
image_size 728 base pass resolution; grid 52x52
patch_size 14
mlp_ratio 8960/1536 MLP hidden = int(width * mlp_ratio) = 8960
hidden_act "quick_gelu" x * sigmoid(1.702 * x)
layer_norm_eps 1e-5
use_cls_token false checkpoints may spell this ues_cls_token (typo alias, must be honored)
use_ln_pre / use_ln_post true / false
use_abs_posemb true learned absolute positions, bilinear-resized for non-52 grids
use_rope2d true 2D rotary applied to q/k inside every block
ls_init_value 0.1 LayerScale init (weights come from the checkpoint; null means 1.0)
rope_theta 10000.0 for the 2D rope

Module hierarchy and weight shapes (default config)

All linear weights below are stored (out_features, in_features), the layout UnifiedLinear in mlxcel already consumes (it transposes at matmul time; see src/vision/encoders/paddleocr_vl.rs:158 for the same pattern done manually). Conv shapes are given in the checkpoint's storage layout here; the required permutations to MLX's channels-last layout are spelled out in the sanitize section.

Text decoder (identical math to Step3p5Model):

model.embed_tokens.weight                (vocab=128896, hidden=4096)
model.layers.{i}  (i in 0..45)
  self_attn.q_proj.weight                (n_heads*head_dim=8192, hidden=4096)
  self_attn.k_proj.weight                (n_kv_heads*head_dim=1024, hidden=4096)
  self_attn.v_proj.weight                (n_kv_heads*head_dim=1024, hidden=4096)
  self_attn.o_proj.weight                (hidden=4096, n_heads*head_dim=8192)
  self_attn.q_norm.weight                (head_dim=128)   per-head RMSNorm
  self_attn.k_norm.weight                (head_dim=128)
  self_attn.g_proj.weight                (n_heads=64, hidden=4096)  only if use_head_wise_attn_gate
  input_layernorm.weight                 (hidden=4096)
  post_attention_layernorm.weight        (hidden=4096)
  -- dense layers (i not in moe_layers_enum):
  mlp.gate_proj.weight / up_proj.weight  (intermediate=11264, hidden=4096)
  mlp.down_proj.weight                   (hidden=4096, intermediate=11264)
  -- MoE layers:
  mlp.gate.gate.weight                   (num_experts=288, hidden=4096)
  mlp.gate.router_bias                   (num_experts=288)  float32
  mlp.switch_mlp.gate_proj.weight        (num_experts=288, moe_intermediate=1280, hidden=4096)  stacked experts
  mlp.switch_mlp.up_proj.weight          (num_experts=288, moe_intermediate=1280, hidden=4096)
  mlp.switch_mlp.down_proj.weight        (num_experts=288, hidden=4096, moe_intermediate=1280)
  mlp.share_expert.gate_proj/up_proj     (share_expert_dim=1280, hidden=4096)
  mlp.share_expert.down_proj             (hidden=4096, share_expert_dim=1280)
model.norm.weight                        (hidden=4096)
lm_head.weight                           (vocab=128896, hidden=4096)

Vision tower and projector (conv weights shown in checkpoint storage layout (out_ch, in_ch, kH, kW)):

vision_model.conv1.weight                    (out_ch=1536, in_ch=3, kH=14, kW=14)  no bias
vision_model.positional_embedding            (tokens=2704, width=1536)   52*52; +1 leading row if cls token
vision_model.class_embedding                 (width=1536)                only if use_cls_token
vision_model.ln_pre.{weight,bias}            (width=1536)
vision_model.transformer.{i}  (i in 0..47)
  ln_1.{weight,bias}                         (width=1536)
  attn.in_proj.weight                        (3*width=4608, width=1536)  fused qkv; row blocks [0..1536)=q, [1536..3072)=k, [3072..4608)=v
  attn.in_proj.bias                          (3*width=4608)
  attn.out_proj.weight                       (width=1536, width=1536)
  attn.out_proj.bias                         (width=1536)
  ls_1.gamma / ls_2.gamma                    (width=1536)                LayerScale
  ln_2.{weight,bias}                         (width=1536)
  mlp.c_fc.weight                            (mlp_hidden=8960, width=1536)
  mlp.c_fc.bias                              (mlp_hidden=8960)
  mlp.c_proj.weight                          (width=1536, mlp_hidden=8960)
  mlp.c_proj.bias                            (width=1536)
vision_model.vit_downsampler1.weight         (out_ch=3072, in_ch=1536, kH=3, kW=3)  stride 2, pad 1; bias (3072)
vision_model.vit_downsampler2.weight         (out_ch=6144, in_ch=3072, kH=3, kW=3)  stride 2, pad 1; bias (6144)
vit_large_projector.weight                   (text_hidden=4096, 4*width=6144)  bias (4096) iff projector_bias

Forward math with explicit axes

Text attention (per layer, hidden states x of shape (batch, seq, hidden)):

  1. q = q_proj(x) of shape (batch, seq, n_heads*head_dim), reshaped to (batch, seq, n_heads, head_dim); q_norm (RMSNorm) is applied over the last axis (axis 3, head_dim) BEFORE any transpose; then transpose with axes [0, 2, 1, 3] to (batch, n_heads, seq, head_dim). Same for k with n_kv_heads; v is reshaped and transposed without a norm.
  2. RoPE with per-layer base and rope_dims = head_dim * partial_rotary_factor rotates only the first rope_dims entries of the last axis.
  3. Attention output (batch, n_heads, seq, head_dim) is transposed back with axes [0, 2, 1, 3] to (batch, seq, n_heads, head_dim).
  4. Head-wise gate (only when use_head_wise_attn_gate): g = sigmoid(g_proj(x)) of shape (batch, seq, n_heads), expanded on a new trailing axis to (batch, seq, n_heads, 1), multiplied elementwise into the (batch, seq, n_heads, head_dim) output (broadcast over axis 3).
  5. Reshape to (batch, seq, n_heads*head_dim) and apply o_proj.

MoE routing (per MoE layer, x of shape (batch, seq, hidden)):

  1. s = sigmoid(gate(x)) computed in float32, shape (batch, seq, num_experts=288).
  2. c = s + router_bias (router_bias (num_experts,) broadcasts over axes 0 and 1).
  3. I = argtop_k(c, k=moe_top_k) along the expert axis (axis 2, the last axis), shape (batch, seq, top_k=8).
  4. w = take_along_axis(s, I, axis=2): weights come from the UNCORRECTED scores, indices from the bias-corrected ones.
  5. If norm_expert_weight: w = w / (sum(w, axis=2, keepdims) + 1e-20); then w = w * moe_router_scaling_factor.
  6. Expert outputs are gathered per selected expert into shape (batch, seq, top_k, hidden); multiply by w expanded to (batch, seq, top_k, 1) and sum over the top_k axis (axis 2), giving (batch, seq, hidden); add share_expert(x).

Clamped SwiGLU (when the per-layer limit is > 0): out = min(silu(gate), limit) * clip(x, -limit, +limit), elementwise.

Vision block (x of shape (batch, tokens, width)): x = x + ls_1 * attn(ln_1(x)), then x = x + ls_2 * mlp(ln_2(x)); mlp(x) = c_proj(quick_gelu(c_fc(x))); LayerScale multiplies elementwise with gamma (width,) broadcast over axes 0 and 1.

Vision attention: in_proj(x) gives (batch, tokens, 3*width), reshaped to (batch, tokens, 3, n_heads=16, head_dim=96); q/k/v are slices at indices 0/1/2 of axis 2; each is transposed with axes [0, 2, 1, 3] to (batch, n_heads, tokens, head_dim); softmax attention with scale head_dim^-0.5, no mask; output transposed back [0, 2, 1, 3] and reshaped to (batch, tokens, width) for out_proj.

2D rotary (on q and k in (batch, n_heads, tokens, head_dim=96) layout, where tokens enumerate the grid row-major, token = row * grid_w + col):

  • Quarter-dim inverse frequencies inv_freq[j] = rope_theta^(-2j / (head_dim/2)) for j in 0..head_dim/4 (24 values).
  • Per token at (row, col): freqs = concat(col * inv_freq, row * inv_freq) along the frequency axis (width component first, then height), shape (tokens, head_dim/2=48); each element is repeated 2x along the last axis (element-wise repeat, i.e. f0 f0 f1 f1 ..., not tiling) giving (tokens, head_dim=96); broadcast against q/k over axes 0 and 1.
  • q' = q * cos(freqs) + rotate_half(q) * sin(freqs) where rotate_half reshapes the last axis (..., head_dim) to (..., head_dim/2, 2), maps each pair (a, b) to (-b, a), and reshapes back: (x0, x1, x2, x3, ...) -> (-x1, x0, -x3, x2, ...).

Positional embedding interpolation: the learned table is (tokens=2704, width=1536) covering the 52x52 grid. For a different grid (the 504 px patch pass has grid 36x36) it is reshaped to (1, grid=52, grid=52, width=1536), bilinearly resized over axes 1 and 2 by (gh/52, gw/52), and reshaped to (gh*gw, width). This path is exercised on every patched image, not just edge cases.

Feature pipeline (per pass; convs operate channels-last):

  • Pixel input: the processor emits (num_images, channels=3, height, width); transpose with axes [0, 2, 3, 1] to (num_images, height, width, channels) before conv1, the same convention every mlxcel vision encoder uses (src/vision/mod.rs:206).
  • Base image 728x728: conv1 (k14 s14) -> (B, gh=52, gw=52, width=1536) flattened to (B, tokens=2704, width=1536) -> (+posemb, ln_pre) -> 47 blocks -> reshape back to (B, 52, 52, 1536) -> downsampler1 -> (B, 26, 26, 3072) -> downsampler2 -> (B, 13, 13, 6144) -> flatten to (B, 169, 6144) -> projector -> (B, 169, text_hidden=4096). 169 features per base image.
  • Patch 504x504: grid 36x36 -> (N, 1296, 1536) -> (N, 18, 18, 3072) -> (N, 9, 9, 6144) -> (N, 81, 4096). 81 features per patch.

The downsampler convs are owned by the vision tower (weights under vision_model.) but applied by the top-level model after the encoder output is reshaped back to the spatial grid; the projector then maps into the text hidden size.

Image preprocessing and prompt token layout

Preprocessing per image:

  1. EXIF transpose, convert to RGB.
  2. Square-pad to max(w, h) (paste at top-left, black fill). All later math sees a square image.
  3. If the side exceeds 3024, scale down so the max side is 3024.
  4. Window decision on the (square) size: side <= 728 gives no patches; side > 728 gives window 504. (The general rule is: for long <= 728, window is short if long/short > 1.5 else 0; otherwise min(short, 504) if long/short > 4 else 504. After square padding long == short, so only the two effective outcomes occur.)
  5. Base tensor: resize the padded image to 728x728 (bilinear).
  6. Patch tensors (only when window is 504): per axis with side d and r = d/504, crop target d' = d if r < 1, else 504 * (floor(r) + 1 if r - floor(r) > 0.2 else floor(r)); resize to (d', d'), then tile 504x504 windows at origins 504*i, clamping the last origin to d' - 504 (windows may overlap). Windows enumerate row-major (all columns of row 0, then row 1, ...). Patch i is followed by a newline marker when (i+1) is a multiple of the per-row window count, except the final patch never gets one.
  7. Normalization for both passes: x/255, then (x - mean)/std per channel, mean [0.48145466, 0.4578275, 0.40821073], std [0.26862954, 0.26130258, 0.27577711] (RGB order). Output layout (num_images, channels=3, height, width); base and patch tensors are separate batches (pixel_values and patch_pixel_values).

Prompt expansion (ids resolved from the tokenizer): the placeholder token is <im_patch> (image_token_id, default 128001); specials <im_start>, <im_end>, <patch_start>, <patch_end>, <patch_newline> also exist in the vocab. Per image, the placeholder expands to:

for each patch i:  <patch_start>  81 x <im_patch>  <patch_end>  [<patch_newline> if row end]
then:              <im_start>    169 x <im_patch>  <im_end>

An unpatched image is just <im_start> 169x<im_patch> <im_end>. Embedding merge scatters projected vision features (rows of shape (text_hidden=4096,)) into the sequence positions of the (batch, seq, hidden) embedding tensor where the token id equals image_token_index, in this order per image: all patch features first (81 rows each, patch order), then the base-image features (169 rows). The total <im_patch> count must exactly equal the total feature rows (169 + 81 * num_patches per image); a mismatch must be a hard error, not silent truncation. The chat template ships with the tokenizer (BPE with byte-level decoding).

Delta vs step3p5 as implemented in src/models/step3p5.rs

Text math that is byte-for-byte the same scheme (already implemented and tested in src/models/step3p5.rs, keep it): the attention path in "Forward math" steps 1-5 (per-head q_norm/k_norm over the head_dim axis before the [0, 2, 1, 3] transpose, GQA with per-layer sliding/full selection via layer_types with even-index-sliding fallback, attention_other_setting heads override on sliding layers, per-layer rope_theta and partial_rotary_factors, scale head_dim^-0.5, head-wise gate y * sigmoid(g_proj(x)) expanded to (batch, seq, n_heads, 1)), the MoE routing steps 1-6 (float32 sigmoid scores, bias-corrected top-k indices along the expert axis, uncorrected weights, 1e-20-guarded normalization over the top_k axis, scaling factor, shared expert added), the clamped SwiGLU, and the zero-centered norm and .mtp handling in sanitize.

Actual deltas:

  1. Config layout: src/models/step3p5.rs deserializes a flat config.json (Step3p5Config). step3p7 checkpoints nest the same text fields under text_config and add vision_config plus the top-level keys in the table above. A nested-config constructor is needed; the flat path must keep working.
  2. moe_layers_enum encoding: Step3p5Config parses Option<String> (comma-separated) only, and when the key is absent falls back to "all layers except 0" (moe_layer_indices() in src/models/step3p5.rs). step3p7 checkpoints may encode it as a JSON int array, and the absent-default for this family is layers 3..=44. Accept both encodings (e.g. switch the field to serde_json::Value with a helper); always prefer the explicit config value so the differing fallbacks never matter in practice.
  3. Flipped defaults, only relevant when a checkpoint omits the key: use_head_wise_attn_gate defaults true in src/models/step3p5.rs (default_true) but false for step3p7 text stacks, and g_proj weights may be entirely absent; moe_router_scaling_factor defaults 3.0 there vs 1.0 here; sliding_window defaults 512 there vs unset here (only meaningful when layer_types contains sliding_attention). Gate these defaults on which config shape was parsed.
  4. eos_token_id resolution: top-level value (int or list) first, then text_config.eos_token_id; the flat parser's vec![2] fallback stays last resort.
  5. rope_scaling: when set, it applies only to layers whose layer type is listed in yarn_only_types; other layers use plain RoPE. src/models/step3p5.rs currently parses these fields but always applies plain RoPE (fast_rope with per-layer base). Known step3p5-family checkpoints run without rope_scaling; verify the real step3p7 checkpoint's text_config during validation and implement the scaled path only if the checkpoint actually sets it.
  6. Everything vision-side is net-new relative to src/models/step3p5.rs: the ViT tower, 2D rope, LayerScale, absolute-position interpolation, downsamplers, projector, processor/patcher, placeholder expansion, and embedding scatter.
  7. Forward entry point: Step3p5Model::forward_with_caches embeds tokens internally via embed_tokens.forward, producing (batch, seq, hidden) from (batch, seq) token ids. The VLM wrapper needs an inputs_embeds path that accepts an already-merged (batch, seq, hidden) tensor, plus access to embed_tokens for the text rows, following the forward_with_embeddings pattern in src/vision/paddleocr_vl.rs:184.

Implementation plan

Reuse Step3p5Model as the text backbone; all new files follow the paddleocr_vl layout.

  1. src/models/detection.rs: add "step3p7" => Ok(ModelType::Step3p7) next to the "step3p5" arm (line 215).
  2. src/models/mod.rs: add ModelType::Step3p7 in the Step models group (near line 393), add it to ALL_MODEL_TYPES (near line 548), add the mlxcel arch metadata arm (near line 715, e.g. ("Step-3.7 (ViT + Step-3.5 MoE)", "Step VLM")), and extend the exhaustiveness variants! list in the test module (near line 947).
  3. src/model_metadata.rs: register Step3p7 => { kind: Vlm, directory: Vlm, weight: None, adapter: Some("Step-3.7 cannot be loaded with LoRA adapters yet") } (pattern: PaddleOcrVL at line 126).
  4. src/models/step3p5.rs (+ src/models/step3p5_tests.rs): config-gated extensions only. Accept moe_layers_enum as string or int array; add a constructor that builds Step3p5Config from a nested text_config JSON value with the step3p7 defaults from the delta list; add an inputs_embeds forward variant and expose the embedding table to the wrapper. No behavior change for flat step3p5 configs (existing tests must pass untouched).
  5. src/vision/encoders/step3p7.rs: vision config struct + the ViT tower (patchify conv, optional cls token, absolute posemb with bilinear resize, ln_pre/ln_post flags, blocks with fused-qkv attention, 2D rope, LayerScale, quick-gelu MLP). Register in src/vision/encoders/mod.rs.
  6. src/vision/connectors/step3p7.rs: the two stride-2 downsampler convs + vit_large_projector linear (grid reshape, conv, conv, flatten, project). Register in src/vision/connectors/mod.rs.
  7. src/vision/processors/step3p7.rs: the patcher (square pad, 3024 clamp, window/crop/tile math, newline mask) and tensor conversion with the normalization constants above; expose patch counts and the per-image token layout so prompt expansion and the processor cannot drift apart. Register in src/vision/processors/mod.rs.
  8. src/vision/step3p7.rs: Step3p7VlModel wrapper owning encoder, connector, processor, and the Step3p5Model backbone; input_embeddings() runs the base and patch passes, orders features patches-first per image, and scatters into image_token_index positions (helpers in src/vision/merge.rs); implements LanguageModel with forward_with_embeddings (pattern: src/vision/paddleocr_vl.rs). Register pub mod + pub use in src/vision/mod.rs.
  9. src/loading/vlm_step3p7.rs: parse the nested config, resolve image_token_index/eos ids, sanitize weights (next section), build the wrapper. Wire the #[path = "vlm_step3p7.rs"] mod step3p7; + pub(crate) use step3p7::load_step3p7_vl; pair into src/loading/vlm.rs and the ModelType::Step3p7 => Some(load_step3p7_vl(model_path)?) arm into src/loading/mod.rs (near line 187).
  10. src/loaded_model.rs: LoadedModel::Step3p7VL(vision::Step3p7VlModel) variant plus the LanguageModel delegation arm (pattern: PaddleOcrVL at lines 84 and 213).
  11. src/loaded_model_capabilities.rs: VlmRuntimeRef::Step3p7(&vision::Step3p7VlModel) variant and the LoadedModel -> VlmRuntimeRef mapping.
  12. src/multimodal/step3p7_prompt.rs: expand each image placeholder into the <patch_start>/<patch_end>/<patch_newline>/<im_start>/<im_end> block using the processor's patch counts; register in src/multimodal/mod.rs; add the preparation branch in src/multimodal/vlm_runtime.rs (pattern: the VlmRuntimeRef::PaddleOcr branch at line 315) returning PreparedVlmEmbeddings.
  13. src/distributed/tensor_parallel/inference.rs: add Step3p7 to the VLM group of the model-type name match (near line 231); TP is refused for Vlm-kind models earlier, this only keeps the match exhaustive.
  14. tests/step3p7_parity.rs: synthetic parity test (see validation).
  15. docs/supported-models.md: add Step-3.7 with a short description of the base+patch image pipeline.

Weight loading and sanitize

Checkpoints appear with several key prefixes; normalize all of them to the target names in the shape tables:

  • model.language_model.* -> text keys under model.* (the backbone's expected model.layers.{i}... names).
  • model.layers.*, model.embed_tokens.*, model.norm.* -> keep under model.* for the text backbone.
  • model.vision_model.* -> vision_model.*; bare vision keys (conv1.*, ln_pre.*, ln_post.*, transformer.*, vit_downsampler*, positional_embedding, class_embedding) also map to vision_model.*.
  • model.vit_large_projector.* -> vit_large_projector.*; lm_head.* stays top-level.

Vision-specific normalization:

  • transformer.resblocks.{i}.* -> transformer.{i}.* (both spellings occur).
  • attn.in_proj_weight / attn.in_proj_bias (tensor-attribute naming) -> attn.in_proj.weight / attn.in_proj.bias.
  • Conv weight permutations. Checkpoints store conv kernels as (out_ch, in_ch, kH, kW); MLX convolutions consume channels-last (out_ch, kH, kW, in_ch). Permute with axes [0, 2, 3, 1], exactly the transform existing loaders apply (e.g. src/loading/vlm_gemma.rs:113, src/loading/vlm_kimi_vl.rs:229):
    • vision_model.conv1.weight: (1536, 3, 14, 14) -> (1536, 14, 14, 3)
    • vision_model.vit_downsampler1.weight: (3072, 1536, 3, 3) -> (3072, 3, 3, 1536)
    • vision_model.vit_downsampler2.weight: (6144, 3072, 3, 3) -> (6144, 3, 3, 3072)
    • Key the permutation on whether the trailing axis already equals the expected in_ch (3 / 1536 / 3072 respectively) so re-sanitized or pre-converted checkpoints pass through unchanged (idempotent; same guard as src/vision/encoders/paddleocr_vl.rs:129).
  • No permutation for any linear weight: (out_features, in_features) is exactly what UnifiedLinear consumes. In particular attn.in_proj.weight (4608, 1536), vit_large_projector.weight (4096, 6144), and every text projection load as-is.
  • Stacked expert tensors load as-is in (num_experts, out_features, in_features) order (gate/up (288, 1280, 4096), down (288, 4096, 1280)), matching the existing Step3p5SwitchGLU loader.

Text-specific sanitize (mirror the existing Step3p5Model::sanitize_weights in src/models/step3p5.rs, which already does all of this for flat checkpoints):

  • MoE remap when the checkpoint uses the fused naming: .moe.gate_proj. -> .mlp.switch_mlp.gate_proj., .moe.up_proj. -> .mlp.switch_mlp.up_proj., .moe.down_proj. -> .mlp.switch_mlp.down_proj., .moe.gate. -> .mlp.gate.gate., .moe.router_bias -> .mlp.gate.router_bias, .share_expert. -> .mlp.share_expert..
  • Zero-centered norm convention: if any key still matches a remap source (the pre-remap "vanilla" layout), every *.weight whose key contains norm gets +1 added (this includes q_norm/k_norm and the layer norms).
  • Skip any key containing .mtp (multi-token prediction heads) and any model.layers.{i} with i >= num_hidden_layers.
  • Quantized checkpoints: entries in quantization/quantization_config may key on the pre-remap names; apply the same remapping to those maps. The MoE gate linear (mlp.gate.gate) is quantized at group size 64 / 8 bits regardless of the global setting; src/models/step3p5.rs already hardcodes (64, 8) for it.

src/models/sanitize.rs provides the shared entry points (load_text_weights, sanitize_config_json); the step3p7 loader should apply the prefix normalization and conv permutations first, then reuse the existing step3p5 text sanitize so there is exactly one copy of the MoE remap and norm-offset logic.

Validation and acceptance criteria

  • Co-located unit tests: config parsing (nested text_config, moe_layers_enum string and array forms, flipped defaults, eos resolution) in src/models/step3p5_tests.rs; processor math (window decision, crop/tile counts, newline mask, 169/81 token-count identity, normalization constants) co-located with src/vision/processors/step3p7.rs; 2D rope, conv-permutation idempotence, and posemb-interpolation shape checks co-located with the encoder.
  • Synthetic parity test tests/step3p7_parity.rs: build a tiny config with synthetic weights, run the full wrapper (processor -> encoder -> downsamplers -> projector -> scatter -> text forward) end to end, and assert the geometry identities (52x52 -> 13x13 = 169, 36x36 -> 9x9 = 81, patches-first feature order, hard error on token/feature count mismatch), plus fixed-value checks for the gate math and clamped SwiGLU against precomputed expectations (pattern: tests/paddleocr_vl_parity.rs).
  • Existing step3p5 tests pass unchanged (the config extensions must be additive).
  • Real-checkpoint smoke test on a real step3p7 checkpoint: load through the normal detection path and generate through mlxcel's runtime, both mlxcel CLI with --image and the OpenAI-compatible server with image_url content blocks; text-only prompts against the same checkpoint must also work. Verify during this step whether the checkpoint's text_config sets rope_scaling (delta item 5).
  • mlxcel arch lists the new entry; docs/supported-models.md updated.

Known failure mode, and why the real checkpoint is the completion bar: synthetic parity can pass while a real checkpoint breaks on weight-key layout (prefix variants, resblocks, in_proj_weight, fused-MoE naming, conv layout variants), config defaults (omitted keys resolving differently than the checkpoint expects), tokenizer/chat-template details (special-token ids, byte-level decoding), and MoE fusion. Completion means the model is integrated into the working runtime (detection, loader, prompt path, CLI and server) and generates from a real checkpoint, not that standalone modules compile and pass unit tests.

Out of scope

  • LoRA adapters for this model (register the refusal message like other VLMs).
  • Tensor-parallel serving (refused for Vlm-kind models; only the exhaustive-match arm is in scope).
  • Batched/continuous serving: the Step3p5Model backbone reports supports_batching() == false (internal caches); the wrapper inherits that. Lifting it is separate work.
  • Video input.
  • Quantizing checkpoints (loading already-quantized ones is in scope via the existing unified-weight path).
  • The yarn-scaled rope path, unless the real checkpoint's text_config.rope_scaling turns out to be set (checked during validation).

Activity

  1. added
    status:ready
    type:enhancement
    priority:low
    area:models
    on Jul 1, 2026
  2. added
    status:in-progress
    status:review
    and removed
    status:ready
    status:in-progress
    on Jul 13, 2026
  3. added 4 commits that reference this issue on Jul 13, 2026
    a96d6e5
    c090691
    0364702
    049e5c4
  4. added
    status:done
    and removed
    status:review
    on Jul 13, 2026
  5. added a commit that references this issue on Jul 30, 2026
    735a92d
  6. self-assigned this
    on Aug 31, 2026
  7. added a commit that references this issue on Oct 27, 2026
    316aa02
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