Skip to content

fix(vision): use the DeepSeek-VL2 conversation format and tiny MHA decoder - #3505

Merged
inureyes merged 2 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/deepseek-vl2-prompt
Nov 28, 2026
Merged

inureyes merged 2 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/deepseek-vl2-prompt

Conversation

@Jaeyeong-CHOI

Copy link
Copy Markdown
Contributor

Summary

Closes #3504

DeepSeek-VL2 small now receives its image inside the user turn on both the CLI and the OpenAI-compatible server. Tiny loads its plain multi-head attention (MHA) decoder and generates on NVIDIA GB10. This completes the plain-MHA branch specified in #533. #660 validated small's multi-head latent attention (MLA) branch. The change is based on main 944dbfc2d. Its changes to the vision runtime and model list are on different lines from #3482.

  • Read the processor's sft_format with the upstream default of deepseek. Render the registered deepseek, deepseekv2 and plain conversations. Insert image markers where their content parts occur. Preserve explicit markers and reject a mismatch with the attachment count.
  • Encode the initial system message, each formatted question and each assistant answer separately. Tiny's tokenizer can merge the colon and first answer character (:A is token 48389). Re-encoding a joined multi-turn string changes the actual model input.
  • Use the existing DeepSeek MHA decoder for tiny. The loader and KV sizing share the decoder selection, and the tokenizer supplies the image and EOS IDs. Small and base keep the MLA path. The raw CLI prompt path retains the after-BOS fallback when no markers are supplied.

Which template and decoder

All three DeepSeek releases and all three 4-bit MLX conversions declare sft_format: deepseek. Upstream emits one BOS, formats each stripped user question with a blank assistant turn, splits at each image, then separately encodes each historical assistant answer with EOS. A leading system message is encoded on its own. The registered deepseekv2 roles are spelled differently from the literal User tested by that formatter, so its actual non-empty question ends in EOS. plain emits the user text directly. Upstream processor · Formatter · Registrations

4-bit checkpoint Attention evidence in language_config BOS / EOS / image / user / assistant
tiny use_mla=false, kv_lora_rank=null, zero MLA dimensions, separate Q/K/V weights 0 / 1 / 128815 / 128821 / 128822
small MLA defaults, compressed KV weights 100000 / 100001 / 100003 / 100009 / 100010
base MLA defaults 0 / 1 / 128815 / 128821 / 128822

The MLX model cards identify the three prince-canuma checkpoints as conversion inputs and mlx-vlm 0.1.5 as the converter. Those inputs already have a separate chat_template.json. Its decoded string matches the current mlx-vlm processor default for all three sizes (SHA-256 prefix aae9bf506da51538). Small alone also inherits the DeepSeek Coder string in tokenizer_config.json from the original DeepSeek release (8ba1ca9a4c606d3f in the original, intermediate and MLX checkpoint). The converter saves the processor at mlx_vlm/utils.py:768. For a text-only system/user/assistant/user history, the standalone template yielded 19 tokens vs upstream’s 18 on tiny and 25 vs 21 on small. It inserted whitespace around the system message and omitted the EOS after the historical answer. The one-user-turn controls matched at 7 and 8 tokens. Model card · Intermediate template · Conversion code · Current mlx-vlm processor

On main, src/server/chat_template.rs:443–464 gives standalone templates precedence only if they expect typed parts. The standalone VL2 template expects strings, so small selects the Coder template. src/commands/generate.rs:917 and src/server/chat_request.rs:1061 produce a text-only turn. src/multimodal/deepseek_vl2_prompt.rs:66–80 inserts the missing image run immediately after BOS. Separately, src/loading/vlm_deepseek_vl2.rs:39–40,117,176 assumes small's tokenizer IDs and always builds the V2 decoder. Tiny then fails at the null rank in the non-optional usize at src/models/deepseek_v2.rs:76 before any prompt reaches the model. Upstream makes this architecture choice explicitly at modeling_deepseek.py:1232. Decoder construction

Checkpoint verification

GB10, CUDA 13.0.88, driver 580.178.04, 4-bit tiny 4772de7c, small 1ffbe89b, DeepSeek-OCR 4958b6b0. One or two copies of the same 1024 × 1024 RGB page (SHA-256 5eca426628aab1afa8b67fa1f208d67455dc12b6d4ac0c4bcd21b84f0ffc5500), user text Describe this image in detail., greedy decoding, 24 tokens.

Model and images Main CLI / HTTP Fixed CLI / HTTP DeepSeek upstream mlx-vlm CLI / HTTP IDs
tiny, one load error 2030 / 2030 2030 2030 / 2030
tiny, two load error 4048 / 4048 4048 4048 / 4048
small, one 2090 / 2090 2032 / 2032 2032 2032 / 2032
small, two 4107 / 4107 4050 / 4050 4050 4050 / 4050

The tested commit is e4219cdc683d1cdfd648cea654d40c0e6efd2856, tree 3365abfa6ac8da735db9a781eef14c4306594dc0. The main CLI and server matched the previous GB10 build's SHA-256 manifest for main tree a5d9963e. After switching the private build checkout and touching the changed inputs, the CLI hashes were 5c8e96ac5918… (main) and 1098eaa58428… (fixed), and the server hashes were 88fc0103cc6c… and ac28f153a8bb….

The CLI dump and live HTTP buffer (read with a debugger on return from image expansion) match the upstream ID arrays at every position. Upstream's token-producing methods ran with the released tokenizer and actual PIL image dimensions. Pixel normalization was omitted in this token-only oracle. Both public mlx-vlm entry points produced those exact IDs for both image counts. A read-only observer recorded the processor's returned inputs during the actual CLI and HTTP requests. Generation on GB10 then failed for two-image CLI requests at deepseek_vl_v2.py:340 (CUDA tile slice requires 32-bit indices). All four HTTP requests returned 500 inside generation.py:1814 → apc.py:171 when the image hash tried to evaluate a tensor on a GPU stream unavailable to the worker thread. These are errors after tokenization. A separate direct prepare_inputs(prompts=[text], images=[a,b]) call fails earlier because the processor zips one prompt with the first image. The scalar process_one call accepts both and yields the upstream IDs. mlx-vlm batch path

The corrected one-image inputs are shown in full with run-length notation. For a second image insert another identical run and newline immediately after the first run and newline.

tiny   0 128821 28 223 [128815 × 2017] 201 72188 566 4609 295 6271 339 128822 28
small  100000 100009 25 207 [100003 × 2017] 185 41800 437 3324 279 7988 13 185 185 100010 25
Exact main small IDs, CLI and HTTP

Both arrays start with BOS 100000, immediately followed by 100003 repeated 2017 times for one image or 4034 times for two images. Both end with the same 72-token Coder suffix.

2054 418 274 20838 14203 20308 11 26575 254 20593 30575 339 8587 2019 11 6907 457 20593 30575
7947 11 285 340 889 3510 4313 4523 276 4541 8204 13 1494 48019 13119 4313 11 5424 285 13897
4458 11 285 750 2170 12 36873 8204 4313 11 340 543 20770 276 3510 13 185 13483 50278 25 185
41800 437 3324 279 7988 13 185 13483 21194 25 185 185

Main tiny has no input ID array because loading fails.

Tiny's mlxcel CLI and server and the mlx-vlm CLI returned the same 24 tokens of text about the title and northern distribution network. Small on main described the quarterly report despite the coding template. With the fix it opened “The image is an official document titled …” for one image and “The image displays a document titled …” for two. Stock mlx-vlm on one small image returned $310. and repeated newlines.

Same-prompt teacher-forced trace Top-1 disagreements Disagreements at reference gap ≥ 2 PPL, reference / fixed
tiny 0 / 38 0 / 10 15.7702 / 15.7778
small 36 / 39 0 / 1 236.2041 / 10.2473

The continuation, checkpoint, pixels and full prompt IDs match for each comparison. Small has only one decided position and diverges substantially on the others. Small on main naturally uses different inputs. As a control, a private checkpoint view supplied the corrected single-turn template to the unmodified main binary, with symlinks to the original weights. After verifying all 2032 IDs were identical, every one of its 39 TSV score rows (target, NLL, top-8 IDs and logits) matched the fix byte for byte. Main cannot produce a tiny trace.

Small MLA diagnostic. DeepSeek pairs adjacent elements in its rotary head before rotating. mlxcel's existing MLA path uses interleaved rotation. Stock mlx-vlm small passes its default rope_traditional=False to nn.RoPE on the same weights. In a separate run, changing only that argument in mlx-vlm's MLA attention to true reduced the disagreements from 36/39 to 0/39, including 0/9 decided positions. Reference PPL became 10.1849 versus 10.2473 in mlxcel. This diagnostic uses a modified reference. The stock numbers above are unchanged. DeepSeek rotary layout · mlx-vlm default · mlx-vlm MLA call

