-
Notifications
You must be signed in to change notification settings - Fork 1.9k
[TRTLLM-8754][chore] Refine PyTorchModelEngine with llm args #8493
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
[TRTLLM-8754][chore] Refine PyTorchModelEngine with llm args #8493
Conversation
|
/bot run --disable-fail-fast |
|
PR_Github #21866 [ run ] triggered by Bot. Commit: |
|
PR_Github #21866 [ run ] completed with state |
|
/bot run |
|
PR_Github #21890 [ run ] triggered by Bot. Commit: |
|
PR_Github #21890 [ run ] completed with state |
📝 WalkthroughWalkthroughRefactors 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
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)
✅ 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 (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_configexists 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_pathliteral 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 TorchLlmArgstensorrt_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_dirandllm_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(callsmapping.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
📒 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.pytensorrt_llm/_torch/pyexecutor/model_engine.pytests/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.pytensorrt_llm/_torch/pyexecutor/model_engine.pytests/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.pytensorrt_llm/_torch/pyexecutor/model_engine.pytests/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_argswith 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 NoneThe 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.
ca554d3 to
8ea6c18
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #21976 [ run ] triggered by Bot. Commit: |
QiJune
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM
|
PR_Github #21976 [ run ] completed with state |
Signed-off-by: leslie-fang25 <[email protected]>
8ea6c18 to
36c24c0
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #22101 [ run ] triggered by Bot. Commit: |
|
PR_Github #22101 [ run ] completed with state |
|
/bot run |
|
PR_Github #22127 [ run ] triggered by Bot. Commit: |
|
PR_Github #22127 [ run ] completed with state |
|
/bot skip --comment "unrelated autodeploy mxfp4_moe errors" |
|
PR_Github #22219 [ skip ] triggered by Bot. Commit: |
|
PR_Github #22219 [ skip ] completed with state |
…8493) Signed-off-by: leslie-fang25 <[email protected]> Signed-off-by: yufeiwu-nv <[email protected]>
…8493) Signed-off-by: leslie-fang25 <[email protected]>
…8493) Signed-off-by: leslie-fang25 <[email protected]>
…8493) Signed-off-by: leslie-fang25 <[email protected]>
…8493) Signed-off-by: leslie-fang25 <[email protected]>
Summary by CodeRabbit
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 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.