Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).

## [Unreleased]

### Fixed

- **DeepSeek-OCR's CLIP encoder layers normalize at eps 1e-5.** They used 1e-6, but the checkpoint's own `deepencoder.py` builds them with `layernorm_epsilon = 1e-5`, and mlx-vlm moved to 1e-5 in Blaizzy/mlx-vlm@c6a0d788. The value is now the `ClipConfig` default, which Unlimited-OCR already used. DeepSeek-OCR 2 (no CLIP stage) and GOT-OCR 2.0 (no CLIP encoder) are unchanged.

## [v0.9.0] - 2026-11-30

### Added
Expand Down
2 changes: 1 addition & 1 deletion docs/supported-models.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ Implemented VLM variants include:
- Granite 4 Vision (`granite4_vision`): IBM's document VLM with multi-depth visual injection. A SigLIP tower feeds eight window-QFormer projectors (a QFormer with self+cross attention per `4x4`/`8x8` window, with deepstack mean-pool and spatial strided-offset query downsamplers) whose packed outputs are added into the residual stream at eight different depths of a Granite 4 hybrid (`granitemoehybrid`) text backbone during prefill, rather than merged once. Reuses the shared AnyRes tiling and the four Granite scalar multipliers. Best for document understanding.
- DeepSeek-OCR (`deepseekocr`): DeepSeek's document-OCR VLM. Each view runs a SAM-style ViT-B (windowed / global attention with a decomposed relative-position bias, a two-conv neck, and a two-stage stride-2 conv compressor) and a CLIP-style ViT-L that ingests the SAM grid as its patch embeddings; the two token sets are concatenated on the channel axis, projected to the decoder width, and laid out as a 2D tile mosaic with learned `image_newline` columns and a trailing `view_separator`. A small DeepSeek MoE decoder (12 layers, 64 routed + 2 shared experts, standard attention, reusing `deepseek`) reads the mosaic. The processor pads a global 1024 view and, for larger images, adds a closest-aspect-ratio grid of 640 tiles. The prompt is built the way `modeling_deepseekocr.py::infer` builds it: the instruction is stripped and follows `<image>\n`, one per image, so `-p "Free OCR."` and the model card's `<image>\nFree OCR.` reach the model as the same ids. A prompt that already writes `<image>` is used as written. DeepSeek-OCR 2 is prompted the same way. Best for plain text, markdown, HTML tables, and grounding boxes.
- DeepSeek-OCR 2 (`deepseekocr_2`): the second-generation document-OCR VLM. It keeps DeepSeek-OCR's SAM-style ViT-B (with the compressor emitting 896 channels) but replaces the CLIP stage with a Qwen2-0.5B-shaped query resampler: the SAM grid is concatenated with a learnable query bank and run through 24 GQA + rotary + SwiGLU layers under a mixed mask (image tokens bidirectional among themselves, queries causal and attending to all image tokens); only the query outputs are projected to the decoder width. There is no channel-concat fusion and no `image_newline` mosaic, so features are flat runs assembled per image as `[tiles, global, view_separator]`. The processor tiles every image with 768 tiles (closest-aspect-ratio grid of 1..6) plus the padded global 1024 view. The same DeepSeek MoE decoder reads the features. Best for plain text, markdown, HTML tables, and grounding boxes.
- Unlimited-OCR (`unlimited-ocr`): baidu's document-OCR VLM (`baidu/Unlimited-OCR`), built on the DeepSeek-OCR stack. The SAM ViT-B + CLIP-L/14-224 encoders, the linear projector, the `image_newline` / `view_separator` mosaic, and the 12-layer DeepSeek MoE decoder (64 routed + 2 shared experts) are the same as DeepSeek-OCR, so the whole vision path and processor are reused; the vision differences are that the CLIP encoder layers normalize at eps 1e-5 (the PyTorch default the released encoder uses) where DeepSeek-OCR's use 1e-6, and that the processor allows up to 32 crops where DeepSeek-OCR allows 9. The prompt uses a built-in template (message texts joined by one space, nothing after the last) in place of the DeepSeek-OCR template the MLX conversion ships, whose trailing space the reference never feeds. The one new piece is the decode cache: attention runs against a per-layer ring sliding KV cache that keeps the full prefill KV (prompt + image tokens) permanently and rotates only the most recent `sliding_window_size` (128) decode tokens, with absolute RoPE positions that keep increasing past the window. A single literal `<image>` covers all pages of a multi-page input. Best for long-document OCR where decode runs well past the window without unbounded KV growth.
- Unlimited-OCR (`unlimited-ocr`): baidu's document-OCR VLM (`baidu/Unlimited-OCR`), built on the DeepSeek-OCR stack. The SAM ViT-B + CLIP-L/14-224 encoders, the linear projector, the `image_newline` / `view_separator` mosaic, and the 12-layer DeepSeek MoE decoder (64 routed + 2 shared experts) are the same as DeepSeek-OCR, so the whole vision path and processor are reused; the vision difference is that the processor allows up to 32 crops where DeepSeek-OCR allows 9. Both CLIP encoders normalize their layers at eps 1e-5 (the PyTorch default the released `deepencoder.py` uses, and mlx-vlm's default since Blaizzy/mlx-vlm@c6a0d788). The prompt uses a built-in template (message texts joined by one space, nothing after the last) in place of the DeepSeek-OCR template the MLX conversion ships, whose trailing space the reference never feeds. The one new piece is the decode cache: attention runs against a per-layer ring sliding KV cache that keeps the full prefill KV (prompt + image tokens) permanently and rotates only the most recent `sliding_window_size` (128) decode tokens, with absolute RoPE positions that keep increasing past the window. A single literal `<image>` covers all pages of a multi-page input. Best for long-document OCR where decode runs well past the window without unbounded KV growth.
- Unlimited-OCR-2 (`baidu/Unlimited-OCR-2`): uses the same vision encoder and model type as v1, but marks each page with `<PAGE>` and allows up to 16 crops per page. Its decoder uses page-relative rotary positions and DASH attention: each token attends to a local window and selected remote image blocks. Multi-page requests are supported at batch size 1; chunked prefill and prompt-cache reuse are not supported.
- DeepSeek-VL2 (`deepseek_vl_v2`): DeepSeek's general vision-language model. Each view runs a SigLIP-style ViT (no CLS token, a `patch_size` Conv2d patch embed folded into a linear, a learned absolute position embedding, fused-qkv full attention, GELU-tanh MLP, and a trailing LayerNorm); the `downsample_mlp_gelu` projector folds each 2x2 patch block into one channel-outermost feature vector and maps it to the decoder width with a two-layer GELU MLP. Features are laid out as a 2D tile mosaic with learned `image_newline` columns and a `view_separator`, ordered `[global, view_separator, local]`. Tiny uses plain multi-head attention in its DeepSeek MoE decoder. Small and base use MLA. The conversation format comes from the checkpoint processor’s `sft_format`. The processor pads a global view and, for at most two images, adds a best-fit grid of local tiles chosen from `candidate_resolutions`; three or more images use a single tile each. Best for image description, grounding, and document understanding.
- ERNIE-4.5 MoE VL (`ernie4_5_moe_vl`): Baidu's vision-language MoE. A DFNRope ViT (linear patch embedding over 588-wide merge-window rows, 2D vision RoPE, `cu_seqlens`-packed attention, quick_gelu MLP) feeds a variable-resolution resampler (2x2 spatial fold, temporal pair fold with single-frame duplication, GELU MLP stacks, RMSNorm) whose rows replace the `<|IMAGE_PLACEHOLDER|>` tokens. The text decoder extends ERNIE-4.5 MoE with modality-split expert banks: separate text and multimodal routers and expert stacks selected per token by token type, with a correction bias that shifts expert selection but never the mixing weights, plus a fused shared-experts MLP. Position encoding is interleaved 3D MRoPE (`[T, H, W]` axes assigned per frequency index, adjacent-pair rotation) that degenerates to traditional RoPE for text. Validated against `mlx-community/ERNIE-4.5-VL-28B-A3B-Thinking-4bit` (28B-A3B; text and resampler 4-bit, vision tower bf16). Best for general image chat and grounded reasoning; the checkpoint is a thinking variant and emits reasoning before the answer.
Expand Down
9 changes: 6 additions & 3 deletions src/loading/vlm_deepseekocr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,9 @@ fn deepseekocr_language_args(
}

/// The CLIP encoder configuration [`load_deepseekocr_vlm`] builds: the
/// DeepSeek-OCR encoder layers normalize at eps 1e-6 (mlx-vlm
/// `deepseekocr/config.py` `VisionConfig.layer_norm_eps`).
/// DeepSeek-OCR encoder layers normalize at eps 1e-5 (mlx-vlm
/// `deepseekocr/config.py` `VisionConfig.layer_norm_eps` since c6a0d788, and
/// the checkpoint's own `deepencoder.py`), which is the [`ClipConfig`] default.
fn deepseekocr_clip_config() -> ClipConfig {
ClipConfig::default()
}
Expand All @@ -153,7 +154,9 @@ fn deepseekocr_clip_config() -> ClipConfig {
/// released Unlimited-OCR encoder layers normalize at the PyTorch default eps
/// 1e-5 (mlx-vlm `unlimited_ocr/config.py`, #3235). Neither
/// `baidu/Unlimited-OCR` nor `mlx-community/Unlimited-OCR-4bit` declares
/// `vision_config.layer_norm_eps`, so it is hardcoded as upstream does.
/// `vision_config.layer_norm_eps`, so it is hardcoded as upstream does. It now
/// equals [`deepseekocr_clip_config`]; it stays explicit because each follows
/// its own upstream `config.py`.
fn unlimited_ocr_clip_config() -> ClipConfig {
ClipConfig {
layer_norm_eps: 1e-5,
Expand Down
16 changes: 11 additions & 5 deletions src/loading/vlm_deepseekocr_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use super::{
deepseekocr_clip_config, deepseekocr_language_args, unlimited_ocr_clip_config,
unlimited_ocr_sliding_window,
};
use crate::vision::encoders::deepseekocr_clip::ClipConfig;
use serde_json::{Value, json};

/// The `family` labels the three loaders in this module pass to
Expand Down Expand Up @@ -246,19 +247,24 @@ fn unlimited_ocr_window_falls_back_and_clamps() {
fn unlimited_ocr_clip_uses_layer_norm_eps_1e5() {
let config = unlimited_ocr_clip_config();
assert_eq!(config.layer_norm_eps, 1e-5);
// Only the eps differs from the DeepSeek-OCR encoder.
// The geometry is the DeepSeek-OCR encoder's.
let base = deepseekocr_clip_config();
assert_eq!(config.hidden_size, base.hidden_size);
assert_eq!(config.num_heads, base.num_heads);
assert_eq!(config.num_layers, base.num_layers);
assert_eq!(config.pos_grid, base.pos_grid);
}

/// DeepSeek-OCR keeps its CLIP encoder layers at eps 1e-6 (mlx-vlm
/// `deepseekocr/config.py`).
/// DeepSeek-OCR's CLIP encoder layers normalize at eps 1e-5: the checkpoint's
/// `deepencoder.py` sets `layernorm_epsilon = 1e-5`, mlx-vlm's
/// `deepseekocr/config.py` defaults to it since c6a0d788
/// (`test_deepseek_ocr_clip_norm_default`), and `config.json` declares none.
/// The `ClipConfig` default carries the same value, so the encoder parity test
/// that builds from it runs what the loader runs.
#[test]
fn deepseekocr_clip_keeps_layer_norm_eps_1e6() {
assert_eq!(deepseekocr_clip_config().layer_norm_eps, 1e-6);
fn deepseekocr_clip_uses_layer_norm_eps_1e5() {
assert_eq!(deepseekocr_clip_config().layer_norm_eps, 1e-5);
assert_eq!(ClipConfig::default().layer_norm_eps, 1e-5);
}

#[test]
Expand Down
11 changes: 8 additions & 3 deletions src/vision/encoders/deepseekocr_clip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,11 @@ impl Default for ClipConfig {
hidden_size: 1024,
num_heads: 16,
num_layers: 24,
layer_norm_eps: 1e-6,
// The released encoder (`deepencoder.py`, `vit_model_cfg`) builds
// its CLIP-L layers with `layernorm_epsilon = 1e-5`, and mlx-vlm's
// `deepseekocr/config.py` defaults to it since c6a0d788. The
// checkpoints declare no eps, so the value is hardcoded.
layer_norm_eps: 1e-5,
pos_grid: 16,
}
}
Expand Down Expand Up @@ -245,8 +249,9 @@ impl ClipEncoder {
class_embedding,
position_embedding,
// `pre_layrnorm` is `nn.LayerNorm(hidden)` in the reference: MLX
// default eps 1e-5, whatever `layer_norm_eps` the encoder layers
// use (1e-6 for DeepSeek-OCR, 1e-5 for Unlimited-OCR).
// default eps 1e-5. It is a separate norm that does not read
// `layer_norm_eps`. The encoder layers use the same 1e-5 for both
// DeepSeek-OCR and Unlimited-OCR.
pre_layrnorm: ln(&format!("{prefix}.pre_layrnorm"), 1e-5)?,
config,
layers,
Expand Down
4 changes: 3 additions & 1 deletion tests/deepseekocr_encoder_parity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,12 +86,14 @@ fn sam_and_clip_encoders_match_reference() {
// mlx-vlm 0.8.1 with mlx-community/DeepSeek-OCR-4bit (4958b6b):
// quick GELU in the reference's 24 CLIP layers gives 0.13067; erf GELU
// on the same SAM output gives 0.14360 and must not pass this check.
// mlx-vlm c6a0d788 moved the CLIP layer-norm eps from 1e-6 to 1e-5
// (`ClipConfig::default()` follows), which gives 0.13060 (SAM 0.04305).
assert!(
(sam_am - 0.04304).abs() < 0.002,
"SAM absmean {sam_am} off reference"
);
assert!(
(clip_am - 0.13067).abs() < 0.005,
(clip_am - 0.13060).abs() < 0.005,
"CLIP absmean {clip_am} off reference"
);
}