Skip to content

fix(vision): build the DeepSeek-OCR prompt as the reference does - #3482

Merged
inureyes merged 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:fix/deepseek-ocr-prompt
Nov 28, 2026
Merged

inureyes merged 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:fix/deepseek-ocr-prompt

Conversation

@Jaeyeong-CHOI

Copy link
Copy Markdown
Contributor

Summary

Closes #3481

DeepSeek-OCR and DeepSeek-OCR 2 read a prompt their reference never builds: the image run sat directly after BOS with no \n behind it, and the prompt ended in the space the shipped chat template prints after every message. For Free OCR. on a 1920x1280 page:

ids (128815 = <image>)
deepseek-ai/DeepSeek-OCR infer() with <image>\nFree OCR., and mlx-vlm e8035ae3 with Free OCR. 0, [128815 x 893], 201 '\n', 21431 'Free', 126041 ' OCR', 16 '.'
mlxcel main 0, [128815 x 893], 21431, 126041, 16, 223 ' '
this PR 0, [128815 x 893], 201, 21431, 126041, 16

The prompt for the two families is now built in src/multimodal/deepseekocr_prompt.rs the way upstream's infer() builds it: strip the rendered text, put <image>\n in front when the text names no <image> itself, split on <image>, tokenize the pieces without special tokens, BOS first. Unlimited-OCR, GOT-OCR and DeepSeek-VL2 are untouched and byte-identical.

On GB10 CUDA with mlx-community/DeepSeek-OCR-4bit and mlx-community/DeepSeek-OCR-2-4bit:

  • The prompt ids equal mlx-vlm e8035ae3's in all nine teacher-forced traces (five pages with Free OCR. and two with the document prompt on DeepSeek-OCR, two pages on DeepSeek-OCR 2).
  • With the model card's document prompt, <|grounding|>Convert the document to markdown., main returns 4.4.4.4... for a 1600x1200 page and 21 21 21... for a dense table, and drops the title block's <|ref|>...<|det|> box on the other three pages (every box on one of them). With this PR all five replies have the reference's text and boxes, the coordinates within 2 of the float32 reference's.
  • With Free OCR. the 160-token reply is byte-identical to the float32 reference's on all five DeepSeek-OCR pages and all three DeepSeek-OCR 2 pages. main transcribes nearly the same text but opens every reply with a space, and on four of the eight it changes or drops the heading marks ( **Northern Network: Q3 Operations** where the reference writes ## **Northern Network: Q3 Operations**).
  • Teacher-forced against the float32 reference over the reference's own reply: no disagreement at a decided position in any of the nine traces (main: one in five of them), perplexity within 0.3% of the reference (main: 2.6% to 11.9% higher), largest logit delta on the reference's choice 0.55 to 1.79 (main: 1.42 to 9.89).
  • mlx-vlm given main's prompt ids scores like main (perplexity within 0.3% of main's, no decided disagreement), so the gap is the prompt and not the port.

One page does not improve: on the dense table page Free OCR. makes the reference itself loop (| Shipment | Shipment | ...), and this PR reproduces that loop byte for byte. See "Verification limits".

