Skip to content

fix(dsv41): keep the image block list the checkpoint's template reads - #37

Closed
sivalei wants to merge 1 commit into
Elevatormusic:deepseek-v41-tp2from
sivalei:fix/dsv41-vision-block-list
Closed

sivalei wants to merge 1 commit into
Elevatormusic:deepseek-v41-tp2from
sivalei:fix/dsv41-vision-block-list

Conversation

@sivalei

@sivalei sivalei commented Oct 22, 2026

Copy link
Copy Markdown

DsVision.split flattened a message's content into one string that already held the placeholder. The checkpoint's own chat_template.jinja is written for a block list: its joined_text macro turns an image/image_url block into the placeholder itself, and its guard raises on a string that carries the placeholder. So every image request was refused with the stock template, on this branch and on 07aa02585f64:

the chat template rejected the request: Message content contains image special token
<|deepseek_image|>. Images should be provided as image content blocks.

Keeping the blocks (as the shared split_images already does) is not enough on its own: the base App._prepare renders through normalize_messages, which drops image parts unless allow_images is set, and it called template.prepared() for the shield without that flag too. Both now take allow_images, and DsApp passes it for the request split() already handled.

The three places, in order

1. vision.py: split() keeps the block list. The template's own image path emits the placeholder, so the prompt the model sees is unchanged.

# before
out.append({**m, "content": "\n\n".join(texts)})
# after
blocks = [{"type": "image"} if kind in ("image_url", "image") else {"type": "text", "text": part["text"]} ...]
out.append({**m, "content": blocks})

2. cuda/server.py: _prepare takes and forwards allow_images. normalize_messages needs it to keep the blocks, and the shield's template.prepared() call needs it for the same reason.

3. deepseek_v41/cuda/app.py: pass allow_images=True. split() already replaced every image part, so the blocks are the server's own.

Why the existing test did not catch it

tests/test_deepseek_v41_plain_text.py stubs the template out (SimpleNamespace(render=lambda *a, **k: "")), so the guard that refuses the request never runs. The new tests/test_deepseek_v41_vision_blocks.py renders a template with the same two guards, and one test asserts that the flattened string is what the guard refuses — so the shape is checked, not a stub that accepts anything. The existing test's stub now takes **kwargs for the new parameter.

Receipt

Environment. Commit cb4ceaff + this change. PyTorch 2.13.0a0+9186a08b2c.nv26.07 (NGC 26.07), xgrammar 0.2.8. 2× DGX Spark (GB10, sm_121, aarch64), TP=2. Checkpoint LibertAIDAI/DeepSeek-V4.1-Flash-1017-EXL3-2.9bpw @ afc7aa0aab98ee735c0f54e0a122019af1ac08f1, stock chat_template.jinja (md5 d33c0a9c46a7f13bb36ccc9ebeb6684d, 12 raise_exception guards).

Tests. tests/test_deepseek_v41_plain_text.py, tests/test_plain_text.py, tests/test_deepseek_v41_vision_max_images.py, tests/test_deepseek_v41_vision_blocks.py → 45 passed, 0 failed, 0 skipped.

Images, stock template, this change. tools/dsv41/vision_http.py → 4/6 passed. The two not counted as ok are the harness's own format check; the model's replies are correct ("TensorFold 42" for reads_text, The sign on your screen says **"TensorFold 42"** for image_in_tool_result). Before this change all six were 400.

Direct requests against the stock template, this change: one image → 200 ("blue"), nine images in one message → 200, five + four images across two messages → 200, plain text → 200. Before: all three image cases 400.

Suite. tests/v41_suite.py speed tools schema reasoning format long_context → 30/30 passed (254 s), unchanged from before the change.

What I did not run. The Mac/MLX host suite and tests/cuda — I have CUDA machines only, no Apple Silicon. I also did not run bench_concurrent.py / bench_openai.py / prefill_cold.py: this change touches the image path and adds one flag to a text path that already had a render() call, so I have no before/after numbers for decode or prompt speed. Say if you want them and I will run them on the Sparks.

