[None][fix] Fix chat request bug for modality model#11179
[None][fix] Fix chat request bug for modality model#11179Lihui-Gu wants to merge 1 commit intoNVIDIA:mainfrom
Conversation
📝 WalkthroughWalkthroughTwo 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
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes 🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
228119f to
a405252
Compare
There was a problem hiding this comment.
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 | 🟠 MajorLogic 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 usingStopIteration-safe access for dict first key.While
mm_placeholder_countshould never be empty whenmm_placeholder_count_value > 0(sinceadd_datawas called), usingnext(iter(...))without error handling could raiseStopIterationin 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_valueOr use
next(iter(...), None)with a subsequent check.
Signed-off-by: Lihui-Gu <glh9803@outlook.com>
a405252 to
edd712c
Compare
2ez4bz
left a comment
There was a problem hiding this comment.
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 |
| 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 |
There was a problem hiding this comment.
I could be missing something here, but I think there are still 2 issues with this code:
- 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)). - 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
litaotju
left a comment
There was a problem hiding this comment.
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.
2ez4bz
left a comment
There was a problem hiding this comment.
@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:
- 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)
- 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.
Summary by CodeRabbit
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 thestage-listparameter 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.mdand the
scripts/test_to_stage_mapping.pyhelper.kill
killKill all running builds associated with pull request.
skip
skip --comment COMMENTSkip 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-pipelineReuse 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.