← Back to Pull requests

[Bugfix][Frontend] Align DeepSeek V4.1 images with rendered content #60792

Merged
xijiaat merged 5 files (177 lines) on Oct 19, 2026 05:59 UTC
View on GitHub
xijiaat xijiaat commented on Oct 09, 2026 07:08 UTC
Author

Overview

Fix Python DeepSeek V4.1 rendering when tool results reorder image placeholders or thinking mode drops historical developer content. Carry source image indices through the native encoder and apply the resulting order to both image data and UUIDs.

This follows the source-order approach of #56366, which fixed the Rust frontend only.

Claims

  • Out-of-order tool results keep their own images after sorting into tool-call order.

  • Images belonging to dropped developer content no longer reach multimodal prompt expansion without a placeholder.
  • Validation

    The following results are from the tests run on 2026-10-09, not a new rerun. The four production files tested then are unchanged at the current PR head.

    Two regression cases, each exercised through sync and async rendering; the existing V4/V4.1 tokenizer suites are also included.

    | CPU tests | Result |
    | --- | --- |
    | Baseline source checkout + regression tests | 4 failed, 75 passed |
    | Patched implementation | 79 passed |

    Run in a CPU-only container against the source checkout, with model/processor metadata stubbed and real message parsing, image tracking and native encoding:

    .venv/bin/python -m pytest --confcutdir=/work/checks/tests/tokenizers_ -o addopts= \
      /work/checks/tests/tokenizers_/test_deepseek_v41.py \
      /work/checks/tests/tokenizers_/test_deepseek_v4.py -v
    

    <details>
    <summary>Actual CPU output: baseline failures and patched result</summary>

    Verbatim excerpts from regression-baseline.log:

    FAILED ../checks/tests/tokenizers_/test_deepseek_v41.py::test_tool_images_follow_rendered_order[sync]
    FAILED ../checks/tests/tokenizers_/test_deepseek_v41.py::test_tool_images_follow_rendered_order[async]
    FAILED ../checks/tests/tokenizers_/test_deepseek_v41.py::test_dropped_developer_only_image_leaves_text_prompt[sync]
    FAILED ../checks/tests/tokenizers_/test_deepseek_v41.py::test_dropped_developer_only_image_leaves_text_prompt[async]
    ================== 4 failed, 75 passed, 15 warnings in 15.77s ==================
    

    From regression-patched.log:

    ======================= 79 passed, 15 warnings in 15.66s =======================
    

    </details>

    Full pre-commit checks passed on all five changed files, including mypy and test CI tethering.

    GPU validation passed on the real DeepSeek-V4.1-Flash checkpoint (DeepseekV41ForCausalLM), using 8x H20-3e, TP=8, eager execution and temperature=0. The GPU runtime was vLLM 0.31.0 / PyTorch 2.13.0+cu130 with this PR's four production files mounted unchanged; their SHA-256 hashes were verified against commit f5622b6. This was not a full build of main.

    The same loaded model compared the original media handling (the base renderer without an image-order accumulator) and the patched V4.1 renderer, using generated 560x560 red and blue images:

    | Full-model case | Observed result |
    | --- | --- |
    | Ordered tool results, baseline | A=red, B=blue |
    | Reversed tool results, baseline | A=blue, B=red (wrong image assignment) |
    | Reversed tool results, patched | A=red, B=blue; output token IDs match the ordered baseline |
    | Dropped historical developer image, baseline | AssertionError: Failed to apply prompt replacement for mm_items['image'][0] |
    | Dropped historical developer image, patched | Successful generation, final answer OK |

    <details>
    <summary>Actual full-model GPU output, including generated text and token IDs</summary>

    The in-container validation command was .venv/bin/python /work/gpu_validate.py. These are verbatim result lines from gpu.log, not reconstructed from the summary table:

    torch 2.13.0+cu130 vllm 0.31.0 gpus 8
    

    GPU_RESULT {"case": "ordered_baseline", "text": "A=red, B=blue", "token_ids": [35, 31, 1157, 14, 406, 31, 27602, 1]}
    GPU_RESULT {"case": "reversed_baseline", "text": "A=blue, B=red", "token_ids": [35, 31, 27602, 14, 406, 31, 1157, 1]}
    GPU_RESULT {"case": "reversed_patched", "text": "A=red, B=blue", "token_ids": [35, 31, 1157, 14, 406, 31, 27602, 1]}
    GPU_RESULT {"case": "developer_baseline", "error_type": "AssertionError", "error": "Failed to apply prompt replacement for mm_items['image'][0]"}
    GPU_RESULT {"case": "developer_patched", "text": "We need answer user says \"Reply OK.\" So just reply OK. Need comply. final maybe \"OK\".</think>OK", "token_ids": [2581, 1309, 3287, 3967, 4230, 582, 19905, 20370, 2148, 3016, 1438, 20430, 20370, 16, 21017, 27233, 16, 4087, 10796, 582, 11932, 3305, 128822, 11932, 1]}
    GPU_VALIDATION_PASSED
    

    The log subsequently contains shutdown warnings about force-killing the remaining EngineCore and one leaked shared-memory object. The pass marker covers the inference assertions above, not a warning-free shutdown.

    </details>

    These checks verify the two rendering regressions, not performance or general model accuracy.

    Details

    The encoder already decides which content survives and in what order it renders. Image indices now follow those same merge/sort/drop operations; the renderer does not duplicate those policies or scan text for image markers. The V4.1 renderer applies the order to media and UUIDs together. Existing prompt fixtures and rendering parity checks retain the encoded text.

    Duplicate checks covered open PRs, the related Rust PR's changed files and discussion, and V4.1 frontend searches. #56366 changes Rust files only; #60522 only moves Python imports and does not fix this behavior. No matching Python fix was found.

    ---

    <details>
    <summary> Pull Request Checklist </summary>

  • I used vLLM's /pr-checklist skill. (Mandatory for agents, optional for humans).

  • AI assistance was used during the creation of this PR.

  • Design Fit: Minimizes impact on core components, reuses existing functionality, and justifies added complexity.

  • Testing and Validation: CPU reproduction, 79 regression tests, and full-model GPU before/after checks passed.

  • Code Quality and Style: Keeps code and comments clear and concise, and updates relevant documentation and examples.

  • Pull Request Contents: Includes a brief summary and relevant links, supports claims with evidence, explains root causes and implementation trade-offs, and follows the contributing guide.

  • </details>

    Diff: 177 lines (+159 / -18) across 5 files Reviewer: lesj0610 Review duration: 14331m
    All Vouch review confidence checks passed
    Residual risk 0.04 = Change Risk (0.40) × (1 − Review Confidence (0.90)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.40 · 177 lines diff across 5 files
    0.40
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.97 · 5 substantive comment(s)
    0.97
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    89%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.310
    Real PR Conversation Timeline
    24 items
    claude[bot] claude[bot] commented on Oct 09, 2026 07:36 UTC
    Reviewer

    Claude Code Review

    This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

    Copilot Copilot commented on code on Oct 09, 2026 08:04 UTC
    Code Review
    vllm/renderers/deepseek_v4.py:1
    @@ -34,7 +34,23 @@ def __init__(
             )
     
         def _apply_chat_template(self, *args, **kwargs):
    -        return self.get_tokenizer().apply_chat_template(*args, **kwargs)
    +        return self.get_tokenizer().apply_chat_template(*args, **kwargs), None
    +
    +    def _build_prompt(self, rendered, mm_data, mm_uuids) -> DictPrompt:
    +        prompt_raw, image_order = rendered
    +        prompt = parse_dec_only_prompt(prompt_raw)

    _build_prompt unpacks rendered as (prompt_raw, image_order), and render_messages_async now passes _apply_chat_template_async(...) directly into _build_prompt. Since this PR only updates _apply_chat_template to return a tuple, you should ensure _apply_chat_template_async also returns the same tuple shape; otherwise async rendering will fail at runtime with an unpacking/type error (and V4.1 may silently skip image reordering in async paths). A concrete fix is to override _apply_chat_template_async in these renderers to delegate to the (tuple-returning) _apply_chat_template via an executor/make_async, so both sync and async share the same contract.

    Copilot Copilot commented on code on Oct 09, 2026 08:04 UTC
    Code Review
    vllm/renderers/deepseek_v4.py:1
    @@ -79,16 +89,18 @@ async def render_messages_async(
                 mm_processor_kwargs=params.mm_processor_kwargs,
             )
     
    -        prompt_raw = await self._apply_chat_template_async(
    +        rendered = await self._apply_chat_template_async(
                 conversation=conversation,
                 messages=messages,
                 **params.get_apply_chat_template_kwargs(),
             )
     
    -        prompt = parse_dec_only_prompt(prompt_raw)
    -        if mm_data is not None:
    -            prompt["multi_modal_data"] = mm_data
    -        if mm_uuids is not None:
    -            prompt["multi_modal_uuids"] = mm_uuids
    +        return conversation, self._build_prompt(rendered, mm_data, mm_uuids)

    _build_prompt unpacks rendered as (prompt_raw, image_order), and render_messages_async now passes _apply_chat_template_async(...) directly into _build_prompt. Since this PR only updates _apply_chat_template to return a tuple, you should ensure _apply_chat_template_async also returns the same tuple shape; otherwise async rendering will fail at runtime with an unpacking/type error (and V4.1 may silently skip image reordering in async paths). A concrete fix is to override _apply_chat_template_async in these renderers to delegate to the (tuple-returning) _apply_chat_template via an executor/make_async, so both sync and async share the same contract.

    Copilot Copilot commented on code on Oct 09, 2026 08:04 UTC
    Code Review
    vllm/renderers/deepseek_v4.py:1
    @@ -34,7 +34,23 @@ def __init__(
             )
     
         def _apply_chat_template(self, *args, **kwargs):
    -        return self.get_tokenizer().apply_chat_template(*args, **kwargs)
    +        return self.get_tokenizer().apply_chat_template(*args, **kwargs), None
    +
    +    def _build_prompt(self, rendered, mm_data, mm_uuids) -> DictPrompt:
    +        prompt_raw, image_order = rendered
    +        prompt = parse_dec_only_prompt(prompt_raw)

    parse_dec_only_prompt expects a string prompt, but prompt_raw comes from tokenizer.apply_chat_template(...), which can also return token IDs (e.g., when tokenize=True). With the new tuple-based plumbing, passing a tokenized result would break here. If render_messages(*) is intended to always operate on raw prompts, consider enforcing tokenize=False at the renderer boundary (e.g., override/strip the kwarg) or add a clear error when prompt_raw is not str to avoid hard-to-debug failures.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Oct 09, 2026 08:04 UTC
    Reviewer

    [!WARNING]

    Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

    <!-- ccr-overview-v2 -->

    Copilot review overview

    <details open>
    <summary><strong>3 open findings</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> [_build_prompt unpacks rendered as (prompt_raw, image_order), and render_messages_async now…](#discussion_r4227991380) · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> [_build_prompt unpacks rendered as (prompt_raw, image_order), and render_messages_async now…](#discussion_r4227991421) · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [parse_dec_only_prompt expects a string prompt, but prompt_raw comes from…](#discussion_r4227991446) · New

  • </details>

    <details>
    <summary><strong>What changed in this PR</strong></summary>

    Fixes DeepSeek V4.1 multimodal rendering so image attachments remain aligned with the final encoded prompt after tool-result reordering and thinking/developer-content dropping.

    Changes:

  • Track per-image source indices during message normalization and propagate them through V4.1 encoding/merging.

  • Accumulate the final rendered image order during encoding and apply it to both multi_modal_data["image"] and multi_modal_uuids["image"].

  • Register a dedicated DeepseekV41Renderer and add regression tests for tool-result reorder + dropped developer-only images.
  • | File | Description |
    | ---- | ----------- |
    | vllm/​tokenizers/​deepseek_v41_encoding.py | Propagates and collects _image_indices during preprocessing/rendering to compute a final image_order. |
    | vllm/​tokenizers/​deepseek_v41.py | Assigns source image indices during normalization and threads image_order through apply_chat_template. |
    | vllm/​renderers/​registry.py | Routes deepseek_v41 to the new DeepseekV41Renderer. |
    | vllm/​renderers/​deepseek_v4.py | Adds prompt-building step that reorders/prunes image mm payloads based on image_order; introduces DeepseekV41Renderer. |
    | tests/​tokenizers_/​test_deepseek_v41.py | Adds sync+async regression coverage for tool image reordering and dropped developer-only images. |
    </details>

    🧠 Review effort: Lite

    ---

    💡 <a href="/vllm-project/vllm/new/main?filename=.github/skills/code-review/SKILL.md" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Add a code-review agent skill</a> or configure MCP servers for context-aware, tailored reviews. <a href="https://docs.github.com/copilot/how-tos/use-copilot-agents/request-a-code-review/use-code-review?tool=webui#mcp-servers-and-agent-skills" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Learn more in the docs.</a>

    xijiaat xijiaat commented on code on Oct 09, 2026 08:56 UTC
    Code Review
    vllm/renderers/deepseek_v4.py:1
    @@ -34,7 +34,23 @@ def __init__(
             )
     
         def _apply_chat_template(self, *args, **kwargs):
    -        return self.get_tokenizer().apply_chat_template(*args, **kwargs)
    +        return self.get_tokenizer().apply_chat_template(*args, **kwargs), None
    +
    +    def _build_prompt(self, rendered, mm_data, mm_uuids) -> DictPrompt:
    +        prompt_raw, image_order = rendered
    +        prompt = parse_dec_only_prompt(prompt_raw)

    DeepseekV4Renderer.__init__ already initializes the async wrapper with:

    self._apply_chat_template_async = make_async(
        self._apply_chat_template, executor=self._executor
    )
    

    This binds the overridden method on DeepseekV41Renderer as well, so both sync and async paths return (prompt_raw, image_order). A separate async override should therefore not be necessary.

    Constructor and renderer implementation at the current PR head.

    xijiaat xijiaat commented on code on Oct 09, 2026 08:56 UTC
    Code Review
    vllm/renderers/deepseek_v4.py:1
    @@ -79,16 +89,18 @@ async def render_messages_async(
                 mm_processor_kwargs=params.mm_processor_kwargs,
             )
     
    -        prompt_raw = await self._apply_chat_template_async(
    +        rendered = await self._apply_chat_template_async(
                 conversation=conversation,
                 messages=messages,
                 **params.get_apply_chat_template_kwargs(),
             )
     
    -        prompt = parse_dec_only_prompt(prompt_raw)
    -        if mm_data is not None:
    -            prompt["multi_modal_data"] = mm_data
    -        if mm_uuids is not None:
    -            prompt["multi_modal_uuids"] = mm_uuids
    +        return conversation, self._build_prompt(rendered, mm_data, mm_uuids)

    This is the same async-contract concern as the earlier comment; the existing constructor already wraps self._apply_chat_template with make_async, including the V4.1 override. The awaited result is therefore the same (prompt_raw, image_order) tuple consumed by _build_prompt.

    I've added the constructor details and source reference in this reply.

    xijiaat xijiaat commented on code on Oct 09, 2026 08:57 UTC
    Code Review
    vllm/renderers/deepseek_v4.py:1
    @@ -34,7 +34,23 @@ def __init__(
             )
     
         def _apply_chat_template(self, *args, **kwargs):
    -        return self.get_tokenizer().apply_chat_template(*args, **kwargs)
    +        return self.get_tokenizer().apply_chat_template(*args, **kwargs), None
    +
    +    def _build_prompt(self, rendered, mm_data, mm_uuids) -> DictPrompt:
    +        prompt_raw, image_order = rendered
    +        prompt = parse_dec_only_prompt(prompt_raw)

    parse_dec_only_prompt supports both strings and token ID lists. Its list branch validates that the elements are integers and returns TokensPrompt(prompt_token_ids=prompt).

    _build_prompt unpacks the tuple before calling this helper, so tokenize=True remains supported. Forcing tokenize=False would unnecessarily restrict the existing input contract.

    The parser's string and list branches at the current PR head.

    xijiaat xijiaat commented on Oct 10, 2026 10:18 UTC
    Author

    Hi @chaunceyjiang, when you have a chance, would you mind taking a look at this fix? The PR description includes the reproduction and CPU/H20 validation results, and I've replied to the automated review comments with the relevant source references.

    Please let me know if any additional changes or tests would be helpful. I understand reviews take time and appreciate your help. Thank you!

    lesj0610 lesj0610 approved these changes on Oct 10, 2026 10:42 UTC
    Approved Reviewer

    Checked the image ordering and async rendering paths. Image data and UUIDs follow the rendered order, and the async wrapper uses the overridden _apply_chat_template.

    xijiaat xijiaat commented on Oct 12, 2026 05:57 UTC
    Author

    LGTM. The sync and async tests pass for reordered tool images and dropped developer images. Image data and UUIDs follow the same rendered order; V4 keeps its existing ordering.

    thanks for the reveiw!!!

    chaunceyjiang chaunceyjiang commented on Oct 16, 2026 10:01 UTC
    Reviewer

    Could you paste some actual test results into the PR description?

    xijiaat xijiaat commented on Oct 17, 2026 16:31 UTC
    Author

    Thanks @chaunceyjiang. I've added the actual CPU and full-model H20 output to the PR description: the four baseline regression failures, the patched 79 passed result, and all five GPU case results with generated text and token IDs.

    The reversed-image case changes from A=blue, B=red to the correct A=red, B=blue; the dropped-developer-image case changes from an assertion failure to a successful OK response. These are the October 9 results, with the tested runtime and scope stated explicitly; the four production files are unchanged at the current PR head. Thank you for reviewing!

    robertgshaw2-redhat robertgshaw2-redhat commented on Oct 17, 2026 22:40 UTC
    Contributor

    Merged main and fixed a test import.

    Before: on current main, tests/tokenizers_/test_deepseek_v41.py failed to load (ModuleNotFoundError: vllm.entrypoints.chat_utils), because chat_utils moved to vllm/renderers/. That took down every V4.1 tokenizer test, not just the new ones.

    After: the import is now from vllm.renderers.chat_utils import BaseMultiModalItemTracker. pytest tests/tokenizers_/test_deepseek_v41.py tests/tokenizers_/test_deepseek_v4.py: 79 passed.

    No other changes.

    github-actions[bot] github-actions[bot] commented on Oct 17, 2026 22:50 UTC
    Bot

    ✅ @xijiaat, CI is now available for this PR.

  • /ci run starts upstream CI; /amd-ci run starts AMD CI only.

  • Run commands test your branch with every commit currently on its upstream target branch. If it is behind, the bot merges the target branch into it first (pull before pushing again). Append --allow-stale to a run command to test an outdated branch as is, at your own risk.

  • /ci retry retries failed jobs in the CI build for the current PR head. If the current head has no CI build, it starts a new CI build for the current head containing only jobs that failed in the latest earlier CI build for this PR.

  • /amd-ci retry retries failed jobs in AMD CI for the current PR head. Use /amd-ci run when the current head has no AMD CI build.

  • /ci cancel cancels scheduled or running CI builds for this PR branch; /amd-ci cancel does the same for AMD CI only.
  • <!-- vllm-ci-authorized -->

    robertgshaw2-redhat robertgshaw2-redhat commented on Oct 17, 2026 22:50 UTC
    Contributor

    /ci run

    github-actions[bot] github-actions[bot] commented on Oct 17, 2026 22:50 UTC
    Bot

    ✅ Triggered Buildkite CI #95629 for commit d8fd027c7f27.

    robertgshaw2-redhat robertgshaw2-redhat commented on Oct 17, 2026 22:51 UTC
    Contributor

    What this fixes: the assistant calls two tools, red then blue, and the results come back in the other order, each with an image.

    [{"role": "assistant", "tool_calls": [call("red"), call("blue")]},
     {"role": "tool", "tool_call_id": "blue", "content": [text("blue"), image("blue")]},
     {"role": "tool", "tool_call_id": "red",  "content": [text("red"),  image("red")]}]
    

    The encoder sorts tool results into call order, so the prompt reads <tool_result>red <image> then <tool_result>blue <image>.

    Broken (main): images are passed in message order, [blue, red], so each result gets the other result's image.

    Fixed (this PR): images follow the prompt order, [red, blue].

    Verified with test_tool_images_follow_rendered_order: it fails on main (['blue', 'red'] != ['red', 'blue']) and passes here.

    robertgshaw2-redhat robertgshaw2-redhat commented on Oct 17, 2026 22:54 UTC
    Contributor

    The official DeepSeek encoder had this bug too and fixed it on 2026-10-16 (314113f, also in the 1017 release). It now sorts tool results before collecting images, so on the case above it returns ['red.png', 'blue.png'], the same as this PR.

    The approach differs: the reference encoder collects the images itself and returns them in prompt order, while vLLM collects them earlier, so this PR records each image's index and reorders afterwards.

    xijiaat xijiaat commented on Oct 18, 2026 02:12 UTC
    Author

    /ci run

    github-actions[bot] github-actions[bot] commented on Oct 18, 2026 02:13 UTC
    Bot

    ✅ Triggered Buildkite CI #95647 for commit 64b90c287529.

    xijiaat xijiaat commented on Oct 18, 2026 14:07 UTC
    Author

    Thanks @robertgshaw2-redhat for merging main, fixing the test import, validating the regression, and kicking off CI. The explanation and comparison with the official encoder were really helpful. I appreciate your time and help getting this fix reviewed!

    chaunceyjiang chaunceyjiang approved these changes on Oct 19, 2026 05:59 UTC
    Approved Reviewer

    Thanks~

    Reviewers
    Assignees
    xijiaat xijiaat
    Labels
    risk: low confidence: 90.0% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 39.9% (MEDIUM) · Higher = larger blast radius
    39.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 90.0% · Lower = rushed or shallow review
    90.0%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 4% · Safe to merge
    4%