-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[None][feat] AutoDeploy: per graph or whole module transform infrastructure #8157
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?
[None][feat] AutoDeploy: per graph or whole module transform infrastructure #8157
Conversation
# NOTE: for now we do _not_ include input_ids since we are not guaranteed that input_ids | ||
# is part of the graph, e.g., in situations where the graph is a submodule of the overall | ||
# model. In such instances, the graph usually sees inputs_embeds. However, we assume for | ||
# now that position_ids is always part of the graph. |
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.
@Fridah-nv, replying to your question here. I am not happy with the current solution but I think any other more elegant solution would require a more drastic change to how we handle the attention interface arguments that are passed to prepare_metadata
and I would like to do at a different time together with considering a better split of prefill vs decode.
To answer your question. Now that we do subgraph capture is some instances the graph might not see input_ids
but might see inputs_embeds
because the eager code has already embedded the input ids and not pass input_ids
to the graph itself.
On the other hand, position_ids
is always passed through. And we don't really need position_ids
or input_ids
in prepare_metadata
anyway. Right now, we just use it to analyze the shape and detect if it's a prefill, mixed, or decode-only batch. We can do that with position_ids
as well
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.
Got it, thanks for the information!
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.
On the other hand, position_ids is always passed through
how confident are we when making this claim?
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.
95+% confident.position_ids
is broadly used for rope in HF and so is usually passed into the text model
run_shape_prop: true | ||
match_eager_attention: | ||
stage: pattern_matcher | ||
requires_shape_prop: true |
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.
@Fridah-nv Not sure why this is needed. It got triggered for one the models.
/bot run |
PR_Github #20677 [ run ] triggered by Bot |
📝 WalkthroughWalkthroughRefactors transform pipeline to operate on full nn.Module instead of GraphModule, adds TransformInfo composition, and consolidates cleanup logic. Updates configs to control per-graph execution and shape propagation. Standardizes prepare_metadata APIs to remove input_ids and rely on position_ids across custom ops. Adjusts optimizer and tests accordingly. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor User
participant Optimizer
participant Transform
participant Model as nn.Module
participant GraphUtils as _graph utils
User->>Optimizer: __call__(cm, mod)
alt run_per_gm = false (full-model)
Optimizer->>Transform: __call__(mod, cm, factory, shared_config)
Transform->>Transform: _apply_to_full_model(mod, ...)
Transform->>GraphUtils: _run_cleanup(mod, clean_graph/shape)
Transform-->>Optimizer: (mod', TransformInfo)
else run_per_gm = true
Optimizer->>Transform: __call__(mod, cm, ...)
Transform->>Transform: _apply_per_gm_or_whole_model(mod, ...)
note right of Transform: Iterates sub GraphModules
Transform-->>Optimizer: (mod', TransformInfo)
end
Optimizer-->>User: mod'
sequenceDiagram
autonumber
participant Caller as Attn/CausalConv/MHA caller
participant Prepare as prepare_metadata op
participant SeqInfo as SequenceInfo
Caller->>Prepare: position_ids, seq_len, input_pos, cache_loc, pages_per_seq, slot_idx, page_size
Prepare->>SeqInfo: _get_sanitized_seq_len/num_sequences(position_ids, seq_len)
SeqInfo-->>Prepare: sanitized seq_len / num_seq
Prepare-->>Caller: metadata tensors (seq_len, input_pos, cache_loc, seq_start, ...)
note over Prepare,Caller: input_ids no longer required
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Suggested reviewers
Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ Passed checks (1 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: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (15)
tensorrt_llm/_torch/auto_deploy/custom_ops/torch_backend_attention.py (3)
1-1
: Add NVIDIA Apache-2.0 header (compliance).Prepend the required NVIDIA Apache-2.0 header at file top.
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. + # 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.
250-271
: Declare mutated cache args in custom op (fix alias analysis).This op updates k_cache/v_cache but mutates_args=() claims purity. Mark them as mutated.
-@torch.library.custom_op("auto_deploy::torch_cached_attention_with_cache", mutates_args=()) +@torch.library.custom_op("auto_deploy::torch_cached_attention_with_cache", mutates_args=(7, 8))
368-376
: Ensure num_seq is Python int to avoid slice errors.convert 0‑d tensor to int for slicing.
- num_seq = SequenceInfo._get_sanitized_num_sequences(position_ids, seq_len) + num_seq = int(SequenceInfo._get_sanitized_num_sequences(position_ids, seq_len))tensorrt_llm/_torch/auto_deploy/custom_ops/triton_attention.py (3)
1-1
: Add NVIDIA Apache-2.0 header (compliance).+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. + # 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.
185-206
: Declare mutated cache args in custom op (fix alias analysis).update_kv_cache mutates k_cache/v_cache; annotate mutates_args accordingly.
-@torch.library.custom_op("auto_deploy::triton_attention_flattened_mha_with_cache", mutates_args=()) +@torch.library.custom_op( + "auto_deploy::triton_attention_flattened_mha_with_cache", mutates_args=(7, 8) +)
296-304
: Cast num_seq to int to avoid slicing issues.- num_seq = SequenceInfo._get_sanitized_num_sequences(position_ids, seq_len) + num_seq = int(SequenceInfo._get_sanitized_num_sequences(position_ids, seq_len))tensorrt_llm/_torch/auto_deploy/custom_ops/torch_backend_mamba.py (2)
1-1
: Add NVIDIA Apache-2.0 header (compliance).+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. + # 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.
156-175
: Fix mutates_args declaration (type and index).The op mutates ssm_state_cache (arg index 10). Current mutates_args={} is invalid and misses side effects.
-@torch.library.custom_op("auto_deploy::torch_cached_ssm_transform", mutates_args={}) +@torch.library.custom_op("auto_deploy::torch_cached_ssm_transform", mutates_args=(10,))tensorrt_llm/_torch/auto_deploy/custom_ops/attention_interface.py (2)
1-1
: Add NVIDIA Apache-2.0 header (compliance).+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. + # 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.
516-531
: Return Python int from _get_sanitized_num_sequences.Prevents downstream slicing/type issues in prepare_metadata ops.
@staticmethod def _get_sanitized_num_sequences( input_or_position_ids: torch.Tensor, seq_len: torch.Tensor ) -> int: @@ - b, s = input_or_position_ids.shape[:2] - if s > 1: - num_seq = torch.sum(seq_len > 0) + b, s = input_or_position_ids.shape[:2] + if s > 1: + num_seq = int(torch.sum(seq_len > 0).item()) assert seq_len[num_seq:].sum() == 0, "seq_len should be zero-padded" - else: - num_seq = b - return num_seq + else: + num_seq = int(b) + return num_seqtests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_kv_cache.py (1)
1-1
: Add NVIDIA Apache-2.0 header (tests).Apply the standard header for consistency/compliance.
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. + # 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.tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_cuda_causal_conv_cached_op.py (1)
1-1
: Add NVIDIA Apache-2.0 header (policy requirement)Per coding guidelines, prepend the standard NVIDIA Apache-2.0 header to all .py files.
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# +# 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.As per coding guidelines
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_torch_causal_conv_cached_op.py (1)
1-1
: Add NVIDIA Apache-2.0 header (policy requirement)Please prepend the standard NVIDIA Apache-2.0 header to this test file as well.
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# +# 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.As per coding guidelines
tensorrt_llm/_torch/auto_deploy/transform/library/export_to_gm.py (1)
1-1
: Add NVIDIA Apache-2.0 header (policy requirement)Please add the standard header to comply with repository guidelines.
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# +# 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.As per coding guidelines
tensorrt_llm/_torch/auto_deploy/transform/optimizer.py (1)
1-1
: Add NVIDIA Apache-2.0 header (policy requirement)Please prepend the standard header.
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# +# 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.As per coding guidelines
🧹 Nitpick comments (5)
tensorrt_llm/_torch/auto_deploy/custom_ops/torch_backend_attention.py (1)
381-389
: Fake variant: fix unused args and num_seq type.Prefix unused args; cast num_seq to int. Silences Ruff ARG001 and prevents slicing issues.
-@torch_backend_prepare_metadata.register_fake -def torch_backend_prepare_metadata_fake( - position_ids, seq_len, input_pos, cache_loc, pages_per_seq, slot_idx, page_size -): - num_seq = SequenceInfo._get_sanitized_num_sequences(position_ids, seq_len) +@torch_backend_prepare_metadata.register_fake +def torch_backend_prepare_metadata_fake( + position_ids, seq_len, input_pos, cache_loc, _pages_per_seq, _slot_idx, _page_size +): + num_seq = int(SequenceInfo._get_sanitized_num_sequences(position_ids, seq_len))tensorrt_llm/_torch/auto_deploy/custom_ops/triton_attention.py (1)
311-320
: Fake variant: fix unused args and num_seq type.-@prepare_fused_mha_metadata.register_fake -def prepare_fused_mha_metadata_fake( - position_ids, seq_len, input_pos, cache_loc, pages_per_seq, slot_idx, page_size -): - num_seq = SequenceInfo._get_sanitized_num_sequences(position_ids, seq_len) +@prepare_fused_mha_metadata.register_fake +def prepare_fused_mha_metadata_fake( + position_ids, seq_len, input_pos, cache_loc, _pages_per_seq, _slot_idx, _page_size +): + num_seq = int(SequenceInfo._get_sanitized_num_sequences(position_ids, seq_len))tensorrt_llm/_torch/auto_deploy/custom_ops/torch_backend_mamba.py (1)
144-154
: Fake variant: prefix unused args.Silences Ruff ARG001; no behavior change.
-@_torch_ssm_prepare_metadata.register_fake -def _torch_ssm_prepare_metadata_fake( - position_ids, seq_len, input_pos, cache_loc, pages_per_seq, slot_idx, page_size -): +@_torch_ssm_prepare_metadata.register_fake +def _torch_ssm_prepare_metadata_fake( + position_ids, seq_len, _input_pos, _cache_loc, _pages_per_seq, slot_idx, _page_size +):tensorrt_llm/_torch/auto_deploy/custom_ops/attention_interface.py (1)
328-333
: Minor: use tuple splat instead of concatenation.Cleaner and meets Ruff RUF005.
- return ("position_ids",) + self._cached_arg_names + return ("position_ids", *self._cached_arg_names)tensorrt_llm/_torch/auto_deploy/transform/optimizer.py (1)
60-63
: Fail fast if no build/load transform is configuredStarting with an empty nn.Module when mod is None can lead to opaque failures if the config lacks a builder/load transform. Add an early guard.
- # start with an empty model if not provided - if mod is None: - mod = nn.Module() + # start with an empty model if not provided + if mod is None: + # Require a build/load step in the pipeline if no model was passed in + has_builder = any( + name in self.config + for name in ("build_model", "build_and_load_factory_model", "load_weights") + ) + if not has_builder: + raise ValueError( + "No model provided and no build/load transform configured. " + "Pass an initialized nn.Module or include a build/load transform." + ) + mod = nn.Module()
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (24)
tensorrt_llm/_torch/auto_deploy/config/default.yaml
(5 hunks)tensorrt_llm/_torch/auto_deploy/config/transformers.yaml
(1 hunks)tensorrt_llm/_torch/auto_deploy/custom_ops/attention_interface.py
(3 hunks)tensorrt_llm/_torch/auto_deploy/custom_ops/cuda_backend_causal_conv.py
(2 hunks)tensorrt_llm/_torch/auto_deploy/custom_ops/flashinfer_attention.py
(2 hunks)tensorrt_llm/_torch/auto_deploy/custom_ops/mla.py
(2 hunks)tensorrt_llm/_torch/auto_deploy/custom_ops/torch_backend_attention.py
(2 hunks)tensorrt_llm/_torch/auto_deploy/custom_ops/torch_backend_causal_conv.py
(2 hunks)tensorrt_llm/_torch/auto_deploy/custom_ops/torch_backend_mamba.py
(2 hunks)tensorrt_llm/_torch/auto_deploy/custom_ops/triton_attention.py
(2 hunks)tensorrt_llm/_torch/auto_deploy/transform/interface.py
(9 hunks)tensorrt_llm/_torch/auto_deploy/transform/library/build_model.py
(4 hunks)tensorrt_llm/_torch/auto_deploy/transform/library/compile_model.py
(3 hunks)tensorrt_llm/_torch/auto_deploy/transform/library/export_to_gm.py
(2 hunks)tensorrt_llm/_torch/auto_deploy/transform/library/kvcache.py
(5 hunks)tensorrt_llm/_torch/auto_deploy/transform/library/kvcache_transformers.py
(6 hunks)tensorrt_llm/_torch/auto_deploy/transform/library/load_weights.py
(3 hunks)tensorrt_llm/_torch/auto_deploy/transform/optimizer.py
(1 hunks)tensorrt_llm/_torch/auto_deploy/transformations/_graph.py
(6 hunks)tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_cuda_causal_conv_cached_op.py
(1 hunks)tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_torch_attention_op.py
(2 hunks)tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_torch_causal_conv_cached_op.py
(1 hunks)tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_torch_mamba_cached_op.py
(1 hunks)tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_kv_cache.py
(1 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/auto_deploy/custom_ops/torch_backend_causal_conv.py
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_torch_attention_op.py
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_torch_mamba_cached_op.py
tensorrt_llm/_torch/auto_deploy/transform/library/kvcache.py
tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_kv_cache.py
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_torch_causal_conv_cached_op.py
tensorrt_llm/_torch/auto_deploy/transform/library/compile_model.py
tensorrt_llm/_torch/auto_deploy/custom_ops/torch_backend_mamba.py
tensorrt_llm/_torch/auto_deploy/transform/library/load_weights.py
tensorrt_llm/_torch/auto_deploy/custom_ops/flashinfer_attention.py
tensorrt_llm/_torch/auto_deploy/custom_ops/triton_attention.py
tensorrt_llm/_torch/auto_deploy/custom_ops/torch_backend_attention.py
tensorrt_llm/_torch/auto_deploy/transform/optimizer.py
tensorrt_llm/_torch/auto_deploy/custom_ops/cuda_backend_causal_conv.py
tensorrt_llm/_torch/auto_deploy/custom_ops/attention_interface.py
tensorrt_llm/_torch/auto_deploy/transformations/_graph.py
tensorrt_llm/_torch/auto_deploy/transform/library/build_model.py
tensorrt_llm/_torch/auto_deploy/transform/library/export_to_gm.py
tensorrt_llm/_torch/auto_deploy/transform/library/kvcache_transformers.py
tensorrt_llm/_torch/auto_deploy/transform/interface.py
tensorrt_llm/_torch/auto_deploy/custom_ops/mla.py
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_cuda_causal_conv_cached_op.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/auto_deploy/custom_ops/torch_backend_causal_conv.py
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_torch_attention_op.py
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_torch_mamba_cached_op.py
tensorrt_llm/_torch/auto_deploy/transform/library/kvcache.py
tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_kv_cache.py
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_torch_causal_conv_cached_op.py
tensorrt_llm/_torch/auto_deploy/transform/library/compile_model.py
tensorrt_llm/_torch/auto_deploy/custom_ops/torch_backend_mamba.py
tensorrt_llm/_torch/auto_deploy/transform/library/load_weights.py
tensorrt_llm/_torch/auto_deploy/custom_ops/flashinfer_attention.py
tensorrt_llm/_torch/auto_deploy/custom_ops/triton_attention.py
tensorrt_llm/_torch/auto_deploy/custom_ops/torch_backend_attention.py
tensorrt_llm/_torch/auto_deploy/transform/optimizer.py
tensorrt_llm/_torch/auto_deploy/custom_ops/cuda_backend_causal_conv.py
tensorrt_llm/_torch/auto_deploy/custom_ops/attention_interface.py
tensorrt_llm/_torch/auto_deploy/transformations/_graph.py
tensorrt_llm/_torch/auto_deploy/transform/library/build_model.py
tensorrt_llm/_torch/auto_deploy/transform/library/export_to_gm.py
tensorrt_llm/_torch/auto_deploy/transform/library/kvcache_transformers.py
tensorrt_llm/_torch/auto_deploy/transform/interface.py
tensorrt_llm/_torch/auto_deploy/custom_ops/mla.py
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_cuda_causal_conv_cached_op.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/auto_deploy/custom_ops/torch_backend_causal_conv.py
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_torch_attention_op.py
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_torch_mamba_cached_op.py
tensorrt_llm/_torch/auto_deploy/transform/library/kvcache.py
tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_kv_cache.py
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_torch_causal_conv_cached_op.py
tensorrt_llm/_torch/auto_deploy/transform/library/compile_model.py
tensorrt_llm/_torch/auto_deploy/custom_ops/torch_backend_mamba.py
tensorrt_llm/_torch/auto_deploy/transform/library/load_weights.py
tensorrt_llm/_torch/auto_deploy/custom_ops/flashinfer_attention.py
tensorrt_llm/_torch/auto_deploy/custom_ops/triton_attention.py
tensorrt_llm/_torch/auto_deploy/custom_ops/torch_backend_attention.py
tensorrt_llm/_torch/auto_deploy/transform/optimizer.py
tensorrt_llm/_torch/auto_deploy/custom_ops/cuda_backend_causal_conv.py
tensorrt_llm/_torch/auto_deploy/custom_ops/attention_interface.py
tensorrt_llm/_torch/auto_deploy/transformations/_graph.py
tensorrt_llm/_torch/auto_deploy/transform/library/build_model.py
tensorrt_llm/_torch/auto_deploy/transform/library/export_to_gm.py
tensorrt_llm/_torch/auto_deploy/transform/library/kvcache_transformers.py
tensorrt_llm/_torch/auto_deploy/transform/interface.py
tensorrt_llm/_torch/auto_deploy/custom_ops/mla.py
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_cuda_causal_conv_cached_op.py
🧬 Code graph analysis (17)
tensorrt_llm/_torch/auto_deploy/custom_ops/torch_backend_causal_conv.py (1)
tensorrt_llm/_torch/auto_deploy/custom_ops/attention_interface.py (2)
_get_sanitized_seq_len
(473-513)seq_len
(381-382)
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_torch_attention_op.py (1)
tensorrt_llm/_torch/auto_deploy/custom_ops/attention_interface.py (4)
seq_len
(381-382)input_pos
(385-386)cache_loc
(389-390)pages_per_seq
(393-394)
tensorrt_llm/_torch/auto_deploy/transform/library/kvcache.py (2)
tensorrt_llm/_torch/auto_deploy/transform/interface.py (4)
_apply_to_full_model
(490-500)SharedConfig
(60-66)TransformInfo
(121-174)BaseTransform
(213-500)tensorrt_llm/_torch/auto_deploy/shim/interface.py (3)
CachedSequenceInterface
(11-88)named_args
(28-30)initialize_caches
(59-66)
tensorrt_llm/_torch/auto_deploy/transform/library/compile_model.py (6)
tensorrt_llm/_torch/auto_deploy/transform/interface.py (4)
_apply_to_full_model
(490-500)SharedConfig
(60-66)TransformInfo
(121-174)get
(519-521)tensorrt_llm/_torch/auto_deploy/transform/library/build_model.py (2)
_apply_to_full_model
(39-52)_apply_to_full_model
(68-92)tensorrt_llm/_torch/auto_deploy/transform/library/export_to_gm.py (1)
_apply_to_full_model
(52-76)tensorrt_llm/_torch/auto_deploy/transform/library/kvcache_transformers.py (2)
_apply_to_full_model
(110-136)_apply_to_full_model
(247-277)tensorrt_llm/_torch/auto_deploy/shim/interface.py (1)
CachedSequenceInterface
(11-88)tensorrt_llm/_torch/auto_deploy/compile/compiler.py (2)
CompileBackendRegistry
(12-31)get
(25-27)
tensorrt_llm/_torch/auto_deploy/custom_ops/torch_backend_mamba.py (1)
tensorrt_llm/_torch/auto_deploy/custom_ops/attention_interface.py (6)
SequenceInfo
(50-812)_get_sanitized_seq_len
(473-513)seq_len
(381-382)input_pos
(385-386)cache_loc
(389-390)pages_per_seq
(393-394)
tensorrt_llm/_torch/auto_deploy/transform/library/load_weights.py (6)
tensorrt_llm/_torch/auto_deploy/transform/interface.py (3)
_apply_to_full_model
(490-500)SharedConfig
(60-66)TransformInfo
(121-174)tensorrt_llm/_torch/auto_deploy/transform/library/build_model.py (2)
_apply_to_full_model
(39-52)_apply_to_full_model
(68-92)tensorrt_llm/_torch/auto_deploy/transform/library/compile_model.py (1)
_apply_to_full_model
(42-65)tensorrt_llm/_torch/auto_deploy/transform/library/export_to_gm.py (1)
_apply_to_full_model
(52-76)tensorrt_llm/_torch/auto_deploy/models/factory.py (2)
ModelFactory
(23-266)load_or_random_init
(168-209)tensorrt_llm/_torch/auto_deploy/transformations/_graph.py (1)
move_to_device
(135-142)
tensorrt_llm/_torch/auto_deploy/custom_ops/flashinfer_attention.py (1)
tensorrt_llm/_torch/auto_deploy/custom_ops/attention_interface.py (6)
seq_len
(381-382)SequenceInfo
(50-812)_get_sanitized_seq_len
(473-513)input_pos
(385-386)cache_loc
(389-390)pages_per_seq
(393-394)
tensorrt_llm/_torch/auto_deploy/custom_ops/triton_attention.py (1)
tensorrt_llm/_torch/auto_deploy/custom_ops/attention_interface.py (2)
_get_sanitized_num_sequences
(516-531)seq_len
(381-382)
tensorrt_llm/_torch/auto_deploy/custom_ops/torch_backend_attention.py (1)
tensorrt_llm/_torch/auto_deploy/custom_ops/attention_interface.py (2)
_get_sanitized_num_sequences
(516-531)seq_len
(381-382)
tensorrt_llm/_torch/auto_deploy/transform/optimizer.py (2)
tensorrt_llm/_torch/auto_deploy/shim/interface.py (1)
CachedSequenceInterface
(11-88)tensorrt_llm/_torch/auto_deploy/transform/interface.py (2)
TransformRegistry
(503-531)get
(519-521)
tensorrt_llm/_torch/auto_deploy/custom_ops/cuda_backend_causal_conv.py (1)
tensorrt_llm/_torch/auto_deploy/custom_ops/attention_interface.py (2)
_get_sanitized_seq_len
(473-513)seq_len
(381-382)
tensorrt_llm/_torch/auto_deploy/transformations/_graph.py (1)
tensorrt_llm/module.py (1)
Module
(33-226)
tensorrt_llm/_torch/auto_deploy/transform/library/build_model.py (6)
tensorrt_llm/_torch/auto_deploy/transform/interface.py (3)
_apply_to_full_model
(490-500)SharedConfig
(60-66)TransformInfo
(121-174)tensorrt_llm/_torch/auto_deploy/transform/library/compile_model.py (1)
_apply_to_full_model
(42-65)tensorrt_llm/_torch/auto_deploy/transform/library/export_to_gm.py (1)
_apply_to_full_model
(52-76)tensorrt_llm/_torch/auto_deploy/transform/library/kvcache.py (2)
_apply_to_full_model
(242-314)_apply_to_full_model
(319-333)tensorrt_llm/_torch/auto_deploy/transform/library/kvcache_transformers.py (2)
_apply_to_full_model
(110-136)_apply_to_full_model
(247-277)tensorrt_llm/_torch/auto_deploy/models/factory.py (3)
ModelFactory
(23-266)model
(54-56)build_model
(63-102)
tensorrt_llm/_torch/auto_deploy/transform/library/export_to_gm.py (5)
tensorrt_llm/_torch/auto_deploy/transform/interface.py (3)
_apply_to_full_model
(490-500)SharedConfig
(60-66)TransformInfo
(121-174)tensorrt_llm/_torch/auto_deploy/shim/interface.py (1)
CachedSequenceInterface
(11-88)tensorrt_llm/_torch/auto_deploy/models/factory.py (2)
ModelFactory
(23-266)get_example_inputs
(239-249)tensorrt_llm/_torch/auto_deploy/custom_ops/attention_interface.py (1)
set_example_sequence
(560-590)tensorrt_llm/_torch/auto_deploy/export/export.py (1)
torch_export_to_gm
(198-273)
tensorrt_llm/_torch/auto_deploy/transform/library/kvcache_transformers.py (3)
tensorrt_llm/_torch/auto_deploy/transform/interface.py (4)
_apply_to_full_model
(490-500)SharedConfig
(60-66)TransformInfo
(121-174)_apply
(475-488)tensorrt_llm/_torch/auto_deploy/transform/library/kvcache.py (4)
_apply_to_full_model
(242-314)_apply_to_full_model
(319-333)_apply
(37-61)_apply
(132-207)tensorrt_llm/_torch/auto_deploy/shim/interface.py (2)
CachedSequenceInterface
(11-88)named_args
(28-30)
tensorrt_llm/_torch/auto_deploy/transform/interface.py (5)
tensorrt_llm/_torch/auto_deploy/shim/interface.py (2)
CachedSequenceInterface
(11-88)args
(23-25)tensorrt_llm/_torch/auto_deploy/transformations/_graph.py (5)
run_shape_prop
(218-243)named_graphmodules
(95-99)canonicalize_graph
(174-187)lift_to_meta
(79-92)placeholders_on_meta
(312-341)tensorrt_llm/_torch/auto_deploy/transform/library/build_model.py (2)
_apply_to_full_model
(39-52)_apply_to_full_model
(68-92)tensorrt_llm/_torch/auto_deploy/transform/library/compile_model.py (1)
_apply_to_full_model
(42-65)tensorrt_llm/_torch/auto_deploy/transform/library/export_to_gm.py (1)
_apply_to_full_model
(52-76)
tensorrt_llm/_torch/auto_deploy/custom_ops/mla.py (2)
tensorrt_llm/_torch/auto_deploy/custom_ops/attention_interface.py (5)
_get_sanitized_num_sequences
(516-531)seq_len
(381-382)input_pos
(385-386)cache_loc
(389-390)pages_per_seq
(393-394)tensorrt_llm/_torch/attention_backend/flashinfer.py (1)
page_size
(185-189)
🪛 Ruff (0.13.3)
tensorrt_llm/_torch/auto_deploy/custom_ops/torch_backend_causal_conv.py
169-169: Unused function argument: input_pos
(ARG001)
169-169: Unused function argument: cache_loc
(ARG001)
169-169: Unused function argument: pages_per_seq
(ARG001)
169-169: Unused function argument: page_size
(ARG001)
tensorrt_llm/_torch/auto_deploy/transform/library/kvcache.py
246-246: Unused method argument: factory
(ARG002)
247-247: Unused method argument: shared_config
(ARG002)
323-323: Unused method argument: factory
(ARG002)
324-324: Unused method argument: shared_config
(ARG002)
tensorrt_llm/_torch/auto_deploy/transform/library/compile_model.py
46-46: Unused method argument: factory
(ARG002)
47-47: Unused method argument: shared_config
(ARG002)
tensorrt_llm/_torch/auto_deploy/custom_ops/torch_backend_mamba.py
144-144: Unused function argument: input_pos
(ARG001)
144-144: Unused function argument: cache_loc
(ARG001)
144-144: Unused function argument: pages_per_seq
(ARG001)
144-144: Unused function argument: page_size
(ARG001)
tensorrt_llm/_torch/auto_deploy/transform/library/load_weights.py
42-42: Unused method argument: cm
(ARG002)
44-44: Unused method argument: shared_config
(ARG002)
71-71: Unused method argument: factory
(ARG002)
72-72: Unused method argument: shared_config
(ARG002)
tensorrt_llm/_torch/auto_deploy/custom_ops/flashinfer_attention.py
216-216: Unused function argument: input_pos
(ARG001)
216-216: Unused function argument: pages_per_seq
(ARG001)
216-216: Unused function argument: slot_idx
(ARG001)
216-216: Unused function argument: page_size
(ARG001)
tensorrt_llm/_torch/auto_deploy/custom_ops/triton_attention.py
311-311: Unused function argument: pages_per_seq
(ARG001)
311-311: Unused function argument: slot_idx
(ARG001)
311-311: Unused function argument: page_size
(ARG001)
tensorrt_llm/_torch/auto_deploy/custom_ops/torch_backend_attention.py
381-381: Unused function argument: pages_per_seq
(ARG001)
381-381: Unused function argument: slot_idx
(ARG001)
381-381: Unused function argument: page_size
(ARG001)
tensorrt_llm/_torch/auto_deploy/custom_ops/cuda_backend_causal_conv.py
83-83: Unused function argument: input_pos
(ARG001)
83-83: Unused function argument: cache_loc
(ARG001)
83-83: Unused function argument: pages_per_seq
(ARG001)
83-83: Unused function argument: page_size
(ARG001)
tensorrt_llm/_torch/auto_deploy/custom_ops/attention_interface.py
332-332: Consider ("position_ids", *self._cached_arg_names)
instead of concatenation
Replace with ("position_ids", *self._cached_arg_names)
(RUF005)
tensorrt_llm/_torch/auto_deploy/transform/library/build_model.py
41-41: Unused method argument: mod
(ARG002)
42-42: Unused method argument: cm
(ARG002)
44-44: Unused method argument: shared_config
(ARG002)
70-70: Unused method argument: mod
(ARG002)
73-73: Unused method argument: shared_config
(ARG002)
tensorrt_llm/_torch/auto_deploy/transform/library/export_to_gm.py
57-57: Unused method argument: shared_config
(ARG002)
tensorrt_llm/_torch/auto_deploy/transform/library/kvcache_transformers.py
114-114: Unused method argument: factory
(ARG002)
115-115: Unused method argument: shared_config
(ARG002)
tensorrt_llm/_torch/auto_deploy/transform/interface.py
346-346: Do not catch blind exception: Exception
(BLE001)
tensorrt_llm/_torch/auto_deploy/custom_ops/mla.py
199-199: Unused function argument: position_ids
(ARG001)
199-199: Unused function argument: pages_per_seq
(ARG001)
199-199: Unused function argument: slot_idx
(ARG001)
199-199: Unused function argument: page_size
(ARG001)
⏰ 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 (27)
tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_kv_cache.py (1)
166-176
: LGTM: per‑module execution toggles added.run_per_gm=False in factory/export aligns with module‑level transform flow.
Also applies to: 172-176
tensorrt_llm/_torch/auto_deploy/config/transformers.yaml (1)
9-9
: ```bash
#!/bin/bash
set -euo pipefailtransforms=(
build_and_load_factory_model
move_inputs_to_device
detect_hf_attn_layers
transformers_replace_cached_attn
initialize_cache
resize_kv_cache
)for t in "${transforms[@]}"; do
echo "Checking transform: $t"
files=$(rg -l -t py "@TransformRegistry\.register\("$t"\)")
if [[ -z "$files" ]]; then
echo " ✗ no registration found for $t"
continue
fi
for f in $files; do
echo " File: $f"
if grep -q -n "def _apply_to_full_model" "$f"; then
grep -n "def _apply_to_full_model" "$f"
else
echo " ✗ _apply_to_full_model not implemented"
fi
done
done</blockquote></details> <details> <summary>tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_cuda_causal_conv_cached_op.py (1)</summary><blockquote> `179-179`: **API alignment confirmed**: All causal_conv_prepare_metadata calls now use only position_ids and seq_len; no input_ids remain. </blockquote></details> <details> <summary>tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_torch_causal_conv_cached_op.py (1)</summary><blockquote> `171-171`: **API alignment confirmed: input_ids removal complete** All torch_causal_conv_prepare_metadata call sites and tests updated to the new signature without input_ids. </blockquote></details> <details> <summary>tensorrt_llm/_torch/auto_deploy/transform/library/export_to_gm.py (1)</summary><blockquote> `63-71`: **Full-model export path LGTM; manually verify example-input keys match forward signature** Ensure `factory.get_example_inputs()` returns keys that align with the model’s `forward` signature, since `kwargs=cm.named_args` will be used. </blockquote></details> <details> <summary>tensorrt_llm/_torch/auto_deploy/transform/library/compile_model.py (1)</summary><blockquote> `42-65`: **LGTM! Clean refactor to full-model transform.** The method signature and implementation correctly shift from GraphModule-based to nn.Module-based transformation, aligning with the PR's objective to support per-full-model execution. </blockquote></details> <details> <summary>tensorrt_llm/_torch/auto_deploy/config/default.yaml (6)</summary><blockquote> `9-9`: **LGTM! Configuration aligns with full-model transform.** Setting `run_per_gm: false` correctly configures the build_model transform to operate on the full model instead of per-GraphModule, consistent with the implementation changes. --- `18-19`: **LGTM! Cleanup enabled after export.** Enabling `run_graph_cleanup: true` ensures the exported graph is canonicalized, which is appropriate for a newly exported GraphModule. --- `39-39`: **LGTM! Shape propagation requirement added.** Setting `requires_shape_prop: true` ensures shape information is available before matching eager attention patterns, which is likely needed for pattern recognition. --- `92-96`: **LGTM! Weight loading transforms configured for full-model execution.** Both load_weights and move_inputs_to_device are correctly configured with `run_per_gm: false` to operate on the full model. --- `145-148`: **LGTM! Cache initialization transforms configured for full-model execution.** Both initialize_cache and resize_kv_cache are correctly configured with `run_per_gm: false`, consistent with their implementations that operate on the full model. --- `154-154`: **LGTM! Compilation transform configured for full-model execution.** Setting `run_per_gm: false` for compile_model aligns with the implementation that compiles the entire model. </blockquote></details> <details> <summary>tensorrt_llm/_torch/auto_deploy/custom_ops/flashinfer_attention.py (2)</summary><blockquote> `156-209`: **LGTM! Public API correctly updated to use position_ids.** The function signature and implementation now use `position_ids` as the primary sequence reference instead of `input_ids`, aligning with the broader refactor to standardize metadata preparation across custom ops. The sequence length sanitization logic remains correct. --- `215-227`: **LGTM! Fake variant updated consistently.** The fake registration correctly mirrors the real variant's signature and sanitization logic using `position_ids`. </blockquote></details> <details> <summary>tensorrt_llm/_torch/auto_deploy/transform/library/build_model.py (2)</summary><blockquote> `39-52`: **LGTM! Transform correctly operates on full model.** The signature change from `_apply` to `_apply_to_full_model` with `nn.Module` parameter type aligns with the per-full-model execution strategy. The logic correctly builds the model via factory and returns appropriate metadata. --- `68-92`: **LGTM! Consistent refactor for build-and-load variant.** The signature changes mirror those in BuildModel, maintaining consistency across the transform hierarchy. </blockquote></details> <details> <summary>tensorrt_llm/_torch/auto_deploy/transform/library/kvcache.py (2)</summary><blockquote> `242-314`: **LGTM! Cache resize transform correctly refactored.** The method signature and implementation updated to operate on the full model (`nn.Module`) instead of per-GraphModule. The forward pass invocation (line 278) and all return statements correctly use `mod`. --- `319-333`: **LGTM! Cache initialization transform correctly refactored.** The signature changes are consistent with the ResizeKVCache transform, maintaining uniform interfaces across cache-related transforms. </blockquote></details> <details> <summary>tensorrt_llm/_torch/auto_deploy/custom_ops/cuda_backend_causal_conv.py (2)</summary><blockquote> `56-78`: **LGTM! Metadata preparation updated to use position_ids.** The function signature correctly removes `input_ids` and uses `position_ids` as the primary sequence reference. The sanitization logic (line 69) is updated consistently. --- `82-91`: **LGTM! Fake variant updated consistently.** The fake registration mirrors the real variant's signature and sanitization approach using `position_ids`. </blockquote></details> <details> <summary>tensorrt_llm/_torch/auto_deploy/transform/library/kvcache_transformers.py (2)</summary><blockquote> `110-136`: **LGTM! Transform correctly profiles attention layers on full model.** The refactor to `_apply_to_full_model` is correct. The approach of attaching a fake GraphModule (`mod._gm`) to the model for profiling is appropriate for HuggingFace transformers, where we need to track attention nodes without full graph export. --- `247-277`: **LGTM! Cached attention replacement correctly integrated.** The transform properly: 1. Switches to cached attention inputs 2. Runs the parent transform on the fake GraphModule (`mod._gm`) 3. Registers the cached attention operator 4. Patches the forward method to inject metadata preparation 5. Updates config only for submodules with attention nodes This hybrid approach (full model + fake GraphModule) is appropriate for transformers models. </blockquote></details> <details> <summary>tensorrt_llm/_torch/auto_deploy/transform/interface.py (5)</summary><blockquote> `121-175`: **LGTM! TransformInfo composition operators enhance maintainability.** The addition of: - `from_last_info` class method for initializing from previous transform state - `__or__` operator for OR-merging (is_clean=True if either is clean) - `__and__` operator for AND-merging (is_clean=True only if both are clean) These operators enable cleaner composition of transform metadata throughout the pipeline, replacing in-place dict updates with functional composition. --- `277-417`: **LGTM! Transform execution flow correctly refactored.** The changes successfully: 1. Replace GraphModule-centric types with nn.Module throughout 2. Use TransformInfo operators for cleaner metadata composition 3. Introduce `_apply_per_gm_or_whole_model` to dispatch between execution modes 4. Update all internal references from `gm` to `mod` The logic is preserved and the new structure supports both per-GraphModule and full-model transform execution. --- `439-473`: **LGTM! Cleanup logic consolidated effectively.** The new `_run_cleanup` method consolidates the previous pre/post cleanup logic into a single, well-structured method. The conditional logic correctly handles: - Shape propagation requirements (clean_shape → canonicalize + run_shape_prop) - Graph cleanup requirements (clean_graph → canonicalize only) - Conditional execution based on current state (is_clean, has_valid_shapes) This reduces code duplication and improves maintainability. --- `475-500`: **LGTM! Dual execution mode support added.** The addition of `_apply_to_full_model` alongside the existing `_apply` method enables transforms to support either per-GraphModule or full-model execution. The NotImplementedError messages clearly indicate which mode each transform supports, guiding implementation. --- `85-85`: **run_per_gm default change verified safe** All transforms explicitly set run_per_gm in their configs; changing the default to True will not alter existing behavior. </blockquote></details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
def _apply_to_full_model( | ||
self, | ||
gm: GraphModule, | ||
mod: nn.Module, | ||
cm: CachedSequenceInterface, | ||
factory: ModelFactory, | ||
shared_config: SharedConfig, | ||
) -> Tuple[GraphModule, TransformInfo]: | ||
# at this point we assume the gm is just a dummy graph module | ||
assert len(gm.graph.nodes) == 0, "Expected empty graph module." | ||
|
||
# retrieve the actual model from the dummy graph module | ||
model = gm.get_submodule("factory_model") | ||
|
||
) -> Tuple[nn.Module, TransformInfo]: | ||
# set the example sequence |
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.
Minor: silence unused shared_config
shared_config is required by the interface but unused here; silence the linter.
def _apply_to_full_model(
self,
mod: nn.Module,
cm: CachedSequenceInterface,
factory: ModelFactory,
- shared_config: SharedConfig,
+ shared_config: SharedConfig,
) -> Tuple[nn.Module, TransformInfo]:
+ _ = shared_config # intentionally unused
📝 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.
def _apply_to_full_model( | |
self, | |
gm: GraphModule, | |
mod: nn.Module, | |
cm: CachedSequenceInterface, | |
factory: ModelFactory, | |
shared_config: SharedConfig, | |
) -> Tuple[GraphModule, TransformInfo]: | |
# at this point we assume the gm is just a dummy graph module | |
assert len(gm.graph.nodes) == 0, "Expected empty graph module." | |
# retrieve the actual model from the dummy graph module | |
model = gm.get_submodule("factory_model") | |
) -> Tuple[nn.Module, TransformInfo]: | |
# set the example sequence | |
def _apply_to_full_model( | |
self, | |
mod: nn.Module, | |
cm: CachedSequenceInterface, | |
factory: ModelFactory, | |
shared_config: SharedConfig, | |
) -> Tuple[nn.Module, TransformInfo]: | |
_ = shared_config # intentionally unused | |
# set the example sequence |
🧰 Tools
🪛 Ruff (0.13.3)
57-57: Unused method argument: shared_config
(ARG002)
🤖 Prompt for AI Agents
In tensorrt_llm/_torch/auto_deploy/transform/library/export_to_gm.py around
lines 52 to 59, the shared_config parameter is required by the interface but
unused in _apply_to_full_model; silence the linter by explicitly referencing it
(for example add a line like "del shared_config" or "_ = shared_config #
silence unused parameter" at the start of the function) so the signature remains
unchanged and the unused-argument warning is suppressed.
def move_to_device(mod: nn.Module, device: DeviceLikeType) -> None: | ||
"""Move the entire graph module and all sub-GraphModules to the specified device.""" | ||
# get device | ||
device = torch.device(device) | ||
|
||
for _, subgm in reversed(list(named_graphmodules(gm))): | ||
for _, subgm in reversed(list(named_graphmodules(mod))): | ||
# recompile graph to update self generated codes in subgraph | ||
_move_single_gm_to_device(subgm, device) | ||
|
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.
Regression: non-FX modules never leave the checkpoint device
move_to_device
now iterates only over GraphModule
s. When the pipeline hands us a plain nn.Module
(the default right after build_model
/load_weights
), this loop is empty, so nothing moves. We rely on this helper immediately after loading weights (often onto CPU via adconfig_checkpoint_device
) to push the assembled model to the final target device. After this change, the model simply stays on the checkpoint device and the next stages run with tensors on the wrong device. Please restore the old behavior by moving the root module as well before fixing up FX submodules.
def move_to_device(mod: nn.Module, device: DeviceLikeType) -> None:
"""Move the entire graph module and all sub-GraphModules to the specified device."""
# get device
device = torch.device(device)
+ mod.to(device)
+
for _, subgm in reversed(list(named_graphmodules(mod))):
# recompile graph to update self generated codes in subgraph
_move_single_gm_to_device(subgm, device)
📝 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.
def move_to_device(mod: nn.Module, device: DeviceLikeType) -> None: | |
"""Move the entire graph module and all sub-GraphModules to the specified device.""" | |
# get device | |
device = torch.device(device) | |
for _, subgm in reversed(list(named_graphmodules(gm))): | |
for _, subgm in reversed(list(named_graphmodules(mod))): | |
# recompile graph to update self generated codes in subgraph | |
_move_single_gm_to_device(subgm, device) | |
def move_to_device(mod: nn.Module, device: DeviceLikeType) -> None: | |
"""Move the entire graph module and all sub-GraphModules to the specified device.""" | |
# get device | |
device = torch.device(device) | |
mod.to(device) | |
for _, subgm in reversed(list(named_graphmodules(mod))): | |
# recompile graph to update self generated codes in subgraph | |
_move_single_gm_to_device(subgm, device) |
🤖 Prompt for AI Agents
In tensorrt_llm/_torch/auto_deploy/transformations/_graph.py around lines 135 to
143, the function only moves FX GraphModules and omits moving the root
nn.Module, so non-FX root modules remain on the checkpoint device; restore
behavior by first converting the device (torch.device(device)) and calling
mod.to(device) to move the root module, then iterate
reversed(named_graphmodules(mod)) and call _move_single_gm_to_device(subgm,
device) for each FX submodule so the root and all sub-GraphModules end up on the
target device.
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.
TODO for @lucaslie. that seems relevant
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.
@lucaslie, confirmed - this is indeed relevant. The current implementation will skip moving the root module when it's a plain nn.Module
(not a GraphModule
), which would cause the model to remain on the checkpoint device after load_weights
.
The suggested fix looks correct: adding mod.to(device)
before the loop ensures the root module and all its non-FX submodules are moved, while the subsequent loop handles the FX-specific node metadata updates for any GraphModule children.
PR_Github #20677 [ run ] completed with state |
|
||
# retrieve sanitzed metadata | ||
seq_len = SequenceInfo._get_sanitized_seq_len(input_ids, seq_len) | ||
seq_len = SequenceInfo._get_sanitized_seq_len(position_ids, seq_len) |
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.
looks like we really only need either input_ids/position_ids to compute seq_len or num_seq. Would it not be better to provide seq_len as inputs to the prepare metadata op?
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.
I agree and long-term this should be the goal. Note that non-truncated seq_len
is already passed in.
However, right now we use position_ids
shape to infer num sequences and sequence length for decode-only batches ([b, 1]
) because in such instance we don't want to rely on using seq_len
directly to make it cudagraph-compatible.
Unfortunately, there is a bit of technical limitation we are facing here for extracting number of sequences for all use cases:
- torch export graphs only want tensors as input --> so we can't pass in integres
- cudagraph doesn't want us to access data (
.item()
) during graph capture --> so we can't use tensors
The trick we are using right now is to "sneak in" an integer-like input via the tensor shape. When we get rid of position_ids
here we don't have a good way anymore
So this would require some more work that I didn't want to mix in with this PR
/bot run |
PR_Github #20819 [ run ] triggered by Bot |
PR_Github #20819 [ run ] completed with state |
Signed-off-by: Lucas Liebenwein <[email protected]>
4bd6884
to
43965a2
Compare
), | ||
get_small_model_config_pytest_param( | ||
"mistralai/Mistral-Small-3.1-24B-Instruct-2503", | ||
pytest_param_kwargs={ |
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.
seems to fail on A30. Will reenable with the changes in #8203
/bot run |
PR_Github #20823 [ run ] triggered by Bot |
PR_Github #20823 [ run ] completed with state |
Summary by CodeRabbit
Breaking Changes
New Features
Refactor
Tests
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
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-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.