-
Notifications
You must be signed in to change notification settings - Fork 1.9k
[None][feat] support Qwen3-VL dense model in pytorch backend #9060
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
base: main
Are you sure you want to change the base?
Conversation
Signed-off-by: Nekofish-L <liuxiangyang@mail.ustc.edu.cn>
📝 WalkthroughWalkthroughThe PR introduces Qwen3VL multimodal support into TensorRT LLM, adding a comprehensive vision-language model class with vision encoding and text generation capabilities. It extends the existing Qwen3 model to support multi-modal RoPE (MRoPE) with configurable parameters and optional deepstack visual embeddings. Additionally, it updates attention mechanisms and removes deprecated AutoConfig registration. Changes
Sequence DiagramsequenceDiagram
participant User
participant InputProcessor as Qwen3VLInputProcessor
participant VisionEncoder as Vision Model
participant LanguageModel as Language Model
participant Attention as QKNormRoPE Attention
User->>InputProcessor: inputs (text + images/video)
InputProcessor->>InputProcessor: tokenize & preprocess
InputProcessor->>InputProcessor: compute MRoPE config
InputProcessor-->>User: token_ids + multimodal_data
User->>VisionEncoder: multimodal_data
VisionEncoder->>VisionEncoder: extract visual features
VisionEncoder-->>LanguageModel: visual_embeddings
LanguageModel->>LanguageModel: fuse text & visual embeddings
LanguageModel->>LanguageModel: early layer: inject deepstack_visual
loop for each decoder layer
LanguageModel->>Attention: hidden_states + mrope_config
Attention->>Attention: check mrope_config
alt if mrope_config
Attention->>Attention: apply interleaved RoPE
else
Attention->>Attention: apply standard RoPE + QK norm
end
Attention-->>LanguageModel: attention_output
end
LanguageModel-->>User: output_logits
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ 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 |
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: 4
🧹 Nitpick comments (6)
tensorrt_llm/_torch/models/modeling_qwen3vl.py (6)
42-42: Use explicitOptionaltype hint.PEP 484 prohibits implicit
Optional. Update the type annotation to be explicit.Apply this diff:
def process_weights( - weights: Dict, prefix: str = "visual", weight_name_mapping: Dict[str, str] = None + weights: Dict, prefix: str = "visual", weight_name_mapping: Optional[Dict[str, str]] = None ) -> Dict:
126-139: Remove commented-out code.The commented
get_mm_token_idsmethod should either be implemented or removed entirely. Leaving commented code reduces maintainability.Apply this diff:
- # def get_mm_token_ids(self) -> torch.Tensor: - # """Get the IDs of all multimodal tokens (placeholders and special tokens alike).""" - # return torch.tensor([ - # # This is the `<|image_pad|>` token id inserted into the prompt that should be replaced with image - # # embeddings. - # self.processor.image_token_id, - # # This is the `<|video_pad|>` token id inserted into the prompt that should be replaced with video - # # embeddings. - # self.processor.video_token_id, - # # This is the `<|vision_start|>` token id to signify the start of vision part. - # self.processor.vision_start_token_id, - # # This is the `<|vision_end|>` token id to signify the end of vision part. - # self.processor.vision_end_token_id, - # ]) -
97-97: Remove commented debug statements.Commented
print()statements are debugging artifacts and should be removed to keep the code clean.Apply this diff:
- # print(self.model_config) self.tllm_multimodal_token_id = self.model_config.text_config.vocab_size + 1- # print(model_config) spatial_merge_size = model_config.vision_config.spatial_merge_sizeAlso applies to: 158-158
474-474: Remove commented debug statement.The commented
print()statement is a debugging artifact and should be removed.Apply this diff:
- # print("shapes", image_embeds.shape, len(deepstack_image_embeds)) embeds.append(image_embeds)
710-716: Consider shortening the exception message.The error message is quite long. Consider moving details to documentation or shortening it while keeping essential information.
Apply this diff:
if mm_token_indices.shape[0] != mm_embed.shape[0]: raise ValueError( - f"Multimodal token count mismatch: found {len(mm_token_indices)} image tokens in input_ids " - f"but received {mm_embed.shape[0]} image embeddings. " - "This is likely due to KV cache reuse, chunk prefill, or other optimizations that " - "cause token count mismatches within the inference batch." + f"Multimodal token count mismatch: found {len(mm_token_indices)} tokens in input_ids " + f"but received {mm_embed.shape[0]} embeddings (KV cache reuse or chunked prefill may cause this)." )
832-832: Remove commented debug statement.Commented debugging code should be removed to maintain clean, production-ready code.
Apply this diff:
self.mm_encoder.load_state_dict(vision_encoder_weights, strict=True) - # print(weights.keys()) transformed_weights = {}
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
tensorrt_llm/_torch/models/__init__.py(2 hunks)tensorrt_llm/_torch/models/modeling_qwen3.py(5 hunks)tensorrt_llm/_torch/models/modeling_qwen3_next.py(1 hunks)tensorrt_llm/_torch/models/modeling_qwen3vl.py(1 hunks)tensorrt_llm/_torch/modules/qk_norm_attention.py(2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Use only spaces, no tabs; indent with 4 spaces.
Files:
tensorrt_llm/_torch/models/modeling_qwen3_next.pytensorrt_llm/_torch/models/__init__.pytensorrt_llm/_torch/modules/qk_norm_attention.pytensorrt_llm/_torch/models/modeling_qwen3.pytensorrt_llm/_torch/models/modeling_qwen3vl.py
**/*.py
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.py: Python code must target Python 3.8+.
Indent Python code with 4 spaces; do not use tabs.
Maintain module namespace when importing; prefer 'from package.subpackage import foo' then 'foo.SomeClass()' instead of importing the class directly.
Python filenames should be snake_case (e.g., some_file.py).
Python classes use PascalCase names.
Functions and methods use snake_case names.
Local variables use snake_case; prefix 'k' for variables that start with a number (e.g., k_99th_percentile).
Global variables use upper SNAKE_CASE prefixed with 'G' (e.g., G_MY_GLOBAL).
Constants use upper SNAKE_CASE (e.g., MY_CONSTANT).
Avoid shadowing variables from an outer scope.
Initialize all externally visible members of a class in the constructor.
Prefer docstrings for interfaces that may be used outside a file; comments for in-function or file-local interfaces.
Use Google-style docstrings for classes and functions (Sphinx-parsable).
Document attributes and variables inline so they render under the class/function docstring.
Avoid reflection when a simpler, explicit approach suffices (e.g., avoid dict(**locals()) patterns).
In try/except, catch the most specific exceptions possible.
For duck-typing try/except, keep the try body minimal and use else for the main logic.
Files:
tensorrt_llm/_torch/models/modeling_qwen3_next.pytensorrt_llm/_torch/models/__init__.pytensorrt_llm/_torch/modules/qk_norm_attention.pytensorrt_llm/_torch/models/modeling_qwen3.pytensorrt_llm/_torch/models/modeling_qwen3vl.py
**/*.{cpp,cxx,cc,h,hpp,hh,hxx,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Prepend the NVIDIA Apache-2.0 copyright header with current year to the top of all source files (e.g., .cpp, .h, .cu, .py).
Files:
tensorrt_llm/_torch/models/modeling_qwen3_next.pytensorrt_llm/_torch/models/__init__.pytensorrt_llm/_torch/modules/qk_norm_attention.pytensorrt_llm/_torch/models/modeling_qwen3.pytensorrt_llm/_torch/models/modeling_qwen3vl.py
🧠 Learnings (7)
📓 Common learnings
Learnt from: eopXD
Repo: NVIDIA/TensorRT-LLM PR: 6767
File: cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp:0-0
Timestamp: 2025-08-15T06:46:53.813Z
Learning: In the TensorRT-LLM KV cache manager, SWA (Sliding Window Attention) combined with beam search is currently in a broken/non-functional state and is planned for future rework. During preparatory refactoring phases, code related to SWA+beam search may intentionally remain in a non-working state until the broader rework is completed.
Learnt from: MatthiasKohl
Repo: NVIDIA/TensorRT-LLM PR: 6904
File: tensorrt_llm/_torch/attention_backend/trtllm.py:259-262
Timestamp: 2025-08-14T15:43:23.107Z
Learning: In TensorRT-LLM's attention backend, tensor parameters in the plan() method are assigned directly without validation (dtype, device, contiguity checks). This maintains consistency across all tensor inputs and follows the pattern of trusting callers to provide correctly formatted tensors.
Learnt from: yechank-nvidia
Repo: NVIDIA/TensorRT-LLM PR: 6254
File: tensorrt_llm/_torch/pyexecutor/model_engine.py:1201-1204
Timestamp: 2025-07-22T09:22:14.726Z
Learning: In TensorRT-LLM's multimodal processing pipeline, shared tensor recovery using `from_shared_tensor()` is only needed during the context phase. Generation requests reuse the already-recovered tensor data and only need to call `strip_for_generation()` to remove unnecessary multimodal data while preserving the recovered tensors. This avoids redundant tensor recovery operations during generation.
Learnt from: fredricz-20070104
Repo: NVIDIA/TensorRT-LLM PR: 7645
File: tests/integration/test_lists/qa/llm_function_core.txt:648-648
Timestamp: 2025-09-09T09:40:45.658Z
Learning: In TensorRT-LLM test lists, it's common and intentional for the same test to appear in multiple test list files when they serve different purposes (e.g., llm_function_core.txt for comprehensive core functionality testing and llm_function_core_sanity.txt for quick sanity checks). This duplication allows tests to be run in different testing contexts.
Learnt from: yibinl-nvidia
Repo: NVIDIA/TensorRT-LLM PR: 6506
File: examples/models/core/mixtral/requirements.txt:3-3
Timestamp: 2025-08-01T15:14:45.673Z
Learning: In TensorRT-LLM, examples directory can have different dependency versions than the root requirements.txt file. Version conflicts between root and examples dependencies are acceptable because examples are designed to be standalone and self-contained.
Learnt from: djns99
Repo: NVIDIA/TensorRT-LLM PR: 7104
File: cpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/fusion/sm90_visitor_scatter.hpp:399-417
Timestamp: 2025-08-21T21:48:35.135Z
Learning: CUTLASS extensions in TensorRT-LLM (located under cpp/tensorrt_llm/cutlass_extensions/) are designed to integrate with and extend functionality in the external CUTLASS repository. When analyzing these extensions, their consumers and functionality wiring may exist in the CUTLASS codebase rather than within TensorRT-LLM itself.
Learnt from: ixlmar
Repo: NVIDIA/TensorRT-LLM PR: 7294
File: tensorrt_llm/_torch/modules/rms_norm.py:17-17
Timestamp: 2025-08-27T14:23:55.566Z
Learning: The TensorRT-LLM project requires Python 3.10+ as evidenced by the use of TypeAlias from typing module, match/case statements, and union type | syntax throughout the codebase, despite some documentation still mentioning Python 3.8+.
Learnt from: nv-lschneider
Repo: NVIDIA/TensorRT-LLM PR: 7910
File: cpp/tensorrt_llm/thop/allreduceOp.cpp:352-446
Timestamp: 2025-09-23T15:12:38.312Z
Learning: In TensorRT-LLM NCCL device implementation, NCCL version 2.28+ requirements are handled at runtime in the nccl_device/config layer rather than with compile-time guards. This allows the allreduceOp to remain version-agnostic and delegates version compatibility validation to the appropriate lower-level components that can gracefully handle unsupported configurations.
Learnt from: djns99
Repo: NVIDIA/TensorRT-LLM PR: 6728
File: cpp/tensorrt_llm/plugins/mixtureOfExperts/mixtureOfExpertsPlugin.cpp:966-966
Timestamp: 2025-08-08T04:10:19.038Z
Learning: TensorRT plugins currently don't support padding functionality, and TensorRT is not getting new features (in maintenance mode). This means that duplicating parameters like mExpertHiddenSize in function calls, even with TODO comments, can be acceptable as pragmatic solutions within these constraints.
📚 Learning: 2025-10-20T17:07:18.745Z
Learnt from: nvchenghaoz
Repo: NVIDIA/TensorRT-LLM PR: 8469
File: tensorrt_llm/_torch/auto_deploy/models/patches/nemotron_h.py:98-116
Timestamp: 2025-10-20T17:07:18.745Z
Learning: In NemotronH models (tensorrt_llm/_torch/auto_deploy/models/patches/nemotron_h.py), the gate (self.gate) returns topk_indices and topk_weights that are already in the correct shape to be passed directly to torch_ops.auto_deploy.torch_moe without needing to reshape them when hidden_states is flattened.
Applied to files:
tensorrt_llm/_torch/models/modeling_qwen3_next.py
📚 Learning: 2025-09-29T15:14:28.503Z
Learnt from: amitz-nv
Repo: NVIDIA/TensorRT-LLM PR: 8063
File: tensorrt_llm/lora_manager.py:1080-1112
Timestamp: 2025-09-29T15:14:28.503Z
Learning: In tensorrt_llm/lora_manager.py, when calculating part_sizes for attn_qkv fused LoRA modules, the sizes are correctly multiplied by tp_size because model_config.num_heads and model_config.num_kv_heads are already divided by tp_size (per-TP-rank values), so multiplication is needed to get the original full concatenated dimension size. The interleave_fused_lora_weights_for_tp function provides proper validation with asserts for total size and TP divisibility.
Applied to files:
tensorrt_llm/_torch/modules/qk_norm_attention.py
📚 Learning: 2025-09-29T15:14:28.503Z
Learnt from: amitz-nv
Repo: NVIDIA/TensorRT-LLM PR: 8063
File: tensorrt_llm/lora_manager.py:1080-1112
Timestamp: 2025-09-29T15:14:28.503Z
Learning: In tensorrt_llm/lora_manager.py, when calculating part_sizes for attn_qkv fused LoRA modules, the sizes are correctly multiplied by tp_size because model_config.num_heads and model_config.num_kv_heads are already divided by tp_size (per-TP-rank values), so multiplication is needed to get the original full concatenated dimension size. The interleave_fused_lora_weights_for_tp function provides proper validation.
Applied to files:
tensorrt_llm/_torch/modules/qk_norm_attention.py
📚 Learning: 2025-08-15T06:46:53.813Z
Learnt from: eopXD
Repo: NVIDIA/TensorRT-LLM PR: 6767
File: cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp:0-0
Timestamp: 2025-08-15T06:46:53.813Z
Learning: In the TensorRT-LLM KV cache manager, SWA (Sliding Window Attention) combined with beam search is currently in a broken/non-functional state and is planned for future rework. During preparatory refactoring phases, code related to SWA+beam search may intentionally remain in a non-working state until the broader rework is completed.
Applied to files:
tensorrt_llm/_torch/models/modeling_qwen3vl.py
📚 Learning: 2025-07-22T09:22:14.726Z
Learnt from: yechank-nvidia
Repo: NVIDIA/TensorRT-LLM PR: 6254
File: tensorrt_llm/_torch/pyexecutor/model_engine.py:1201-1204
Timestamp: 2025-07-22T09:22:14.726Z
Learning: In TensorRT-LLM's multimodal processing pipeline, shared tensor recovery using `from_shared_tensor()` is only needed during the context phase. Generation requests reuse the already-recovered tensor data and only need to call `strip_for_generation()` to remove unnecessary multimodal data while preserving the recovered tensors. This avoids redundant tensor recovery operations during generation.
Applied to files:
tensorrt_llm/_torch/models/modeling_qwen3vl.py
📚 Learning: 2025-08-14T06:36:40.701Z
Learnt from: timlee0212
Repo: NVIDIA/TensorRT-LLM PR: 6886
File: tensorrt_llm/_torch/models/modeling_deepseekv3.py:0-0
Timestamp: 2025-08-14T06:36:40.701Z
Learning: In DeepSeek V3 model (tensorrt_llm/_torch/models/modeling_deepseekv3.py), the disagreement between AllReduce.__init__ guard and _compute_mlp_tp_size logic for MNNVL usage is expected by design. The AllReduce component and MLP TP-size computation intentionally use different criteria for MNNVL availability decisions.
Applied to files:
tensorrt_llm/_torch/models/modeling_qwen3vl.py
🧬 Code graph analysis (3)
tensorrt_llm/_torch/models/__init__.py (1)
tensorrt_llm/_torch/models/modeling_qwen3vl.py (1)
Qwen3VLModelTRT(812-843)
tensorrt_llm/_torch/modules/qk_norm_attention.py (4)
tensorrt_llm/_torch/attention_backend/interface.py (3)
AttentionMetadata(44-394)PositionalEmbeddingParams(564-582)PredefinedAttentionMask(588-597)tensorrt_llm/functional.py (1)
AllReduceParams(3900-3939)tensorrt_llm/_torch/modules/attention.py (9)
Attention(131-623)forward(518-597)forward(1909-1946)apply_rope(599-618)apply_rope(1042-1054)split_qkv(365-368)convert_qkv(370-376)forward_impl(460-516)forward_impl(1111-1209)tensorrt_llm/_torch/utils.py (1)
Fp4QuantizedTensor(110-117)
tensorrt_llm/_torch/models/modeling_qwen3vl.py (7)
tensorrt_llm/_torch/models/checkpoints/base_weight_mapper.py (1)
BaseWeightMapper(10-165)tensorrt_llm/inputs/multimodal.py (1)
MultimodalParams(197-521)tensorrt_llm/_utils.py (2)
nvtx_range(872-891)nvtx_range_debug(894-918)tensorrt_llm/inputs/registry.py (3)
InputProcessor(29-48)MultimodalPlaceholderMetadata(370-383)register_input_processor(519-545)tensorrt_llm/_torch/modules/embedding.py (1)
Embedding(180-264)tensorrt_llm/_torch/models/modeling_multimodal_utils.py (4)
_cache_multimodal_embeddings(60-96)_get_uncached_multimodal_params(33-57)filter_mm_token_from_input_ids(246-283)find_input_mm_embeds(168-243)tensorrt_llm/_torch/models/modeling_utils.py (2)
register_auto_model(617-623)register_vision_encoder(626-655)
🪛 Ruff (0.14.4)
tensorrt_llm/_torch/modules/qk_norm_attention.py
274-274: Unused method argument: kwargs
(ARG002)
tensorrt_llm/_torch/models/modeling_qwen3vl.py
42-42: PEP 484 prohibits implicit Optional
Convert to T | None
(RUF013)
339-339: Unused method argument: sampling_params
(ARG002)
492-492: Unused method argument: args
(ARG002)
694-694: Unused function argument: kwargs
(ARG001)
711-716: Avoid specifying long messages outside the exception class
(TRY003)
⏰ 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/__init__.py (2)
30-30: LGTM!The import statement follows the established pattern in this file and correctly imports the new Qwen3VLModelTRT class.
38-51: LGTM!The
__all__list correctly exposes the newQwen3VLModelTRTclass and the reformatting improves readability.tensorrt_llm/_torch/models/modeling_qwen3_next.py (1)
321-322: LGTM – Cleanup aligns with transformers 4.57.0 update.The comment correctly explains that AutoConfig registration is no longer needed with transformers >= 4.57.0, which aligns with the PR's declared dependency.
| for layer_idx, decoder_layer in enumerate(self.layers): | ||
| hidden_states, residual = decoder_layer( | ||
| position_ids=position_ids, | ||
| hidden_states=hidden_states, | ||
| attn_metadata=attn_metadata, | ||
| residual=residual, | ||
| spec_metadata=spec_metadata, | ||
| mrope_config=mrope_config, | ||
| ) | ||
| # add visual features to the hidden states of first several layers | ||
| if deepstack_visual_embeds is not None and layer_idx in range( | ||
| len(deepstack_visual_embeds)): | ||
| hidden_states = hidden_states + deepstack_visual_embeds[ | ||
| layer_idx] |
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.
Deepstack visual embeds must be applied before speculative capture.
Qwen3DecoderLayer pushes its hidden/residual pair into SpecMetadata before it returns. Because the deepstack addition happens out here after the layer call, the tensors cached for speculative decoding miss the visual contribution, so replaying the layer during speculation diverges from the runtime path as soon as deepstack is enabled. Please pass the per-layer visual tensor down into the decoder layer and add it before maybe_capture_hidden_states() so both execution paths see the same activations.
Apply this diff:
@@
- spec_metadata: Optional[SpecMetadata] = None,
- mrope_config: Optional[dict] = None,
+ spec_metadata: Optional[SpecMetadata] = None,
+ mrope_config: Optional[dict] = None,
+ deepstack_visual_embed: Optional[torch.Tensor] = None,
**kwargs,
) -> torch.Tensor:
@@
- hidden_states = self.mlp(
+ hidden_states = self.mlp(
hidden_states,
all_rank_num_tokens=attn_metadata.all_rank_num_tokens,
final_all_reduce_params=AllReduceParams(
enable_allreduce=not self.disable_allreduce),
cutlass_min_latency_mode=False,
)
+ if deepstack_visual_embed is not None:
+ hidden_states = hidden_states + deepstack_visual_embed
+
if spec_metadata is not None:
spec_metadata.maybe_capture_hidden_states(self.layer_idx,
hidden_states, residual)
@@
- for layer_idx, decoder_layer in enumerate(self.layers):
- hidden_states, residual = decoder_layer(
+ for layer_idx, decoder_layer in enumerate(self.layers):
+ visual_embed = None
+ if deepstack_visual_embeds is not None and layer_idx < len(deepstack_visual_embeds):
+ visual_embed = deepstack_visual_embeds[layer_idx]
+
+ hidden_states, residual = decoder_layer(
position_ids=position_ids,
hidden_states=hidden_states,
attn_metadata=attn_metadata,
residual=residual,
spec_metadata=spec_metadata,
- mrope_config=mrope_config,
+ mrope_config=mrope_config,
+ deepstack_visual_embed=visual_embed,
)
- # add visual features to the hidden states of first several layers
- if deepstack_visual_embeds is not None and layer_idx in range(
- len(deepstack_visual_embeds)):
- hidden_states = hidden_states + deepstack_visual_embeds[
- layer_idx]Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In tensorrt_llm/_torch/models/modeling_qwen3.py around lines 210 to 223, the
deepstack visual embeddings are added to hidden_states after the decoder_layer
returns, so SpecMetadata captured inside Qwen3DecoderLayer misses the visual
contribution; modify the call to pass the per-layer visual tensor (e.g.,
deepstack_visual_embeds[layer_idx] or None) into decoder_layer and change
Qwen3DecoderLayer to add that visual tensor to its hidden_states before calling
maybe_capture_hidden_states()/pushing into SpecMetadata so both normal and
speculative paths see identical activations.
| @@ -0,0 +1,843 @@ | |||
| import copy | |||
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.
Add the required NVIDIA Apache-2.0 copyright header.
Per coding guidelines, all Python source files must include the NVIDIA Apache-2.0 copyright header with the current year (2025) at the top of the file.
Apply this diff:
+# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
import copy📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| import copy | |
| # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | |
| # SPDX-License-Identifier: Apache-2.0 | |
| # | |
| # Licensed under the Apache License, Version 2.0 (the "License"); | |
| # you may not use this file except in compliance with the License. | |
| # You may obtain a copy of the License at | |
| # | |
| # http://www.apache.org/licenses/LICENSE-2.0 | |
| # | |
| # Unless required by applicable law or agreed to in writing, software | |
| # distributed under the License is distributed on an "AS IS" BASIS, | |
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| # See the License for the specific language governing permissions and | |
| # limitations under the License. | |
| import copy |
🤖 Prompt for AI Agents
In tensorrt_llm/_torch/models/modeling_qwen3vl.py around lines 1 to 1, the file
is missing the required NVIDIA Apache-2.0 copyright header; add the standard
NVIDIA Apache-2.0 header block at the very top of the file (using the current
year 2025), ensuring it precedes any imports or code and follows the exact
header text used across the repo.
| transformed_weights[new_key] = value | ||
| else: | ||
| transformed_weights[key] = value | ||
| print("mapper:", weight_mapper) |
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.
Replace debug print with logger statement.
Debug print() statements should not be in production code. Use logger.debug() or logger.info() instead for proper logging control.
Apply this diff:
- print("mapper:", weight_mapper)
+ logger.debug(f"Weight mapper: {weight_mapper}")
self.llm.load_weights(transformed_weights, weight_mapper)Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In tensorrt_llm/_torch/models/modeling_qwen3vl.py around line 841, replace the
debug print statement "print(\"mapper:\", weight_mapper)" with a logger call:
use an existing module logger (e.g., logger.debug or logger.info) to emit the
same message and variable; if no logger exists in the module, import or create
one (e.g., from logging import getLogger; logger = getLogger(__name__)). Ensure
the log level is appropriate (debug for development noise) and preserve the
message content and variable interpolation.
| qkv = self.qkv_proj(hidden_states) | ||
| if bool(lora_params): | ||
| qkv_lora = self.splitted_qkv_lora(hidden_states, lora_params, | ||
| self.layer_idx) | ||
| if qkv_lora is not None: | ||
| qkv = qkv + qkv_lora | ||
| qkv_lora = self.fused_qkv_lora(hidden_states, lora_params, | ||
| self.layer_idx) | ||
| if qkv_lora is not None: | ||
| qkv = qkv + qkv_lora | ||
| q, k, v = qkv, None, None | ||
| # check mrope_config to decide whether to apply RoPE here | ||
| if mrope_config is None or mrope_config.get("mrope_rotary_cos_sin", | ||
| None) is None: | ||
| # no mrope, use standard QK Norm + RoPE path | ||
| q, k, v = self.apply_rope(q, k, v, position_ids) | ||
| else: | ||
| # mrope activated. We should only apply QK Norm, and not apply RoPE. | ||
| # mrope_rotary_cos_sin = mrope_config['mrope_rotary_cos_sin'] | ||
| # print(mrope_rotary_cos_sin.shape) | ||
| q, k, v = self.split_qkv(q, k, v) | ||
| q, k = self.apply_qk_norm(q, k) | ||
| q, k, v = self.convert_qkv(q, k, v) | ||
| if attention_sinks is not None: | ||
| assert self.attn_backend == "TRTLLM", "Attention sinks are only supported for TRTLLM backend." | ||
| attn_output = self.forward_impl(q, | ||
| k, | ||
| v, | ||
| attn_metadata, | ||
| attention_mask, | ||
| attention_window_size, | ||
| attention_mask_data, | ||
| mrope_config=mrope_config, | ||
| attention_sinks=attention_sinks) | ||
| attn_output = self.o_proj(attn_output, | ||
| all_reduce_params=all_reduce_params, | ||
| lora_params=lora_params, | ||
| layer_idx=self.layer_idx) | ||
| return attn_output |
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.
Restore attn_output_gate behavior
The new forward() override drops the gate split/multiply logic that Attention.forward() provides. When attn_output_gate is True, we now skip computing gate entirely, so the attention output is no longer modulated and the layer returns incorrect activations for gated heads. Please restore the gate split/rescale both before and after forward_impl.
- qkv = self.qkv_proj(hidden_states)
- if bool(lora_params):
+ qkv = self.qkv_proj(hidden_states)
+ gate = None
+ if bool(lora_params):
...
- q, k, v = qkv, None, None
+ if self.attn_output_gate:
+ q_gate, k, v = qkv.split(
+ [self.q_size * 2, self.kv_size, self.kv_size], dim=-1)
+ orig_shape = q_gate.shape[:-1]
+ q, gate = [
+ t.reshape(*orig_shape, -1) for t in torch.chunk(
+ q_gate.view(*orig_shape, self.num_heads, -1), 2, dim=-1)
+ ]
+ else:
+ q, k, v = qkv, None, None
...
attn_output = self.o_proj(...)
- return attn_output
+ if self.attn_output_gate:
+ gate = torch.sigmoid(gate)
+ attn_output = attn_output * gate
+ return attn_output🤖 Prompt for AI Agents
In tensorrt_llm/_torch/modules/qk_norm_attention.py around lines 276 to 314, the
new forward override removed the attn_output_gate gating logic so when
attn_output_gate is True the gate is never computed or applied; restore the
original behavior by splitting qkv output into attn_output and gate (or compute
gate from qkv) before calling forward_impl, rescaling the attn_output by gate
(elementwise multiply) after forward_impl and before calling o_proj, and if the
implementation expects the gate to be applied to the final projected output
instead, pass the gate through and multiply it with attn_output after o_proj;
ensure all rescaling uses the same dtype/shape as attn_output and respect
lora/all_reduce params unchanged.
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.
Thanks for your contribution!
Could you also add some (unit/accuracy) tests similar to those for Qwen2(2.5)-VL?
| self.mrope_position_ids_padding_cuda.view(3, -1) | ||
| ] | ||
| cos, sin = cos_sin[:, :, 0, :], cos_sin[:, :, 1, :] | ||
| cos = apply_interleaved_rope(cos, self.mrope_section) |
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.
Can we move these mrope-interleaved logic (get_cos_sin) to rotary_embedding.py by extending the MRotaryEmbedding class?
| if not DISAGG: | ||
| vision_encoder_weights = process_weights(weights, "visual") | ||
| self.mm_encoder.load_state_dict(vision_encoder_weights, strict=True) | ||
| # print(weights.keys()) |
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.
remove print statement
| transformed_weights[new_key] = value | ||
| else: | ||
| transformed_weights[key] = value | ||
| print("mapper:", weight_mapper) |
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.
remove print statement
| "image.image_grid_thw", | ||
| "video.pixel_values_videos", | ||
| "video.video_grid_thw", | ||
| "multimodal_embedding", |
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.
wondering if we should add deepstack_features in the list..
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.
Also, we should remove image_grid_thw and video_grid_thw from the list.
|
|
||
| assert model_config.attn_backend == "TRTLLM", "Qwen3-VL only supports TRTLLM backend now" | ||
| super().__init__(config) | ||
| self.init_mrope_embedding(model_config) |
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.
like in qwen2.5-vl, do we need disable_fuse_rope option here?
Also, a quick question, maybe to @yechank-nvidia , if we enable disable_fuse_rope (so cos_sin not computed in vit), where are the rope_cos_sin values computed?
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.
if we enable disable_fuse_rope (so cos_sin not computed in vit), where are the rope_cos_sin values computed?
It will go through to MropeRotaryEmbedding module and it has own forwrad. For Qwen-VL series, we need to have 3D position ides.
| rope=RopeParams.from_config(config), | ||
| mrope_section=config.rope_scaling.get("mrope_section", None), | ||
| ) | ||
| self.rotary_cos_sin = pos_embd_params.rope.create_rope_const_params(interleave=False)[ |
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.
also, same as above, try to use/extend MRotaryEmbedding
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 your review!
I'm working on implementing this now to extend the MRotaryEmbedding class.
yechank-nvidia
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 contribution. I left several comments. Can you please revise?
Also, we are enforcing the unittest for newly added models. Can you follow this?
Reference: Qwen2.5-VL
| self._processor = AutoProcessor.from_pretrained( | ||
| model_path, use_fast=True, trust_remote_code=trust_remote_code | ||
| ) | ||
| # print(self.model_config) |
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.
nit; please remove the print line
| "image.image_grid_thw", | ||
| "video.pixel_values_videos", | ||
| "video.video_grid_thw", | ||
| "multimodal_embedding", |
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.
Also, we should remove image_grid_thw and video_grid_thw from the list.
| self.model_config = model_config | ||
| self.model_dtype = config.torch_dtype | ||
|
|
||
| if model_class == Qwen3VLVisionModel: |
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.
We are deprecating the HF's implementation now. Can you change Attention and Linear layers from Qwen3VLVisionModel to TRT-LLM's module?
|
|
||
| assert model_config.attn_backend == "TRTLLM", "Qwen3-VL only supports TRTLLM backend now" | ||
| super().__init__(config) | ||
| self.init_mrope_embedding(model_config) |
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.
if we enable disable_fuse_rope (so cos_sin not computed in vit), where are the rope_cos_sin values computed?
It will go through to MropeRotaryEmbedding module and it has own forwrad. For Qwen-VL series, we need to have 3D position ides.
| assert model_config.attn_backend == "TRTLLM", "Qwen3-VL only supports TRTLLM backend now" | ||
| super().__init__(config) | ||
| self.init_mrope_embedding(model_config) | ||
|
|
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.
We need to have out of the path for when not using pre-computed mrope. Can you also add it, please?
| q, k, v = self.apply_rope(q, k, v, position_ids) | ||
| else: | ||
| # mrope activated. We should only apply QK Norm, and not apply RoPE. | ||
| # mrope_rotary_cos_sin = mrope_config['mrope_rotary_cos_sin'] |
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.
nit; please remove unnecessary lines.
| @@ -253,3 +258,57 @@ def apply_rope(self, q: torch.Tensor, k: Optional[torch.Tensor], | |||
| if k is not None and v is not None: | |||
| qkv = torch.concat([q, k, v], dim=-1) | |||
| return self.apply_qk_norm_rope(qkv, position_ids) | |||
|
|
|||
| def forward( | |||
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.
Can I ask why we need separate forward()? If it is for not fusing_rope due to mrope things, we need to disable fuse_qk_norm_rope when init() when the model is using mrope.
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 your review!
Here’s why I implemented a separate forward():
During the prefill stage, I use precomputed mrope_rotary_cos_sin to implement pe. At this point, no additional RoPE calculations are performed outside the attention op, which is equivalent to disabling fuse_qk_norm_rope and enabling skip_rope.
In the decode stage, since precomputed mrope_rotary_cos_sin is no longer available, but only text content is involved, I fallback to the standard RoPE calculation process, apply RoPE outside the attention op. This is equivalent to disabling skip_rope.
It's challenging to achieve this workflow through simple parameter settings.
Additionally, enabling fuse_qk_norm_rope seems to produce different outputs compared to explicitly applying RoPE after normalization. Therefore, I’ve globally disabled fuse_qk_norm_rope, though I’m still not totally sure what’s causing the difference.
Signed-off-by: Nekofish-L <liuxiangyang@mail.ustc.edu.cn>
Signed-off-by: Nekofish-L <liuxiangyang@mail.ustc.edu.cn>
Summary by CodeRabbit
New Features
Refactor
Description
This PR implements support for the Qwen3-VL dense model in TensorRT-LLM pytorch backend, based on the 1.2.0rc2 tag.
Dependency
Performance Benchmarks
model: Qwen3-VL-32B-Instruct
device: NVIDIA H20-96G
Accuracy
Speed
Related Issue
#8722
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.
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.