-
Notifications
You must be signed in to change notification settings - Fork 1.9k
[TRTLLM-7442][model] Remove unnecessary D2H copies #7273
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
📝 WalkthroughWalkthroughConvert/propagate image_sizes between tensor and Python list in Mistral3 input/forward paths and ensure PixtralVisionModel's position ids are created on the same device as pixel_values to avoid host↔device copies. No public API signatures changed. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor C as Caller
participant IP as Mistral3InputProcessor
participant M as Mistral3VLM
participant B as _batch_pixel_values
participant V as VisionBackbone
C->>IP: prepare(multimodal_inputs{pixel_values, image_sizes (tensor)})
IP-->>C: processed{pixel_values, image_sizes (list)}
C->>M: forward(processed)
note right of M: convert image_sizes lists -> torch.tensor before batching
M->>B: batch(pixel_values, image_sizes: List[torch.Tensor])
B-->>M: batched_pixel_values (Tensor)
M->>V: extract_features(batched_pixel_values, image_sizes)
V-->>M: image_features
M-->>C: outputs
sequenceDiagram
autonumber
actor C as Caller
participant P as PixtralVisionModel
participant E as PatchEmbed/PosEnc
C->>P: forward(pixel_values, image_sizes)
rect rgba(220,240,255,0.5)
note right of P: create position ids on same device as pixel_values
P->>P: with torch.device(pixel_values.device): position_ids_in_meshgrid(...)
end
P->>E: compute embeddings (uses position_ids)
E-->>P: vision_features
P-->>C: vision_features
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. 📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro 💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration. 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
🔇 Additional comments (1)
✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
|
/bot run |
|
PR_Github #16610 [ run ] triggered by Bot |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
tensorrt_llm/_torch/models/modeling_pixtral.py (1)
1-1: Add NVIDIA copyright header.Repository guidelines require the NVIDIA copyright header on all source files for 2025.
Apply at file top:
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.tensorrt_llm/_torch/models/modeling_mistral.py (1)
1-1: Add NVIDIA copyright header.Please prepend the required 2025 NVIDIA header.
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
🧹 Nitpick comments (4)
tensorrt_llm/_torch/models/modeling_mistral.py (4)
445-456: Type alignment and shape sanity for image_features.
- Pass-through of List[List[int]] is consistent; however, projector/patch-merger still annotate image_sizes as torch.Tensor. Update their signatures for consistency.
- Also, squeeze(0) is likely a no-op because PixtralVisionModel returns [tokens, hidden_size]; confirm shapes.
- image_features = self._multi_modal_projector(image_outputs.squeeze(0), - image_sizes) + image_features = self._multi_modal_projector(image_outputs, image_sizes)And update downstream type hints (see comments below).
466-501: Compute max shape without constructing a torch tensor; avoid extra CPU tensor materialization.Pure-Python max avoids an intermediate tensor and keeps intent clear.
- image_sizes_tensor = torch.tensor(image_sizes) - max_shape = image_sizes_tensor.max(dim=0).values.tolist() + max_h = max(h for h, w in image_sizes) + max_w = max(w for h, w in image_sizes) @@ - padding=[ - 0, 0, max_shape[1] - image.shape[-1], - max_shape[0] - image.shape[-2] - ], + padding=[0, 0, max_w - image.shape[-1], max_h - image.shape[-2]], @@ - return torch.cat(pixel_values) + return torch.cat(pixel_values)Please confirm torchvision v2 F.pad handles batched tensors [B, C, H, W] in your deployment (it should); otherwise we need to pad per-image then stack.
598-605: Update type hints to match List[List[int]] across projector.Keep annotations consistent end-to-end.
- def forward(self, image_features: torch.Tensor, image_sizes: torch.Tensor): + def forward( + self, + image_features: torch.Tensor, + image_sizes: List[List[int]], + ):
525-531: Update type hints to match List[List[int]] in patch merger.Annotation currently claims torch.Tensor but the new caller supplies a Python list.
- def forward(self, image_features: torch.Tensor, - image_sizes: torch.Tensor) -> torch.Tensor: + def forward( + self, + image_features: torch.Tensor, + image_sizes: List[List[int]], + ) -> torch.Tensor:
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
tensorrt_llm/_torch/models/modeling_mistral.py(4 hunks)tensorrt_llm/_torch/models/modeling_pixtral.py(2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.py: Code must target Python 3.8+
Indent Python code with 4 spaces; do not use tabs
Preserve module namespaces when importing; import modules/packages and access members via the module (e.g., from package.subpackage import foo; foo.SomeClass())
Python file names should be snake_case
Python class names should be PascalCase
Python functions/methods and local variables should be snake_case; variables beginning with a number should be prefixed with k_ (e.g., k_99th_percentile)
Global variables should be UPPER_SNAKE_CASE prefixed with G_ (e.g., G_MY_GLOBAL); constants should be UPPER_SNAKE_CASE
Avoid shadowing variables from outer scopes; initialize all externally visible members in init
Prefer docstrings for interfaces used outside a file; comments should be reserved for in-function or file-local interfaces
Use Google-style docstrings for classes and functions; attributes and variables may be documented inline with trailing string literals
Avoid reflection when simpler, explicit code suffices (e.g., avoid dict(**locals()) patterns)
In try/except, catch the narrowest exceptions possible
For duck-typing patterns, keep the try body minimal and move logic to else to avoid masking unrelated failures
Files:
tensorrt_llm/_torch/models/modeling_pixtral.pytensorrt_llm/_torch/models/modeling_mistral.py
**/*.{c,cc,cpp,cxx,h,hh,hpp,hxx,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Prepend the NVIDIA copyright header (current year) to all source files (.cpp, .h, .cu, .py, etc.)
Files:
tensorrt_llm/_torch/models/modeling_pixtral.pytensorrt_llm/_torch/models/modeling_mistral.py
🧠 Learnings (2)
📓 Common learnings
Learnt from: dbari
PR: NVIDIA/TensorRT-LLM#6714
File: tests/integration/defs/triton_server/build_model.sh:724-726
Timestamp: 2025-08-13T08:21:13.006Z
Learning: Mistral Small 3.1 multimodal (pixtral model type) supports any batch size for the multimodal encoder, not just batch size 1. The max_batch_size parameter can be set to values like 2 without conflicts with the runtime batching logic.
📚 Learning: 2025-08-13T08:21:13.006Z
Learnt from: dbari
PR: NVIDIA/TensorRT-LLM#6714
File: tests/integration/defs/triton_server/build_model.sh:724-726
Timestamp: 2025-08-13T08:21:13.006Z
Learning: Mistral Small 3.1 multimodal (pixtral model type) supports any batch size for the multimodal encoder, not just batch size 1. The max_batch_size parameter can be set to values like 2 without conflicts with the runtime batching logic.
Applied to files:
tensorrt_llm/_torch/models/modeling_mistral.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Pre-commit Check
🔇 Additional comments (3)
tensorrt_llm/_torch/models/modeling_pixtral.py (1)
202-206: Verify all call sites and downstream type hints for the updatedimage_sizesAPIThe signature of
PixtralVisionModel.forwardwas changed so that theimage_sizesparameter is now aList[List[int]]. We weren’t able to automatically locate any direct calls using the named parameter in the codebase, which suggests some callers may be relying on positional arguments or live in code paths we didn’t search. Please manually verify that:
- In
modeling_mistral.py, all invocations ofself._vision_tower.forwardnow passimage_sizesas aList[List[int]](not a tuple or other shape).- Any projector or patch-merger modules that consume the
image_sizesoutput are updated to expect and type-hintList[List[int]].- Unit tests in
tests/unittest/_torch/modeling/test_modeling_pixtral.pycorrectly constructimage_sizesasList[List[int]]where they invokeforward.Ensuring consistency here will prevent static-typing drift and runtime shape mismatches after the PR.
tensorrt_llm/_torch/models/modeling_mistral.py (2)
261-267: Converting image_sizes to lists to avoid device transfers — good change.This removes needless device traffic while preserving semantics.
395-402: No leftover tuple-unpacks in_batch_pixel_valuescallers
- Only one invocation of
self._batch_pixel_valuesexists intensorrt_llm/_torch/models/modeling_mistral.py(lines 400–401), and it’s directly assigned to a single variable (batched_pixel_values)—no tuple unpacking detected.- The method’s return contract (now a single tensor instead of a tuple) is handled correctly throughout this call site.
Optional nitpick: consider renaming
batched_image_sizestoflat_image_sizesfor clearer intent.
|
PR_Github #16610 [ run ] completed with state |
|
/bot run |
|
PR_Github #16620 [ run ] triggered by Bot |
|
PR_Github #16620 [ run ] completed with state |
|
/bot run |
|
PR_Github #16725 [ run ] triggered by Bot |
|
PR_Github #16725 [ run ] completed with state |
rakib-hasan
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the change. LGTM overall. Just added a minor comment.
f352050 to
de1b721
Compare
|
/bot run |
chang-l
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM
|
/bot run |
|
PR_Github #17007 [ run ] triggered by Bot |
|
PR_Github #17007 [ run ] completed with state |
|
/bot run |
|
PR_Github #17014 [ run ] triggered by Bot |
|
PR_Github #17050 [ run ] triggered by Bot |
|
PR_Github #17050 [ run ] completed with state |
* Why? Initial profiling showed there were multiple D2H / H2D copies being scheduled in the mistral 3.1 small model. * What? This commit removes those unnecessary copies by returning `image_sizes` as a simple list instead of a tensor. Signed-off-by: William Zhang <[email protected]>
01a4d6d to
81aa882
Compare
|
/bot run |
|
PR_Github #17389 [ run ] triggered by Bot |
|
/bot kill |
81aa882 to
112ec10
Compare
|
/bot run |
|
PR_Github #17391 [ kill ] triggered by Bot |
|
PR_Github #17389 [ run ] completed with state |
|
PR_Github #17391 [ kill ] completed with state |
|
PR_Github #17392 [ run ] triggered by Bot |
|
PR_Github #17392 [ run ] completed with state |
|
/bot run |
|
PR_Github #17453 [ run ] triggered by Bot |
|
PR_Github #17453 [ run ] completed with state |
|
/bot run |
|
PR_Github #17481 [ run ] triggered by Bot |
|
PR_Github #17481 [ run ] completed with state |
|
/bot run |
|
PR_Github #17547 [ run ] triggered by Bot |
|
PR_Github #17547 [ run ] completed with state |
* Why? Initial profiling showed there were multiple D2H / H2D copies being scheduled in the mistral 3.1 small model. * What? This commit removes those unnecessary copies by returning `image_sizes` as a simple list instead of a tensor. Signed-off-by: William Zhang <[email protected]>

Summary by CodeRabbit
Performance Improvements
Stability
Compatibility
Description
Initial profiling showed there were multiple D2H / H2D copies being
scheduled in the mistral 3.1 small model.
This commit removes those unnecessary copies by returning
image_sizesas a simple list instead of a tensor.
Test Coverage
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.
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.