Skip to content

Conversation

stnie
Copy link
Collaborator

@stnie stnie commented Jul 21, 2025

  • Implemented static cache indirection buffer in model engine for beam search to allow for CUDA graph usage.
  • Updated batch size calculations to account for max beam width.
  • Modified dummy request creation to support variable beam widths.
  • Added unit tests for beam search output shapes with CUDA graph configurations.

This change enables beam search + CUDA graph operations in the PyTorch model engine.

Summary by CodeRabbit

  • New Features
    • Enabled support for running beam search with CUDA graphs, improving performance for advanced decoding strategies.
    • Introduced persistent cache indirection buffers to optimize beam search execution.
  • Bug Fixes
    • Adjusted batch size and token calculations to properly account for beam width during execution and padding.
  • Tests
    • Updated tests to verify output shapes and behavior when using beam search with CUDA graphs.
  • Refactor
    • Enhanced attention metadata to support cache indirection handling for beam search scenarios.

Description

Beam Search, was not usable with CUDA Graphs. This PR enables CUDA Graph support for beam search.

Test Coverage

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.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 21, 2025

📝 Walkthrough

Walkthrough

The changes enable beam search support with CUDA graph execution by removing previous restrictions, updating batch and cache handling logic, and adjusting attention metadata and warmup routines. The resource manager and test suite are updated to handle beam width-aware dummy requests and to validate beam search functionality with CUDA graphs. Additionally, attention metadata structures are extended to support cache indirection buffers needed for beam search.

Changes

File(s) Change Summary
tensorrt_llm/_torch/pyexecutor/model_engine.py Removes CUDA graph restriction with beam search, adds use_beam_search property, updates batch/cache/metadata logic for beam width. Introduces persistent cache indirection buffer.
tensorrt_llm/_torch/pyexecutor/resource_manager.py Updates add_dummy_requests to accept max_beam_width and set sampling parameters accordingly for beam search.
tensorrt_llm/_torch/attention_backend/interface.py Adds optional cache_indirection field to AttentionMetadata dataclass for beam search support.
tensorrt_llm/_torch/attention_backend/trtllm.py Removes cache_indirection attribute from TrtllmAttentionMetadata dataclass and updates related comment.
tests/unittest/_torch/test_beam_search.py Adds CUDA graph-specific beam search tests and fixture, updates imports and test logic for new scenarios.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant LLM
    participant ModelEngine
    participant KVCacheManager

    User->>LLM: Request inference (with beam search, CUDA graph enabled)
    LLM->>ModelEngine: Prepare input, check use_beam_search
    ModelEngine->>KVCacheManager: add_dummy_requests(max_beam_width)
    ModelEngine->>ModelEngine: Adjust batch size, cache, metadata for beam width
    ModelEngine->>ModelEngine: Warmup and run CUDA graph execution
    ModelEngine->>LLM: Return outputs
    LLM->>User: Return results
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~45 minutes

Possibly related PRs

  • [ci] Speedup beam search unit tests with fixtures for LLM #5843: The main PR removes the previous NotImplementedError blocking CUDA graph usage with beam search in model_engine.py and adds full support for beam search with CUDA graphs, while the retrieved PR explicitly adds that NotImplementedError to prevent CUDA graph usage with beam search; thus, they modify the same functionality in opposite ways and are directly related.

Suggested reviewers

  • Funatiq
  • QiJune
  • Naveassaf

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

🪧 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.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai 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:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

Documentation and Community

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

@stnie
Copy link
Collaborator Author

stnie commented Jul 21, 2025

/bot run

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

🧹 Nitpick comments (2)
tensorrt_llm/_torch/pyexecutor/model_engine.py (2)

498-514: Fix line length issue while keeping the logic intact.

The warmup logic correctly accounts for beam search resource usage. However, line 511 exceeds the 120-character limit.

-                # Divide by max_beam_width to get an approximation of the number of tokens that can be added to the final request.
+                # Divide by max_beam_width to get an approximation of the number of tokens
+                # that can be added to the final request.

1439-1448: Fix line length while approving the cache indirection logic.

The cache indirection buffer handling is correct, including the special case for CUDA graph warmup. However, line 1440 exceeds the character limit.

-            # CUDA Graph needs to set beam width during warmup (where the graph is captured), to ensure that cache indirection buffer is correctly picked up by the CUDA graph
+            # CUDA Graph needs to set beam width during warmup (where the graph is captured),
+            # to ensure that cache indirection buffer is correctly picked up by the CUDA graph
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9832bef and dd044e7.

📒 Files selected for processing (3)
  • tensorrt_llm/_torch/pyexecutor/model_engine.py (12 hunks)
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py (1 hunks)
  • tests/unittest/_torch/test_beam_search.py (3 hunks)
🧰 Additional context used
🧠 Learnings (1)
tensorrt_llm/_torch/pyexecutor/model_engine.py (1)

Learnt from: amitz-nv
PR: #5616
File: tensorrt_llm/executor/worker.py:375-384
Timestamp: 2025-07-17T09:01:27.374Z
Learning: In tensorrt_llm/executor/worker.py, the LoRA adapter cache optimization logic that checks is_adapter_in_cpu_cache() and conditionally passes None for weights/config has a known race condition issue that cannot be solved with simple error handling or verification checks. This is a known limitation that requires a more comprehensive solution.

🪛 Ruff (0.12.2)
tensorrt_llm/_torch/pyexecutor/model_engine.py

511-511: Line too long (130 > 120)

(E501)


1440-1440: Line too long (174 > 120)

(E501)

⏰ 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 (9)
tensorrt_llm/_torch/pyexecutor/resource_manager.py (1)

376-384: Implementation looks correct for beam search integration.

The parameter addition and sampling configuration updates properly support beam search in dummy request creation. The logic correctly enables beam search when beam_width > 1 and maintains backward compatibility with the default value.

tests/unittest/_torch/test_beam_search.py (3)

8-8: Import addition is appropriate.

Adding CudaGraphConfig and KvCacheConfig imports supports the new CUDA graph test fixture and aligns with the expanded functionality.


53-67: CUDA graph fixture setup looks good.

The new fixture properly mirrors the existing llm fixture with CUDA graph enabled, maintaining consistent configuration while enabling the target functionality.


126-173: Comprehensive test coverage for CUDA graph beam search.

The test function provides thorough validation of beam search functionality with CUDA graph integration, including:

  • Output shape verification
  • Context and generation logits validation
  • Log probability handling
  • Text output correctness
  • Proper skip conditions for unsupported scenarios
tensorrt_llm/_torch/pyexecutor/model_engine.py (5)

450-453: LGTM! Clean property implementation.

The use_beam_search property provides a clear abstraction for checking if beam search is active.


421-430: LGTM! Proper initialization of cache indirection buffer.

The persistent cache indirection buffer is correctly initialized with appropriate dimensions when beam search is enabled. This allows it to be reused across forward passes and captured by CUDA graphs.


752-757: LGTM! Proper backend-specific handling of cache indirection.

The cache indirection buffer is correctly passed only to the TRTLLM attention backend, maintaining compatibility with other backends.

Also applies to: 783-785


816-817: LGTM! Consistent batch size scaling for beam search.

The batch size calculations correctly multiply by max_beam_width to account for the total number of sequences when beam search is active. This is properly applied across CUDA graph creation and metadata setup.

Also applies to: 926-940


849-855: LGTM! Proper dummy request creation for beam search.

The dummy request is correctly created with the max_beam_width parameter to ensure it's compatible with beam search operations during CUDA graph padding.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #12448 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@stnie stnie changed the title [TRTLLM-6520][feat] Enhance beam search support with CUDA graph integration [TRTLLM-6650][feat] Enhance beam search support with CUDA graph integration Jul 22, 2025
@stnie stnie requested a review from dcampora July 22, 2025 09:17
@stnie stnie marked this pull request as ready for review July 22, 2025 09:17
@stnie stnie requested a review from a team as a code owner July 22, 2025 09:17
@stnie stnie requested review from Funatiq and lfr-0531 July 22, 2025 11:55
@dcampora dcampora enabled auto-merge (squash) July 23, 2025 10:25
@stnie stnie force-pushed the develop/beam_search_features/cuda_graph branch from dd044e7 to 0fc112a Compare July 23, 2025 13:47
@stnie stnie requested a review from a team as a code owner July 23, 2025 13:47
@stnie stnie force-pushed the develop/beam_search_features/cuda_graph branch from 0fc112a to a897cd4 Compare July 23, 2025 13:48
@stnie
Copy link
Collaborator Author

stnie commented Jul 23, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #12714 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@stnie
Copy link
Collaborator Author

stnie commented Jul 23, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #12726 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

stnie added 2 commits July 24, 2025 09:28
- Implemented static cache indirection buffer in model engine for beam search to allow for CUDA graph usage.
- Updated batch size calculations to account for max beam width.
- Modified dummy request creation to support variable beam widths.
- Added unit tests for beam search output shapes with CUDA graph configurations.

This change enables  beam search + CUDA graph operations in the PyTorch model engine.

Signed-off-by: Stefan Niebler <[email protected]>
- Moved the cache indirection buffer into AttentionMetadata instead of TrtllmAttentionMetadata
- Updated PyTorchModelEngine to utilize the cache indirection buffer conditionally based on the attention backend.
- Combined the beam search testcases for overlap scheduling and cuda graphs.
- Adjusted size estimation of cache indirection buffer in model_engine to correctly cover overlap scheduling

Signed-off-by: Stefan Niebler <[email protected]>
@stnie stnie force-pushed the develop/beam_search_features/cuda_graph branch from a897cd4 to 0236a0a Compare July 24, 2025 07:28
@stnie
Copy link
Collaborator Author