Notes

  • split()'s docstring said "content as one string, DeepSeek's join" — that is the shape the template refuses. Updated to say why the blocks stay.
  • The 8-image limit (a request may carry at most 8 images) is a separate matter, fixed in 56f5aab; this change is only about the shape handed to the template.
  • We run this on the two Sparks; it has been serving images since 2026-10-22 with the stock template and no template patch.

DsVision.split flattened a message's content into one string that already held the placeholder. The
checkpoint's own chat_template.jinja is written for a block list: its joined_text macro turns an
image/image_url block into the placeholder itself, and its guard raises on a string carrying the
placeholder. So every image request was refused with the stock template, on this branch and on
07aa025:

  the chat template rejected the request: Message content contains image special token
  <|deepseek_image|>. Images should be provided as image content blocks.

Keeping the blocks (as the shared split_images already does) is not enough on its own: the base
App._prepare renders through normalize_messages, which drops image parts unless allow_images is set,
and it called template.prepared() for the shield without that flag too. Both now take allow_images,
and DsApp passes it for the request split() already handled.

tests/test_deepseek_v41_vision_blocks.py renders a template with the same two guards, so the shape
the engine hands over is checked rather than a stub that accepts anything. The existing plain-text
test's stub takes **kwargs for the new parameter.
@sivalei

sivalei commented Oct 22, 2026

Copy link
Copy Markdown
Author

Context for reviewers: this is the fix for the mechanism I described in #28 (comment 6321363724). That comment had the symptom and the shape mismatch; this PR has the change, the regression test, and the receipt.

Two things that took a while to find, in case they save you time:

  1. split() keeping the blocks is not enough. App._prepare renders through normalize_messages, which drops image parts unless allow_images is set — so after fixing split() alone the request failed with a different message (this server accepts text parts only; image, audio and video inputs are unsupported).
  2. The shield call is the third place. App._prepare calls template.prepared() a second time for PlainText.shield, before render(). That call also needed allow_images; without it the original error came back even with the first two fixed. It is the least obvious of the three.

The test renders a template with the same two guards rather than a stub, because the stub is exactly why this stayed hidden: tests/test_deepseek_v41_plain_text.py replaces the template with render=lambda *a, **k: "", so the guard never runs.

I did not measure decode or prompt speed — this touches the image path plus one flag on a text path that already called render(). Happy to run bench_openai.py / prefill_cold.py on the Sparks if you want the numbers before landing.

@Elevatormusic Elevatormusic left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the fix and for the clear write-up. The stock-template failure is real. I ask for changes because of two problems: the PR breaks image input with the chat template that our recipe installs, and the plain-text shield path still renders without allow_images.

1. The recipe's chat template (blocker). The recipe (DeepSeek-V4.1-Flash-1017-EXL3-TensorFold-2x-DGX-Spark) puts its own chat_template.jinja into every model view. That template has no image branch. For a user or tool turn whose content is a list, it writes message.content | tojson. With this PR, the content is a block list, so the prompt gets the JSON text [{"type": "text", ...}, {"type": "image"}] and no <|deepseek_image|>. Then vision.expand finds no placeholder for the picture, and the request fails. On the current branch (string content with the placeholder), the same request works. So the PR moves the failure from the stock template to the recipe's template.

The two templates need opposite shapes: the stock one needs blocks and refuses a string that has the placeholder, and the recipe's one needs the string. I suggest that the engine selects the shape from the loaded template. For example, probe the template once at start (as late_system_role does), or set a family flag from the template source. Please add a test that renders both shapes through both kinds of template.

2. The plain-text shield path (blocker). DsApp.plain_message_text is True. When any text in the request has an added-token spelling, shield.table is not empty and _prepare renders with self.template.render(shield.messages, ...) at server.py line 321. That call does not pass allow_images. So prepared() runs normalize_messages(allow_images=False) on the {"type": "image"} blocks and refuses them with "this server accepts text parts only; image, audio and video inputs are unsupported" (HTTP 400). An image request plus a tool result or pasted text that has a DSML tag or <|end▁of▁sentence|> meets this. The new wiring test does not find it, because it sets _plain_text to None and replaces template.prepared with an identity function.

Smaller items (not blockers):

  • split(): the first loop still builds texts, but nothing reads it now, and a second loop walks the same parts to build blocks. One loop can build the blocks.
  • DsApp._prepare: plain_keep=(PLACEHOLDER,) keeps nothing now, because no content has the placeholder. test_the_image_placeholder_is_kept_only_on_the_image_path still stubs split to return the old string shape.
  • The DsVision class docstring still says "a placeholder text block, a message's blocks joined by blank lines".
  • server.py line 327: render(body["messages"], allow_images=allow_images) alone does the same as the conditional. The line 321 render needs the same argument.
  • Please also cover an image in a tool result: both templates handle the tool role in a different branch from the user role.

blocks.append({"type": "image"})
elif kind == "text":
blocks.append({"type": "text", "text": part["text"]})
out.append({**m, "content": blocks})

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the recipe's chat_template.jinja, list content is written as message.content | tojson, so this block list reaches the prompt as JSON text without the image placeholder, and expand then has no placeholder for the picture. See point 1 in the review.

plain = self._plain_text()
# the shield sees the messages as the template gets them: a JSON escape or a split text part hides nothing
shield = plain.shield(self.template.prepared(body["messages"]), tools, kwargs,
shield = plain.shield(self.template.prepared(body["messages"], allow_images=allow_images), tools, kwargs,

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The shield now sees the blocks (allow_images here), but the render on the shield path below (line 321, self.template.render(shield.messages, ...)) does not pass allow_images. So normalize_messages refuses the image blocks whenever shield.table is not empty. See point 2 in the review.

@Elevatormusic

Copy link
Copy Markdown
Owner

@sivalei please fill in the pull request template in the description:

  • Tick one box under Type (for this change, type: fix). The pr-template check uses it to add the label.
  • Add the AI disclosure block at the end, with both lines: AI: <model and size> via <harness> (or AI: none) and Checked: <what you did yourself>.

The template is in .github/pull_request_template.md. Thanks.

@Elevatormusic

Copy link
Copy Markdown
Owner

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-22T02:03:48.518824Z 83e3369 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 83e3369ca3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

prompt = plain.encode(text, shield)
else:
text = render(body["messages"])
text = render(body["messages"], allow_images=allow_images) if allow_images else render(body["messages"])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Forward allow_images through the shielded render

When a DeepSeek image request also activates PlainText shielding—for example, its caption or tools contain an added-token spelling such as </think> (or the tokenizer has a normalizer)—execution takes the preceding shielded branch instead of this unshielded render. That branch calls ChatTemplate.render without allow_images, so render() normalizes the preserved {"type": "image"} block again with its default False and rejects the request as unsupported before the checkpoint template runs; pass the flag to the shielded render as well.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner

I am carrying the stock-template repair forward in #55 with an explicit native-template mode. It also forwards allow_images through the shielded render and preserves the recipe's legacy string-template mode. That keeps the two existing template formats usable and covers images in tool results. Your report and tests identified the original stock-template failure; thank you. I am holding this PR while the overlap and remaining qualification checks are resolved, so the two approaches do not land together.

Copy link
Copy Markdown
Owner

The image-block approach is now carried in merged PR #55, commit 8559c41c5c91f1f7181503c45a13dd72bb5c83b5. That PR credits your report and this contribution.

The integrated version uses the startup opt-in TF_DS_VISION_TEMPLATE=native, forwards the native-image flag through the text shield, and preserves the recipe's legacy placeholder default. It also keeps the newly merged prompt cache and its whole-input fallback. All 113 focused cases pass, with current CI and a fresh clean Codex review. Live EAQ, token-hash, image-quality, and paired performance qualification remain open.

I am closing this overlapping PR under the contribution policy. Its current head is not merged because its global default change would break the legacy recipe path. The compatible implementation is in #55.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants