Skip to content

[TRTLLM-15764][refactor] Split PyTorchModelEngine construction into named phases - #20851

Merged
lori-ren merged 7 commits into
NVIDIA:mainfrom
lori-ren:refactor/engine-construction-phases
Oct 26, 2026
Merged

lori-ren merged 7 commits into
NVIDIA:mainfrom
lori-ren:refactor/engine-construction-phases

Conversation

@lori-ren

@lori-ren lori-ren commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Dev Engineer Review

PyTorchModelEngine.__init__ now delegates setup to named phases. The new plan_cuda_graphs function centralizes CUDA graph sizing and prefill capture filtering in cuda_graph.py. Verify that engine attributes and graph settings remain consistent, and that failures in each phase leave state available to cleanup().

Construction order changes affect loader, communicator, input processor, model caller, and execution-service initialization. The supplied evidence does not include test results to confirm the reported compatibility checks.

QA Engineer Review

The reported test changes cover test_pytorch_model_engine.py, test_pytorch_model_engine_warmup.py, tests under tests/unittest/_torch/executor/engine/, and test_llm_args.py. The test_llm_args.py changes move piecewise CUDA-graph filter tests to the new public function. The test database includes test_pytorch_model_engine.py -k "test_spec_decode_graph_step_gather_kernel" in l0_b200.yml; listing status for the other reported tests is not established. Coverage verdict: needs follow-up.

Per-File QA Perspective

  • tensorrt_llm/_torch/pyexecutor/model_engine.py: Verify the initialization phases preserve engine attributes and values, and that failures in each phase leave state available to cleanup().
  • tensorrt_llm/_torch/pyexecutor/engine/cuda_graph.py: Verify defaults, candidate filtering, unreachable-size handling, and the empty-decode-batch case in plan_cuda_graphs and filter_prefill_capture_num_tokens.
  • .claude/skills/perf-regression-cookbook/references/cuda-graph-and-compile/piecewise-cudagraph-far-ceiling-append.md: The cookbook command now imports the filter from cuda_graph.py; verify the command matches the function’s API.
  • tests/unittest/llmapi/test_llm_args.py: The piecewise CUDA-graph filter tests now import the relocated function. The supplied test-list result does not establish whether this file is listed.
  • tests/unittest/_torch/executor/test_pytorch_model_engine.py: The objective reports engine-construction coverage. One test selector appears in test-db/l0_b200.yml; listing status for the other tests is not established.
  • tests/unittest/_torch/executor/test_pytorch_model_engine_warmup.py and tests/unittest/_torch/executor/engine/: The objective reports warmup and engine coverage. Specific changed tests and test-list status are not established.

Description

PyTorchModelEngine.__init__ becomes a short sequence of named construction phases, each ending at a fact the next one relies on: the requested sizes and argument-derived services, the loaded model, the model's facts copied onto the engine with capacity clamped to them, the CUDA graph sizes for that capacity, the compiled model, and the execution services built around it. The phase bodies are the old constructor body moved verbatim, except that the later phases read llm_args, mapping and spec_config from the attributes the first phase stores them in. The constructor signature, the attribute set and every attribute's value are unchanged.

The CUDA graph sizing reads only its arguments, so it moves to engine/cuda_graph.py as plan_cuda_graphs, together with the prefill capture filter it uses (now filter_prefill_capture_num_tokens). The torch.compile step stays on the engine for now: it shares _apply_torch_compile with the refit path.

Three commits change behavior, each only during construction:

  • The checkpoint loader is built when the model is loaded, after the PP communicator, the expert statistics and the input processor instead of before them. This only shows if building it fails.
  • The model caller is built at the end of the compile phase, before the attention backend, the runner type and the speculation update. Its constructor only stores what compilation produced.
  • cleanup() now completes after a failure in any phase, because the state it reads is declared before the first phase. Before, it stopped with an AttributeError when construction failed early.

With these two moves, the only value handed from one phase to a later one is the encoder token budget before any multimodal increase, which the compile phase needs after _init_from_model may have raised encoder_max_num_tokens. Construction is the only code touched; the forward path is unchanged.

Test Coverage

  • tests/unittest/_torch/executor/test_pytorch_model_engine.py, tests/unittest/_torch/executor/test_pytorch_model_engine_warmup.py and tests/unittest/_torch/executor/engine/.
  • tests/unittest/llmapi/test_llm_args.py for the prefill capture filter, now imported from engine/cuda_graph.py.

During development, the engine's attributes after construction were compared against the unsplit constructor for decoder-only, torch.compile, piecewise, prefill-only, speculation, encoder-decoder, encode-only, MM-encoder and pooling engines, with a failure injected into each phase and with TP=2 userbuffers. Everything matched apart from the failure-path change above. On the final base, AST checks show that the split is a verbatim move of the constructor body, that the sizing move and the reads from self change nothing else, and that each reorder moves one statement unchanged.

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)

  • If PR introduces API changes, an appropriate PR label is added - either api-compatible or api-breaking. For api-breaking, include BREAKING in the PR title.

  • Any new dependencies have been scanned for license and vulnerabilities

  • CODEOWNERS updated if ownership changes

  • Documentation updated as needed

  • Update tava architecture diagram if there is a significant design change in PR.

  • 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

To see a list of available CI bot commands, please comment /bot help.

@lori-ren
lori-ren force-pushed the refactor/engine-construction-phases branch from d93cac7 to b3d2f3f Compare October 24, 2026 05:47
…amed phases

The phase bodies are the old __init__ body moved verbatim, cut where
an irreversible fact is established.

Signed-off-by: Lori Ren <[email protected]>
…raph.py function

plan_cuda_graphs reads only its arguments, and the new _size_cuda_graphs phase writes its plan back to the same attributes. _compile_model keeps only the compile; the prefill capture filter moves next to the other graph filters.

