-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[TRTLLM-6650][feat] Enhance beam search support with CUDA graph integration #6217
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[TRTLLM-6650][feat] Enhance beam search support with CUDA graph integration #6217
Conversation
📝 WalkthroughWalkthroughThe 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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
Note ⚡️ Unit Test Generation is now available in beta!Learn more here, or try it out under "Finishing Touches" below. ✨ Finishing Touches
🧪 Generate unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
Documentation and Community
|
/bot run |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 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
📒 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
andKvCacheConfig
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.
PR_Github #12448 [ run ] triggered by Bot |
PR_Github #12448 [ run ] completed with state |
dd044e7
to
0fc112a
Compare
0fc112a
to
a897cd4
Compare
/bot run |
PR_Github #12714 [ run ] triggered by Bot |
PR_Github #12714 [ run ] completed with state |
/bot run |
PR_Github #12726 [ run ] triggered by Bot |
PR_Github #12726 [ run ] completed with state |
- 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]>
a897cd4
to
0236a0a
Compare
/bot run |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (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
📒 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 themax_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. Themax_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
bymax_beam_width
, with a clear explanatory comment. The dummy request creation maintains consistency by passing themax_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.
PR_Github #12821 [ run ] triggered by Bot |
PR_Github #12821 [ run ] completed with state |
…ration (NVIDIA#6217) Signed-off-by: Stefan Niebler <[email protected]> Signed-off-by: Shreyas Misra <[email protected]>
…ration (NVIDIA#6217) Signed-off-by: Stefan Niebler <[email protected]> Signed-off-by: Ransiki Zhang <[email protected]>
…ration (NVIDIA#6217) Signed-off-by: Stefan Niebler <[email protected]> Signed-off-by: Lanyu Liao <[email protected]>
This change enables beam search + CUDA graph operations in the PyTorch model engine.
Summary by CodeRabbit
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 thestage-list
parameter to access the appropriate container environment. Note: Does NOT update GitHub check status.For guidance on mapping tests to stage names, see
docs/source/reference/ci-overview.md
and the
scripts/test_to_stage_mapping.py
helper.kill
kill
Kill all running builds associated with pull request.
skip
skip --comment COMMENT
Skip testing for latest commit on pull request.
--comment "Reason for skipping build/test"
is required. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.reuse-pipeline
reuse-pipeline
Reuse a previous pipeline to validate current commit. This action will also kill all currently running builds associated with the pull request. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.