Skip to content

fix(vision): match DeepSeek-OCR CLIP and SAM encoder numerics - #3456

Merged
inureyes merged 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:fix/3235-deepseek-ocr-encoder-numerics
Nov 27, 2026
Merged

inureyes merged 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:fix/3235-deepseek-ocr-encoder-numerics

Conversation

@Jaeyeong-CHOI

Copy link
Copy Markdown
Contributor

Summary

Closes #3235.

The DeepSeek-OCR vision encoder, which Unlimited-OCR reuses, now computes what the reference computes in the four places the issue lists: quick_gelu in the CLIP MLP, antialiased bicubic for the CLIP position-grid resample (on a float32 copy, cast back to the table dtype), half-pixel sampling for the SAM relative-position resample, and LayerNorm eps 1e-5 in Unlimited-OCR's CLIP encoder layers. Each change is the minimal one the issue asks for, and each has a test that fails on main and fails again when only that change is reverted.

On GB10 CUDA, teacher-forced against mlx-vlm e8035ae3 (which contains Neywa-Labs/mlx-vlm#2603) in float32 on a 1920x1280 page, the logit delta on the reference's own token drops from p50 0.648 / max 2.447 to 0.088 / 0.697 on DeepSeek-OCR-4bit, and from 0.749 / 8.576 to 0.126 / 1.751 on Unlimited-OCR-4bit. On a dense page of alphanumeric codes, Unlimited-OCR on main disagrees with the reference at one decided position (reference gap 2.80) and the fix at none. Every other trace has 0 decided disagreements on both arms, so on those pages the issue's decided-position gate does not separate the arms; see "Teacher-forced traces" and "Verification limits". GOT-OCR 2.0 traces byte-identically before and after.

What changed

Numbered as in the issue's "Required changes".

  1. src/vision/encoders/deepseekocr_clip.rs: ClipLayer::forward applies GeluActivation::Fast.apply (gelu_sigmoid, x * sigmoid(1.702 x)) between fc1 and fc2 instead of mlxcel_core::gelu. GeluActivation's Used by: roster (src/lib/mlxcel-core/src/utils.rs) adds "the DeepSeek-OCR / Unlimited-OCR CLIP MLP (quick_gelu, fix(vision): match DeepSeek-OCR CLIP and SAM encoder numerics #3235)", and row V54 of docs/gelu-call-sites.md records the switch. No local quick_gelu.
  2. Same file, ClipEncoder::abs_pos: the 16x16 grid is cast to float32, resampled with bicubic_resample(.., true), and cast back to the table's dtype before the CLS row is prepended. The forward comment now says "antialiased bicubic". bicubic_resample's doc comment no longer describes the CLIP call as the plain-kernel user.
  3. src/vision/encoders/deepseekocr_sam.rs, get_rel_pos: the source coordinates are max((i + 0.5) * scale - 0.5, 0) in float32 (computed on the host, max_rel_dist entries), with floor, ceil = min(floor + 1, L - 1) and the linear weights unchanged. The function gains a doc comment naming the PyTorch call it reproduces and a Used by: line for DeepSeek-OCR, Unlimited-OCR, DeepSeek-OCR-2 and GOT-OCR 2.0. It is a private fn, so the line is documentation only; check_used_by.py covers pub fn in utils.rs and layers.rs.
  4. src/loading/vlm_deepseekocr.rs: the two loaders take their CLIP configuration from deepseekocr_clip_config() (ClipConfig::default(), eps 1e-6) and unlimited_ocr_clip_config() (ClipConfig { layer_norm_eps: 1e-5, ..ClipConfig::default() }), so the tests can assert what each loader passes. The value is hardcoded, as upstream does: neither config.json of mlx-community/Unlimited-OCR-4bit (rev 945968c0) nor that of baidu/Unlimited-OCR (rev 8249d20b) contains a layer_norm_eps or layernorm key. docs/supported-models.md (Unlimited-OCR entry) and CHANGELOG.md (Unreleased, Fixed) say so.

The pre_layrnorm eps (1e-5) was already right for both families; its comment now says it does not follow layer_norm_eps.

Where this differs from the issue text, or adds to it

  • The issue asks for the two eps tests to "assert the config each loader passes". Neither loader can run in a unit test (they read a checkpoint), so the configuration moved into two small functions the loaders call. To run the eps tests on unmodified main, the reproduction tree is main plus the tests plus the same two functions returning ClipConfig::default(), which is a behaviour-free extraction.
  • get_rel_pos keeps the resampled table in float32. The reference (mlx-vlm and the checkpoints' deepencoder.py) casts the resampled table back to the table dtype (bf16 in these checkpoints). The issue does not ask for that cast, and mlxcel's non-resample branch was already float32, so this PR leaves it alone.
  • Item 2's float32 round trip has no dedicated test: the test grid is float32, so the casts are no-ops there. The test pins the kernel choice (antialiased, and differing from plain by more than 1e-3).

Found while validating, not changed here

  • DeepSeek-OCR's own encoder code uses eps 1e-5 too. deepencoder.py in mlx-community/DeepSeek-OCR-4bit (rev 4958b6b0) is byte-identical to the one in mlx-community/Unlimited-OCR-4bit (rev 945968c0; sha256 0ae2fb6d…ddcf2), and its vit_model_cfg sets layernorm_epsilon = 1e-5 for the CLIP-L that both build. mlx-vlm's deepseekocr/config.py keeps 1e-6, and the issue says DeepSeek-OCR keeps 1e-6, so this PR does too. Whether DeepSeek-OCR should move to 1e-5 is a question for the reference first.
  • Unlimited-OCR preprocessing. mlx-vlm's UnlimitedOCRProcessor allows up to 32 crops (16 with page_layout); mlxcel's shared DeepSeek-OCR processor allows 9. On the 1600x1200 page, mlx-vlm picks a 4x3 grid (1503 image tokens) and mlxcel a 3x2 grid (893), so --mlxcel-prompt refuses that pair. The 1920x1280 and dense pages are 3:2, where both pick 3x2. Separately, mlx-vlm renders the Unlimited-OCR prompt in 897 tokens and mlxcel in 898. In free-running generation both mlxcel arms open the Unlimited-OCR answer with a date line (2014年1月1日, 2018-04-20 15:00:00, …) that the mlx-vlm run does not produce. I did not establish which token differs or whether it causes the date line.
  • mlx-vlm's float32 DeepSeek-OCR forward fails on CUDA. With --float32, mlx 0.32.4's CUDA backend fails the batched SAM forward over six 640x640 crops with cudaMallocAsync(&data, size, stream) failed: out of memory at about 5 GiB of MLX peak memory, with over 100 GiB free (a per-stage wrapper located it in SAMEncoder.__call__ on the (6, 640, 640, 3) batch). The float32 references below therefore run SAM one image at a time (see "Reference arms").

Verification

Spark2: NVIDIA GB10, driver 580.178.04, CUDA 13.0.88, Linux 7.0.0-1019-nvidia aarch64, rustc 1.97.1 (the pinned toolchain), --features cuda, --profile test-fast, MLX_ENABLE_TF32=0 MLXCEL_SDPA_DETERMINISTIC=1. Base 01e6516b73017193d3a4d0489ccf1b7a760c2d66. main has since moved one commit, to f74dd84eb (#3453, Raon-1 mini exports). git merge-tree merges this commit onto it without conflict; nothing was rerun on it. Tested tree 3894d41f30e8601c8d5f5faef9969ff80c35007d, the tree of the commit. The real-checkpoint binaries were built from tree 1a6a0204 (the same tree without the CHANGELOG.md entry). The main arm was built from 1e1b89cf (main plus tests plus the behaviour-free config extraction).

  • cargo fmt --all -- --check
  • cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings
  • python3 scripts/ci/check_used_by.py (used-by: OK, 76 top-level pub fn in 2 shared files, 55 annotated, 628 caller-file references resolved), bash scripts/ci/check_used_by_test.sh (all cases passed), python3 scripts/insert_apache_header.py --check, python3 scripts/ci/check_env_var_docs.py, python3 scripts/ci/check_kernel_dtype_keys.py, python3 scripts/ci/check_cross_repo_refs.py
  • make verify-test-cuda with a private 0700 TMPDIR (22:05 to 22:44): 17,178 passed, 1 failed, 517 ignored over 197 test result lines. The tree was 3894d41f before and after. The one failure is models::deepseek_v32::rope_tests::prefill_and_decode_cache_yarn_rotated_keys_past_the_original_context (cached k_pe at positions 16..24 must be YaRN-rotated (max diff 1.6620973)), the CUDA failure tracked in fix(cuda): MLX CUDA RoPE gives every row of a broadcast input the same rotation, failing make verify-test-cuda on main #3442 (fix in fix(cuda): rotate broadcast RoPE inputs in a dense output #3443). The same test, run alone from a build of unmodified 01e6516b, fails with the same message and the same max diff 1.6620973. The library target has 13,180 tests on main and 13,185 here (the five new tests).

Tests

cargo test --locked --profile test-fast --features cuda -p mlxcel --lib -- <name> --test-threads=1:

Test main (+ tests) fix
vision::encoders::deepseekocr_sam::tests::get_rel_pos_uses_half_pixel_centers FAIL: rel_pos [0][0]: expected 2, got 1.6666666 pass
vision::encoders::deepseekocr_clip::tests::clip_mlp_activation_is_quick_gelu FAIL: expected quick_gelu(1) = 0.84579575, got 0.8413447 pass
vision::encoders::deepseekocr_clip::tests::clip_position_resample_is_antialiased FAIL: entry 0: expected -0.15950315, got -0.38733935 pass
loading::vlm::deepseekocr::tests::unlimited_ocr_clip_uses_layer_norm_eps_1e5 FAIL: left: 1e-6, right: 1e-5 pass
loading::vlm::deepseekocr::tests::deepseekocr_clip_keeps_layer_norm_eps_1e6 pass (guard) pass
  • get_rel_pos_uses_half_pixel_centers: the (5, 1) table [0, 1, 2, 3, 4] with q = k = 2 gives [0][0] = 2, [0][1] = 1/3, [1][0] = 11/3, [1][1] = 2 (tolerance 1e-4), the values in the issue.
  • clip_mlp_activation_is_quick_gelu drives ClipLayer::forward itself: zero attention output projection, layer_norm2 with weight 0 and bias 1, identity fc1 / fc2, so the output is act(1).
  • clip_position_resample_is_antialiased drives ClipEncoder::abs_pos on a dense 16x16 (+ CLS) table at 10x10: the CLS row passes through, the grid equals bicubic_resample(.., true) within 1e-5 and differs from bicubic_resample(.., false) by more than 1e-3.

Mutation, each production change reverted alone with the tests kept (evidence-spark2/mutation/summary.txt):

Reverted Fails Passes
quick_gelu -> mlxcel_core::gelu clip_mlp_activation_is_quick_gelu the other 4
antialias true -> false clip_position_resample_is_antialiased the other 4
half-pixel -> i * scale get_rel_pos_uses_half_pixel_centers the other 4
Unlimited eps 1e-5 -> ClipConfig::default() unlimited_ocr_clip_uses_layer_norm_eps_1e5 the other 4

Related filters on the same binary, single-threaded, main (+ tests) -> fix: deepseekocr 28 passed 4 failed -> 32 passed; clip 60 / 3 failed / 1 ignored -> 63 / 1 ignored; gelu 19 / 1 failed -> 20; unlimited_ocr 6 / 1 failed -> 7; got_ocr 26 -> 26; resample_matrix 9 -> 9; interp 32 -> 32; bicubic 13 / 1 ignored -> 13 / 1 ignored. Every failure on main is one of the four new tests.

Real checkpoints, main against fix

Checkpoint HF revision
mlx-community/DeepSeek-OCR-4bit 4958b6b0d46d7dc3cf27556989dab659996ea426
mlx-community/Unlimited-OCR-4bit 945968c0fd6883390c2ef71f26a3e9955ad379c0
mlx-community/DeepSeek-OCR-2-4bit 378131e9d1a6fb1fa2e130d2e81e46ada0a2c10d
mlx-community/GOT-OCR2_0-4bit 0e28c87720de5d8af67389a0444cf8397524cb61

Pages, rendered with DejaVu fonts: page-1600x1200.png (a report with three paragraphs and a table; six 640 crops for DeepSeek-OCR), page-1920x1280.png (the same content at 3:2), page-dense-1920x1280.png (44 rows of random 8-character codes, lots, weights and bins), page-1024.png (the report at 1024x1024, for GOT-OCR). Prompt Free OCR. (GOT-OCR: OCR: ).

mlxcel generate --image PAGE -p PROMPT -n 160 --temp 0, reply bytes compared:

Model / page main vs fix
DeepSeek-OCR, 1600x1200 identical
DeepSeek-OCR, 1920x1280 identical
DeepSeek-OCR, 1024x1024 differs: the markdown table's padding (`
DeepSeek-OCR, dense differs: main transcribes rows; the fix emits `
Unlimited-OCR, 1600x1200 differs: leading date line and box coordinates ([40, 60, 595, 105] vs [40, 60, 595, 103], …)
Unlimited-OCR, 1920x1280 differs: leading date line and box coordinates
Unlimited-OCR, dense differs: box coordinates only ([19, 24, 390, 47] vs [18, 24, 390, 47], [17, 58, 239, 934] vs [16, 58, 237, 934])
DeepSeek-OCR 2, 1600x1200 and 1920x1280 identical
GOT-OCR 2.0, 1024x1024 identical

The same greedy run in mlx-vlm (mlx_vlm.generate, bf16 and float32) gives:

  • DeepSeek-OCR, dense: | Shipment | Shipment | Shipment | …, a degenerate table in both precisions, like the fix and unlike main. The first generated token is a near-tie in every arm: the float32 reference prefers token 1349 over 369 by 0.20, bf16 ties them at 18.125, the fix picks 369 by 0.125 and main picks 2616 by 0.125. The clean main transcription is therefore not reference behaviour.
  • Unlimited-OCR, dense: [18, 24, 390, 47] and [16, 58, 237, 934], the fix's coordinates.
  • Unlimited-OCR, 1920x1280: title [38, 64, 562, 112], the fix's coordinates (main: [38, 62, 562, 112]).

mlxcel-server (/v1/chat/completions, the page as a data URL, temperature 0, 160 tokens) on the 1600x1200 page: DeepSeek-OCR replies identical main vs fix; Unlimited-OCR replies differ in the same lines as the CLI. Both families reach the changed encoder through the CLI and the server; no new code path.

Teacher-forced traces against mlx-vlm

examples/logit_trace MODEL REPLY 128 1 8 with MLXCEL_TRACE_IMAGE=PAGE MLXCEL_TRACE_IMAGE_PROMPT="Free OCR.", the fix's own reply teacher-forced on both arms, then scripts/mlx_vlm_image_logit_trace.py MODEL PAGE fix.tsv --prompt "Free OCR." --mlxcel-prompt [--float32] and scripts/compare_logit_traces.py REF ARM --decided 2. Prompt ids are identical across the fix arm, the main arm and both references in every row below. Logit delta is on the reference's own top-1 token (p50 / p90 / max).

Model / page Reference Decided disagreements, main -> fix Logit delta, main Logit delta, fix Perplexity vs reference, main -> fix
DeepSeek-OCR, 1920x1280 f32 0/125 -> 0/125 0.648 / 1.472 / 2.447 0.088 / 0.252 / 0.697 +0.278% -> +0.024%
DeepSeek-OCR, 1920x1280 bf16 0/125 -> 0/125 0.625 / 1.375 / 2.750 0.125 / 0.250 / 1.000 +0.194% -> -0.060%
DeepSeek-OCR, 1600x1200 f32 0/125 -> 0/125 0.546 / 1.132 / 1.623 0.110 / 0.343 / 0.835 -0.024% -> +0.128%
DeepSeek-OCR, dense f32 0/123 -> 0/123 0.139 / 0.574 / 1.078 0.085 / 0.199 / 0.532 -0.210% -> -0.107%
DeepSeek-OCR, dense bf16 0/123 -> 0/123 0.125 / 0.625 / 1.125 0.125 / 0.125 / 0.500 -0.446% -> -0.343%
Unlimited-OCR, 1920x1280 f32 0/118 -> 0/118 0.749 / 2.178 / 8.576 0.126 / 0.504 / 1.751 +2.665% -> +0.058%
Unlimited-OCR, 1920x1280 bf16 0/119 -> 0/119 0.750 / 2.500 / 8.000 0.125 / 0.500 / 1.750 +2.307% -> -0.290%
Unlimited-OCR, dense f32 1/117 -> 0/117 0.945 / 4.059 / 7.364 0.233 / 0.833 / 1.770 +1.656% -> -0.279%
Unlimited-OCR, dense bf16 1/117 -> 0/117 0.875 / 3.875 / 8.500 0.250 / 1.000 / 1.750 +1.546% -> -0.386%
DeepSeek-OCR 2, 1920x1280 f32 0/126 -> 0/126 0.107 / 0.351 / 0.824 0.092 / 0.368 / 0.568 +0.070% -> -0.089%
DeepSeek-OCR 2, 1600x1200 f32 (stock, batched) 0/127 -> 0/127 0.101 / 0.328 / 0.703 0.078 / 0.208 / 0.562 -0.018% -> +0.034%

The decided disagreement on the Unlimited-OCR dense page is position 118: the reference prefers token 52 over 125484 by 2.80 (float32), the fix by 3.0, and main picks 125484 by 0.75. Of the other top-1 disagreements, all at undecided positions, main has 4 and the fix 1 on that page against float32.

DeepSeek-OCR 2 shares only the SAM tower, so only item 3 reaches it; both arms are close there. Unlimited-OCR moves the most because it has all four changes, eps included.

GOT-OCR 2.0 (page-1024.png, OCR: , 287 prompt tokens): the main and fix trace rows are byte-identical. The SAM grid is 64x64 there, so the resample branch is never reached.

Reference arms

  • mlx-vlm e8035ae3b9740d5e3fc6cb0de4894132d60c8682 (2026-11-24, contains Fix Unlimited-OCR FP32 fusion and chunked prefill reference retention Neywa-Labs/mlx-vlm#2603), mlx 0.32.4 with the mlx-cuda-13 wheel, on the GB10's CUDA device. On a non-Metal host mlx-vlm's bicubic_interpolate takes its pure-MLX path (_bicubic_interpolate_mlx), so that is the antialiased resample the reference ran here.
  • "f32" is --float32 with mlx-vlm's DeepSeek-OCR SAMEncoder applied one image at a time (a wrapper around the stock script, not part of this PR), because the batched float32 SAM fails as described above. Checking that wrapper in bf16, where the batched forward works, against the stock batched run on the 1600x1200 page: 0 top-1 disagreements, logit delta p50 0 / p90 0.25 / max 0.5 (bf16 rounding of a different launch shape). That is the noise floor of the f32 rows.
  • "bf16" is the stock script and stock batched forward in the checkpoint's own dtype.
  • mlx-vlm's tokenizer setup prints six lines to stdout, which compare_logit_traces.py cannot parse. They were filtered out (grep -E '^(#|[0-9]+\t)'); the raw files are kept.

Verification limits

  • The decided-position gate separates the arms only on the Unlimited-OCR dense page, by one position. On the clean pages, every arm agrees with the reference at every decided position, before and after. The improvement shows in the logit deltas and perplexities, not in the gate the issue names.
  • No float32 reference ran on unmodified mlx-vlm: the batched SAM forward fails in float32 on this host, so those rows depend on the per-image wrapper. A CPU float32 run was tried and stopped after 7.7 minutes on one core (watch.log).
  • Metal and ROCm not run; the issue's commands (--features metal,accelerate) were run here with --features cuda.
  • One page per layout and one prompt; the pages are synthetic renders, not scans.
  • No run with a 1280 base view (base_size 1280, 20x20 CLIP grid); mlxcel's processor always uses 1024 + 640.
  • tests/deepseekocr_encoder_parity.rs needs models/deepseek-ocr-4bit in the repository and was skipped, as on every host without it.

The DeepSeek-OCR vision encoder, shared with Unlimited-OCR, diverged from
the reference (the checkpoints' deepencoder.py and mlx-vlm after
Neywa-Labs/mlx-vlm#2603) in four places:

- The CLIP MLP applied erf GELU; the reference applies quick_gelu,
  x * sigmoid(1.702 x). It now goes through GeluActivation::Fast.
- The CLIP position grid was resized with plain bicubic; the reference
  resizes a float32 copy with antialiased bicubic and casts back to the
  table dtype. abs_pos now does the same through bicubic_resample(.., true).
- get_rel_pos resampled the SAM decomposed relative-position tables at
  i * scale; PyTorch F.interpolate(mode="linear", align_corners=False)
  samples at max((i + 0.5) * scale - 0.5, 0). The shared SAM tower serves
  DeepSeek-OCR, Unlimited-OCR, DeepSeek-OCR 2 and GOT-OCR 2.0; only a SAM
  grid other than 64x64 reaches the resample branch, which GOT-OCR's fixed
  1024 canvas never does.
- Unlimited-OCR's CLIP encoder layers normalized at eps 1e-6; its released
  encoder uses 1e-5. DeepSeek-OCR keeps 1e-6. Neither Unlimited-OCR
  checkpoint declares vision_config.layer_norm_eps, so the loader
  hardcodes it as upstream does.

The loaders' CLIP configurations move into deepseekocr_clip_config() and
unlimited_ocr_clip_config() so the tests can assert them. GeluActivation's
Used by roster and docs/gelu-call-sites.md (V54) record the new quick_gelu
site.

Five tests: get_rel_pos_uses_half_pixel_centers,
clip_mlp_activation_is_quick_gelu, clip_position_resample_is_antialiased,
unlimited_ocr_clip_uses_layer_norm_eps_1e5 and
deepseekocr_clip_keeps_layer_norm_eps_1e6. The first four fail on main and
each fails again when only its own production change is reverted.

On GB10 CUDA, against mlx-vlm e8035ae3 in float32 on a 1920x1280 page
(six 640 crops), the logit delta on the reference's own token drops from
p50 0.65 / max 2.45 to 0.09 / 0.70 on DeepSeek-OCR-4bit and from
0.75 / 8.58 to 0.13 / 1.75 on Unlimited-OCR-4bit. GOT-OCR2_0-4bit traces
byte-identically before and after.

Closes lablup#3235
@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:medium Medium priority area:models Model architectures, weights, loading, metadata modelsize:small 4-bit checkpoint <= 10GB; fast iteration, safe for smoke tests modeltype:vlm Vision-language model arch:moe Sparse mixture-of-experts decoder labels Nov 27, 2026
@inureyes

Copy link
Copy Markdown
Member

Hardening review

Target PR: #3456. Linked issue: #3235.

Findings

No changes needed; nothing was pushed.

Each of the four numeric changes was checked against mlx-vlm 466069f5 (references/mlx-vlm, which contains Neywa-Labs/mlx-vlm#2603):

  • CLIP MLP activation: deepseekocr/vision.py MLP.activation_fn = quick_gelu (x * sigmoid(1.702 x)); GeluActivation::Fast is the same formula. Unlimited-OCR imports the same VisionModel, so one site covers both families. The dense and quantized fc1/fc2 paths share ClipLayer::forward, so the change reaches both.
  • CLIP position resample: the reference casts the grid to float32, calls bicubic_interpolate(.., antialias=True) and casts back to the table dtype; the PR does the same. The CLS row passes through in both.
  • SAM get_rel_pos: the reference samples at max((i + 0.5) * scale - 0.5, 0) in float32 with ceil = min(floor + 1, L - 1); the PR matches. DeepSeek-OCR-2 imports deepseekocr.sam.SAMEncoder upstream, so it receives the same fix there too. The host-side index vector has 2 * max(q, k) - 1 entries, bounded by the fixed SAM grid, so request input cannot inflate it.
  • LayerNorm eps: deepseekocr/config.py keeps 1e-6, unlimited_ocr/config.py sets 1e-5; the loaders now pass exactly those. pre_layrnorm stays at 1e-5 in both, as in the reference.
  • Attention scaling, dtype promotion around the position add, and the non-resample get_rel_pos branch are unchanged and still match.
  • docs/gelu-call-sites.md V54 records the switch in the file's **#N:** now ... convention, and the GeluActivation Used by: roster names the new caller; check_used_by.py passes.

Security: no new request-controlled sizes or allocations. Performance: two extra astype ops on a 16x16xhidden table per tile batch and a host Vec<f32> of at most a few hundred entries per global-attention block; no extra evals or host round-trips on the decode path.

Validation (Mac Studio M3 Ultra, Metal)

Remote CI was cancelled by maintainer decision (none was running for this head); the merge relies on the local checks below.

  • cargo fmt --all -- --check: pass
  • python3 scripts/ci/check_used_by.py: used-by: OK, 76 top-level pub fn in 2 shared files, 55 annotated
  • cargo clippy -p mlxcel -p mlxcel-core --all-targets --features metal,accelerate -- -D warnings: pass
  • cargo test -p mlxcel --lib --profile test-fast --features metal,accelerate -- <filter> --test-threads=1 (RUST_MIN_STACK=16777216): deepseekocr 32 passed, clip_ 41 passed, gelu 20 passed, unlimited_ocr 7 passed, got_ocr 26 passed, bicubic 13 passed / 1 ignored. All five new tests pass on Metal.
  • No DeepSeek-OCR, Unlimited-OCR or GOT-OCR checkpoint is present on this host, so the real-checkpoint and teacher-forced results in the PR body (GB10 CUDA) were not reproduced here.

@inureyes
inureyes merged commit fcddafa into lablup:main Nov 27, 2026
33 checks passed
inureyes added a commit to Jaeyeong-CHOI/mlxcel that referenced this pull request Nov 27, 2026
The Unlimited-OCR entry in docs/supported-models.md said the DeepSeek-OCR processor is reused unchanged, which stopped being true once the crop limit and prompt template diverged. The entry now names the 32-crop limit (16 for `dash` checkpoints) and the built-in template, and CHANGELOG.md gains the Unreleased / Fixed entry the PR did not have. The PR body left this line for whichever of lablup#3456 and this PR merged second.

Refs lablup#3472, Refs lablup#3473
inureyes added a commit that referenced this pull request Nov 27, 2026
…3473)

* fix(vision): match the Unlimited-OCR processor crop limit and prompt

Unlimited-OCR reused DeepSeek-OCR's processor and, on the MLX conversion,
DeepSeek-OCR's chat template. Both differ from the Unlimited-OCR reference
(mlx-vlm's UnlimitedOCRProcessor and baidu/Unlimited-OCR):

- The crop grid was capped at DeepSeek-OCR's 9 tiles. The reference allows
  32 (16 for an Unlimited-OCR-2 config whose
  sparse_attention_config.training_stage is "dash", mlx-vlm's page_layout).
  A 1600x1200 page was cut 3x2 (893 image tokens) instead of 4x3 (1503),
  and a 1000x3000 page 1x3 (603) instead of 2x6 (1533).
  DeepSeekOcrProcessor::unlimited_ocr() is the V1 preset with that limit,
  and load_unlimited_ocr_vlm uses it.
- mlx-community/Unlimited-OCR-4bit ships DeepSeek-OCR's chat_template.jinja,
  which prints a space after every message, so the prompt ended in token
  223 (' ') that the reference never feeds: 898 tokens where mlx-vlm has 897
  on a 1920x1280 page. The model then opened its answer with an invented
  date line ("2014-10-20 15:00:00"); mlx-vlm given the same trailing space
  does the same. mlx-vlm removed this suffix from its own template in
  Neywa-Labs/mlx-vlm#2169. Unlimited-OCR now renders a built-in template
  (mlx-vlm's default_chat_template: message texts joined by one space,
  nothing after the last, typed content as its text parts) that replaces the
  shipped one, through the builtin_template_overrides_checkpoint path
  Nemotron-Parse uses.

DeepSeek-OCR keeps its 9-tile limit and its shipped template.

Six tests: unlimited_ocr_crops_up_to_32_tiles,
unlimited_ocr_2_crops_up_to_16_tiles,
unlimited_ocr_replaces_the_shipped_deepseek_ocr_template and
unlimited_ocr_builtin_joins_messages_with_one_space fail before this change;
deepseekocr_keeps_9_tiles and deepseek_ocr_keeps_its_shipped_template pin
DeepSeek-OCR.

On GB10 CUDA with Unlimited-OCR-4bit, the prompt ids now equal mlx-vlm
e8035ae3's on 1600x1200, 1000x3000 and 1920x1280 pages (1507, 1537, 897
tokens), the date line is gone, and a teacher-forced trace against the
float32 reference has no disagreement at a decided position on any of the
three (main: one each, the first token, reference gap 12.9 to 19.7).
DeepSeek-OCR-4bit output and traces are byte-identical before and after.

* docs: record the Unlimited-OCR crop limit and template

The Unlimited-OCR entry in docs/supported-models.md said the DeepSeek-OCR processor is reused unchanged, which stopped being true once the crop limit and prompt template diverged. The entry now names the 32-crop limit (16 for `dash` checkpoints) and the built-in template, and CHANGELOG.md gains the Unreleased / Fixed entry the PR did not have. The PR body left this line for whichever of #3456 and this PR merged second.

Refs #3472, Refs #3473

---------

Co-authored-by: Jeongkyu Shin <[email protected]>
inureyes added a commit to Jaeyeong-CHOI/mlxcel that referenced this pull request Nov 27, 2026
lablup#3456 moved the DeepSeek-OCR CLIP MLP activation from line 100 to line 106 of `deepseekocr_clip.rs`. This PR refreshes the line references of `docs/gelu-call-sites.md` row V42, so V54 is brought up to date in the same pass to keep the inventory consistent with the code after both land.

Refs lablup#3236, Refs lablup#3460
inureyes added a commit that referenced this pull request Nov 27, 2026
…3460)

* fix(vision): RF-DETR, Muse Glimmer and Mage-VL-Cowork parity fixes

Four vision-side fixes mlx-vlm landed for families mlxcel already ships.

- RF-DETR: the projector's ConvX LayerNorms (every C2f cv1, cv2 and
  bottleneck conv, stored as `bn`) and the final projector norm load at
  eps 1e-6, rfdetr's channel LayerNorm default, instead of nn.LayerNorm's
  1e-5 (Neywa-Labs/mlx-vlm#2709). Segmentation mask logits are upsampled with
  resize_bilinear_nhwc(.., align_corners false, no antialias) and kept at
  `> 0`, as rfdetr's PostProcess does, instead of bicubic
  (Neywa-Labs/mlx-vlm#2713). The other RF-DETR norms already matched and are
  unchanged.
- Muse Glimmer: the reference samples the learned position table with
  meshgrid(pos_h, pos_w, indexing="xy"), so height and width swap roles in
  bilinear_indices_and_weights (Neywa-Labs/mlx-vlm#2746). The flattened order
  changes with them, so every non-square grid gets different embeddings;
  square grids are unchanged. The vision RoPE is not touched.
- Mage-VL-Cowork: microsoft/Mage-VL-Cowork declares
  model_type "llava_onevision2" and stores the tower under bare `visual.*`.
  Detection and the registry aliases map it to Mage-VL, and
  remap_mage_vl_weight_key rewrites `visual.` to `vision_tower.`
  (Neywa-Labs/mlx-vlm#2636). Its preprocessor_config.json has the same
  pixel bounds and normalization keys as Mage-VL's. Its config states
  tie_word_embeddings nowhere, and its lm_head differs from embed_tokens
  (max |diff| 0.177). Transformers' Qwen3 config and mlx-vlm's Mage-VL
  config default to untied, the shared Qwen3 args to tied, so
  mage_vl_text_config now fills in the top-level flag or false. Without
  this the loaded model decoded through the embedding matrix.
- Mage ViT: layernorm_pre, layer_norm1, layer_norm2 and the merger's ln_q
  go through layer_norm_f32 (f32 input, weight and bias, one rounding back
  to the activation dtype), and the MLP and merger GELUs through gelu_f32
  (f32 upcast, one rounding), as upstream's tower does since ae763da4. The
  weights stay in their loaded dtype. The shared kernel in f16 or bf16
  rounds the normalized value before the affine. The bridge GELU widens a
  half input through its f32 constants, but the CUDA build promotes bf16
  with f32 to bf16, so on CUDA a bf16 activation ran the whole GELU in bf16.

Tests: projector eps and the bilinear mask path for RF-DETR, the xy
position-table order and an unchanged square grid for Muse Glimmer, Cowork
detection, key remap and the untied default, and Mage LayerNorm/GELU
rounding against an f32 reference in f16 and bf16. The mask test uses [[-1, 3.2], [3.2, -1]]
rather than [[-1, 1], [1, -1]], which thresholds to the same plane under
both resizes.

Closes #3236

* docs: point the V54 GELU row at the moved CLIP call site

#3456 moved the DeepSeek-OCR CLIP MLP activation from line 100 to line 106 of `deepseekocr_clip.rs`. This PR refreshes the line references of `docs/gelu-call-sites.md` row V42, so V54 is brought up to date in the same pass to keep the inventory consistent with the code after both land.

Refs #3236, Refs #3460

---------

Co-authored-by: Jeongkyu Shin <[email protected]>
inureyes pushed a commit that referenced this pull request Nov 30, 2026
…3578)

The CLIP MLP has used mlx-vlm's quick GELU since #3456, but the parity test still expected the absmean of the older erf GELU (0.14356), so it failed on GB10. Refresh the target to 0.13067, reproduced independently with mlx-vlm 0.8.1 on the same checkpoint revision. The erf variant gives 0.14360 and stays outside the unchanged 0.005 tolerance.

Replace the test's pointer to a missing scratchpad script with `scripts/deepseekocr_encoder_reference.py`. The script loads only the model, so it does not depend on processor resolution. Resolve the checkpoint through `tests/common` so `MLXCEL_REQUIRE_MODELS=1` fails instead of skipping.

Validated on GB10 CUDA with the real checkpoint (SAM 0.04302, CLIP 0.13064). Metal remains unverified.

Refs #3563
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

arch:moe Sparse mixture-of-experts decoder area:models Model architectures, weights, loading, metadata modelsize:small 4-bit checkpoint <= 10GB; fast iteration, safe for smoke tests modeltype:vlm Vision-language model priority:medium Medium priority status:review Under review type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(vision): match DeepSeek-OCR CLIP and SAM encoder numerics

2 participants