Skip to content

[None][fix] Fix chat request bug for modality model#11179

Open
Lihui-Gu wants to merge 1 commit intoNVIDIA:mainfrom
Lihui-Gu:dev_qwen3_vl
Open

[None][fix] Fix chat request bug for modality model#11179
Lihui-Gu wants to merge 1 commit intoNVIDIA:mainfrom
Lihui-Gu:dev_qwen3_vl

Conversation

@Lihui-Gu
Copy link
Copy Markdown

@Lihui-Gu Lihui-Gu commented Feb 2, 2026

Summary by CodeRabbit

  • Bug Fixes
    • Fixed position encoding computation in model inference for improved accuracy.
    • Corrected multimodal placeholder counting in chat messages to properly handle multiple media items per message.

Description

Test Coverage

PR Checklist

Please review the following before submitting your PR:

  • PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.

  • PR Follows TRT-LLM CODING GUIDELINES to the best of your knowledge.

  • Test cases are provided for new code paths (see test instructions)

  • Any new dependencies have been scanned for license and vulnerabilities

  • CODEOWNERS updated if ownership changes

  • Documentation updated as needed

  • Update tava architecture diagram if there is a significant design change in PR.

  • The reviewers assigned automatically/manually are appropriate for the PR.

  • Please check this after reviewing the above items as appropriate for this PR.

GitHub Bot Help

/bot [-h] ['run', 'kill', 'skip', 'reuse-pipeline'] ...

Provide a user friendly way for developers to interact with a Jenkins server.

Run /bot [-h|--help] to print this help message.

See details below for each supported subcommand.

Details

