-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[TRTLLM-8836][chore] Create ModelEngine from LlmArgs #8600
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
Signed-off-by: junq <[email protected]>
/bot run |
📝 WalkthroughWalkthroughRefactors configuration passing to PyTorchModelEngine and ModelLoader by replacing PyTorchConfig parameter with TorchLlmArgs as the primary configuration object. Updates constructor signatures, internal state storage, and all downstream field references across the model engine, loader, and executor creator. Changes
Sequence DiagramsequenceDiagram
participant PyExecutorCreator as PyExecutorCreator
participant ModelEngine as PyTorchModelEngine.__init__
participant Loader as ModelLoader.__init__
PyExecutorCreator->>PyExecutorCreator: Create llm_args: TorchLlmArgs
PyExecutorCreator->>ModelEngine: Pass llm_args (instead of pytorch_backend_config)
ModelEngine->>ModelEngine: Store self.llm_args
ModelEngine->>ModelEngine: Extract cuda_graph_config from llm_args
ModelEngine->>ModelEngine: Extract torch_compile_config from llm_args
ModelEngine->>Loader: Pass llm_args to ModelLoader
Loader->>Loader: Store self.llm_args
Loader->>Loader: Access llm_args.load_format, llm_args.kv_cache_config, etc.
Note over PyExecutorCreator,Loader: Configuration centralized via TorchLlmArgs
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20–25 minutes The refactoring follows a consistent, repetitive pattern across three files (parameter renaming, field access updates), which reduces complexity. However, careful verification is required to ensure all field references were properly updated throughout the codebase, particularly in 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: 0
🧹 Nitpick comments (2)
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (1)
279-292
: Ensure consistent dual assignments for mm_encoder_only mode.The synchronization of
mm_encoder_only
,load_format
, anddisable_overlap_scheduler
across both config objects is correct but fragile.Apply this verification to ensure all three fields are consistently set:
#!/bin/bash # Verify that all three fields are set together when mm_encoder_only is enabled rg -A 15 'mm_encoder_only\s*=' --type=py | rg -C 3 'load_format|disable_overlap_scheduler'tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
228-247
: Consider helper function to reduce config extraction verbosity.The pattern of extracting config fields with fallback to defaults is repeated multiple times (e.g., lines 229-232 for
cuda_graph_config
, lines 234-247 fortorch_compile_config
). While functionally correct, this is verbose and repetitive.Consider extracting this pattern into a helper function:
def get_config_field(config_obj, config_class, field_name): """Get field from config object or return default from config class.""" if config_obj is not None: return getattr(config_obj, field_name) return config_class.model_fields[field_name].default # Usage: cuda_graph_batch_sizes = get_config_field( self.cuda_graph_config, CudaGraphConfig, 'batch_sizes') cuda_graph_padding_enabled = get_config_field( self.cuda_graph_config, CudaGraphConfig, 'enable_padding')This would improve maintainability without changing behavior.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
tensorrt_llm/_torch/pyexecutor/model_engine.py
(13 hunks)tensorrt_llm/_torch/pyexecutor/model_loader.py
(6 hunks)tensorrt_llm/_torch/pyexecutor/py_executor_creator.py
(4 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/model_engine.py
tensorrt_llm/_torch/pyexecutor/model_loader.py
tensorrt_llm/_torch/pyexecutor/py_executor_creator.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/model_engine.py
tensorrt_llm/_torch/pyexecutor/model_loader.py
tensorrt_llm/_torch/pyexecutor/py_executor_creator.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/model_engine.py
tensorrt_llm/_torch/pyexecutor/model_loader.py
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py
🧠 Learnings (1)
📚 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
tensorrt_llm/_torch/pyexecutor/model_loader.py
🧬 Code graph analysis (3)
tensorrt_llm/_torch/pyexecutor/model_engine.py (3)
cpp/tensorrt_llm/kernels/userbuffers/userbuffersManager.h (1)
tensorrt_llm
(23-82)tensorrt_llm/llmapi/llm_args.py (3)
CudaGraphConfig
(108-165)TorchCompileConfig
(2314-2361)TorchLlmArgs
(2364-2824)tensorrt_llm/_torch/compilation/backend.py (1)
Backend
(23-166)
tensorrt_llm/_torch/pyexecutor/model_loader.py (1)
tensorrt_llm/llmapi/llm_args.py (2)
TorchLlmArgs
(2364-2824)LoadFormat
(2299-2304)
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (1)
tensorrt_llm/llmapi/llm_args.py (1)
LoadFormat
(2299-2304)
⏰ 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 (11)
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (4)
323-330
: LGTM: Main model engine creation updated correctly.The PyTorchModelEngine constructor now receives
llm_args
instead ofpytorch_backend_config
, which aligns with the PR's objective to centralize configuration throughTorchLlmArgs
.
366-375
: LGTM: Draft model engine updated consistently.The draft model engine constructor now receives
draft_llm_args
, which properly isolates the draft model's configuration from the main model's configuration.
274-277
: Dual assignment pattern is consistently applied; verify future changes maintain synchronization.The code properly synchronizes updates to both
pytorch_backend_config
andllm_args
across all current mutations (lines 274–277, 281–292, 360–364). However, this dual-update pattern increases risk of divergence if a future change modifies one object without the other, especially since reads frompytorch_backend_config
occur in_util.py
(lines 251, 873) and elsewhere in the file.The TODO is valid technical debt. Consider:
- Pinning this in your issue tracker for cleanup
- Adding comments at key synchronization points to flag the coupling
- In code review, verify that any new mutations to
pytorch_backend_config
fields also update correspondingllm_args
fields
359-364
: Code is safe as written.Verification confirms the shallow copy at line 361 is sufficient. While
TorchLlmArgs
contains nested mutable objects (e.g.,cuda_graph_config
,moe_config
), the code only modifies the simpleload_format
field ondraft_llm_args
. The nested configuration objects are never modified after the copy, so there is no risk of unintended side effects on the originalllm_args
.tensorrt_llm/_torch/pyexecutor/model_loader.py (3)
160-186
: LGTM: ModelLoader constructor signature updated correctly.The constructor now accepts
llm_args: TorchLlmArgs
instead ofpytorch_backend_config: PyTorchConfig
, with documentation and internal storage updated accordingly. This centralizes configuration access throughTorchLlmArgs
.
204-204
: LGTM: Field access patterns correctly migrated to llm_args.All configuration field accesses have been consistently updated to use
self.llm_args.*
instead ofself.pytorch_backend_config.*
. The derivation ofuse_cuda_graph
from the presence ofcuda_graph_config
(line 296) is a reasonable approach.Also applies to: 295-317
10-10
: ****Both import paths resolve to the same
LoadFormat
enum. The verification confirms:
- Only one
LoadFormat
definition exists intensorrt_llm/llmapi/llm_args.py:2299
config.py
importsLoadFormat
fromtensorrt_llm.llmapi.llm_args
and re-exports itmodel_loader.py
imports through the re-export:from .config import LoadFormat
py_executor_creator.py
imports directly:from tensorrt_llm.llmapi.llm_args import LoadFormat
This is standard Python practice—importing through a module re-export versus directly from the source is not an inconsistency. Both reference the identical enum object.
Likely an incorrect or invalid review comment.
tensorrt_llm/_torch/pyexecutor/model_engine.py (4)
23-24
: LGTM: Import additions support llm_args-based configuration.The addition of
CudaGraphConfig
,TorchCompileConfig
, andTorchLlmArgs
imports enables the new configuration pattern where these configs are extracted fromllm_args
.
130-168
: LGTM: Constructor updated to use TorchLlmArgs.The constructor signature now accepts
llm_args: TorchLlmArgs
and properly stores it for later use. Runtime sizes are correctly extracted viallm_args.get_runtime_sizes()
.
262-295
: LGTM: torch.compile backend initialization uses derived configuration.The Backend initialization correctly uses the derived configuration values from
llm_args
(or their defaults), and the conditional torch.compile application based on model type is preserved.
192-192
: LGTM: All llm_args field accesses are correct and consistent.The scattered field accesses throughout the file consistently use
self.llm_args.*
to retrieve configuration values. The ModelLoader instantiation at line 192 correctly passesllm_args
instead of the deprecatedpytorch_backend_config
.Also applies to: 214-214, 223-223, 299-299, 554-554, 2298-2298, 2462-2462
PR_Github #22229 [ run ] triggered by Bot. Commit: |
PR_Github #22229 [ run ] completed with state |
Signed-off-by: junq <[email protected]>
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.
The test case as in
pytorch_backend_config=pytorch_backend_config, |
pytorch_backend_config.disable_overlap_scheduler = True | ||
|
||
llm_args.disable_overlap_scheduler = 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.
I think we need to be cautious when modifying the llm_args
fields, as they are parsed from user input. I haven’t found a better solution yet—perhaps we should create a copy of llm_args
from the original input?
@@ -283,6 +287,10 @@ def create_py_executor( | |||
"when only processing vision encoder inputs.") | |||
pytorch_backend_config.disable_overlap_scheduler = True | |||
|
|||
llm_args.mm_encoder_only = True | |||
llm_args.load_format = LoadFormat.VISION_ONLY | |||
llm_args.disable_overlap_scheduler = 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.
ditto
Signed-off-by: junq <[email protected]>
Summary by CodeRabbit
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.