Skip to content

feat(models): port DeepSeek-OCR (vision encoder + text decoder OCR) #540

Closed

Description

@inureyes

Summary

Add DeepSeek-OCR support to mlxcel. Checkpoints ship config.json with model_type: "deepseekocr" (verified on mlx-community/DeepSeek-OCR-bf16); mlxcel has no arm for that string in src/models/detection.rs, so loading fails with "Unsupported model type".

DeepSeek-OCR is a document-OCR VLM: a SAM-style windowed ViT-B encoder with a two-stage convolutional compressor feeds a CLIP-style ViT-L encoder in series (the compressor output becomes the second encoder's patch embeddings), the two encoders' token features are concatenated channel-wise, projected by a single linear layer into the decoder width, laid out as a 2D tile mosaic with learned newline and view-separator embeddings, and consumed by a small DeepSeek MoE text decoder (12 layers, 64 routed + 2 shared experts, standard multi-head attention, not MLA). It emits recognized text, markdown, HTML tables, and grounding boxes.

Sibling issue: #542 (DeepSeek-OCR 2, deepseekocr_2) builds directly on the modules added here; design the SAM encoder, processor, and loader glue with that reuse in mind (see the parameterization notes below).

Current state in mlxcel

  • src/models/detection.rs maps "deepseek", "deepseek_v2", "deepseek_v3", "deepseek_v32" (lines ~152-155). No deepseekocr arm.
  • Text decoder: reuse src/models/deepseek.rs (DeepSeekModel). It already implements everything this checkpoint's decoder needs: standard attention with full-head RoPE, softmax top-k routing with routed_scaling_factor, optional shared experts, first_k_dense_replace, moe_layer_freq. Verified against the checkpoint: MoEGate::forward (softmax over the expert axis, greedy top-k) and MoE::forward (weighted sum + shared-expert add) match the checkpoint's routing exactly. Do NOT use src/models/deepseek_v2.rs / deepseek_v3.rs: those are MLA-attention implementations, and this checkpoint sets use_mla: false, qk_nope_head_dim: 0, q_lora_rank: null, kv_lora_rank: null and stores plain q_proj/k_proj/v_proj/o_proj weights.
  • Two gaps in src/models/deepseek.rs for this use:
    1. ModelArgs requires rms_norm_eps and rope_theta (no serde defaults); the checkpoint's language_config omits both. Supply defaults 1e-6 and 10000.0 (serde defaults or loader-side injection).
    2. DeepSeekModel does not override LanguageModel::forward_with_embeddings / embed_tokens (the trait defaults in src/lib/mlxcel-core/src/generate.rs ignore embeddings). VLM prefill needs both.
  • MoE weight stacking already exists: SwitchLinear::from_weights in src/models/switch_layers.rs accepts a pre-stacked ...mlp.switch_mlp.{gate,up,down}_proj.weight tensor and falls back to stacking per-expert ...mlp.experts.{E}.{proj}.weight keys. Both published weight layouts (below) are covered once keys are namespaced correctly.
  • No SAM-style encoder exists under src/vision/encoders/ (nothing has windowed attention with decomposed relative-position bias or a conv compressor). Useful precedents: src/vision/encoders/internvl.rs (conv patch embedding with layout-detecting transpose), src/vision/encoders/youtu_vl_window.rs (windowed-attention bookkeeping split into a testable module), src/vision/encoders/kimi_vl_pos_emb.rs (separable bicubic resampling of a (in_h, in_w, dim) grid, exactly what the SAM and CLIP position embeddings need).
  • No CLIP-style encoder with a class token that accepts externally injected patch embeddings; src/vision/encoders/siglip.rs is the nearest pre-LN layer template.
  • Tiling precedent: src/vision/processors/internvl.rs implements the same closest-aspect-ratio dynamic tile-grid selection this processor uses.
  • Canonical VLM integration file set to mirror (PaddleOCR-VL, itself an OCR VLM): 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 (wired into src/loading/vlm.rs and src/loading/mod.rs), runtime arm in src/multimodal/vlm_runtime.rs + src/loaded_model_capabilities.rs, parity test tests/paddleocr_vl_parity.rs, docs entry in docs/supported-models.md.
  • Feature splicing helper: merge_llava in src/vision/merge.rs scatters image features into placeholder-token positions of the embedded prompt.

Architecture

Conventions used throughout: activation shapes are written channels-last, (batch, height, width, channels) or (batch, tokens, channels); MLX conv2d takes input (B, H, W, C_in) with weight (C_out, kH, kW, C_in); linear weights are stored (out_features, in_features) and applied as x @ W^T + b. Axis numbers below always refer to the shape written immediately before them.

config.json keys (verified on mlx-community/DeepSeek-OCR-bf16)

Root: model_type: "deepseekocr", candidate_resolutions: [[1024, 1024]], tile_tag: "2D", global_view_pos: "head", bos_token_id: 0, eos_token_id: 1; weights are bf16. The text-decoder keys appear twice: nested under language_config and flattened at the root. Parse language_config when present and fall back to the root copy.

language_config (text decoder):

key value note
hidden_size 1280
num_hidden_layers 12
num_attention_heads 10 head_dim = 1280/10 = 128
num_key_value_heads 10 MHA, no GQA
intermediate_size 6848 dense layer 0 only
moe_intermediate_size 896 per routed expert
n_routed_experts 64
num_experts_per_tok 6
n_shared_experts 2 fused as one SwiGLU MLP with intermediate 2*896 = 1792
first_k_dense_replace 1 layer 0 dense, layers 1..11 MoE
moe_layer_freq absent default 1
topk_method "greedy" plain top-k, no correction bias
n_group / topk_group 1 / 1 grouping disabled
routed_scaling_factor absent default 1.0
scoring_func absent default "softmax"
vocab_size 129280
max_position_embeddings 8192
rms_norm_eps absent default 1e-6
rope_theta absent default 10000.0
use_mla false with qk_nope_head_dim: 0, qk_rope_head_dim: 0, v_head_dim: 0, q_lora_rank: null, kv_lora_rank: null: standard attention, ignore the MLA fields
attention_bias absent false; checkpoint has no attention bias tensors
tie_word_embeddings absent false; separate lm_head.weight

vision_config: model_type: "vision", model_name: "deeplip_b_l", image_size: 1024, mlp_ratio: 3.7362 (informational; the actual MLP width comes from the weights, 4096), and a width map with the two towers:

  • width["sam_vit_b"]: layers: 12, width: 768, heads: 12, global_attn_indexes: [2, 5, 8, 11], downsample_channels: [512, 1024]
  • width["clip-l-14-224"]: layers: 24, width: 1024, heads: 16, patch_size: 14, image_size: 224

projector_config: projector_type: "linear", input_dim: 2048, n_embed: 1280.

Processor constants (shipped in processor_config.json): patch_size: 16, downsample_ratio: 4, image_mean: [0.5, 0.5, 0.5], image_std: [0.5, 0.5, 0.5], image_token: "<image>".

Vision stack, stage by stage

Every image view (one global view, plus zero or more tiles) runs through the same SAM -> CLIP -> fuse -> project pipeline. Shapes below show the global view (input 1024x1024) with the tile case (input 640x640) in parentheses.

1. SAM-style encoder (sam_model.*, ViT-B).

  • Patch embedding: conv 16x16, stride 16, 3 -> 768, with bias. (B, 1024, 1024, 3) -> (B, 64, 64, 768) (tiles: (N, 640, 640, 3) -> (N, 40, 40, 768)).
  • Absolute position embedding sam_model.pos_embed, stored (1, 64, 64, 768), added elementwise. When the token grid is not 64x64 (tiles: 40x40), bicubically resample the (64, 64) grid per channel to (40, 40) first (precedent: bicubic_resample in src/vision/encoders/kimi_vl_pos_emb.rs operates on (in_h, in_w, dim)).
  • 12 pre-LN transformer blocks operating on the (B, H, W, 768) layout: LayerNorm(eps 1e-6) -> attention -> residual -> LayerNorm -> MLP(lin1 768->3072, GELU, lin2 3072->768) -> residual. Attention uses a fused qkv linear (2304, 768) with bias, weight rows ordered [q; k; v]; split the projected activations (.., 2304) on their last axis into three 768-wide chunks; 12 heads, head_dim 64; output proj (768, 768) with bias.
  • Window attention: blocks NOT in global_attn_indexes = {2, 5, 8, 11} attend within 14x14 windows. Partition: pad (B, H, W, C) on axes 1 and 2 up to multiples of 14, reshape to (B, H'/14, 14, W'/14, 14, C), transpose axes to (B, H'/14, W'/14, 14, 14, C) (permutation [0, 1, 3, 2, 4, 5]), reshape to (B * nWin, 14, 14, C); attend; invert; crop the padding. Blocks 2, 5, 8, 11 attend over the full grid.
  • Decomposed relative-position bias, added to the attention logits (this formula exists nowhere in-tree). Per block there are two tables rel_pos_h, rel_pos_w of shape (2*S - 1, 64) where S is the attention grid side (14 for windowed blocks -> (27, 64); 64 for global blocks -> (127, 64)). For query grid (q_h, q_w) and key grid (k_h, k_w) (equal here):
    • R_h[i, k] = rel_pos_h[i - k + (S - 1)], a (q_h, k_h, 64) gather; same for width.
    • With queries reshaped to (B*heads, q_h, q_w, 64): rel_h[b, i, j, k_h] = sum_c q[b, i, j, c] * R_h[i, k_h, c] and rel_w[b, i, j, k_w] = sum_c q[b, i, j, c] * R_w[j, k_w, c].
    • Bias added to logits: attn[b, (i*q_w + j), (k_h*k_w_dim + k_w)] += rel_h[b, i, j, k_h] + rel_w[b, i, j, k_w], i.e. reshape rel_h to (B*heads, q_h*q_w, k_h, 1) and rel_w to (B*heads, q_h*q_w, 1, k_w), broadcast-add, reshape to (B*heads, q_h*q_w, k_h*k_w).
    • When the required length 2*max(q_side, k_side) - 1 differs from the stored table length, linearly interpolate the table along axis 0. This fires in the four global blocks for 640 tiles (need 2*40-1 = 79 rows from the stored 127).
  • Neck, operating on the block output (B, 64, 64, 768) (tiles (N, 40, 40, 768)): conv 1x1 768->256 no bias -> LayerNorm over the channel axis (axis 3) -> conv 3x3 pad 1 256->256 no bias -> LayerNorm. Output (B, 64, 64, 256) (tiles (N, 40, 40, 256)).
  • Compressor: net_2 conv 3x3 stride 2 pad 1, 256 -> 512, no bias; net_3 conv 3x3 stride 2 pad 1, 512 -> 1024, no bias. Grid 64 -> 32 -> 16 (tiles 40 -> 20 -> 10). SAM output: (B, 16, 16, 1024) global, (N, 10, 10, 1024) per tile. For feat(models): port DeepSeek-OCR 2 (vision encoder + text decoder OCR (v2)) #542 the only SAM change is net_3's output channels (896), so parameterize that.

2. CLIP-style encoder (vision_model.*, ViT-L body). Consumes the SAM output as its patch embeddings; its own conv patch embedding is bypassed on this path (the tensor still exists in the checkpoint and must be tolerated by the loader).

  • Flatten SAM output axes 1-2: (B, 16, 16, 1024) -> (B, 256, 1024) (tiles (N, 100, 1024)).
  • Prepend the class embedding (1024,) broadcast to (B, 1, 1024), concat on axis 1 -> (B, 257, 1024) (tiles (N, 101, 1024)).
  • Learned position embedding table (257, 1024): row 0 is the CLS position, rows 1..256 form a 16x16 grid. For 257 tokens add directly. For 101 tokens: reshape rows 1..256 to (16, 16, 1024), bicubically resample to (10, 10, 1024), flatten to (100, 1024), concat the CLS row on axis 0, add.
  • pre_layrnorm (the checkpoint key really is spelled pre_layrnorm), then 24 pre-LN layers: LayerNorm(eps 1e-6) -> attention -> residual -> LayerNorm -> MLP(fc1 1024->4096, GELU, fc2 4096->1024) -> residual. Attention: fused qkv_proj (3072, 1024) with bias, weight rows ordered [q; k; v]; split the projected activations (B, tokens, 3072) on axis 2 into three 1024-wide chunks; 16 heads, head_dim 64; out_proj (1024, 1024) with bias; bidirectional (no mask). No final post-norm.
  • Drop the CLS token (slice axis 1 from 1): (B, 256, 1024) (tiles (N, 100, 1024)).

3. Channel fusion. Concatenate on axis 2 (channels): [CLIP tokens (B, 256, 1024), SAM tokens flattened (B, 256, 1024)] -> (B, 256, 2048) (tiles (N, 100, 2048)). CLIP features come first.

4. Projector (projector.layers). Single linear 2048 -> 1280, weight (1280, 2048), bias (1280,). Output (B, 256, 1280) (tiles (N, 100, 1280)).

5. 2D layout with learned separators. Two learned vectors, image_newline (1280,) and view_separator (1280,), are woven in:

  • Global view: (256, 1280) -> reshape (16, 16, 1280) -> concat image_newline broadcast to (16, 1, 1280) on axis 1 -> (16, 17, 1280) -> flatten axes 0-1 -> (272, 1280).
  • Tiles (grid w_tiles x h_tiles): stack per-tile features (n_tiles, 100, 1280) -> reshape (h_tiles, w_tiles, 10, 10, 1280) (axes: tile row, tile col, in-tile row, in-tile col, channels) -> transpose axes [0, 2, 1, 3, 4] -> (h_tiles, 10, w_tiles, 10, 1280) -> reshape (h_tiles*10, w_tiles*10, 1280) -> concat image_newline column on axis 1 -> (h_tiles*10, w_tiles*10 + 1, 1280) -> flatten axes 0-1.
  • Per-image feature sequence, concatenated on axis 0: [tile mosaic rows, global rows, view_separator (1, 1280)] when tiles exist; [global rows, view_separator] otherwise. This ordering defines which feature lands at which placeholder position.

Text decoder

DeepSeek MoE, 12 layers, hidden 1280. Layer 0 dense SwiGLU (intermediate 6848); layers 1..11 MoE: router gate.weight (64, 1280), logits x @ gate.weight^T of shape (tokens, 64), scores = softmax over the expert axis (axis 1 of that shape), top-6 by score, y = sum_e score_e * SwiGLU_e(x) with per-expert intermediate 896, plus a shared SwiGLU MLP (intermediate 1792) added unconditionally. Attention: 10 heads, head_dim 128, q/k/v/o projections (1280, 1280) no bias, RoPE over the full 128 dims, theta 10000, non-traditional layout. RMSNorm eps 1e-6 for input_layernorm, post_attention_layernorm, final model.norm. Untied lm_head (129280, 1280). All of this maps 1:1 onto src/models/deepseek.rs; no new decoder math is needed.

Processor

  • Pixel pipeline per view: scale to [0, 1] (divide by 255), then normalize (x - 0.5) / 0.5 per channel (mean = std = 0.5). Emit channels-last (views, H, W, 3) for the encoders.
  • Global view: pad the image to a square base_size x base_size (default 1024) preserving aspect ratio, padding color = the mean color (grey 127,127,127).
  • Dynamic tiling (default mode): if the image is at most 640x640, no tiles. Otherwise pick the tile grid (w_tiles, h_tiles) with 2 <= w_tiles*h_tiles <= 9 whose aspect ratio w_tiles/h_tiles is closest to the image's width/height (tie broken toward more area coverage), resize the image to (640*w_tiles, 640*h_tiles), and slice non-overlapping 640x640 tiles in row-major order. Same algorithm family as src/vision/processors/internvl.rs.
  • Placeholder expansion: every image contributes one flat run of <image> tokens (id 128815) whose length equals the feature-sequence length from stage 5:
    • global contribution: (16 + 1) * 16 + 1 = 273 (16 = ceil((1024/16)/4) from patch_size 16 and downsample_ratio 4; the per-row +1 matches the newline column; the trailing +1 matches the view separator);
    • tiles add (10*w_tiles + 1) * (10*h_tiles) (10 = ceil((640/16)/4)).
    • Example: an 800x600 image picks grid (3, 2): 273 + (31 * 20) = 893 placeholders.
  • Single-view mode (no tiling, optional processor knob): resize/pad to one square image_size view; placeholders (nq + 1) * nq + 1 with nq = ceil((image_size/16)/4): 512 -> 73, 640 -> 111, 1024 -> 273, 1280 -> 421. The initial port must implement the default dynamic mode and this global-only fallback; exposing the alternative base sizes as options is nice-to-have.
  • Sequence assembly: [bos (id 0)] + tokenized text with each "<image>" occurrence replaced by its placeholder run. Feature vectors are scattered into the placeholder positions in order.

Prompt format

The checkpoint's chat template is a pass-through (it concatenates message contents and appends a space; no role markers are inserted). OCR prompts are raw strings containing the <image> placeholder:

  • <image>\n<|grounding|>Convert the document to markdown.
  • <image>\n<|grounding|>OCR this image.
  • <image>\nFree OCR.
  • <image>\nLocate <|ref|>text<|/ref|> in the image. (output carries <|det|>[[x1, y1, x2, y2]]<|/det|>, coordinates normalized to 0-1000)

Special token ids (from tokenizer.json): bos 0, eos 1, pad 2, <image> 128815, <|ref|> 128816, <|/ref|> 128817, <|det|> 128818, <|/det|> 128819, <|grounding|> 128820, <|User|> 128825, <|Assistant|> 128826. Greedy decoding (temperature 0) is the recommended OCR setting. The <image> id must never be emitted during decode; return it from LanguageModel::output_suppressed_token_ids.

Implementation plan

  1. src/models/detection.rs: add "deepseekocr" => Ok(ModelType::DeepSeekOcrVLM) next to the other deepseek arms. src/models/mod.rs: add the DeepSeekOcrVLM variant to the ModelType enum (~line 266 block), ALL_MODEL_TYPES (~line 412), and metadata() (~line 573); the detection test enumerates mapped strings and asserts ALL_MODEL_TYPES membership, so missing a table fails CI.
  2. src/models/deepseek.rs: serde defaults for rms_norm_eps (1e-6) and rope_theta (10000.0); override embed_tokens and forward_with_embeddings in impl LanguageModel for DeepSeekModel (mirror how other VLM text backbones do it); override output_suppressed_token_ids support via the wrapper if preferred.
  3. src/vision/encoders/deepseekocr_sam.rs (new): patch embed conv, resampled absolute position embedding, 12 blocks with window partition + decomposed rel-pos bias, neck, net_2/net_3 compressor with a parameterized final channel count (1024 here, 896 in feat(models): port DeepSeek-OCR 2 (vision encoder + text decoder OCR (v2)) #542). Keep the pure index bookkeeping (window partition math, rel-pos gathers) in testable helper fns per the youtu_vl_window.rs pattern. Register in src/vision/encoders/mod.rs.
  4. src/vision/encoders/deepseekocr_clip.rs (new): CLS + injected patch embeddings + position-embedding resample + pre_layrnorm + 24 pre-LN layers with fused qkv_proj.
  5. src/vision/connectors/deepseekocr.rs (new): channel concat (axis 2), linear projector, newline column insertion, tile mosaic assembly, view-separator append. Register in src/vision/connectors/mod.rs.
  6. src/vision/processors/deepseekocr.rs (new): normalization, pad-to-square global view, dynamic tile grid (reuse/adapt the closest-aspect-ratio selection style from src/vision/processors/internvl.rs), placeholder counting. Parameterize tile size and grid bounds (640/2..9 here; 768/1..6 in feat(models): port DeepSeek-OCR 2 (vision encoder + text decoder OCR (v2)) #542). Register in src/vision/processors/mod.rs.
  7. src/vision/deepseekocr.rs (new): DeepSeekOcrVlModel { text_model: models::deepseek::DeepSeekModel, sam_encoder, clip_encoder, connector, processor, image_token_id, ... } with an input_embeddings() that runs the vision stack per image and splices features via merge_llava (src/vision/merge.rs). Re-export via src/vision/mod.rs. Mirror src/vision/paddleocr_vl.rs.
  8. src/loading/vlm_deepseekocr.rs (new), wired via a #[path] module include + pub(crate) use in src/loading/vlm.rs and a ModelType::DeepSeekOcrVLM => Some(load_deepseekocr(model_path)?) arm in src/loading/mod.rs (template: the PaddleOcrVL arm at ~line 187). Use read_sanitized_vlm_config / parse_required_vlm_subconfig for language_config with root-level fallback; remap weights as specified below.
  9. src/loaded_model.rs: LoadedModel::DeepSeekOcrVL(vision::DeepSeekOcrVlModel) plus the dispatch macro arms. src/loaded_model_capabilities.rs: a VlmRuntimeRef::DeepSeekOcr variant and the vlm_runtime() mapping.
  10. src/multimodal/deepseekocr_prompt.rs (new): expand each <image> id in the tokenized prompt into the placeholder run computed from the processor's grid decision; add the preparation arm in src/multimodal/vlm_runtime.rs (next to VlmRuntimeRef::PaddleOcr).
  11. tests/deepseekocr_parity.rs (new): see validation below.
  12. docs/supported-models.md: add the entry describing the architecture and OCR prompt usage.

Weight loading and sanitize

Two published on-disk layouts exist for this family and both must load:

  • Layout A (verified: mlx-community/DeepSeek-OCR-bf16, 631 tensors, bf16): keys already namespaced language_model.model.* / language_model.lm_head.weight / sam_model.* / vision_model.* / projector.layers.* / image_newline / view_separator; MoE experts pre-stacked as ...mlp.switch_mlp.{gate,up,down}_proj.weight; conv weights already channels-last (C_out, kH, kW, C_in).
  • Layout B (raw export layout of the same family): everything under a model. prefix (model.layers.*, model.embed_tokens.weight, model.norm.weight, top-level lm_head.weight, model.sam_model.*, model.vision_model.*, model.projector.*, model.image_newline, and the misspelled model.view_seperator); MoE experts per-expert model.layers.{L}.mlp.experts.{E}.{gate,up,down}_proj.weight; conv weights in (C_out, C_in, kH, kW) order.

Key remap (loader-side, like remap_paddleocr_weights in src/loading/vlm_paddleocr.rs):

  • strip the language_model. prefix (layout A) so the text backbone sees the model.layers.* / model.embed_tokens / model.norm / lm_head keys src/models/deepseek.rs expects; layout B text keys already match,
  • strip the leading model. from model.sam_model.*, model.vision_model.*, model.projector.*, model.image_newline (layout B),
  • rename view_seperator -> view_separator (accept both spellings),
  • MoE: nothing to do beyond namespacing; SwitchLinear::from_weights (src/models/switch_layers.rs) consumes the pre-stacked layout-A tensors and stacks layout-B per-expert keys (new leading expert axis) automatically,
  • tolerate vision_model.embeddings.patch_embedding.weight (present but bypassed) and any stray position_ids buffers.

Weight-layout permutations, per family (source = layout B storage, target = what MLX conv2d needs; layout A already ships the target shapes, so gate every permutation on a shape check like the one in src/vision/encoders/internvl.rs, which transposes only when (out_ch >= d1 && out_ch >= d2 && d1 == d2) fails):

family key layout B shape target shape permutation
SAM patch embed sam_model.patch_embed.proj.weight (768, 3, 16, 16) (768, 16, 16, 3) axes [0, 2, 3, 1]
SAM neck sam_model.neck.0.weight (256, 768, 1, 1) (256, 1, 1, 768) [0, 2, 3, 1]
SAM neck sam_model.neck.2.weight (256, 256, 3, 3) (256, 3, 3, 256) [0, 2, 3, 1]
compressor sam_model.net_2.weight (512, 256, 3, 3) (512, 3, 3, 256) [0, 2, 3, 1]
compressor sam_model.net_3.weight (1024, 512, 3, 3) (1024, 3, 3, 512) [0, 2, 3, 1]
CLIP patch embed (bypassed, still loadable) vision_model.embeddings.patch_embedding.weight (1024, 3, 14, 14) (1024, 14, 14, 3) [0, 2, 3, 1]

No permutation needed for: sam_model.pos_embed (1, 64, 64, 768) (stored channels-last in both layouts); rel_pos_h/rel_pos_w (27, 64) windowed / (127, 64) global; neck.1/neck.3 LayerNorm vectors (256,); every linear weight ((out_features, in_features): SAM qkv (2304, 768) rows [q; k; v], CLIP qkv_proj (3072, 1024), projector.layers.weight (1280, 2048), text q/k/v/o (1280, 1280), experts (896, 1280)/(1280, 896) stacked to (64, 896, 1280)/(64, 1280, 896), embed_tokens/lm_head (129280, 1280)); embedding tables (vision_model.embeddings.position_embedding.weight (257, 1024), class_embedding (1024,)); the learned vectors image_newline (1280,), view_separator (1280,).

Validation and acceptance criteria

  1. Co-located unit tests (in the new modules): window partition/unpartition round trip including the padding path; rel-pos gather + axis-0 interpolation against a small closed-form case; bicubic position-embedding resample shape/identity cases; mosaic assembly ordering (tile grid 2x1 with distinguishable per-tile constants); placeholder-count formulas (273 global; (10w+1)*10h tiles; the 800x600 -> 893 example); tile-grid selection for known sizes; processor normalization values.
  2. Synthetic parity test tests/deepseekocr_parity.rs: build the SAM encoder, CLIP encoder, connector, and text decoder from a synthetic WeightMap (both key layouts, exercising the permutation and expert-stacking paths), run an end-to-end forward on a synthetic image + prompt, and assert every intermediate shape from the tables above plus greedy-decode determinism. Follow the structure of tests/paddleocr_vl_parity.rs.
  3. Real-checkpoint smoke test: load mlx-community/DeepSeek-OCR-bf16 through mlxcel's normal detection -> loading -> runtime path and generate through the CLI or server with a document test image and the prompt <image>\n<|grounding|>OCR this image.; the output must contain the text visible in the image. Also verify a small (< 640px) image takes the no-tile path and still generates.
  4. Known failure mode, and why step 3 is the completion bar: synthetic parity can pass while a real checkpoint still breaks on weight-key layout (layout A vs B, the view_seperator spelling, pre-stacked vs per-expert MoE tensors), config defaults (rms_norm_eps/rope_theta absent from language_config), tokenizer/chat-template details (pass-through template, bos 0/eos 1/pad 2, <image> = 128815), and MoE fusion. Real-checkpoint load + generate is required before this issue closes.
  5. Integration, not modules: completion requires the model to work end to end through mlxcel's working runtime (mlxcel CLI generation and the OpenAI-compatible server path used by other VLMs), with the detection arm, loader dispatch, LoadedModel/VlmRuntimeRef arms, prompt expansion, and docs entry all landed. Standalone encoder modules do not close this issue.

Out of scope

  • DeepSeek-OCR 2 (deepseekocr_2): feat(models): port DeepSeek-OCR 2 (vision encoder + text decoder OCR (v2)) #542, which reuses the SAM encoder, processor, text decoder, and glue from this issue and swaps the second encoder stage.
  • Checkpoints of this family shipping model_type: "deepseek_vl_v2" (raw exports reuse the DeepSeek-VL2 family id); mapping that string needs disambiguation against actual DeepSeek-VL2 and is not added here.
  • Grounding-box post-processing (parsing/drawing <|det|> boxes), PDF ingestion, multi-image prompts (single image per prompt is the required scope; the placeholder math generalizes), and quantized-variant validation (bf16 first).
  • Alternative single-view resolution presets (512/640/1280) beyond exposing the processor knob.

Effort: medium-high

Activity

  1. added
    type:enhancement
    status:ready
    priority:low
    area:models
    on Jul 1, 2026
  2. added a commit that references this issue on Jul 4, 2026
    d2842b7
  3. self-assigned this
    on Jul 4, 2026
  4. 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