stnie commented Jul 24, 2025

/bot run

@coderabbitai coderabbitai bot requested review from Naveassaf and QiJune July 24, 2025 07:28
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 (1)
tensorrt_llm/_torch/pyexecutor/model_engine.py (1)

516-516: Fix line length violations.

Three lines exceed the 120-character limit and should be reformatted for better readability:

-            # Divide by max_beam_width to get an approximation of the number of requests that can be run in parallel.
+            # Divide by max_beam_width to get an approximation of the number of 
+            # requests that can be run in parallel.
-        cache_indirection = self.cache_indirection_attention if self.attn_backend.Metadata is TrtllmAttentionMetadata else None
+        cache_indirection = (self.cache_indirection_attention 
+                           if self.attn_backend.Metadata is TrtllmAttentionMetadata 
+                           else None)
-        if self.use_beam_search and num_generation_requests > 0:
+        if (self.use_beam_search and num_generation_requests > 0):

Also applies to: 757-757, 1466-1466

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a897cd4 and 0236a0a.

📒 Files selected for processing (5)
  • tensorrt_llm/_torch/attention_backend/interface.py (1 hunks)
  • tensorrt_llm/_torch/attention_backend/trtllm.py (1 hunks)
  • tensorrt_llm/_torch/pyexecutor/model_engine.py (12 hunks)
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py (1 hunks)
  • tests/unittest/_torch/test_beam_search.py (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • tensorrt_llm/_torch/attention_backend/interface.py
  • tensorrt_llm/_torch/attention_backend/trtllm.py
  • tests/unittest/_torch/test_beam_search.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
🧰 Additional context used
🧠 Learnings (1)
tensorrt_llm/_torch/pyexecutor/model_engine.py (1)

Learnt from: amitz-nv
PR: #5616
File: tensorrt_llm/executor/worker.py:375-384
Timestamp: 2025-07-17T09:01:27.402Z
Learning: In tensorrt_llm/executor/worker.py, the LoRA adapter cache optimization logic that checks is_adapter_in_cpu_cache() and conditionally passes None for weights/config has a known race condition issue that cannot be solved with simple error handling or verification checks. This is a known limitation that requires a more comprehensive solution.

🪛 Ruff (0.12.2)
tensorrt_llm/_torch/pyexecutor/model_engine.py

516-516: Line too long (130 > 120)

(E501)


757-757: Line too long (127 > 120)

(E501)


1466-1466: Line too long (174 > 120)

(E501)

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

425-434: LGTM! Proper conditional cache indirection buffer setup.

The cache indirection buffer is correctly allocated only when beam search is enabled, with appropriate dimensions and device placement. The conditional logic ensures memory efficiency by avoiding unnecessary allocation when beam search is not used.


455-457: LGTM! Clean property implementation.

The use_beam_search property provides a clear and readable way to determine when beam search is active based on the max_beam_width configuration.


502-529: LGTM! Proper beam width consideration in warmup resource calculations.

The warmup logic correctly adjusts available block and token calculations by dividing by max_beam_width, providing a conservative estimate of parallel request capacity under beam search scenarios. The max_beam_width parameter is properly passed to dummy request creation.


757-785: LGTM! Clean cache indirection parameter handling.

The implementation properly addresses the previous review feedback by using explicit conditional assignment for cache_indirection rather than kwargs. The parameter is only passed when using the TrtllmAttentionMetadata backend, which is the correct behavior.


817-855: LGTM! Correct batch size handling for beam search sequences.

The implementation properly calculates the total number of sequences by multiplying batch_size by max_beam_width, with a clear explanatory comment. The dummy request creation maintains consistency by passing the max_beam_width parameter.


927-942: LGTM! Consistent beam width handling in CUDA graph creation.

The CUDA graph creation properly calculates num_sequences_in_batch by accounting for beam width and consistently passes this value to all graph components (metadata, runner). This ensures proper resource allocation and graph structure for beam search scenarios.


1465-1475: LGTM! Proper cache indirection buffer management and beam width setup.

The implementation correctly handles cache indirection buffer copying with appropriate offset adjustments and properly sets the beam width in attention metadata. The special case for CUDA graph during warmup ensures correct graph capture behavior.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #12821 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #12821 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #9555 completed with status: 'SUCCESS'
Pipeline passed with automatic retried tests. Check the rerun report for details.

@dcampora dcampora merged commit 0df758e into NVIDIA:main Jul 24, 2025
3 checks passed
NVShreyas pushed a commit to NVShreyas/TensorRT-LLM that referenced this pull request Jul 28, 2025
Ransiki pushed a commit to Ransiki/TensorRT-LLM that referenced this pull request Jul 29, 2025
lancelly pushed a commit to lancelly/TensorRT-LLM that referenced this pull request Aug 6, 2025
@stnie stnie deleted the develop/beam_search_features/cuda_graph branch September 9, 2025 08:37
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