run [--reuse-test (optional)pipeline-id --disable-fail-fast --skip-test --stage-list "A10-PyTorch-1, xxx" --gpu-type "A30, H100_PCIe" --test-backend "pytorch, cpp" --add-multi-gpu-test --only-multi-gpu-test --disable-multi-gpu-test --post-merge --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" --detailed-log --debug(experimental)]

Launch build/test pipelines. All previously running jobs will be killed.

--reuse-test (optional)pipeline-id (OPTIONAL) : Allow the new pipeline to reuse build artifacts and skip successful test stages from a specified pipeline or the last pipeline if no pipeline-id is indicated. If the Git commit ID has changed, this option will be always ignored. The DEFAULT behavior of the bot is to reuse build artifacts and successful test results from the last pipeline.

--disable-reuse-test (OPTIONAL) : Explicitly prevent the pipeline from reusing build artifacts and skipping successful test stages from a previous pipeline. Ensure that all builds and tests are run regardless of previous successes.

--disable-fail-fast (OPTIONAL) : Disable fail fast on build/tests/infra failures.

--skip-test (OPTIONAL) : Skip all test stages, but still run build stages, package stages and sanity check stages. Note: Does NOT update GitHub check status.

--stage-list "A10-PyTorch-1, xxx" (OPTIONAL) : Only run the specified test stages. Examples: "A10-PyTorch-1, xxx". Note: Does NOT update GitHub check status.

--gpu-type "A30, H100_PCIe" (OPTIONAL) : Only run the test stages on the specified GPU types. Examples: "A30, H100_PCIe". Note: Does NOT update GitHub check status.

--test-backend "pytorch, cpp" (OPTIONAL) : Skip test stages which don't match the specified backends. Only support [pytorch, cpp, tensorrt, triton]. Examples: "pytorch, cpp" (does not run test stages with tensorrt or triton backend). Note: Does NOT update GitHub pipeline status.

--only-multi-gpu-test (OPTIONAL) : Only run the multi-GPU tests. Note: Does NOT update GitHub check status.

--disable-multi-gpu-test (OPTIONAL) : Disable the multi-GPU tests. Note: Does NOT update GitHub check status.

--add-multi-gpu-test (OPTIONAL) : Force run the multi-GPU tests in addition to running L0 pre-merge pipeline.

--post-merge (OPTIONAL) : Run the L0 post-merge pipeline instead of the ordinary L0 pre-merge pipeline.

--extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" (OPTIONAL) : Run the ordinary L0 pre-merge pipeline and specified test stages. Examples: --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx".

--detailed-log (OPTIONAL) : Enable flushing out all logs to the Jenkins console. This will significantly increase the log volume and may slow down the job.

--debug (OPTIONAL) : Experimental feature. Enable access to the CI container for debugging purpose. Note: Specify exactly one stage in the stage-list parameter to access the appropriate container environment. Note: Does NOT update GitHub check status.

For guidance on mapping tests to stage names, see docs/source/reference/ci-overview.md
and the scripts/test_to_stage_mapping.py helper.

kill

kill

Kill all running builds associated with pull request.

skip

skip --comment COMMENT

Skip testing for latest commit on pull request. --comment "Reason for skipping build/test" is required. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.

reuse-pipeline

reuse-pipeline

Reuse a previous pipeline to validate current commit. This action will also kill all currently running builds associated with the pull request. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.

@Lihui-Gu Lihui-Gu requested a review from a team as a code owner February 2, 2026 07:10
@Lihui-Gu Lihui-Gu requested a review from joyang-nv February 2, 2026 07:10
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Feb 2, 2026

📝 Walkthrough

Walkthrough

Two files are modified with targeted logic adjustments: one updates mrope position ID slicing computation in model execution, and the other refactors multimodal placeholder count tracking in chat message parsing.

Changes

Cohort / File(s) Summary
Model Execution
tensorrt_llm/_torch/pyexecutor/model_engine.py
Modified previous_seq_slots_device to compute total_num_mtokens from concatenated mrope_position_ids and use this value for slice length when copying to mrope_position_ids_cuda, replacing previous total_num_tokens usage.
Chat Message Parsing
tensorrt_llm/serve/chat_utils.py
Introduced mm_placeholder_count_value tracking variable in parse_chat_messages_coroutines to count multimodal data items per message, then conditionally update the first key of placeholder count mapping with this per-message count.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description only contains the template with commented sections but no actual implementation details, rationale, or test coverage information filled in. Fill in the Description section explaining the chat request bug and its fix, and add Test Coverage section with relevant test names or procedures.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the fix being applied to a specific feature area (chat request handling for multimodal models).
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tensorrt_llm/serve/chat_utils.py (1)

283-296: ⚠️ Potential issue | 🟠 Major

Logic error: Mixed modalities produce incorrect per-message placeholder counts

The approach of overwriting only the first key in mm_placeholder_count (line 292) produces incorrect results when a message contains multiple modality types.

The tracker maintains cumulative counts across all messages. When placeholder_counts() is called at line 290, it returns the cumulative state. The code then overwrites only the first dictionary key with the per-message count, leaving other modality keys with cumulative values.

For a message with both images and videos:

  • After add_data() calls: tracker has {"<image>": N, "<video>": M} (cumulative)
  • mm_placeholder_count_value = 2 (per-message total)
  • Line 292 overwrites first key: {"<image>": 2, "<video>": M} ← incorrect; <video> retains cumulative count
  • Expected: {"<image>": 1, "<video>": 1} (per-message only)

This breaks downstream processing for models supporting mixed modalities (like NemotronH_Nano_VL_V2), which expects per-modality counts per message.

The placeholder count dict appended to the list at line 296 should contain only the counts for the current message. Either track per-message counts separately from the cumulative tracker, or reset/clear the tracker after each message.

🧹 Nitpick comments (1)
tensorrt_llm/serve/chat_utils.py (1)

291-292: Consider using StopIteration-safe access for dict first key.

While mm_placeholder_count should never be empty when mm_placeholder_count_value > 0 (since add_data was called), using next(iter(...)) without error handling could raise StopIteration in unexpected edge cases.

A more defensive pattern:

if mm_placeholder_count_value and mm_placeholder_count:
    first_key = next(iter(mm_placeholder_count))
    mm_placeholder_count[first_key] = mm_placeholder_count_value

Or use next(iter(...), None) with a subsequent check.

Signed-off-by: Lihui-Gu <glh9803@outlook.com>
@svc-trtllm-gh-bot svc-trtllm-gh-bot added the Community want to contribute PRs initiated from Community label Feb 2, 2026
@Lihui-Gu Lihui-Gu closed this Feb 2, 2026
@Lihui-Gu Lihui-Gu reopened this Feb 2, 2026
Comment thread tensorrt_llm/_torch/pyexecutor/model_engine.py
Comment thread tensorrt_llm/serve/chat_utils.py
Copy link
Copy Markdown
Collaborator

@2ez4bz 2ez4bz left a comment

Choose a reason for hiding this comment

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

Thanks for the PR! Please see my comment re the 2nd bug - I tested my suggestion with the following

from unittest.mock import MagicMock

import pytest
from transformers import AutoConfig

from tensorrt_llm.inputs.registry import MULTIMODAL_PLACEHOLDER_REGISTRY
from tensorrt_llm.serve.chat_utils import parse_chat_messages_coroutines

_MODEL_TYPE = "qwen3_vl"
_IMG_PLACEHOLDER = MULTIMODAL_PLACEHOLDER_REGISTRY.get_placeholder(
    model_type=_MODEL_TYPE, modality="image"
)
_VIDEO_PLACEHOLDER = MULTIMODAL_PLACEHOLDER_REGISTRY.get_placeholder(
    model_type=_MODEL_TYPE, modality="video"
)


@pytest.mark.parametrize(
    "messages, expected_mm_placeholder_counts",
    [
        # Case #1: 2 messages with 1 image each, 3rd message is text-only.
        (
            [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "What's in this image?"},
                        {"type": "image_url", "image_url": {"url": "foo"}},
                    ],
                },
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "And this one?"},
                        {"type": "image_url", "image_url": {"url": "bar"}},
                    ],
                },
                {"role": "user", "content": "No image here, just text"},
            ],
            [{_IMG_PLACEHOLDER: 1}, {_IMG_PLACEHOLDER: 1}, {}],
        ),
        # Case #2: first and last message have one image each, 2nd is text-only.
        (
            [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "What's in this image?"},
                        {"type": "image_url", "image_url": {"url": "foo"}},
                    ],
                },
                {"role": "user", "content": "No image here, just text"},
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "And this one?"},
                        {"type": "image_url", "image_url": {"url": "bar"}},
                    ],
                },
            ],
            [{_IMG_PLACEHOLDER: 1}, {}, {_IMG_PLACEHOLDER: 1}],
        ),
        # Case #3: 1st image with several images, 2nd without any, 3rd with a video.
        (
            [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "What do these images have in common?"},
                        {"type": "image_url", "image_url": {"url": "foo1"}},
                        {"type": "image_url", "image_url": {"url": "foo2"}},
                        {"type": "image_url", "image_url": {"url": "foo3"}},
                    ],
                },
                {"role": "user", "content": "No image here, just text"},
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "Describe the image and the video."},
                        {"type": "image_url", "image_url": {"url": "bar"}},
                        {"type": "video_url", "video_url": {"url": "baz"}},
                    ],
                },
            ],
            [{_IMG_PLACEHOLDER: 3}, {}, {_IMG_PLACEHOLDER: 1, _VIDEO_PLACEHOLDER: 1}],
        ),
        # Case #4: 1st image with image and video, 2nd with several videos, last is text-only.
        (
            [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "Describe the image and the video."},
                        {"type": "image_url", "image_url": {"url": "bar"}},
                        {"type": "video_url", "video_url": {"url": "baz"}},
                    ],
                },
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "What do these videos have in common?"},
                        {"type": "video_url", "video_url": {"url": "foo1"}},
                        {"type": "video_url", "video_url": {"url": "foo2"}},
                        {"type": "video_url", "video_url": {"url": "foo3"}},
                    ],
                },
                {"role": "user", "content": "No image here, just text"},
            ],
            [{_IMG_PLACEHOLDER: 1, _VIDEO_PLACEHOLDER: 1}, {_VIDEO_PLACEHOLDER: 3}, {}],
        ),
    ],
)
def test_image_pad_accumulation_bug(messages, expected_mm_placeholder_counts):
    mock_config = MagicMock(spec=AutoConfig)
    mock_config.model_type = _MODEL_TYPE

    _, _, mm_placeholder_counts = parse_chat_messages_coroutines(messages, mock_config, None)

    assert mm_placeholder_counts == expected_mm_placeholder_counts