MLXCEL_PRINT_TOKEN_IDS=1 mlxcel generate -m "$MODEL" --image "$PAGE" -p "$QUESTION" --temp 0 -n 24
MLXCEL_TRACE_IMAGE="$PAGE" MLXCEL_TRACE_IMAGE_PROMPT="$QUESTION" logit_trace "$MODEL" continuation.txt 64 1 8
python scripts/mlx_vlm_image_logit_trace.py "$MODEL" "$PAGE" fix.tsv --prompt "$QUESTION" --topk 8
python3 scripts/compare_logit_traces.py reference.tsv fix.tsv --decided 2

The server ran as mlxcel-server -m "$MODEL" --host 127.0.0.1 --port 18979. The HTTP client posted the same text and 1–2 image_url data-URL parts to /apply-template and /v1/chat/completions with temperature 0 and max_tokens 24. Repeating --image "$PAGE" on the CLI supplies image two.

The comparison consumes TSV headers and rows after removing the reference processor's six initialization messages. The CLI, HTTP, and reference processes ran serially. Model runs used a 44 GiB RSS watchdog and 25 GiB host-available floor. The first isolated binary could not locate CCCL headers at JIT time. Setting MLXCEL_CCCL_DIR to the reused headers resolved it.

Regression and review checks

  1. Boundary inputs. Covered zero, one, two and three images, mixed content, a literal marker with and without attachments, mismatched counts, system and assistant history, and zero, negative and overflowing run lengths. A tiny real-vocabulary fixture pins the per-turn token IDs for all three formats.
  2. Large inputs. Expansion counts the output, reserves once, and emits in order. Time is linear in the input plus output lengths. A 100,000-block test checks every image/text boundary.
  3. Other callers. The same normalized config drives loading and KV sizing. Four template-family controls passed on main. On real checkpoints the full main/fix prompt and generated IDs are identical for DeepSeek-OCR (698 input / 24 output), OCR 2 (406 / 8), Unlimited-OCR (697 / 8) and GOT-OCR (287 / 8). DeepSeek-OCR's HTTP response text also matches byte for byte.
  4. Formatting. cargo fmt --all -- --check passed on Spark2.

With the new renderer and loader tests copied onto main, cargo test --locked --profile test-fast --features cuda --lib deepseek_vl2 -- --test-threads=1 returned 16 passed and 5 failed. The failures cover tiny's decoder, image formats, explicit/interleaved markers, system/history boundaries and the exact multi-turn request IDs. On the final tree the same command returned 23 passed. With the filter replaced by deepseekocr, got_ocr and unlimited_ocr, it returned 35, 26 and 12 passed, respectively.

cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings passed in 7m 20s. python3 scripts/ci/check_used_by.py resolved 636 caller-file references and bash scripts/ci/check_used_by_test.sh passed all 35 cases. The applicable scripts/ci/check_.py checks and scripts/ci/_test.sh self-tests passed, including 49 WebUI contract fixtures. The Apache header check and 252 Python tooling tests passed. The ROCm overlay and CUDA runtime-directory checks were host-only. Multi-host and ROCm execution were outside this single-GB10 run. The initial WebUI check used the host interpreter, which lacked compatible JSON Schema dependencies. Both normal and self-test modes passed with the isolated dependency set and the existing venv interpreter.

TMPDIR="$R/tmp" make verify-test-cuda ran to completion with mode 0700 on TMPDIR. Across 196 outer test targets, 17,413 passed, 5 failed, 517 ignored (make exit 2). Two additional one-test summaries in the lib log belong to filtered subprocesses, and are excluded from this total. mlxcel-xla's library had 586 passed and 23 ignored, including its registered-golden check. The DeepSeek-V3.2 YaRN tests passed. Gate peak process-group RSS was 26.64 GiB with 85.48 GiB minimum available and no watchdog intervention.

Other gate commands included python3 scripts/ci/check_webui_contract.py with and without --self-test, python3 scripts/ci/check_webui_evidence.py --self-test, python3 scripts/insert_apache_header.py --check and make verify-rocm-overlay verify-cuda-runtime-dir verify-python-tooling. The remaining check_*.py scripts ran with no arguments and each *_test.sh ran under bash.

The five failing tests are

models::raon1_mini::speculative::tests::a_steered_verify_block_applies_the_alpha_exactly_as_decode_does
models::raon1_mini::speculative::tests::a_verify_block_equals_the_decode_chain_byte_for_byte
models::raon1_mini::speculative::tests::rollback_after_a_partial_accept_equals_a_fresh_decode_of_the_accepted_tokens
models::raon1_mini::speculative::tests::the_exactness_probe_passes_on_the_tiny_model
models::raon_mhc::tests::compiled_site_equals_the_eager_site_bit_for_bit

On unmodified main 944dbfc (tree a5d9963e, clean index and worktree), cargo test --locked --profile test-fast --features cuda -p mlxcel --lib -- --test-threads=1 raon1_mini::speculative raon_mhc::tests::compiled_site_equals_the_eager_site_bit_for_bit returned 4 passed and the same 5 failed. The sets of fully qualified failure names were compared directly. On the same clean main, cargo test --locked --profile test-fast -p mlxcel-xla --lib -- --test-threads=1 independently returned 586 passed, 0 failed and 23 ignored.

Verification limits

The final Mac and Spark2 trees matched and both worktrees were clean. The Spark2 directory occupied 51.18 GiB (48.63 GiB in Cargo target). No checkpoint weights were downloaded. Existing CUDA dependencies, checkpoints and the reference environment were reused.

Base was checked against published configs and tokenizer files. Its weights were not loaded. The original DeepSeek implementation supplied the prompt oracle. Numerical comparisons used mlx-vlm's CUDA model on one page and one fixed continuation per size.

inureyes pushed a commit that referenced this pull request Nov 28, 2026
DeepSeek-OCR and DeepSeek-OCR 2 prompts are now built the way upstream `modeling_deepseekocr.py::infer()` does: the prompt is stripped, `<image>\n` is added per image when the prompt has no marker, each text piece is tokenized without special tokens, and id 0 leads. Grounding prompts now return boxed titles and paragraphs instead of the `4.4.4` failure.

Hardening review: merged main locally, compared against upstream, ran fmt, clippy (cuda, all targets) and 457 lib tests on a combined tree with #3505, a revert experiment (6 OCR prompt tests fail without the fix), and real-checkpoint runs on DeepSeek-OCR and OCR 2 whose prompt ids match an upstream-transcribed oracle exactly (898/903 and 1126/1131 tokens).

Closes #3481
The disaggregated router refuses any request whose chat renderer produced token ids. Since DeepSeek-VL2 now encodes each turn natively, its text-only requests reach the same refusal, whose message named only Kimi K3. The message now names both formats, and the Unlimited-OCR rationale that was dropped with builtin_template_overrides_checkpoint is restored next to the inlined family check.
@inureyes

Copy link
Copy Markdown
Member

Hardening review

Reviewed against #3504 and upstream DeepSeek-VL2 processing_deepseek_vl_v2.py::format_messages_v2 / conversation.py (ef9f91e2): the deepseek, deepseekv2 and plain formats, first-turn-only system message, per-turn encoding and answer+EOS all match. Tiny's config (use_mla:false, kv_lora_rank:null) fits models::deepseek, and loading and KV sizing use the same selection. No CRITICAL, HIGH or MEDIUM findings.

Pushed (96324d13)

  • LOW: text-only DeepSeek-VL2 requests through the disaggregated router now hit the native-token-ids refusal, whose message named only Kimi K3. It now names both formats (src/server/router_front.rs).
  • LOW: restored the Unlimited-OCR template-override rationale that was dropped when builtin_template_overrides_checkpoint was inlined (src/server/chat_template.rs).

Validation (main + #3482 + this PR)

  • cargo fmt --all -- --check, cargo clippy --locked -p mlxcel --all-targets --features cuda -- -D warnings, check_used_by.py, check_env_var_docs.py, check_cross_repo_refs.py, license headers: pass.
  • Lib tests (--profile test-fast --features cuda, deepseek/VL2/chat_template/vlm_runtime/router_front filters): 457 passed, 0 failed.
  • Revert experiment: disabling the VL2 MHA selection and typed image markers fails the tiny-decoder loader test and 3 renderer/server-id tests.
  • Real checkpoints on GB10: prompt ids match an oracle transcribed from upstream with the checkpoint's tokenizer.json exactly. Tiny 1/2 images: 2030/4048 tokens; small: 2032/4050. Tiny now loads (it failed on main) and describes the page correctly; small no longer gets the Coder system prompt. Server /v1/chat/completions multi-turn gives 32 prompt tokens, matching upstream per-turn encoding.

Not changed: a request with tools is rendered without the tools for this family, since the model has no tool format.

@inureyes
inureyes merged commit c26cb10 into lablup:main Nov 28, 2026
33 checks passed
@inureyes inureyes added status:done Completed type:bug Bug fixes, error corrections, or issue resolutions priority:medium Medium priority 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

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-VL2 small uses a coding prompt for images and tiny fails to load

2 participants