Skip to content

Conversation

@leslie-fang25
Copy link
Collaborator

@leslie-fang25 leslie-fang25 commented Oct 20, 2025

Summary by CodeRabbit

  • Refactor
    • Streamlined PyTorch executor model engine initialization by consolidating multiple configuration parameters into a unified object, improving API consistency and maintainability.

Description

Refine PyTorchModelEngine with llm args.

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 the stage-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.

@leslie-fang25
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #21866 [ run ] triggered by Bot. Commit: ca554d3

@tensorrt-cicd
Copy link
Collaborator

PR_Github #21866 [ run ] completed with state SUCCESS. Commit: ca554d3
/LLM/main/L0_MergeRequest_PR pipeline #16484 completed with status: 'FAILURE'

@leslie-fang25
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #21890 [ run ] triggered by Bot. Commit: ca554d3

@tensorrt-cicd
Copy link
Collaborator

PR_Github #21890 [ run ] completed with state SUCCESS. Commit: ca554d3
/LLM/main/L0_MergeRequest_PR pipeline #16502 completed with status: 'SUCCESS'

@leslie-fang25 leslie-fang25 marked this pull request as ready for review October 21, 2025 01:11
@leslie-fang25 leslie-fang25 requested a review from a team as a code owner October 21, 2025 01:11
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 21, 2025

📝 Walkthrough

Walkthrough

Refactors PyTorchModelEngine constructor to consolidate multiple runtime configuration parameters (batch_size, max_beam_width, max_num_tokens, max_seq_len, sparse_attention_config, lora_config) and checkpoint_loader into a single llm_args object. Updates all call sites in executor creator and tests accordingly.

Changes

Cohort / File(s) Change Summary
Core Refactoring
tensorrt_llm/_torch/pyexecutor/model_engine.py
Updated PyTorchModelEngine.__init__ to replace seven individual parameters (checkpoint_loader, batch_size, max_beam_width, max_num_tokens, max_seq_len, sparse_attention_config, lora_config) with single llm_args parameter. Internal initialization extracts configuration from llm_args and dynamically constructs checkpoint_loader via _construct_checkpoint_loader.
Usage Updates
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py
Removed checkpoint_loader construction and sparse_attention_config extraction. Updated PyTorchModelEngine and draft model instantiation to pass consolidated llm_args instead of individual parameters. KvCacheCreator and related calls updated to reference llm_args fields.
Test Updates
tests/unittest/_torch/executor/test_pytorch_model_engine.py
Refactored test to construct TorchLlmArgs object and pass as llm_args parameter. Removed individual batch_size and max_seq_len parameter passing. Updated model_path from empty string to "dummy".

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

The changes represent a systematic parameter consolidation refactoring applied consistently across three files with clear, repetitive patterns. While each file requires understanding the new llm_args-driven structure, the modifications follow a cohesive theme—extracting parameters from llm_args instead of passing them individually—reducing cognitive burden compared to heterogeneous changes. Logic density is moderate, centered on initialization and checkpoint loader construction.

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The PR description is largely incomplete compared to the template requirements. The "Description" section contains only one sentence ("Refine PyTorchModelEngine with llm args.") without explaining the issue being solved or the motivation for the refactoring. The "Test Coverage" section is entirely empty with no mention of which tests safeguard these changes, despite the raw summary indicating that tests were modified. Most of the PR checklist items remain unchecked, with only the final catch-all checkbox marked. While the changes themselves are substantial (consolidating multiple parameters into a centralized llm_args object across multiple files) and have passed CI tests, the description fails to provide the context and detail required by the template. Add a substantive Description section explaining the rationale for consolidating the PyTorchModelEngine constructor parameters into an llm_args object and the benefits of this refactoring. Complete the Test Coverage section by listing the specific test files and test cases that validate these changes (e.g., tests/unittest/_torch/executor/test_pytorch_model_engine.py). Review and appropriately check the individual PR checklist items to verify compliance with coding guidelines, test coverage, and documentation requirements.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The PR title "[TRTLLM-8754][chore] Refine PyTorchModelEngine with llm args" is fully related to the main change in the changeset, which involves consolidating multiple constructor parameters (batch_size, max_beam_width, max_num_tokens, max_seq_len, sparse_attention_config, checkpoint_loader, and lora_config) into a single llm_args parameter in PyTorchModelEngine. The title follows the required format with a JIRA ticket ID and type designation, is concise and clear, and would allow teammates scanning commit history to understand the primary refactoring being performed.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
tests/unittest/_torch/executor/test_pytorch_model_engine.py (1)

1-1: Add NVIDIA Apache-2.0 header (2025) at file top.

