Skip to content

Conversation

@QiJune
Copy link
Collaborator

@QiJune QiJune commented Aug 26, 2025

Summary by CodeRabbit

  • Refactor

    • CUDA graph execution now uses a shared preallocated pool for static tensors with per-call slicing, improving memory reuse, throughput, and stability for speculative decoding and large batch/beam scenarios.
    • Improved lifecycle and cleanup for CUDA graphs, reducing initialization overhead and lowering capture/replay latency.
  • Tests

    • Test helpers updated to support larger max token counts for engine mocks.

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 added 2 commits August 26, 2025 10:12
Signed-off-by: junq <[email protected]>

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

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

Signed-off-by: junq <[email protected]>
Signed-off-by: junq <[email protected]>
@QiJune QiJune requested a review from a team as a code owner August 26, 2025 02:14
@QiJune QiJune requested a review from HuiGao-NV August 26, 2025 02:15
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 26, 2025

📝 Walkthrough

Walkthrough

Replaces per-(batch,draft_len) static CUDA tensor allocations with a single preallocated shared_static_tensors pool sized by max_possible_draft_len and max-supported batch/beam; capture/replay slice into the pool. Adds helpers, lifecycle cleanup, and removes _cuda_graphs initialization in PyTorchModelEngine.__init__.

Changes

Cohort / File(s) Summary
CUDA Graph Runner refactor
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
Added max_possible_draft_len and shared_static_tensors; removed static_inputs. Added _create_shared_static_tensors(), __del__(), _get_engine(), and several properties (draft_len, spec_metadata, draft_tokens_cuda, attn_metadata). Capture/replay reworked to slice and reuse the shared pool; graph_metadata now gets spec_metadata from initial_inputs; clear() updated.
Model Engine init adjustment
tensorrt_llm/_torch/pyexecutor/model_engine.py
Removed initialization of private _cuda_graphs member from PyTorchModelEngine.__init__.
Tests / Mocks
tests/unittest/_torch/helpers.py
create_mock_engine now sets max_num_tokens=8192 on the mock engine instance (adds property to mock engine).

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant App
  participant Engine as PyTorchModelEngine
  participant Runner as CUDAGraphRunner
  participant Pool as shared_static_tensors

  App->>Engine: instantiate(...)
  Engine->>Runner: instantiate(..., cuda_graphs enabled)
  activate Runner
  Runner->>Runner: compute max_possible_draft_len
  Runner->>Runner: _create_shared_static_tensors()
  Runner->>Pool: allocate big tensors (input_ids, position_ids, [mrope_position_deltas])
  deactivate Runner

  App->>Runner: capture(initial_inputs)
  activate Runner
  Runner->>Pool: slice views for batch/beam/token range (sliced_static_tensors)
  Runner->>Runner: build capture_inputs using sliced_static_tensors
  Runner-->>App: return graph_metadata (includes spec_metadata)
  deactivate Runner

  App->>Runner: replay(current_inputs)
  activate Runner
  Runner->>Pool: copy current inputs into appropriate slice
  Runner->>Runner: launch CUDA graph replay
  Runner-->>App: outputs
  deactivate Runner
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45–75 minutes

Possibly related PRs

Suggested labels

Community want to contribute

Suggested reviewers

  • lfr-0531
  • HuiGao-NV
  • mikeiovine
  • yuxianq

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • 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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @coderabbitai title anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@QiJune
Copy link
Collaborator Author

QiJune commented Aug 26, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16499 [ run ] triggered by Bot

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: 1

Caution

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

⚠️ Outside diff range comments (2)
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py (2)

1-1: Add the required 2025 NVIDIA copyright header at file top

Per repo guidelines, every Python source must prepend the NVIDIA copyright header (current year). This file is missing it.

Apply:

+# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
 import bisect
 import contextlib
 import weakref

281-287: Invoke engine.use_mrope() instead of referencing the bound method

The grep run confirmed two spots where engine.use_mrope is used without parentheses, causing a bound-method object (always truthy) to be passed or tested instead of its boolean return value.

· tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py:72
· tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py:285