# so that we only replace position_ids with mrope_position_ids when it is not a dummy request and for models who is using mrope.
mrope_position_ids = torch.cat(mrope_position_ids, dim=-1)
total_num_mtokens = mrope_position_ids.shape[-1]
# assert mrope_position_ids.shape[-1] >= total_num_tokens
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit: remove.

mm_placeholder_count = mm_data_tracker.placeholder_counts()
if mm_placeholder_count:
if mm_placeholder_count_value:
mm_placeholder_count[next(iter(mm_placeholder_count))] = mm_placeholder_count_value
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I could be missing something here, but I think there are still 2 issues with this code:

  1. there could be several modalities in a given message, but this line is only updating the first key returned by next(iter(mm_placeholder_count)).
  2. it does not update it when mm_placeholder_count_value > 0, which means messages with no multimodal data would get the cumulative sum of the 1st key's placeholder counts here instead of 0.

Would something like this work? I also think it is slightly easier to follow:

diff --git a/tensorrt_llm/inputs/utils.py b/tensorrt_llm/inputs/utils.py
index 0dc09547b3..b1165ac34e 100644
--- a/tensorrt_llm/inputs/utils.py
+++ b/tensorrt_llm/inputs/utils.py
@@ -500,7 +500,7 @@ class MultimodalDataTracker:
                  media_type: str,
                  data: Union[Coroutine, Any],
                  *,
