[TRTLLM-8690][feat] add more tensors to share buffers#8691
[TRTLLM-8690][feat] add more tensors to share buffers#8691HuiGao-NV merged 6 commits intoNVIDIA:mainfrom
Conversation
|
/bot run |
|
PR_Github #22654 [ run ] triggered by Bot. Commit: |
📝 WalkthroughWalkthroughThis PR introduces CUDA-graph-aware buffer management across attention backends and memory utilities. It adds buffer allocation abstraction methods to the attention metadata interface, implements a managed buffer pool with pooling utilities, and updates various backend implementations to route tensor allocations through the new buffer management interface while tracking CUDA graph capture state. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Code as Attention Backend
participant GetEmpty as AttentionMetadata.get_empty()
participant BufferMgr as Buffers (Buffer Manager)
participant MemPool as Managed Buffer Pool
participant CUDA as CUDA Device
Code->>GetEmpty: get_empty(buffers, shape, dtype, cache_name, capture_graph)
alt buffers is None
GetEmpty->>CUDA: torch.empty(shape, dtype)
else buffers provided
GetEmpty->>BufferMgr: get_buffer(cache_name, shape, dtype, capture_graph)
BufferMgr->>BufferMgr: calculate required_memory_size
alt cached buffer exists with sufficient size
BufferMgr->>MemPool: return cached buffer
else
BufferMgr->>MemPool: _get_managed_buffer(required_memory_size)
MemPool->>CUDA: allocate new tensor
MemPool->>MemPool: store in managed_buffers pool
end
BufferMgr->>GetEmpty: return pooled/allocated tensor
end
GetEmpty->>Code: return tensor
rect rgb(200, 220, 240)
Note over Code,CUDA: CUDA Graph Capture State<br/>tracked via capture_graph parameter
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes
Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 12
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/attention_backend/sparse/dsa.py (1)
289-385: Undefined nameget_empty; qualify and pass buffers.Bare
get_empty(...)is undefined and will raise NameError. Use the static helper via the instance and pass the buffer pool.Apply this consolidated diff:
- self.indexer_k_cache_block_offsets = get_empty( - [self.max_num_sequences, self.kv_cache_manager.max_blocks_per_seq], + self.indexer_k_cache_block_offsets = self.get_empty( + self.cuda_graph_buffers, + [self.max_num_sequences, self.kv_cache_manager.max_blocks_per_seq], cache_name="indexer_k_cache_block_offsets", dtype=torch.int32, capture_graph=capture_graph) # For mla_rope_append_paged_kv_assign_q if not self.enable_context_mla_with_cached_kv: - self.ctx_cached_token_indptr = get_empty( - (self.max_num_requests + 1, ), + self.ctx_cached_token_indptr = self.get_empty( + self.cuda_graph_buffers, (self.max_num_requests + 1, ), cache_name="ctx_cached_token_indptr", dtype=torch.int64, capture_graph=capture_graph) ... - self.ctx_kv_indptr = get_empty((self.max_num_requests + 1, ), + self.ctx_kv_indptr = self.get_empty(self.cuda_graph_buffers, (self.max_num_requests + 1, ), cache_name="ctx_kv_indptr", dtype=torch.int64, capture_graph=capture_graph) - self.gen_cached_token_indptr = get_empty( - (self.max_num_requests + 1, ), + self.gen_cached_token_indptr = self.get_empty( + self.cuda_graph_buffers, (self.max_num_requests + 1, ), cache_name="gen_cached_token_indptr", dtype=torch.int64, capture_graph=capture_graph) ... - self.gen_kv_indptr = get_empty((self.max_num_requests + 1, ), + self.gen_kv_indptr = self.get_empty(self.cuda_graph_buffers, (self.max_num_requests + 1, ), cache_name="gen_kv_indptr", dtype=torch.int64, capture_graph=capture_graph) ... - self.slot_mapping_fp8 = get_empty((self.max_num_tokens, ), + self.slot_mapping_fp8 = self.get_empty(self.cuda_graph_buffers, (self.max_num_tokens, ), cache_name="slot_mapping_fp8", dtype=torch.int64, capture_graph=capture_graph) ... - self.slot_mapping_scale = get_empty((self.max_num_tokens, ), + self.slot_mapping_scale = self.get_empty(self.cuda_graph_buffers, (self.max_num_tokens, ), cache_name="slot_mapping_scale", dtype=torch.int64, capture_graph=capture_graph) ... - self.req_idx_per_token = get_empty((self.max_num_tokens, ), + self.req_idx_per_token = self.get_empty(self.cuda_graph_buffers, (self.max_num_tokens, ), cache_name="req_idx_per_token", dtype=torch.int32, capture_graph=capture_graph) ... - self.block_table = get_empty( - (self.max_num_requests, self.kv_cache_manager.max_blocks_per_seq), + self.block_table = self.get_empty( + self.cuda_graph_buffers, + (self.max_num_requests, self.kv_cache_manager.max_blocks_per_seq), cache_name="block_table", dtype=torch.int32, capture_graph=capture_graph) - self.scheduler_metadata_buffer = get_empty( - (self.num_sms + 1, 2), + self.scheduler_metadata_buffer = self.get_empty( + self.cuda_graph_buffers, (self.num_sms + 1, 2), cache_name="scheduler_metadata_buffer", dtype=torch.int32, capture_graph=capture_graph) - self.cu_seqlen_ks = get_empty((self.max_num_tokens, ), + self.cu_seqlen_ks = self.get_empty(self.cuda_graph_buffers, (self.max_num_tokens, ), cache_name="cu_seqlen_ks", dtype=torch.int32, capture_graph=capture_graph) - self.cu_seqlen_ke = get_empty((self.max_num_tokens, ), + self.cu_seqlen_ke = self.get_empty(self.cuda_graph_buffers, (self.max_num_tokens, ), cache_name="cu_seqlen_ke", dtype=torch.int32, capture_graph=capture_graph)This also addresses Ruff F821 hints. Based on static analysis hints.
🧹 Nitpick comments (3)
tensorrt_llm/_torch/memory_buffer_utils.py (3)
74-76: Unused field and data structure choice.
- max_buffer_concurrency is unused; either use it or remove to avoid confusion.
- OrderedDict is fine, but keys aren’t kept sorted; helpers use min/max so it’s OK.
124-132: Python 3.8 typing compliance.You use list[int] (PEP 585) while targeting Python 3.8+. Either:
- Add
from __future__ import annotationsat top, or- Replace with typing.Sequence[int]/typing.List[int].
Prefer Sequence[int] for generality.
Also applies to: 48-50
109-114: Catch specific exceptions and improve logging.Use RuntimeError for CUDA alloc failures and structured logging.
-except Exception as ex: - logger.debug( - f"Exception happened to create tensor from given memory pool: {str(ex)}" - ) +except RuntimeError as ex: + logger.debug("Alloc from shared pool failed: %s", ex)Also applies to: 168-176
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
tensorrt_llm/_torch/attention_backend/flashinfer.py(2 hunks)tensorrt_llm/_torch/attention_backend/interface.py(1 hunks)tensorrt_llm/_torch/attention_backend/sparse/dsa.py(3 hunks)tensorrt_llm/_torch/attention_backend/sparse/rocket.py(1 hunks)tensorrt_llm/_torch/attention_backend/trtllm.py(3 hunks)tensorrt_llm/_torch/memory_buffer_utils.py(4 hunks)tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_deepgemm.py(3 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/attention_backend/flashinfer.pytensorrt_llm/_torch/attention_backend/sparse/rocket.pytensorrt_llm/_torch/attention_backend/trtllm.pytensorrt_llm/_torch/attention_backend/sparse/dsa.pytensorrt_llm/_torch/modules/fused_moe/ops/moe_op_deepgemm.pytensorrt_llm/_torch/memory_buffer_utils.pytensorrt_llm/_torch/attention_backend/interface.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/attention_backend/flashinfer.pytensorrt_llm/_torch/attention_backend/sparse/rocket.pytensorrt_llm/_torch/attention_backend/trtllm.pytensorrt_llm/_torch/attention_backend/sparse/dsa.pytensorrt_llm/_torch/modules/fused_moe/ops/moe_op_deepgemm.pytensorrt_llm/_torch/memory_buffer_utils.pytensorrt_llm/_torch/attention_backend/interface.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/attention_backend/flashinfer.pytensorrt_llm/_torch/attention_backend/sparse/rocket.pytensorrt_llm/_torch/attention_backend/trtllm.pytensorrt_llm/_torch/attention_backend/sparse/dsa.pytensorrt_llm/_torch/modules/fused_moe/ops/moe_op_deepgemm.pytensorrt_llm/_torch/memory_buffer_utils.pytensorrt_llm/_torch/attention_backend/interface.py
🧬 Code graph analysis (7)
tensorrt_llm/_torch/attention_backend/flashinfer.py (2)
tensorrt_llm/_torch/attention_backend/trtllm.py (1)
_post_init_with_buffers(636-736)tensorrt_llm/_torch/attention_backend/interface.py (1)
get_empty(353-380)
tensorrt_llm/_torch/attention_backend/sparse/rocket.py (2)
tensorrt_llm/_torch/auto_deploy/compile/backends/torch_cudagraph.py (1)
capture_graph(90-143)tensorrt_llm/_torch/attention_backend/interface.py (1)
get_empty(353-380)
tensorrt_llm/_torch/attention_backend/trtllm.py (1)
tensorrt_llm/_torch/attention_backend/interface.py (2)
get_empty(353-380)get_empty_like(383-390)
tensorrt_llm/_torch/attention_backend/sparse/dsa.py (1)
tensorrt_llm/_torch/attention_backend/interface.py (1)
get_empty(353-380)
tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_deepgemm.py (1)
tensorrt_llm/_torch/memory_buffer_utils.py (2)
get_memory_buffers(231-233)get_buffer(124-188)
tensorrt_llm/_torch/memory_buffer_utils.py (3)
cpp/tests/unit_tests/kernels/mixtureOfExpertsTest.cu (1)
managed_buffers(263-270)tensorrt_llm/_utils.py (1)
numel(990-991)tensorrt_llm/logger.py (1)
debug(144-145)
tensorrt_llm/_torch/attention_backend/interface.py (1)
tensorrt_llm/_torch/memory_buffer_utils.py (1)
get_buffer(124-188)
🪛 Ruff (0.14.1)
tensorrt_llm/_torch/attention_backend/sparse/dsa.py
312-312: Undefined name get_empty
(F821)
332-332: Undefined name get_empty
(F821)
343-343: Undefined name get_empty
(F821)
352-352: Undefined name get_empty
(F821)
362-362: Undefined name get_empty
(F821)
367-367: Undefined name get_empty
(F821)
372-372: Undefined name get_empty
(F821)
377-377: Undefined name get_empty
(F821)
381-381: Undefined name get_empty
(F821)
tensorrt_llm/_torch/memory_buffer_utils.py
84-85: Avoid specifying long messages outside the exception class
(TRY003)
98-98: Unpacked variable buffer_1 is never used
Prefix it with an underscore or any other dummy variable pattern
(RUF059)
109-109: Do not catch blind exception: Exception
(BLE001)
112-112: Use explicit conversion flag
Replace with conversion flag
(RUF010)
131-131: Undefined name _get_managed_buffer
(F821)
209-209: Unused method argument: args
(ARG002)
209-209: Unused method argument: kwargs
(ARG002)
224-224: Undefined name current_shape
(F821)
tensorrt_llm/_torch/attention_backend/interface.py
386-386: Unused static method argument: capture_graph
(ARG004)
⏰ 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/attention_backend/flashinfer.py (1)
127-129: Allocation path looks good; verify dtype expectations.The buffered allocations are correct. Please confirm FlashInfer wrappers expect int32 for page indices; if so, prefer torch.int32 for _paged_kv_indices to match other buffers and avoid implicit casts.
Also applies to: 173-177
tensorrt_llm/_torch/attention_backend/trtllm.py (1)
644-657: Buffered allocations look consistent; relies on get_empty_like forwarding capture_graph.The refactor routes allocations through the buffer manager correctly. Ensure interface.get_empty_like forwards capture_graph (see separate comment in interface.py).
Also applies to: 672-704, 706-732
tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_deepgemm.py (2)
19-19: LGTM on centralizing buffer access.Importing get_memory_buffers here keeps allocation policy consistent across backends.
28-28: OK to cache buffers at class level.This is fine given a global pool; if you later need per-instance isolation, move it into init.
Confirm this op isn’t instantiated concurrently with different lifetimes that would require separate pools.
tensorrt_llm/_torch/memory_buffer_utils.py (1)
48-50: OK: utility to compute byte size.No changes needed.
|
PR_Github #22654 [ run ] completed with state |
a450c7e to
bf078a1
Compare
|
/bot run |
|
PR_Github #22746 [ run ] triggered by Bot. Commit: |
bf078a1 to
2191b8f
Compare
|
PR_Github #22746 [ run ] completed with state |
6af7f70 to
8f7d535
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #22773 [ run ] triggered by Bot. Commit: |
|
PR_Github #22773 [ run ] completed with state |
|
/bot run --stage-list "B200_PCIe-PyTorch-2,B300-PyTorch-1,H100_PCIe-PyTorch-3,H100_PCIe-PyTorch-Perf-1" |
|
/bot run --stage-list "B200_PCIe-PyTorch-2,B300-PyTorch-1,H100_PCIe-PyTorch-3,H100_PCIe-PyTorch-Perf-1" --disable-fail-fast |
|
PR_Github #22810 [ run ] triggered by Bot. Commit: |
|
PR_Github #22812 [ run ] triggered by Bot. Commit: |
|
PR_Github #22810 [ run ] completed with state |
|
PR_Github #22812 [ run ] completed with state |
2e73126 to
e22d69c
Compare
|
/bot run --stage-list "H100_PCIe-PyTorch-Perf" |
|
PR_Github #22881 [ run ] triggered by Bot. Commit: |
|
PR_Github #22881 [ run ] completed with state |
125ebe4 to
b9ae472
Compare
Signed-off-by: Hui Gao <huig@nvidia.com>
b9ae472 to
12b1a5b
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #23349 [ run ] triggered by Bot. Commit: |
Signed-off-by: Hui Gao <huig@nvidia.com>
|
/bot run --disable-fail-fast |
|
PR_Github #23357 [ run ] triggered by Bot. Commit: |
|
PR_Github #23349 [ run ] completed with state |
|
PR_Github #23357 [ run ] completed with state |
Signed-off-by: Hui Gao <huig@nvidia.com>
|
/bot reuse-pipeline |
|
PR_Github #23459 [ reuse-pipeline ] triggered by Bot. Commit: |
|
PR_Github #23459 [ reuse-pipeline ] completed with state |
Signed-off-by: Hui Gao <huig@nvidia.com> Signed-off-by: FredricZ-2007 <226039983+fredricz-20070104@users.noreply.github.com>
Support to share more buffers
Summary by CodeRabbit
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.
Details
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-listparameter 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.mdand the
scripts/test_to_stage_mapping.pyhelper.kill
killKill all running builds associated with pull request.
skip
skip --comment COMMENTSkip 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-pipelineReuse 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.