Signed-off-by: Lori Ren <[email protected]>
… after the first phase

The later phases read llm_args, mapping and spec_config from the attributes the first phase stores them in, the same objects, and drop the duplicate parameters.

Signed-off-by: Lori Ren <[email protected]>
@lori-ren
lori-ren force-pushed the refactor/engine-construction-phases branch from b3d2f3f to b5808b0 Compare October 26, 2026 03:32
… is loaded

Behavior change: the loader is built after the PP communicator, the expert statistics and the input processor instead of before them, which only shows if building it fails. _init_from_args no longer hands it over.

Signed-off-by: Lori Ren <[email protected]>
…pile phase

Behavior change in order only: the caller is built before the attention backend, the runner type and the speculation update instead of after them, and its constructor only stores what compilation produced. _compile_model no longer hands the auxiliary streams over.

Signed-off-by: Lori Ren <[email protected]>
…onstruction phases

cleanup() now completes after a construction failure in any phase; before, it stopped on a missing model_loader or _torch_compile_backend.

Signed-off-by: Lori Ren <[email protected]>
Draft engines are no longer built, and stub models now come in through model= rather than an overridden _load_model.

Signed-off-by: Lori Ren <[email protected]>
@lori-ren
lori-ren force-pushed the refactor/engine-construction-phases branch from b5808b0 to 5b06f57 Compare October 26, 2026 03:54
@lori-ren
lori-ren marked this pull request as ready for review October 26, 2026 04:08
@lori-ren
lori-ren requested review from a team as code owners October 26, 2026 04:08
@coderabbitai

coderabbitai Bot commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between da002db and 5b06f57.

Files selected for processing: 4
  • .claude/skills/perf-regression-cookbook/references/cuda-graph-and-compile/piecewise-cudagraph-far-ceiling-append.md
  • tensorrt_llm/_torch/pyexecutor/engine/cuda_graph.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tests/unittest/llmapi/test_llm_args.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.

Walkthrough

The PR adds public CUDA graph planning APIs and moves graph sizing into that planner. Model engine initialization is divided into setup stages. Tests and a diagnostic command now import the public prefill capture filter.

Changes

CUDA graph planning

Layer / File(s) Summary
Define and validate CUDA graph planning
tensorrt_llm/_torch/pyexecutor/engine/cuda_graph.py, tests/unittest/llmapi/test_llm_args.py, .claude/skills/perf-regression-cookbook/references/cuda-graph-and-compile/piecewise-cudagraph-far-ceiling-append.md
The module exports filter_prefill_capture_num_tokens, CudaGraphPlan, and plan_cuda_graphs. The filter handles candidate limits, reachable ceilings, clamping, sorting, and deduplication. Tests and the diagnostic command use the public filter.
Integrate graph planning into engine initialization
tensorrt_llm/_torch/pyexecutor/model_engine.py
Initialization is split into setup stages. CUDA graph sizing uses plan_cuda_graphs. Compilation and execution-service setup are also separated.

Priority: Low

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Suggested reviewers: schetlur-nv

Merge Risk: Minimal · up to 5b06f

The refactor preserves the reviewed CUDA graph behavior, with no identified issue requiring correction before merge.

Pre-merge checks: Passed 5
Check name Status Explanation
Title check Passed The title clearly identifies the refactor of PyTorchModelEngine construction into named phases and uses the required ticket and type format.
Description check Passed The description includes the required Description, Test Coverage, and PR Checklist sections. It clearly explains the refactor, behavior changes, affected tests, and validation performed.
Docstring Coverage Passed Docstring coverage is 85.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 20 functions across 3 files. (1 skipped: 1 …
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 85.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 20 functions across 3 files. (1 skipped: 1 unsupported.)

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@lori-ren

Copy link
Copy Markdown
Contributor Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #80534 [ run ] triggered by Bot. Commit: 5b06f57 Link to invocation

@bo-nv bo-nv left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

From the disagg side this looks good. Everything the disagg path reads from the engine — capacity, CUDA graph batch sizes, spec widths, attention DP — keeps its value and is still only read after __init__ returns, and the reordered steps allocate no GPU memory, so KV sizing is unchanged. Nothing blocking from my side; I'd like to see blossom-ci #80534 pass on this head before merge.

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #80534 [ run ] completed with state FAILURE. Commit: 5b06f57
/LLM/main/L0_MergeRequest_PR pipeline #66296 completed with status: 'UNSTABLE'

CI Report

⚠️ Multi-GPU Label Required:
Multi-GPU tests require the ci: full pre-merge approved label on this PR. Either:

  • Wait for the PR to be fully approved — the label is added automatically once approval is complete. Having unresolved open comments is fine, or
  • If needed, ask a member of NVIDIA/trt-llm-ci-approvers to add the label manually.
    Then re-trigger CI with the same bot command (no rebase needed).

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

Link to invocation

@kaiyux kaiyux left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Approving on behalf of agent devs. Thx.

@github-actions

Copy link
Copy Markdown

Automatically added "ci: full pre-merge approved" because this PR has satisfied the required GitHub review approvals. Unresolved review conversations and other required checks remain independent merge requirements.

@lori-ren

Copy link
Copy Markdown
Contributor Author

/bot run

@lori-ren
lori-ren enabled auto-merge (squash) October 26, 2026 10:01
@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #80597 [ run ] triggered by Bot. Commit: 5b06f57 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #80597 [ run ] completed with state SUCCESS. Commit: 5b06f57
/LLM/main/L0_MergeRequest_PR pipeline #66355 completed with status: 'SUCCESS'

CI Report

Link to invocation

@lori-ren
lori-ren merged commit 0113164 into NVIDIA:main Oct 26, 2026
21 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants