Skip to content

Conversation

QiJune
Copy link
Collaborator

@QiJune QiJune commented Oct 23, 2025

Summary by CodeRabbit

  • Refactor
    • Updated PyTorch model engine initialization to consolidate configuration handling through a unified configuration object, streamlining model setup and improving consistency across initialization pathways.

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

@QiJune QiJune requested a review from a team as a code owner October 23, 2025 02:21
@QiJune QiJune requested a review from Naveassaf October 23, 2025 02:21
@QiJune
Copy link
Collaborator Author

QiJune commented Oct 23, 2025

/bot run

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 23, 2025

📝 Walkthrough

Walkthrough

Refactors 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

Cohort / File(s) Change Summary
Model Engine Core
tensorrt_llm/_torch/pyexecutor/model_engine.py
Constructor parameter changed from pytorch_backend_config: PyTorchConfig to llm_args: TorchLlmArgs (required). Adds imports for CudaGraphConfig, TorchCompileConfig, and TorchLlmArgs. Replaces all internal references to pytorch_backend_config.* with llm_args.* (e.g., enable_layerwise_nvtx_marker, disable_overlap_scheduler, cuda_graph_config, torch_compile_config, attn_backend, mm_encoder_only, enable_autotuner). Configuration extraction logic updated to derive CUDA graph and torch.compile configs from llm_args fields.
Model Loader
tensorrt_llm/_torch/pyexecutor/model_loader.py
Constructor parameter changed from pytorch_backend_config: PyTorchConfig to llm_args: TorchLlmArgs. Adds TorchLlmArgs import from tensorrt_llm.llmapi.llm_args. Internal state stores self.llm_args instead of self.pytorch_backend_config. All method calls updated to access configuration via self.llm_args fields (e.g., load_format, enable_min_latency, kv_cache_config, moe_config, attn_backend, moe_backend).
Executor Creator
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py
Updates PyTorchModelEngine instantiation to pass llm_args parameter instead of pytorch_backend_config. Introduces draft_llm_args for draft model configuration isolation. Adds configuration synchronization logic between pytorch_backend_config and llm_args for overlap scheduler and encoder-only mode flags. Adds TODO comments flagging remaining pytorch_backend_config cleanup opportunities.

Sequence Diagram

sequenceDiagram
    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
Loading

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 _load_and_validate_config() and other methods that access numerous configuration fields. The systematic nature of changes makes review more straightforward but demands thorough spot-checking.

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description Check ⚠️ Warning The pull request description is essentially empty, consisting only of the template structure with placeholder comments. The required sections—Description and Test Coverage—have not been filled out by the author. While the PR checklist is present and one item is marked as checked, the substantive content explaining what the pull request does (the issue and solution) and what tests safeguard the changes is entirely missing. This fails to meet the repository's description template requirements for meaningful PR context. The author should fill in the Description section with a clear explanation of the refactoring (e.g., why centralizing configuration through LlmArgs is beneficial and how it improves the architecture) and the Test Coverage section should list specific tests that validate the new signature changes and ensure backward compatibility or proper migration paths. The raw summary provided contains substantial technical details that should be translated into a human-readable description section for reviewers.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The title "[TRTLLM-8836][chore] Create ModelEngine from LlmArgs" clearly and concisely summarizes the primary change in the pull request. The raw summary indicates the main refactoring is replacing PyTorchConfig with TorchLlmArgs as the central configuration object for PyTorchModelEngine and related classes. The title directly references this shift to using LlmArgs for model engine creation, making it specific and meaningful for scanning commit history. It follows the project's required format with a valid JIRA ticket and valid type indicator ([chore]), and avoids vague or generic language.
✨ 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: 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, and disable_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 for torch_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

📥 Commits

Reviewing files that changed from the base of the PR and between 77fa5df and 25bd4be.

📒 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 of pytorch_backend_config, which aligns with the PR's objective to centralize configuration through TorchLlmArgs.


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 and llm_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 from pytorch_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 corresponding llm_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 simple load_format field on draft_llm_args. The nested configuration objects are never modified after the copy, so there is no risk of unintended side effects on the original llm_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 of pytorch_backend_config: PyTorchConfig, with documentation and internal storage updated accordingly. This centralizes configuration access through TorchLlmArgs.


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 of self.pytorch_backend_config.*. The derivation of use_cuda_graph from the presence of cuda_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 in tensorrt_llm/llmapi/llm_args.py:2299
  • config.py imports LoadFormat from tensorrt_llm.llmapi.llm_args and re-exports it
  • model_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, and TorchLlmArgs imports enables the new configuration pattern where these configs are extracted from llm_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 via llm_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 passes llm_args instead of the deprecated pytorch_backend_config.

Also applies to: 214-214, 223-223, 299-299, 554-554, 2298-2298, 2462-2462

@QiJune QiJune changed the title [TRTLLM-8754][chore] Create ModelEngine from LlmArgs [TRTLLM-8836][chore] Create ModelEngine from LlmArgs Oct 23, 2025
@tensorrt-cicd
Copy link
Collaborator

PR_Github #22229 [ run ] triggered by Bot. Commit: 25bd4be

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22229 [ run ] completed with state SUCCESS. Commit: 25bd4be
/LLM/main/L0_MergeRequest_PR pipeline #16759 completed with status: 'FAILURE'

Signed-off-by: junq <[email protected]>
Copy link
Collaborator

@leslie-fang25 leslie-fang25 left a 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,
may also need to be updated.

pytorch_backend_config.disable_overlap_scheduler = True

llm_args.disable_overlap_scheduler = True
Copy link
Collaborator

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
Copy link
Collaborator

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]>
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