-                 is_embedding: bool = False):
+                 is_embedding: bool = False) -> Optional[str]:
         current_count = len(self._data[media_type]) + len(
             self._embeddings[media_type]) + 1
         placeholder = retrieve_multimodal_placeholder(self._model_type,
@@ -509,6 +509,7 @@ class MultimodalDataTracker:
          if is_embedding else self._data)[media_type].append(data)
         if placeholder:
             self._placeholder_counts[placeholder] += 1
+        return placeholder
 
     def placeholder_counts(self) -> Dict[str, int]:
         """Get the count of multimodal placeholders."""
diff --git a/tensorrt_llm/serve/chat_utils.py b/tensorrt_llm/serve/chat_utils.py
index e08caadaaf..283d69ac3a 100644
--- a/tensorrt_llm/serve/chat_utils.py
+++ b/tensorrt_llm/serve/chat_utils.py
@@ -277,21 +277,25 @@ def parse_chat_messages_coroutines(
     mm_placeholder_counts = []
     mm_data_tracker = MultimodalDataTracker(model_config.model_type,
                                             multimodal_server_config)
-
     for msg in messages:
         parsed_msg = parse_chat_message_content(msg, mm_data_tracker)
         conversation.append(parsed_msg)
+
+        # Track placeholders added for this message only
+        msg_placeholder_counts = {}
         if parsed_msg["media"]:
             for mdata in parsed_msg["media"]:
-                mm_data_tracker.add_data(mdata["modality"],
-                                         mdata["data"],
-                                         is_embedding=mdata["is_embedding"])
-        mm_placeholder_count = mm_data_tracker.placeholder_counts()
-        if mm_placeholder_count:
+                placeholder = mm_data_tracker.add_data(mdata["modality"],
+                                                       mdata["data"],
+                                                       is_embedding=mdata["is_embedding"])
+                if placeholder:
+                    msg_placeholder_counts[placeholder] = msg_placeholder_counts.get(placeholder, 0) + 1
+
+        if msg_placeholder_counts:
             parsed_msg["content"] = add_multimodal_placeholders(
                 model_config.model_type, parsed_msg["content"],
-                mm_placeholder_count)
-        mm_placeholder_counts.append(mm_placeholder_count)
+                msg_placeholder_counts)
+        mm_placeholder_counts.append(msg_placeholder_counts)
 
     return conversation, mm_data_tracker.retrieve_all_async(
     ), mm_placeholder_counts

Copy link
Copy Markdown
Collaborator

@litaotju litaotju left a comment

Choose a reason for hiding this comment

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

LGTM with nit — both fixes are correct. Minor concern: next(iter(mm_placeholder_count)) in chat_utils.py assumes single modality. Fine for now but could break if multi-modality (e.g. image+audio) is added later. Consider a TODO comment. AI-reviewed on behalf of Tao Li.

Copy link
Copy Markdown
Collaborator

@2ez4bz 2ez4bz left a comment

Choose a reason for hiding this comment

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

@litaotju I believe I've fixed the multimodal placeholder bug in #11461 in a more general way. For the issue in tensorrt_llm/_torch/pyexecutor/model_engine.py, I have asked for more details on the issue thread itself, since:

  1. I do not understand how this manifests itself / need a repro (from my understanding, this only affects models that use mrope, which are Qwen*-VL models, which populate mrope positions for both MM requests and text-only requests)
  2. Even supposing we have a repro, I don't think this fix is correct, as it assumes MM requests precede text-only requests, when in fact they could be interleaved.

I am "requesting changes" to block this PR from merging in its current state.

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

Labels

Community want to contribute PRs initiated from Community Multimodal Label for issues & PRs regarding Multimodal related objects

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants