Repository navigation
Description
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 withrouter_bias, SwitchGLU experts + shared expert, per-layerrope_thetaandpartial_rotary_factors. It implementsLanguageModelwith internalRefCellcaches andsupports_batching() == false.src/models/detection.rs:215:"step3p5" => Ok(ModelType::Step3p5). Nostep3p7arm anywhere (grep -rn step3p7 src/is empty).src/model_metadata.rs:210:Step3p5is registered askind: Text, directory: ConfigBackedwithdir_loader: models::Step3p5Model::load.- There are no Step files under
src/vision/,src/vision/encoders/,src/vision/connectors/, orsrc/vision/processors/. Step support today is text-only. docs/supported-models.mdlists "Step 3.5" in the text-model families line only.- Canonical VLM port file set exists and is verifiable via the
paddleocr_vlport: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, loadersrc/loading/vlm_paddleocr.rswired intosrc/loading/vlm.rs(#[path]module +pub(crate) use) andsrc/loading/mod.rs:187, runtime variant insrc/loaded_model.rs:84andsrc/loaded_model_capabilities.rs(VlmRuntimeRef::PaddleOcr), preparation branch insrc/multimodal/vlm_runtime.rs:315, parity testtests/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)):
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.- RoPE with per-layer base and
rope_dims = head_dim * partial_rotary_factorrotates only the firstrope_dimsentries of the last axis. - Attention output
(batch, n_heads, seq, head_dim)is transposed back with axes[0, 2, 1, 3]to(batch, seq, n_heads, head_dim). - 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). - Reshape to
(batch, seq, n_heads*head_dim)and applyo_proj.
MoE routing (per MoE layer, x of shape (batch, seq, hidden)):
s = sigmoid(gate(x))computed in float32, shape(batch, seq, num_experts=288).c = s + router_bias(router_bias(num_experts,)broadcasts over axes 0 and 1).I = argtop_k(c, k=moe_top_k)along the expert axis (axis 2, the last axis), shape(batch, seq, top_k=8).w = take_along_axis(s, I, axis=2): weights come from the UNCORRECTED scores, indices from the bias-corrected ones.- If
norm_expert_weight:w = w / (sum(w, axis=2, keepdims) + 1e-20); thenw = w * moe_router_scaling_factor. - Expert outputs are gathered per selected expert into shape
(batch, seq, top_k, hidden); multiply bywexpanded to(batch, seq, top_k, 1)and sum over the top_k axis (axis 2), giving(batch, seq, hidden); addshare_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))forj 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)whererotate_halfreshapes 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)beforeconv1, 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:
- EXIF transpose, convert to RGB.
- Square-pad to
max(w, h)(paste at top-left, black fill). All later math sees a square image. - If the side exceeds 3024, scale down so the max side is 3024.
- Window decision on the (square) size: side <= 728 gives no patches; side > 728 gives window 504. (The general rule is: for
long <= 728, window isshortiflong/short > 1.5else 0; otherwisemin(short, 504)iflong/short > 4else 504. After square paddinglong == short, so only the two effective outcomes occur.) - Base tensor: resize the padded image to 728x728 (bilinear).
- Patch tensors (only when window is 504): per axis with side
dandr = d/504, crop targetd' = difr < 1, else504 * (floor(r) + 1 if r - floor(r) > 0.2 else floor(r)); resize to(d', d'), then tile 504x504 windows at origins504*i, clamping the last origin tod' - 504(windows may overlap). Windows enumerate row-major (all columns of row 0, then row 1, ...). Patchiis followed by a newline marker when(i+1)is a multiple of the per-row window count, except the final patch never gets one. - Normalization for both passes:
x/255, then(x - mean)/stdper 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_valuesandpatch_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:
- Config layout:
src/models/step3p5.rsdeserializes a flatconfig.json(Step3p5Config).step3p7checkpoints nest the same text fields undertext_configand addvision_configplus the top-level keys in the table above. A nested-config constructor is needed; the flat path must keep working. moe_layers_enumencoding:Step3p5ConfigparsesOption<String>(comma-separated) only, and when the key is absent falls back to "all layers except 0" (moe_layer_indices()insrc/models/step3p5.rs).step3p7checkpoints 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 toserde_json::Valuewith a helper); always prefer the explicit config value so the differing fallbacks never matter in practice.- Flipped defaults, only relevant when a checkpoint omits the key:
use_head_wise_attn_gatedefaultstrueinsrc/models/step3p5.rs(default_true) butfalseforstep3p7text stacks, andg_projweights may be entirely absent;moe_router_scaling_factordefaults 3.0 there vs 1.0 here;sliding_windowdefaults 512 there vs unset here (only meaningful whenlayer_typescontainssliding_attention). Gate these defaults on which config shape was parsed. eos_token_idresolution: top-level value (int or list) first, thentext_config.eos_token_id; the flat parser'svec![2]fallback stays last resort.rope_scaling: when set, it applies only to layers whose layer type is listed inyarn_only_types; other layers use plain RoPE.src/models/step3p5.rscurrently parses these fields but always applies plain RoPE (fast_ropewith per-layer base). Knownstep3p5-family checkpoints run withoutrope_scaling; verify the realstep3p7checkpoint'stext_configduring validation and implement the scaled path only if the checkpoint actually sets it.- 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. - Forward entry point:
Step3p5Model::forward_with_cachesembeds tokens internally viaembed_tokens.forward, producing(batch, seq, hidden)from(batch, seq)token ids. The VLM wrapper needs aninputs_embedspath that accepts an already-merged(batch, seq, hidden)tensor, plus access toembed_tokensfor the text rows, following theforward_with_embeddingspattern insrc/vision/paddleocr_vl.rs:184.
Implementation plan
Reuse Step3p5Model as the text backbone; all new files follow the paddleocr_vl layout.
src/models/detection.rs: add"step3p7" => Ok(ModelType::Step3p7)next to the"step3p5"arm (line 215).src/models/mod.rs: addModelType::Step3p7in the Step models group (near line 393), add it toALL_MODEL_TYPES(near line 548), add themlxcel archmetadata arm (near line 715, e.g.("Step-3.7 (ViT + Step-3.5 MoE)", "Step VLM")), and extend the exhaustivenessvariants!list in the test module (near line 947).src/model_metadata.rs: registerStep3p7 => { kind: Vlm, directory: Vlm, weight: None, adapter: Some("Step-3.7 cannot be loaded with LoRA adapters yet") }(pattern:PaddleOcrVLat line 126).src/models/step3p5.rs(+src/models/step3p5_tests.rs): config-gated extensions only. Acceptmoe_layers_enumas string or int array; add a constructor that buildsStep3p5Configfrom a nestedtext_configJSON value with thestep3p7defaults from the delta list; add aninputs_embedsforward variant and expose the embedding table to the wrapper. No behavior change for flatstep3p5configs (existing tests must pass untouched).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 insrc/vision/encoders/mod.rs.src/vision/connectors/step3p7.rs: the two stride-2 downsampler convs +vit_large_projectorlinear (grid reshape, conv, conv, flatten, project). Register insrc/vision/connectors/mod.rs.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 insrc/vision/processors/mod.rs.src/vision/step3p7.rs:Step3p7VlModelwrapper owning encoder, connector, processor, and theStep3p5Modelbackbone;input_embeddings()runs the base and patch passes, orders features patches-first per image, and scatters intoimage_token_indexpositions (helpers insrc/vision/merge.rs); implementsLanguageModelwithforward_with_embeddings(pattern:src/vision/paddleocr_vl.rs). Registerpub mod+pub useinsrc/vision/mod.rs.src/loading/vlm_step3p7.rs: parse the nested config, resolveimage_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 intosrc/loading/vlm.rsand theModelType::Step3p7 => Some(load_step3p7_vl(model_path)?)arm intosrc/loading/mod.rs(near line 187).src/loaded_model.rs:LoadedModel::Step3p7VL(vision::Step3p7VlModel)variant plus theLanguageModeldelegation arm (pattern:PaddleOcrVLat lines 84 and 213).src/loaded_model_capabilities.rs:VlmRuntimeRef::Step3p7(&vision::Step3p7VlModel)variant and theLoadedModel -> VlmRuntimeRefmapping.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 insrc/multimodal/mod.rs; add the preparation branch insrc/multimodal/vlm_runtime.rs(pattern: theVlmRuntimeRef::PaddleOcrbranch at line 315) returningPreparedVlmEmbeddings.src/distributed/tensor_parallel/inference.rs: addStep3p7to the VLM group of the model-type name match (near line 231); TP is refused forVlm-kind models earlier, this only keeps the match exhaustive.tests/step3p7_parity.rs: synthetic parity test (see validation).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 undermodel.*(the backbone's expectedmodel.layers.{i}...names).model.layers.*,model.embed_tokens.*,model.norm.*-> keep undermodel.*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 tovision_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 whatUnifiedLinearconsumes. In particularattn.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 existingStep3p5SwitchGLUloader.
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
*.weightwhose key containsnormgets+1added (this includesq_norm/k_normand the layer norms). - Skip any key containing
.mtp(multi-token prediction heads) and anymodel.layers.{i}withi >= num_hidden_layers. - Quantized checkpoints: entries in
quantization/quantization_configmay 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.rsalready 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_enumstring and array forms, flipped defaults, eos resolution) insrc/models/step3p5_tests.rs; processor math (window decision, crop/tile counts, newline mask, 169/81 token-count identity, normalization constants) co-located withsrc/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
step3p5tests pass unchanged (the config extensions must be additive). - Real-checkpoint smoke test on a real
step3p7checkpoint: load through the normal detection path and generate through mlxcel's runtime, bothmlxcelCLI with--imageand the OpenAI-compatible server withimage_urlcontent blocks; text-only prompts against the same checkpoint must also work. Verify during this step whether the checkpoint'stext_configsetsrope_scaling(delta item 5). -
mlxcel archlists the new entry;docs/supported-models.mdupdated.
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
Step3p5Modelbackbone reportssupports_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_scalingturns out to be set (checked during validation).
Activity
feat(models): port Step-3 (step3p7)
fix(step3p7): treat null top-level eos_token_id as absent
fix(step3p7): bound the square-pad canvas to max_side before allocation
test(step3p7): cover the square-pad oversized-canvas scale-down path
feat(models): port Step-3 (step3p7) (lablup#781)
feat(models): port Step-3 (step3p7) (lablup#781)