Required by project guidelines for all .py files.

Apply something like:

+# 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.
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (1)

1-1: Add NVIDIA Apache-2.0 header (2025) at file top.

Required for all source files.

See header snippet provided in another comment.

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

1-1: Add NVIDIA Apache-2.0 header (2025) at file top.

Compliance requirement for .py files.

See header snippet provided previously.

♻️ Duplicate comments (1)
tensorrt_llm/_torch/pyexecutor/model_engine.py (1)

133-134: Consolidate config source in a follow‑up (duplicate of prior review).

pytorch_backend_config exists purely as a mirror of llm_args; long‑term, derive it inside and drop the param to prevent drift. [duplicate of QiJune’s note]

🧹 Nitpick comments (4)
tests/unittest/_torch/executor/test_pytorch_model_engine.py (1)

83-94: Use module‑level import and avoid duplicating model path source.

  • Move TorchLlmArgs import to the top (module namespace) per guidelines.
  • Prefer llm_args.model over a separate model_path literal to keep a single source of truth.

Minimal changes:

-        from tensorrt_llm.llmapi.llm_args import TorchLlmArgs
-
-        model_path = "dummy"
-        llm_args = TorchLlmArgs(model=model_path,
+        llm_args = TorchLlmArgs(model="dummy",
                                 max_batch_size=batch_size,
                                 max_seq_len=max_seq_len)
-        super().__init__(model_path=model_path,
+        super().__init__(model_path=llm_args.model,
                          pytorch_backend_config=pytorch_backend_config,
                          mapping=mapping,
                          model=model,
                          llm_args=llm_args)

And at the top of the file add:

+from tensorrt_llm.llmapi.llm_args import TorchLlmArgs
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (1)

313-324: Source of truth for model path: prefer llm_args.model when checkpoint_dir is None.

Avoid divergence between checkpoint_dir and llm_args.model. Safer default:

-        model_engine = PyTorchModelEngine(
-            model_path=checkpoint_dir,
+        model_engine = PyTorchModelEngine(
+            model_path=checkpoint_dir or llm_args.model,
             pytorch_backend_config=pytorch_backend_config,
             mapping=mapping,
             attn_runtime_features=attn_runtime_features,
             dist=dist,
             spec_config=spec_config,
             llm_args=llm_args,
         )
tensorrt_llm/_torch/pyexecutor/model_engine.py (2)

151-154: Checkpoint loader construction: OK. Consider storing for later reuse.

If later reloads or diagnostics are needed, keep a reference (e.g., self.checkpoint_loader = checkpoint_loader). Optional.


155-161: Defensive: ensure mapping is non‑None.

Engine assumes mapping (calls mapping.has_pp()); add an early assert or default mapping fallback to avoid NPEs.

-        self.mapping = mapping
+        assert mapping is not None, "mapping must be provided (use llm_args.parallel_config.to_mapping())"
+        self.mapping = mapping
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d05079b and ca554d3.

📒 Files selected for processing (3)
  • tensorrt_llm/_torch/pyexecutor/model_engine.py (6 hunks)
  • tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (4 hunks)
  • tests/unittest/_torch/executor/test_pytorch_model_engine.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/pyexecutor/py_executor_creator.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tests/unittest/_torch/executor/test_pytorch_model_engine.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/pyexecutor/py_executor_creator.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tests/unittest/_torch/executor/test_pytorch_model_engine.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/pyexecutor/py_executor_creator.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tests/unittest/_torch/executor/test_pytorch_model_engine.py
🧠 Learnings (2)
📚 Learning: 2025-08-26T09:37:10.463Z
Learnt from: jiaganc
PR: NVIDIA/TensorRT-LLM#7031
File: tensorrt_llm/bench/dataclasses/configuration.py:90-104
Timestamp: 2025-08-26T09:37:10.463Z
Learning: In TensorRT-LLM, the `get_pytorch_perf_config()` method returns `self.pytorch_config` which can contain default `cuda_graph_config` values, so `llm_args` may already have this config before the extra options processing.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/model_engine.py
📚 Learning: 2025-08-26T09:37:10.463Z
Learnt from: jiaganc
PR: NVIDIA/TensorRT-LLM#7031
File: tensorrt_llm/bench/dataclasses/configuration.py:90-104
Timestamp: 2025-08-26T09:37:10.463Z
Learning: In TensorRT-LLM's bench configuration, the `get_pytorch_perf_config()` method returns `self.pytorch_config` which is a Dict[str, Any] that can contain default values including `cuda_graph_config`, making the fallback `llm_args["cuda_graph_config"]` safe to use.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/model_engine.py
🧬 Code graph analysis (3)
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (1)
tensorrt_llm/_torch/pyexecutor/config.py (1)
  • PyTorchConfig (16-117)
tensorrt_llm/_torch/pyexecutor/model_engine.py (3)
tensorrt_llm/llmapi/llm_args.py (1)
  • TorchLlmArgs (2382-2842)
tensorrt_llm/_torch/pyexecutor/config.py (1)
  • _construct_checkpoint_loader (171-193)
tensorrt_llm/lora_helper.py (1)
  • LoraConfig (84-103)
tests/unittest/_torch/executor/test_pytorch_model_engine.py (1)
tensorrt_llm/llmapi/llm_args.py (1)
  • TorchLlmArgs (2382-2842)
🔇 Additional comments (5)
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (2)

556-557: Nice: sparse_attention_config now flows from llm_args.

This aligns creator/engine behavior with consolidated args.


202-208: Verification complete: all call sites correctly pass llm_args instead of removed per‑param kwargs.

The search confirms that:

  • PyTorchModelEngine is called at lines 316–318 and 355–357, passing only model_path and pytorch_backend_config
  • create_py_executor is called at test_memory_profiling.py:61 and :70, passing llm_args, checkpoint_dir, and profiling_stage_data

No legacy per-parameter arguments (batch_size, max_seq_len, max_num_tokens, checkpoint_loader, sparse_attention_config) are passed to either function. The refactoring is complete and consistent.

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

170-170: Sparse attention config derivation looks correct.

Draft engines disabling sparse config avoids unintended coupling.


274-274: Attn backend wiring with sparse config: LGTM.


281-289: Review comment is based on incorrect assumption about normalization timing.

The review comment approves the code claiming "Once sizes are normalized via get_runtime_sizes(), these allocations are safe." However, verification reveals this premise is false:

  • get_runtime_sizes() (llm_args.py:2167-2173) simply returns raw Optional values; it does not normalize them
  • The extracted values at py_executor_creator.py:243 are used locally but do not update llm_args
  • PyTorchModelEngine receives the original unmodified llm_args with Optional[int] fields that default to None
  • Lines 146-149 directly assign these possibly-None values to instance variables
  • Lines 281-289 use these instance variables in torch.empty() allocations, which will fail with TypeError if values are None

The direct accesses to llm_args.max_batch_size, llm_args.max_seq_len, etc. at lines 146-149 lack None-checks and represent a potential latent bug, contrary to the review comment's approval.

Likely an incorrect or invalid review comment.

@leslie-fang25 leslie-fang25 force-pushed the leslie/refine_PyTorchModelEngine_creation branch from ca554d3 to 8ea6c18 Compare October 21, 2025 01:50
@leslie-fang25 leslie-fang25 requested a review from QiJune October 21, 2025 01:50
@leslie-fang25
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #21976 [ run ] triggered by Bot. Commit: 8ea6c18

Copy link
Collaborator

@QiJune QiJune left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@QiJune QiJune enabled auto-merge (squash) October 21, 2025 12:15
@tensorrt-cicd
Copy link
Collaborator

PR_Github #21976 [ run ] completed with state SUCCESS. Commit: 8ea6c18
/LLM/main/L0_MergeRequest_PR pipeline #16572 completed with status: 'FAILURE'

@leslie-fang25 leslie-fang25 force-pushed the leslie/refine_PyTorchModelEngine_creation branch from 8ea6c18 to 36c24c0 Compare October 22, 2025 00:53
@leslie-fang25
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22101 [ run ] triggered by Bot. Commit: 36c24c0

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22101 [ run ] completed with state SUCCESS. Commit: 36c24c0
/LLM/main/L0_MergeRequest_PR pipeline #16665 completed with status: 'FAILURE'

@leslie-fang25
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22127 [ run ] triggered by Bot. Commit: 36c24c0

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22127 [ run ] completed with state SUCCESS. Commit: 36c24c0
/LLM/main/L0_MergeRequest_PR pipeline #16685 completed with status: 'FAILURE'

@QiJune
Copy link
Collaborator

QiJune commented Oct 22, 2025

/bot skip --comment "unrelated autodeploy mxfp4_moe errors"

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22219 [ skip ] triggered by Bot. Commit: 36c24c0

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22219 [ skip ] completed with state SUCCESS. Commit: 36c24c0
Skipping testing for commit 36c24c0

@QiJune QiJune merged commit e5865de into NVIDIA:main Oct 23, 2025
5 checks passed
yufeiwu-nv pushed a commit to yufeiwu-nv/TensorRT-LLM that referenced this pull request Oct 24, 2025
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Nov 1, 2025
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Nov 3, 2025
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Nov 3, 2025
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Nov 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants