Skip to content

Conversation

yechank-nvidia
Copy link
Collaborator

@yechank-nvidia yechank-nvidia commented Jul 22, 2025

This PR changes the tensor object in MultimodalParasm into SharedTensor container.

Summary by CodeRabbit

  • New Features
    • Enhanced support for multimodal data with new methods for converting, validating, and transferring tensors between shared memory and devices.
  • Bug Fixes
    • Improved handling and initialization of multimodal data during generation and execution requests.
    • Strengthened error handling and validation for multimodal data operations.
  • Refactor
    • Unified and streamlined multimodal tensor operations for better maintainability and consistency.
  • Chores
    • Removed unused methods and updated logic for managing multimodal configuration data.

@yechank-nvidia yechank-nvidia requested review from a team as code owners July 22, 2025 09:08
@yechank-nvidia yechank-nvidia self-assigned this Jul 22, 2025
Copy link
Contributor

coderabbitai bot commented Jul 22, 2025

Walkthrough

The changes focus on improving the handling of multimodal tensor data throughout the codebase. They introduce new methods for recursively converting, validating, and transferring multimodal data between shared memory and device memory. Control flow in the model engine and API is updated to ensure shared tensor containers are properly managed and reassigned during data preparation. Additionally, runtime data support for multimodal token caching is added.

Changes

File(s) Change Summary
tensorrt_llm/inputs/multimodal.py Added recursive helpers for shared tensor and device transfers, validation, and error handling; replaced strip_for_context; added multimodal_runtime attribute; updated strip_for_generation.
tensorrt_llm/_torch/pyexecutor/model_engine.py Adjusted multimodal parameter preparation to recover and reassign shared tensor containers; reordered operations for context and generation requests.
tensorrt_llm/llmapi/llm.py Explicitly convert multimodal parameters to shared tensor format before generation when present.
tensorrt_llm/executor/worker.py Added conversion from shared tensor format for multimodal data before passing to executor request in PyTorch backend.

Sequence Diagram(s)

sequenceDiagram
    participant API as LLM API
    participant Params as MultimodalParams
    participant Engine as ModelEngine
    participant Worker as Executor Worker

    API->>Params: to_shared_tensor("multimodal_data")
    Params->>Params: _apply_tensor_operation (recursive conversion)
    API->>Engine: Pass multimodal_params (shared tensor)
    Engine->>Params: from_shared_tensor("multimodal_data")
    Params->>Params: _apply_tensor_operation (recover container)
    Engine->>Params: to_device("multimodal_data", "cuda")
    Params->>Params: _apply_tensor_operation (move to device)
    Engine->>Worker: Pass request with multimodal_data
    Worker->>Params: from_shared_tensor("multimodal_data")
    Params->>Params: _apply_tensor_operation (recover container)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐇 In code’s deep burrows, tensors play,
Shared or device, they find their way.
Recursive hops and checks so bright,
Multimodal data takes new flight.
A rabbit’s dance in memory’s glen,
Ensuring smooth flow time and again.
🌟🐰

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
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: 2

🧹 Nitpick comments (3)
tensorrt_llm/inputs/multimodal.py (3)

193-220: Add validation for unknown method_key values.

The method correctly validates method_key values 1 and 2, but returns False for any other value without validation. Consider explicitly handling unknown values to catch potential issues early.

         # Additional validation based on method_key
         method_key = obj.get('method_key')
         if method_key == 1:  # CUDA tensor
             cuda_keys = {'tensor_size', 'storage_handle', 'storage_device'}
             return cuda_keys.issubset(obj.keys())
         elif method_key == 2:  # CPU tensor
             cpu_keys = {'tensor_size', 'storage_handle', 'manager_handle'}
             return cpu_keys.issubset(obj.keys())
+        else:
+            # Log warning for unknown method_key but still return False
+            if method_key is not None:
+                logger.debug(f"Unknown method_key value: {method_key}")
 
         return False

259-259: Remove commented debug print statement.

-                    # print(f"input_data: {input_data}")
                     return SharedTensorContainer.from_dict(

256-257: Consider moving imports to module level for better performance.

The method imports SharedTensorContainer inside the function body, which could impact performance if called frequently. Consider moving these imports to the module level.

At the module level:

from tensorrt_llm._torch.shared_tensor import SharedTensorContainer

Then remove the import statements from within the method.

Also applies to: 278-279

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3e1a0fb and 656820a.

📒 Files selected for processing (3)
  • tensorrt_llm/_torch/pyexecutor/model_engine.py (2 hunks)
  • tensorrt_llm/inputs/multimodal.py (2 hunks)
  • tensorrt_llm/llmapi/llm.py (1 hunks)
🔇 Additional comments (6)
tensorrt_llm/llmapi/llm.py (1)

396-397: LGTM! SharedTensor conversion properly placed.

The addition of multimodal_params.to_shared_tensor("multimodal_data") is correctly positioned after validating that the multimodal parameters have content. This ensures efficient shared memory usage by only converting non-empty multimodal data, and aligns well with the PR objective to support SharedTensor on MultimodalParams.

tensorrt_llm/_torch/pyexecutor/model_engine.py (1)

1161-1167: Approve shared tensor recovery flow

I’ve checked the implementations of from_shared_tensor and to_device in tensorrt_llm/inputs/multimodal.py. Both methods perform input validation by raising ValueError (as documented), and there are no internal try/except blocks—errors are meant to propagate to higher-level handlers. No additional error handling is required here.

All set!

tensorrt_llm/inputs/multimodal.py (4)

305-321: LGTM! Clean validation helper.

The method provides clear error messages and proper validation.


322-342: LGTM! Well-implemented shared tensor conversion.

The method properly validates input and leverages the recursive helper for conversion.


368-395: LGTM! Excellent refactoring of to_device method.

The refactored implementation properly validates input and leverages the unified tensor operation framework with improved error handling.


396-414: LGTM! Correctly preserves entire mrope_config.

The updated implementation properly retains the complete mrope_config dictionary during generation, which aligns with the PR objectives.

@johncalesp
Copy link
Collaborator

Hi @ yechank-nvidia, when you get a chance can you benchmark your branch with genai-perf, I tried testing in a H100 in dlcluster with
genai-perf profile -m Qwen/Qwen2-VL-7B-Instruct -u http://localhost:9010 --endpoint-type multimodal --synthetic-input-tokens-mean 100 --output-tokens-mean 100 --image-width-mean 256 --image-height-mean 256 --request-count 1000 --concurrency 1000 --streaming
but got into memory errors on the endpoint with:

File "/code/tensorrt_llm/tensorrt_llm/_torch/models/modeling_qwen.py", line 161, in forward
    hidden_states, residual = decoder_layer(position_ids=position_ids,
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/torch/nn/modules/module.py", line 1751, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/torch/nn/modules/module.py", line 1762, in _call_impl
    return forward_call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/code/tensorrt_llm/tensorrt_llm/_torch/models/modeling_qwen.py", line 112, in forward
    hidden_states = self.mlp(hidden_states)
                    ^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/torch/nn/modules/module.py", line 1751, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/torch/nn/modules/module.py", line 1762, in _call_impl
    return forward_call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/code/tensorrt_llm/tensorrt_llm/_torch/modules/gated_mlp.py", line 130, in forward
    h1 = self.gate_up_proj(x)
         ^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/torch/nn/modules/module.py", line 1751, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/torch/nn/modules/module.py", line 1762, in _call_impl
    return forward_call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/code/tensorrt_llm/tensorrt_llm/_torch/modules/linear.py", line 1616, in forward
    output = self.apply_linear(input, self.bias, lora_params, layer_idx)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/code/tensorrt_llm/tensorrt_llm/_torch/modules/linear.py", line 1569, in apply_linear
    output = self.quant_method.apply(self, input, bias)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/code/tensorrt_llm/tensorrt_llm/_torch/modules/linear.py", line 282, in apply
    output = F.linear(input, module.weight, bias)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 584.00 MiB. GPU 0 has a total capacity of 93.00 GiB of which 430.81 MiB is free. 

You only notice this if you go really high in number of concurrent request, for low concurrency it does not break

@yechank-nvidia
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #14347 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #14347 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #10841 completed with status: 'FAILURE'

@yechank-nvidia yechank-nvidia force-pushed the multimodal_sharedtensor branch from 6831b59 to ce42696 Compare August 7, 2025 04:13
@yechank-nvidia
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #14377 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #14377 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #10867 completed with status: 'FAILURE'

@yechank-nvidia
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #14392 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #14392 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #10879 completed with status: 'FAILURE'

@yechank-nvidia yechank-nvidia force-pushed the multimodal_sharedtensor branch from ce42696 to e041662 Compare August 8, 2025 01:03
@yechank-nvidia
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #14527 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #14527 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #10975 completed with status: 'FAILURE'

@yechank-nvidia yechank-nvidia force-pushed the multimodal_sharedtensor branch from e7e7a97 to 204c30a Compare August 8, 2025 03:51
@yechank-nvidia
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #14554 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #14554 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #10995 completed with status: 'SUCCESS'
Pipeline passed with automatic retried tests. Check the rerun report for details.

@chang-l chang-l merged commit 60073a7 into NVIDIA:main Aug 11, 2025
4 checks passed
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.

7 participants