What changed

  • src/multimodal/deepseekocr_prompt.rs
    • deepseekocr_prompt_text(prompt, num_images): the text upstream tokenizes. The rendered prompt is stripped (upstream's format_messages strips the message and the assembled prompt). If it contains no <image>, one <image>\n per image goes in front, which is mlx-vlm's MessageFormat.IMAGE_TOKEN_NEWLINE for deepseekocr / deepseekocr_2 and the shape of every prompt on the two model cards. If it does contain <image>, it is used as written, so <image>\nFree OCR. is not prefixed a second time.
    • prepare_deepseekocr_prompt_tokens(prompt_tokens, prompt, counts, image_token_id, encode): splits that text on <image>, tokenizes each piece with add_special = false, expands marker i to counts[i] placeholder ids and puts DEEPSEEKOCR_BOS_TOKEN_ID (0, upstream's literal bos_id = 0) first. It replaces prompt_tokens on success. When the text's own <image> count does not match the number of images it returns None and leaves the tokens alone, which is what insert_deepseekocr_image_tokens did for that case.
    • insert_deepseekocr_image_tokens and insert_unlimited_ocr_image_tokens are unchanged; HunyuanVL and Unlimited-OCR still call them.
  • src/multimodal/vlm_runtime.rs: the VlmRuntimeRef::DeepSeekOcr and VlmRuntimeRef::DeepSeekOcr2 arms of prepare_vlm_embeddings_with_cache call the new builder with the rendered prompt and the encode closure, like the GOT-OCR and FastVLM arms do. mlxcel generate (server::local_media::prepare_local_vlm_embeddings), mlxcel-server (server::model_worker::prepare_request_vlm_embeddings) and examples/logit_trace all reach this function, so the three build the same prompt.
  • docs/supported-models.md: one sentence in the DeepSeek-OCR entry on how the prompt is built.

The checkpoint's chat template is not replaced. It still renders Free OCR. ; the builder strips it. So #3473's deepseek_ocr_keeps_its_shipped_template stays true, and nothing in src/server/chat_template.rs changes.

Choices that differ from mlx-vlm

Upstream is the reference where the two disagree:

  • A prompt that already contains <image>. Upstream takes it as written. mlx-vlm prefixes another <image>\n and then rejects the request (The number of image tokens in the prompt does not match the number of images: 2 != 1). Here -p $'<image>\nFree OCR.' and -p "Free OCR." give the same ids, and <image>Free OCR. (no newline) gets none, as upstream would give it.
  • Whitespace around the instruction. Upstream strips it. mlx-vlm keeps a trailing newline (Free OCR.\n ends in 603 '.\n' there, because the id its processor drops is the template's space) and a leading one. Here Free OCR.\n, Free OCR. and Free OCR. all become the ids of Free OCR..
  • Several messages. The shipped template joins them with its space; that space stays between messages and only the leading and trailing whitespace of the whole render is stripped. Upstream's infer() only ever builds one user message.

Not changed:

  • Text-only requests (no image): the prompt keeps the template's trailing space. mlx-vlm renders the same space there (21431, 126041, 16, 223); upstream would strip it. The image-less path does not go through the prompt builder.
  • Unlimited-OCR: one <image> for all pages and no newline (mlx-vlm SINGLE_IMAGE_TOKEN), which is where the run already goes. Its trailing space was fixed by fix(vision): match the Unlimited-OCR processor crop limit and prompt #3473.
  • GOT-OCR 2.0: its own conversation from modeling_GOT.py::chat (got_ocr_prompt.rs).
  • DeepSeek-VL2: a different prompt and a different problem, described in the issue's "Related" section.
  • CHANGELOG.md: no entry yet, since the issue number does not exist until the issue is filed.

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 92d502ec0b8bd6f59e44788d57126ae3226d0ada. Commit tree ec2c9bd60edec179fda74d489cad7eb362257459, the tree the unit tests, the binaries, clippy and the test gate ran on.

main moved twice while this was being verified (521ba0f71 -> 2b34a2f7a -> 92d502ec0), and the change was rebased and rerun each time. The numbers below are from the last base unless a line says otherwise; the two earlier runs are in "Earlier bases". main has since moved once more, to ef0076b96 (#3462). git merge-tree --write-tree of this commit with it has no conflict; nothing was rerun there.

  • cargo fmt --all -- --check

  • cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings

  • python3 scripts/ci/check_used_by.py (used-by: OK, 78 top-level pub fn in 2 shared files, 57 annotated, 636 caller-file references resolved, 3165 Rust files scanned), bash scripts/ci/check_used_by_test.sh (all used-by checker 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 (no bare 3+-digit '#NNN' added). The two used-by scripts and the cross-repo check also pass on the macOS worktree of the commit.

  • The eight new tests (table below) and the related filters.

  • make verify-test-cuda with a private 0700 TMPDIR (13:40 to 14:07): 17,383 passed, 5 failed, 517 ignored over 199 test result lines, tree ec2c9bd6 before and after. A memory guard (stop the test binary under 25 GiB available) did not trip; the lowest available memory was 63 GiB. The five failures are lib tests in Raon code this PR does not touch. Each, run alone with --exact, fails with the same message on unmodified 92d502ec0 and on this commit:

    models::deepseek_v32::rope_tests::prefill_and_decode_cache_yarn_rotated_keys_past_the_original_context (fix(cuda): rotate broadcast RoPE inputs in a dense output #3443) and the two mlxcel-xla plamo2 golden tests (fix(xla): refresh the plamo2 prefill goldens for the shifted-add scan #3471) pass on this base.
    Before a quiet enough window for the gate came up, the same test set was also run as thirteen processes (the other workspace packages; mlxcel's bins and its 170 integration tests without required-features; doc tests; the 13,345 lib tests in ten --exact chunks). It gave the same totals and the same five failures.

  • fix(vision): match the Unlimited-OCR processor crop limit and prompt #3473 and fix(vision): match DeepSeek-OCR CLIP and SAM encoder numerics #3456 merged while this was in progress and are both in the base. Before that, git merge-tree --write-tree against each (cbb0ec529, e287f903e) was clean.

Tests

cargo test --locked --profile test-fast --features cuda -p mlxcel --lib -- <name> --exact --test-threads=1, all in multimodal::deepseekocr_prompt::tests. The "main" column is main plus the new tests, with the two new functions stubbed to main's behaviour so the tests compile: deepseekocr_prompt_text returns the text unchanged and prepare_deepseekocr_prompt_tokens calls insert_deepseekocr_image_tokens on the tokens the front produced.

Test main (+ tests) this PR
deepseekocr_free_ocr_prompt_has_the_reference_ids FAIL: left: [0, 128815, 128815, 128815, 21431, 126041, 16, 223], right: [0, 128815, 128815, 128815, 201, 21431, 126041, 16] pass
deepseekocr_grounding_prompt_has_the_reference_ids FAIL: left: [0, 128815, 128815, 128820, 21842, 270, 4940, 304, 2121, 7919, 16, 223], right: [0, 128815, 128815, 201, 128820, 21842, 270, 4940, 304, 2121, 7919, 16] pass
deepseekocr_explicit_image_marker_is_not_doubled FAIL: left: [0, 128815, 128815, 201, 21431, 126041, 16, 223], right: [0, 128815, 128815, 201, 21431, 126041, 16] pass
deepseekocr_prompt_is_stripped FAIL on "Free OCR.\n ": left: [0, 128815, 21431, 126041, 16, 223], right: [0, 128815, 201, 21431, 126041, 16] pass
deepseekocr_each_page_gets_its_own_marker FAIL: left: [0, 128815 x 5, 21431, 126041, 16, 223], right: [0, 128815, 128815, 201, 128815, 128815, 128815, 201, 21431, 126041, 16] pass
deepseekocr_prompt_text_adds_markers_only_when_absent FAIL: left: "Free OCR. ", right: "<image>\nFree OCR." pass
deepseekocr_marker_count_mismatch_leaves_the_tokens_alone pass (guard) pass
unlimited_ocr_prompt_has_no_newline_after_the_image pass (guard) pass

The test encoder is a lookup table of the pieces the builder may tokenize, with the ids the checkpoints' tokenizer.json gives them (the file is byte-identical, sha256 a02f8fd5..., in deepseek-ai/DeepSeek-OCR, deepseek-ai/DeepSeek-OCR-2 and the two mlx-community 4-bit conversions). It panics on any other piece, so a stray space or a second <image>\n fails the test rather than mapping to something.

Related filters on the committed tree, all passing: deepseekocr 43, unlimited_ocr 13 (with #3473's deepseek_ocr_keeps_its_shipped_template), deepseek_vl2 14, got_ocr 26, got_chat_template 5, chat_template 199 (5 ignored), vlm_runtime 65, fastvlm 6, hunyuan 33, multimodal:: 388 (28 ignored), builtin_template 6.

Real checkpoints

mlx-community/DeepSeek-OCR-4bit revision 4958b6b0, mlx-community/DeepSeek-OCR-2-4bit 378131e9, mlx-community/Unlimited-OCR-4bit 945968c0, mlx-community/GOT-OCR2_0-4bit 0e28c877, mlx-community/deepseek-vl2-small-4bit 1ffbe89b. Reference: mlx-vlm e8035ae3 (mlx 0.32.4 CUDA) and deepseek-ai/DeepSeek-OCR revision 9f30c71f / deepseek-ai/DeepSeek-OCR-2 revision aaa02f38. Five synthetic pages: the 1024x1024, 1600x1200 and 1920x1280 report pages and the 1920x1280 dense table from #3456, and the 1000x3000 notice from #3473. Temperature 0, 160 tokens. Every model and reference process ran alone under a watchdog (stop below 25 GiB available or above an RSS bound), never beside a build; none tripped.

Prompt ids

MLXCEL_PRINT_TOKEN_IDS=1 mlxcel generate, DeepSeek-OCR, 1920x1280 page, I = the run of 893 image tokens. The upstream column is a transcription of infer()'s steps (strip, split on <image>, tokenize each piece without special tokens, id 0 first) run on the checkpoint's tokenizer.json; the upstream modules themselves were not executed. The mlx-vlm column is its processor on CPU with no weights loaded.

-p main this PR upstream mlx-vlm
Free OCR. 0, I, 21431, 126041, 16, 223 0, I, 201, 21431, 126041, 16 0, I, 201, 21431, 126041, 16 for <image>\nFree OCR. same as upstream
<|grounding|>Convert the document to markdown. 0, I, 128820, 21842, 270, 4940, 304, 2121, 7919, 16, 223 0, I, 201, 128820, 21842, 270, 4940, 304, 2121, 7919, 16 same as this PR, for <image>\n<|grounding|>... same as upstream
<image>\nFree OCR. 0, I, 201, 21431, 126041, 16, 223 0, I, 201, 21431, 126041, 16 same as this PR refuses (2 != 1 image tokens)
<image>\nFree OCR. (README form) 0, I, 201, 21431, 126041, 16, 262 0, I, 201, 21431, 126041, 16 same as this PR refuses
Free OCR.\n 0, I, 21431, 126041, 603, 223 0, I, 201, 21431, 126041, 16 same as this PR, for <image>\nFree OCR.\n 0, I, 201, 21431, 126041, 603
<image>Free OCR. 0, I, 21431, 126041, 16, 223 0, I, 21431, 126041, 16 same as this PR refuses

201 is \n, 223 one space, 262 two spaces, 603 .\n. With this PR the first, third, fourth and fifth prompt give the same ids and the same reply, byte for byte.

DeepSeek-OCR 2 on the same page (1121 image tokens): main 0, I, 21431, 126041, 16, 223, this PR 0, I, 201, 21431, 126041, 16, the ids of mlx-vlm's processor.

examples/logit_trace prints the same # prompt_ids as the CLI on both builds, and scripts/mlx_vlm_image_logit_trace.py (without --mlxcel-prompt) prints the reference's. This PR's line equals the reference's in all nine traces; main's equals it in none.

mlxcel-server does not print prompt ids. One /v1/chat/completions request each (image part, then text part) reports usage.prompt_tokens 898 (Free OCR., 1600x1200), 903 (document prompt) and 1126 (DeepSeek-OCR 2), the CLI's counts, on both builds. With this PR the three server replies are byte-identical to the CLI's. On main the document-prompt reply is byte-identical to the CLI's (4.4.4...), and the two Free OCR. replies equal the CLI's once the CLI's leading space is removed.

Free-running output

mlxcel generate, document prompt, DeepSeek-OCR. Each cell is the first line of the reply; the last column counts the <|det|> blocks in the whole 160-token reply.

Page main this PR mlx-vlm float32 boxes main / PR / ref
1024x1024 Northern Network: Q3 Operations <|ref|>sub_title<|/ref|><|det|>[[37, 41, 562, 71]]<|/det|> <|ref|>sub_title<|/ref|><|det|>[[37, 41, 562, 71]]<|/det|> 3 / 4 / 4
1600x1200 4.4.4.4.4.4.4... (all 160 tokens) <|ref|>sub_title<|/ref|><|det|>[[41, 58, 592, 100]]<|/det|> <|ref|>sub_title<|/ref|><|det|>[[41, 58, 592, 101]]<|/det|> 0 / 4 / 4
1920x1280 Northern Network: Q3 Operations <|ref|>sub_title<|/ref|><|det|>[[40, 62, 558, 108]]<|/det|> <|ref|>sub_title<|/ref|><|det|>[[40, 62, 558, 109]]<|/det|> 0 / 4 / 4
1920x1280 dense table 21 21 21 21 21... (all 160 tokens) <|ref|>title<|/ref|><|det|>[[20, 22, 391, 46]]<|/det|> <|ref|>title<|/ref|><|det|>[[18, 21, 391, 46]]<|/det|> 0 / 2 / 2
1000x3000 1. ScopeThis notice covers the replacement ... (the title is missing) <|ref|>sub_title<|/ref|><|det|>[[66, 24, 840, 45]]<|/det|> <|ref|>sub_title<|/ref|><|det|>[[67, 24, 840, 46]]<|/det|> 3 / 5 / 5

On all five pages this PR's reply and the reference's are the same text once the numbers inside <|det|>[[...]]<|/det|> are masked, with the same number of boxes and every coordinate within 2.

Free OCR.:

Model, page main this PR vs mlx-vlm float32
DeepSeek-OCR, 1024x1024 **Northern Network: Q3 Operations** ... byte-identical (Northern Network: Q3 Operations ...)
DeepSeek-OCR, 1600x1200 Northern Network: Q3 Operations ... byte-identical
DeepSeek-OCR, 1920x1280 Northern Network: Q3 Operations ... (the reference's text behind one space) byte-identical
DeepSeek-OCR, 1920x1280 dense table | | | | | ... (all 160 tokens) byte-identical (| Shipment | Shipment | Shipment | ..., all 160 tokens)
DeepSeek-OCR, 1000x3000 # Dock Door Replacement Notice ... byte-identical (# Dock Door Replacement Notice ...)
DeepSeek-OCR 2, 1600x1200 **Northern Network: Q3 Operations** ... byte-identical (## **Northern Network: Q3 Operations** ...)
DeepSeek-OCR 2, 1920x1280 **Northern Network: Q3 Operations** ... byte-identical (# **Northern Network: Q3 Operations** ...)
DeepSeek-OCR 2, 1000x3000 **Dock Door Replacement Notice** / **1. Scope** ... byte-identical (# Dock Door Replacement Notice / ## 1. Scope ...)

DeepSeek-OCR 2 with the document prompt (float32 reference made for these three pages too): on 1600x1200 and 1920x1280 main already returns the grounded layout (4 boxes, coordinates within 3 of the reference; this PR within 2), so the prompt did not break those two. On 1000x3000 main returns plain text with no box (1. Scope first, the title missing) and this PR returns the reference's text and five boxes, coordinates within 6.

Teacher-forced trace

examples/logit_trace MODEL REPLY 128 1 8 with MLXCEL_TRACE_IMAGE / MLXCEL_TRACE_IMAGE_PROMPT, over the float32 reference's own greedy reply (128 positions), against scripts/mlx_vlm_image_logit_trace.py --float32 on mlx's CUDA device. Decided positions are those where the reference's top-two gap is at least 2 logits. ref(main prompt) is the same reference script scoring main's prompt ids (--mlxcel-prompt).

Trace Arms top-1 disagreements at decided positions largest reference gap at a disagreement logit delta p50 / max perplexity (first arm, second arm)
DeepSeek-OCR, 1024x1024, Free OCR. reference vs main 1/128 0/124 0.150 0.5444 / 2.4606 1.0258, 1.0711 (+4.418%)
reference vs this PR 0/128 0/124 none 0.0893 / 1.1069 1.0258, 1.0269 (+0.111%)
ref(main prompt) vs main 0/128 0/124 none 0.0780 / 0.7725 1.0705, 1.0711 (+0.051%)
reference vs ref(main prompt) 1/128 0/124 0.150 0.4904 / 2.3182 1.0258, 1.0705 (+4.365%)
DeepSeek-OCR, 1600x1200, Free OCR. reference vs main 2/128 0/123 0.419 0.5187 / 8.5297 1.0311, 1.0703 (+3.800%)
reference vs this PR 1/128 0/123 0.033 0.0813 / 1.2279 1.0311, 1.0324 (+0.119%)
ref(main prompt) vs main 0/128 0/123 none 0.0872 / 0.9436 1.0708, 1.0703 (-0.048%)
reference vs ref(main prompt) 2/128 0/123 0.419 0.5150 / 8.6164 1.0311, 1.0708 (+3.849%)
DeepSeek-OCR, 1920x1280, Free OCR. reference vs main 1/128 0/124 0.377 0.4910 / 8.0839 1.0298, 1.0562 (+2.570%)
reference vs this PR 2/128 0/124 0.328 0.1107 / 0.8640 1.0298, 1.0303 (+0.056%)
ref(main prompt) vs main 0/128 0/125 none 0.1056 / 0.7130 1.0571, 1.0562 (-0.085%)
reference vs ref(main prompt) 1/128 0/124 0.377 0.5218 / 8.0546 1.0298, 1.0571 (+2.658%)
DeepSeek-OCR, 1920x1280 dense table, Free OCR. reference vs main 1/128 1/125 2.032 0.1867 / 1.4243 1.0546, 1.1721 (+11.137%)
reference vs this PR 0/128 0/125 none 0.0581 / 0.7100 1.0546, 1.0561 (+0.134%)
ref(main prompt) vs main 2/128 0/124 0.198 0.0581 / 0.4420 1.1721, 1.1721 (+0.003%)
reference vs ref(main prompt) 2/128 1/125 2.032 0.1421 / 1.2384 1.0546, 1.1721 (+11.134%)
DeepSeek-OCR, 1000x3000, Free OCR. reference vs main 1/128 0/126 1.939 0.5545 / 2.4290 1.0080, 1.0691 (+6.064%)
reference vs this PR 0/128 0/126 none 0.1877 / 1.7863 1.0080, 1.0079 (-0.013%)
ref(main prompt) vs main 0/128 0/126 none 0.1912 / 1.9074 1.0696, 1.0691 (-0.046%)
reference vs ref(main prompt) 1/128 0/126 1.939 0.4756 / 2.3707 1.0080, 1.0696 (+6.112%)
DeepSeek-OCR, 1600x1200, document prompt reference vs main 5/128 1/115 6.004 0.3406 / 6.8927 1.0984, 1.1775 (+7.201%)
reference vs this PR 3/128 0/115 0.190 0.1042 / 1.5006 1.0984, 1.1015 (+0.287%)
ref(main prompt) vs main 3/128 0/113 0.341 0.1143 / 1.4979 1.1809, 1.1775 (-0.295%)
reference vs ref(main prompt) 3/128 1/115 6.004 0.3229 / 7.3165 1.0984, 1.1809 (+7.518%)
DeepSeek-OCR, 1920x1280 dense table, document prompt reference vs main 5/128 1/114 6.372 0.2344 / 5.5196 1.1434, 1.1848 (+3.622%)
reference vs this PR 4/128 0/114 0.377 0.0924 / 1.3501 1.1434, 1.1468 (+0.296%)
ref(main prompt) vs main 2/128 0/114 0.135 0.0969 / 1.1762 1.1857, 1.1848 (-0.075%)
reference vs ref(main prompt) 3/128 1/114 6.372 0.1589 / 5.6501 1.1434, 1.1857 (+3.700%)
DeepSeek-OCR 2, 1600x1200, Free OCR. reference vs main 2/128 1/125 6.339 0.9553 / 5.0033 1.0156, 1.0991 (+8.220%)
reference vs this PR 0/128 0/125 none 0.0811 / 0.5528 1.0156, 1.0158 (+0.020%)
ref(main prompt) vs main 0/128 0/126 none 0.0761 / 0.7783 1.0983, 1.0991 (+0.068%)
reference vs ref(main prompt) 2/128 1/125 6.339 0.9859 / 4.8675 1.0156, 1.0983 (+8.147%)
DeepSeek-OCR 2, 1920x1280, Free OCR. reference vs main 2/128 1/126 2.340 0.9319 / 9.8878 1.0151, 1.1363 (+11.946%)
reference vs this PR 0/128 0/126 none 0.0893 / 0.8179 1.0151, 1.0152 (+0.015%)
ref(main prompt) vs main 0/128 0/127 none 0.0940 / 0.7261 1.1354, 1.1363 (+0.084%)
reference vs ref(main prompt) 2/128 1/126 2.340 0.8792 / 9.7660 1.0151, 1.1354 (+11.853%)

Reading it: against the reference on its own prompt, main is 2.6% to 11.9% worse in perplexity and disagrees at a decided position in five traces (the reference's gap there is 2.0 to 6.4); this PR is within 0.3% and disagrees at none. The reference given main's prompt lands where main does (the third row of each block: no decided disagreement, perplexity within 0.3%), and its own distance from itself across the two prompts (the fourth row) is the distance main shows. So the difference between main and the reference is the prompt.

A teacher-forced trace understates the free-running effect: it scores each position behind the reference's own tokens, so the 4.4.4... reply shows up here as one decided disagreement at the first position.

Controls

mlxcel generate, main vs this PR, prompt ids and reply:

Checkpoint, page, prompt prompt ids reply
Unlimited-OCR-4bit, 1920x1280, Free OCR. identical byte-identical
GOT-OCR2_0-4bit, 1024x1024, OCR: identical (287 tokens) byte-identical
deepseek-vl2-small-4bit, 1024x1024, Describe this image in detail. identical (2090 tokens) byte-identical

The Unlimited-OCR and GOT-OCR traces (128 positions over the reply) are row-for-row identical between the two builds, and so is the Unlimited-OCR server reply.

Watchdog, over the three runs: 268 model and reference processes (113, 79 and 76), largest RSS 4.97 GiB, no trip. The lowest available memory seen during a run was 26.9 GiB, in the first run, while another job's vLLM engines held about 53 GiB; in the last run it was 68.5 GiB. Exit codes other than 0 were the servers stopped with TERM after their one request (24) and deepseek-vl2-tiny-4bit, which neither build loads (2).

Earlier bases

Verification limits

  • The dense table page with Free OCR. gets no better. mlx-vlm, in bf16 and in float32, answers it with | Shipment | Shipment | Shipment | ... for all 160 tokens, and this PR now does exactly that. main on the current base loops too (| | | | ...); on 521ba0f71 it transcribed the rows. Matching the reference means matching this as well. With the document prompt the same page is transcribed as a table.
  • Upstream was read, not run. The deepseek-ai ids come from a transcription of infer()'s prompt steps applied to the checkpoint's tokenizer.json; I did not execute the upstream modules or load the PyTorch checkpoints. mlx-vlm e8035ae3 is the reference that actually ran, and its ids equal the transcription's wherever both exist.
  • Server prompt ids are inferred. mlxcel-server prints no ids; the evidence is usage.prompt_tokens equal to the CLI's count and replies byte-identical to the CLI's.
  • More than one image is covered by a unit test only (<image>\n<image>\nFree OCR., one run and one newline per image, from upstream's split loop). My two-image probe of mlx-vlm's processor raised an error, and I ran no multi-image request on a checkpoint. A multi-turn conversation was not run either.
  • Text-only requests are unchanged and still end in the template's space.
  • trim() is not Python's strip() for U+001C..U+001F, which Python strips and Rust does not. No prompt here contains them.
  • Synthetic pages only, and only the 4-bit conversions. No scanned document, no bf16 or 8-bit checkpoint.
  • The float32 DeepSeek-OCR reference ran with the per-image SAM wrapper fix(vision): match DeepSeek-OCR CLIP and SAM encoder numerics #3456 used (it reported mlx 0.32.4's CUDA backend failing the batched float32 SAM forward; I did not retry the unwrapped forward). The DeepSeek-OCR 2 reference ran unmodified.
  • GOT-OCR's reference prompt was not probed (mlx-vlm's GOT processor wants modeling_GOT.py, which the MLX conversion does not ship). Its prompt code is untouched and its ids, reply and trace rows are identical before and after.
  • Metal and ROCm were not run. The change is tokenization only.
  • A second task started building on the same host partway through. From then on each model process waited for a moment with no cargo process; before that, a few processor-only probes (no weights, CPU, under 1 GiB) ran while this task's own first build was in progress.
  • DeepSeek-VL2's prompt is a separate problem (see the issue) and is not touched: deepseek-vl2-small-4bit is byte-identical before and after.

deepseek-ai/DeepSeek-OCR's `infer()` takes a prompt that already names the
page (`<image>\nFree OCR.`), strips it (`format_messages`, 'plain' format),
splits it on `<image>`, tokenizes each piece without special tokens and puts
id 0 first. For `Free OCR.` on a 1920x1280 page that is

    0, <image> x 893, 201 '\n', 21431 'Free', 126041 ' OCR', 16 '.'

mlxcel rendered the instruction through the template the MLX conversions
ship (mlx-vlm's `{{message['content']}} `, a space after every message) and
spliced the image run after BOS, so the model read

    0, <image> x 893, 21431 'Free', 126041 ' OCR', 16 '.', 223 ' '

with no newline after the page and a space token the reference never feeds.
mlx-vlm renders the same template but ends up with the reference ids: it
formats the message as `<image>\n` + text and its processor drops the last
id. DeepSeek-OCR 2 is built by the same upstream code and had the same
prompt.

With the model card's document prompt, `<|grounding|>Convert the document to
markdown.`, the difference decides the output: on DeepSeek-OCR-4bit a
1600x1200 page came back as `4.4.4.4...` and a dense table as
`21 21 21...`, and the other three pages lost the `<|ref|>...<|det|>` box
and heading of their title block (one of them every box), where mlx-vlm
returns the grounded markdown.

`prepare_deepseekocr_prompt_tokens` now builds the prompt for both families
from the rendered text, in the prompt module, the way GOT-OCR and FastVLM
re-tokenize theirs: strip, put one `<image>\n` per page in front when the
text names no `<image>` itself, split on `<image>`, tokenize the pieces,
BOS first. A prompt that already writes `<image>` is only stripped, so the
model card's `<image>\nFree OCR.` and the bare instruction give the same
ids and nothing is doubled. `mlxcel generate`, `mlxcel-server` and
`examples/logit_trace` all go through it.

Unlimited-OCR keeps its own layout (one `<image>` for all pages, no
newline), GOT-OCR its own conversation, and a text-only request is not
touched. A prompt whose own `<image>` count does not match the pages is
left as before.

Eight tests in `deepseekocr_prompt.rs`; against main's behaviour behind the
new functions, six fail (the ids end in 223, and have no 201 unless the
caller wrote the marker) and the two guards (marker count mismatch,
Unlimited-OCR) pass.

On GB10 CUDA the prompt ids equal mlx-vlm e8035ae3's on five pages for
DeepSeek-OCR-4bit and two for DeepSeek-OCR-2-4bit. The 160-token `Free OCR.`
replies are byte-identical to the float32 reference's on all eight
page/model pairs, and the DeepSeek-OCR markdown replies differ from it only
in box coordinates, by at most 2. A teacher-forced trace against that
reference has no disagreement at a decided position on any of the nine
traces (main: one on five of them) and a perplexity within 0.3% of it
(main: 2.6% to 11.9% higher). Unlimited-OCR-4bit, GOT-OCR2_0-4bit and
deepseek-vl2-small-4bit output is byte-identical before and after.
@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 labels Nov 28, 2026
@inureyes
inureyes merged commit 2c41753 into lablup:main Nov 28, 2026
33 checks passed
inureyes pushed a commit that referenced this pull request Nov 28, 2026
…coder (#3505)

DeepSeek-VL2 chat requests are now rendered with the model's own conversation format (`deepseek`, `deepseekv2`, `plain`) and encoded per turn as upstream `format_messages_v2` does, with typed image markers. The tiny variant, whose config has `use_mla:false`, now loads through the MHA decoder in `models::deepseek`. The disaggregated router's refusal for natively tokenized prompts now names DeepSeek-VL2 alongside Kimi K3.

Hardening review: merged main and #3482 locally, compared against upstream at `ef9f91e2`, ran fmt, clippy (cuda, all targets), 457 lib tests, a revert experiment (loader and renderer tests fail without the fix), and real-checkpoint runs on VL2 tiny and small whose prompt ids match an upstream-transcribed oracle exactly (2030/4048 and 2032/4050 tokens).

Closes #3504
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 28, 2026
@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

area:models Model architectures, weights, loading, metadata priority:medium Medium priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(vision): DeepSeek-OCR and DeepSeek-OCR 2 prompts drop the post-image newline and append a stray trailing space

2 participants