Please apply the following fixes:

--- a/tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
@@ -69,7 +69,7 @@
         }
-        if engine.use_mrope:
+        if engine.use_mrope():
             self.shared_static_tensors["mrope_position_deltas"] = torch.zeros(
                 (self.max_supported_batch_size, 1),
             )
@@ -285,7 +285,7 @@
             self.padding_dummy_request = kv_cache_manager.add_dummy_requests(
                 [CUDA_GRAPH_DUMMY_REQUEST_ID],
                 is_gen=True,
-                max_num_draft_tokens=engine.max_draft_len,
-                use_mrope=engine.use_mrope,
+                max_num_draft_tokens=engine.max_draft_len,
+                use_mrope=engine.use_mrope(),
                 max_beam_width=engine.max_beam_width)[0]
             self.padding_dummy_request.is_cuda_graph_dummy = True

These changes ensure that the method’s boolean result is used, not the method object itself.

🧹 Nitpick comments (8)
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py (8)

43-45: Avoid duplicating draft length state; use the existing draft_len property

max_possible_draft_len duplicates the semantics of draft_len. Keeping both invites drift. Use draft_len everywhere.

Apply:

-        self.max_possible_draft_len = (self.spec_config.max_draft_len
-                                       if self.enable_spec_decode else 0)

And below (see other diffs in Lines 61-64 and 173-176) replace self.max_possible_draft_len with self.draft_len.


53-56: Lazily allocate and make release explicit (large buffers)

Creation is unconditional when enabled. Consider:

  • Allocate only if supported_batch_sizes is non-empty.
  • Also free these buffers in clear() to release VRAM under pressure.

Apply in init:

-        if self.enabled:
+        if self.enabled and self.supported_batch_sizes:
             self._create_shared_static_tensors()

And in clear() (see Lines 320-330):

         self.graph_metadata.clear()
         del self.memory_pool
         self.memory_pool = None
+        self.shared_static_tensors.clear()
         torch.cuda.empty_cache()

61-64: Use draft_len property to compute token_per_request

Keeps a single source of truth for the effective draft length.

Apply:

-        token_per_request = self.max_possible_draft_len + 1
+        token_per_request = self.draft_len + 1

177-187: Good: reuse via sliced views; minor improvement

The capture uses views; mirror this pattern in replay for clarity and to protect against accidental over/under-copy if invariants change.

Apply in replay (see Lines 222-235):

-        static_tensors = self.shared_static_tensors
+        token_per_request = self.draft_len + 1
+        expected_tokens = batch_size * self.max_beam_width * token_per_request
+        static_tensors = {
+            "input_ids": self.shared_static_tensors["input_ids"][:expected_tokens],
+            "position_ids": self.shared_static_tensors["position_ids"][:, :expected_tokens],
+        }
+        if "mrope_position_deltas" in self.shared_static_tensors:
+            static_tensors["mrope_position_deltas"] = \
+                self.shared_static_tensors["mrope_position_deltas"][:batch_size]

222-235: Safer copying and shape assertion during replay

Replay currently copies directly into base tensors; if invariants drift, this can silently misalign with captured slices. Add a sanity check or slice as in capture.

Apply:

-        static_tensors = self.shared_static_tensors
-
-        input_ids = current_inputs["input_ids"]
-        seqlen = input_ids.shape[0]
-        static_tensors["input_ids"][:seqlen].copy_(input_ids)
-
-        position_ids = current_inputs["position_ids"]
-        static_tensors["position_ids"][:, :seqlen].copy_(position_ids)
+        token_per_request = self.draft_len + 1
+        expected = batch_size * self.max_beam_width * token_per_request
+        input_ids = current_inputs["input_ids"]
+        seqlen = input_ids.shape[0]
+        assert seqlen == expected, (
+            f"Unexpected input_ids length {seqlen}, expected {expected} for CUDA graph replay."
+        )
+        self.shared_static_tensors["input_ids"][:seqlen].copy_(input_ids)
+
+        position_ids = current_inputs["position_ids"]
+        self.shared_static_tensors["position_ids"][:, :seqlen].copy_(position_ids)
 
         if "mrope_position_deltas" in current_inputs:
-            assert "mrope_position_deltas" in static_tensors
-            static_tensors["mrope_position_deltas"][:batch_size].copy_(
+            assert "mrope_position_deltas" in self.shared_static_tensors
+            self.shared_static_tensors["mrope_position_deltas"][:batch_size].copy_(
                 current_inputs["mrope_position_deltas"])

If you prefer not to assert in production, guard it with a debug flag.


320-330: Consider freeing shared_static_tensors in clear()

clear() releases graphs/mempool but leaves the shared tensor pool allocated. If engines are long-lived, this is fine; if clear() is used for reclamation, also clear the pool.

Apply:

         self.graph_metadata.clear()
         del self.memory_pool
         self.memory_pool = None
+        self.shared_static_tensors.clear()
         torch.cuda.empty_cache()

If we should keep the pool across captures, we can add a separate release_static_pool() method instead. Preference?


127-137: Variable naming is confusing in TP allgather section

Not a bug, but readability suffers (e.g., is_all_gen_only vs all_can_graph). Consider renaming locals for clarity.

No code change required; optional cleanup for future readers.


166-171: Add a brief Google-style docstring for capture() params/returns

Public API, frequently touched. Minimal docstring with Args/Returns improves maintainability.

I can draft it if you’d like.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between b845eb7 and 3ff5b5f.

📒 Files selected for processing (2)
  • tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py (3 hunks)
  • tensorrt_llm/_torch/pyexecutor/model_engine.py (0 hunks)
💤 Files with no reviewable changes (1)
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: Code must target Python 3.8+
Indent Python code with 4 spaces; do not use tabs
Preserve module namespaces when importing; import modules/packages and access members via the module (e.g., from package.subpackage import foo; foo.SomeClass())
Python file names should be snake_case
Python class names should be PascalCase
Python functions/methods and local variables should be snake_case; variables beginning with a number should be prefixed with k_ (e.g., k_99th_percentile)
Global variables should be UPPER_SNAKE_CASE prefixed with G_ (e.g., G_MY_GLOBAL); constants should be UPPER_SNAKE_CASE
Avoid shadowing variables from outer scopes; initialize all externally visible members in init
Prefer docstrings for interfaces used outside a file; comments should be reserved for in-function or file-local interfaces
Use Google-style docstrings for classes and functions; attributes and variables may be documented inline with trailing string literals
Avoid reflection when simpler, explicit code suffices (e.g., avoid dict(**locals()) patterns)
In try/except, catch the narrowest exceptions possible
For duck-typing patterns, keep the try body minimal and move logic to else to avoid masking unrelated failures

Files:

  • tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
**/*.{c,cc,cpp,cxx,h,hh,hpp,hxx,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Prepend the NVIDIA copyright header (current year) to all source files (.cpp, .h, .cu, .py, etc.)

Files:

  • tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
🧬 Code graph analysis (1)
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py (1)
tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
  • use_mrope (480-488)
🪛 Ruff (0.12.2)
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py

51-51: Undefined name Request

(F821)

⏰ 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 (5)
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py (5)

173-176: LGTM: token accounting for capture

Deriving num_tokens_for_capture from batch_size, beam width, and token_per_request is correct for prealloc slicing. Just align token_per_request to use draft_len per earlier comment.

Apply:

-        token_per_request = self.max_possible_draft_len + 1
+        token_per_request = self.draft_len + 1
         num_tokens_for_capture = (batch_size * self.max_beam_width *
                                   token_per_request)

188-191: LGTM: minimal mutation of capture_inputs

Copy-on-write of initial_inputs and updating just the shared slices is clean and avoids reallocations.


194-195: LGTM: spec_metadata sourcing is safer

Pulling spec_metadata from initial_inputs avoids stale local state.


1-4: The scripts are running to locate any Python‐side Request definitions and list the files in the pyexecutor directory. I’ll follow up as soon as we have those results.


236-239: Return the Tensor, not the weak-ref thunk in cuda_graph_runner.replay

Replace the current return of the weak-ref callable with a call to it so that replay() returns a torch.Tensor as typed:

• File: tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
Lines 236–239

Suggested patch:

-        self.graphs[key].replay()
-        output_ref = self.graph_outputs[key]
-
-        return output_ref
+        self.graphs[key].replay()
+        output_ref = self.graph_outputs[key]
+        return output_ref()

All existing call sites (in model_engine.py and the various unit tests under tests/unittest/_torch/…) treat the result of replay(...) as a Tensor, so this change restores the intended API contract.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16499 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #12393 completed with status: 'FAILURE'

@QiJune
Copy link
Collaborator Author

QiJune commented Aug 26, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16569 [ run ] triggered by Bot

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.

LGTM

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16569 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #12443 completed with status: 'SUCCESS'

@QiJune
Copy link
Collaborator Author

QiJune commented Aug 27, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16679 [ run ] triggered by Bot

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: 1

Caution

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

⚠️ Outside diff range comments (1)
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py (1)

14-16: Fix Ruff F821 for forward-declared Request.

Type is only referenced in quotes but Ruff still flags it. Import under TYPE_CHECKING.

Apply:

 if TYPE_CHECKING:
-    from .model_engine import PyTorchModelEngine
+    from .model_engine import PyTorchModelEngine
+    from .scheduler import Request
♻️ Duplicate comments (2)
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py (2)

286-287: Call engine.use_mrope() when adding dummy requests.

Same method/attribute bug as above; otherwise mrope is always treated as True here.

Apply:

-                use_mrope=engine.use_mrope,
+                use_mrope=engine.use_mrope(),

57-78: Call engine.use_mrope() and avoid large device memsets for shared buffers.

  • Bug: engine.use_mrope is a method; attribute check is always truthy and over-allocates mrope buffers. Same issue reappears later.
  • Perf: use torch.empty for big static buffers; you overwrite before use during capture/replay anyway.

Apply:

         self.shared_static_tensors = {
-            "input_ids":
-            torch.ones((max_total_tokens, ), device="cuda", dtype=torch.int32),
-            "position_ids":
-            torch.zeros((1, max_total_tokens), device="cuda",
-                        dtype=torch.int32),
+            "input_ids": torch.empty((max_total_tokens,), device="cuda", dtype=torch.int32),
+            "position_ids": torch.empty((1, max_total_tokens), device="cuda", dtype=torch.int32),
         }
-        if engine.use_mrope:
+        if engine.use_mrope():
             self.shared_static_tensors["mrope_position_deltas"] = torch.zeros(
                 (self.max_supported_batch_size, 1),
                 device="cuda",
                 dtype=torch.int32)
🧹 Nitpick comments (5)
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py (5)

1-1: Add NVIDIA copyright header.

Per repo guidelines, prepend the current-year NVIDIA header to this source file.

Example:

+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.

223-236: Optional: assert replay sizes against preallocated capacity.

Adds an early, clear error if a future change violates sizing invariants.

Apply:

         static_tensors = self.shared_static_tensors
 
         input_ids = current_inputs["input_ids"]
         seqlen = input_ids.shape[0]
+        assert seqlen <= static_tensors["input_ids"].numel(), \
+            "Replay seqlen exceeds preallocated input_ids capacity"
         static_tensors["input_ids"][:seqlen].copy_(input_ids)
 
         position_ids = current_inputs["position_ids"]
+        assert seqlen <= static_tensors["position_ids"].shape[1], \
+            "Replay seqlen exceeds preallocated position_ids capacity"
         static_tensors["position_ids"][:, :seqlen].copy_(position_ids)

99-101: Harden destructor to avoid teardown-time CUDA errors.

Guard clear() in del to prevent noisy exceptions during interpreter shutdown.

Apply:

-    def __del__(self):
-        self.clear()
+    def __del__(self):
+        try:
+            self.clear()
+        except Exception:
+            pass

66-72: Optional: document why int32 is used for IDs.

Quick docstring or comment prevents regressions to wrong dtypes later.


121-136: Nit: variable names are misleading.

is_all_gen_only actually checks can_run_cuda_graph; consider renaming for clarity.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 7821b9d and 3c72803.

📒 Files selected for processing (1)
  • tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py (3 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: Code must target Python 3.8+
Indent Python code with 4 spaces; do not use tabs
Preserve module namespaces when importing; import modules/packages and access members via the module (e.g., from package.subpackage import foo; foo.SomeClass())
Python file names should be snake_case
Python class names should be PascalCase
Python functions/methods and local variables should be snake_case; variables beginning with a number should be prefixed with k_ (e.g., k_99th_percentile)
Global variables should be UPPER_SNAKE_CASE prefixed with G_ (e.g., G_MY_GLOBAL); constants should be UPPER_SNAKE_CASE
Avoid shadowing variables from outer scopes; initialize all externally visible members in init
Prefer docstrings for interfaces used outside a file; comments should be reserved for in-function or file-local interfaces
Use Google-style docstrings for classes and functions; attributes and variables may be documented inline with trailing string literals
Avoid reflection when simpler, explicit code suffices (e.g., avoid dict(**locals()) patterns)
In try/except, catch the narrowest exceptions possible
For duck-typing patterns, keep the try body minimal and move logic to else to avoid masking unrelated failures

Files:

  • tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
**/*.{c,cc,cpp,cxx,h,hh,hpp,hxx,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Prepend the NVIDIA copyright header (current year) to all source files (.cpp, .h, .cu, .py, etc.)

Files:

  • tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
🧬 Code graph analysis (1)
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py (1)
tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
  • use_mrope (481-489)
🪛 Ruff (0.12.2)
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py

51-51: Undefined name Request

(F821)

⏰ 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 (4)
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py (4)

43-45: LGTM: clear max_possible_draft_len calculation.


53-56: LGTM: allocate shared pool only when enabled.


61-65: LGTM: capping by engine.max_num_tokens.

Good safeguard against over-allocation.


73-77: No action needed – use_mrope is correctly used as a @Property

All occurrences of use_mrope were reviewed across the repository. Since it’s implemented as a Python @property, accessing it without parentheses is intentional and correct. No fixes are required.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16679 [ run ] completed with state FAILURE
/LLM/main/L0_MergeRequest_PR pipeline #12522 completed with status: 'FAILURE'

@QiJune
Copy link
Collaborator Author

QiJune commented Aug 27, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16690 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16690 [ run ] completed with state FAILURE
/LLM/main/L0_MergeRequest_PR pipeline #12528 completed with status: 'FAILURE'

@QiJune
Copy link
Collaborator Author

QiJune commented Sep 1, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17254 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17254 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #12970 completed with status: 'FAILURE'

@QiJune
Copy link
Collaborator Author

QiJune commented Sep 2, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17281 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17281 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #12989 completed with status: 'FAILURE'

@QiJune
Copy link
Collaborator Author

QiJune commented Sep 2, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17411 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17411 [ run ] completed with state FAILURE
/LLM/main/L0_MergeRequest_PR pipeline #13085 completed with status: 'FAILURE'

@QiJune
Copy link
Collaborator Author

QiJune commented Sep 4, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17689 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17689 [ run ] completed with state FAILURE
/LLM/main/L0_MergeRequest_PR pipeline #13299 completed with status: 'ABORTED'

@QiJune
Copy link
Collaborator Author

QiJune commented Sep 5, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17799 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17799 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13326 completed with status: 'FAILURE'

@QiJune
Copy link
Collaborator Author

QiJune commented Sep 5, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17826 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17826 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13345 completed with status: 'FAILURE'

@QiJune
Copy link
Collaborator Author

QiJune commented Sep 6, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17852 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17852 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13364 completed with status: 'FAILURE'

@QiJune
Copy link
Collaborator Author

QiJune commented Sep 6, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17886 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17886 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13397 completed with status: 'SUCCESS'

@QiJune QiJune merged commit 12ecb86 into NVIDIA:main Sep 6, 2025
5 checks passed
Wong4j pushed a commit to Wong4j/TensorRT-LLM that referenced this pull request Sep 20, 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.

4 participants