KEMBAR78
[https://nvbugs/5481434][feat] Reuse pytorch memory segments occupied by cudagraph pool by HuiGao-NV · Pull Request #7457 · NVIDIA/TensorRT-LLM · GitHub
Skip to content

Conversation

@HuiGao-NV
Copy link
Collaborator

@HuiGao-NV HuiGao-NV commented Sep 2, 2025

Previous PR of this change was closed automatically after retarget base branch.

Summary by CodeRabbit

  • Bug Fixes
    • Reduced out-of-memory incidents during Mixture-of-Experts execution by reusing workspace memory across runs and CUDA graph capture.
  • Refactor
    • Implemented internal buffer reuse for workspace tensors in DeepGemmFusedMoE, lowering allocation churn and improving memory stability.
    • Added an internal recorder for allocated buffers to enable reuse across execution paths.
    • No changes to public APIs or user-facing configuration.

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.

@HuiGao-NV HuiGao-NV requested a review from a team as a code owner September 2, 2025 01:20
@HuiGao-NV HuiGao-NV requested a review from mikeiovine September 2, 2025 01:20
@HuiGao-NV
Copy link
Collaborator Author

/bot run --add-multi-gpu-test --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17266 [ run ] triggered by Bot

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 2, 2025

📝 Walkthrough

Walkthrough

Adds a capture-aware buffer reuse mechanism to DeepGemmFusedMoE’s workspace allocations in fused_moe_deepgemm.py. Introduces a class-level cache for CUDA tensors, helper functions to select/reuse buffers during graph capture vs runtime, and replaces direct allocations for three workspaces with the new allocator. No public API signatures changed.

Changes

Cohort / File(s) Summary of Changes
DeepGemmFusedMoE workspace reuse
tensorrt_llm/_torch/modules/fused_moe/fused_moe_deepgemm.py
Added class attribute allocated_buffer_recorder for buffer pools; imported math. Implemented select_buffer_with_more_elements and get_empty to reuse CUDA tensors across graph-capture/runtime. Replaced direct allocations for workspace_0, workspace_1, workspace_sf with cache-backed allocation using per-buffer pool keys.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    actor Caller
    participant DeepGemmFusedMoE as DeepGemmFusedMoE
    participant Allocator as get_empty (allocator)
    participant GraphPool as Graph buffer pool
    participant RuntimePool as Runtime buffer pool
    participant CUDA as CUDA Tensor

    Caller->>DeepGemmFusedMoE: forward(...)
    DeepGemmFusedMoE->>Allocator: request workspace_X(shape, dtype, capture_flag)
    alt capture_flag == true
        Allocator->>GraphPool: lookup suitable buffer
        alt found suitable
            Allocator-->>DeepGemmFusedMoE: view/slice of graph buffer
        else not found
            Allocator->>RuntimePool: check reusable buffer
            alt runtime buffer usable
                Allocator->>GraphPool: move/record buffer for capture
                Allocator-->>DeepGemmFusedMoE: view/slice
            else none usable
                Allocator->>CUDA: allocate new tensor
                Allocator->>GraphPool: record buffer
                Allocator-->>DeepGemmFusedMoE: new tensor
            end
        end
    else capture_flag == false
        Allocator->>RuntimePool: lookup suitable buffer
        alt found suitable
            Allocator-->>DeepGemmFusedMoE: reused tensor
        else not found
            Allocator->>CUDA: allocate new tensor
            Allocator->>RuntimePool: record buffer
            Allocator-->>DeepGemmFusedMoE: new tensor
        end
    end
    Note over DeepGemmFusedMoE: Applied for workspace_0, workspace_1, workspace_sf
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • hlu1
  • jinyangyuan-nvidia
  • djns99
  • kaiyux
✨ 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 @coderabbitai in a new review comment at the desired location with your query.
  • 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 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 @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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.

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.

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

🧹 Nitpick comments (1)
tensorrt_llm/_torch/modules/fused_moe/fused_moe_deepgemm.py (1)

1-1: Add NVIDIA copyright header.

This file is missing the required header per guidelines.

Add at the top:

# Copyright (c) 2025, NVIDIA CORPORATION.  All rights reserved.
📜 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 14af1f0 and 01530c6.

📒 Files selected for processing (1)
  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_deepgemm.py (3 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Filenames compiled into a target must be case-insensitively unique

Files:

  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_deepgemm.py
**/*.{h,hpp,hh,hxx,cc,cpp,cxx,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Use spaces, not tabs; indent 4 spaces

Files:

  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_deepgemm.py
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: Code must target Python 3.8+
Indent with 4 spaces; do not use tabs (Python)
Maintain module namespace on import: prefer from package.subpackage import foo; use foo.Symbol()
Python filenames use snake_case
Python class names use PascalCase
Python functions and methods use snake_case
Python local variables use snake_case; if starting with a number concept, prefix with k (e.g., k_99th_percentile)
Python global variables use G_ prefix with UPPER_SNAKE_CASE
Python constants use UPPER_SNAKE_CASE
Avoid shadowing variables from outer scopes
Initialize all externally visible class members in init
For public interfaces, prefer docstrings over comments; comments should be for in-function or file-local interfaces
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes and variables inline with docstrings immediately after assignment
Avoid reflection when a non-reflective approach suffices
Limit except clauses to specific exceptions where possible
When using try/except for duck-typing, keep try body minimal and move logic to else

Files:

  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_deepgemm.py
**/*.{cpp,cc,cxx,h,hpp,hh,hxx,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Prepend NVIDIA copyright header (current year) to all source files

Files:

  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_deepgemm.py
🧠 Learnings (2)
📓 Common learnings
Learnt from: djns99
PR: NVIDIA/TensorRT-LLM#6915
File: cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cu:4616-4626
Timestamp: 2025-08-19T03:35:20.866Z
Learning: In the MOE profiler TMA workspace preparation (cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cu), the overlapping of TMA WS regions for NONE and FINALIZE variants is deliberate design to save memory space, as confirmed by djns99. The comment "reuse the same pointers to save space" reflects this intentional behavior.
📚 Learning: 2025-08-19T03:35:20.866Z
Learnt from: djns99
PR: NVIDIA/TensorRT-LLM#6915
File: cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cu:4616-4626
Timestamp: 2025-08-19T03:35:20.866Z
Learning: In the MOE profiler TMA workspace preparation (cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cu), the overlapping of TMA WS regions for NONE and FINALIZE variants is deliberate design to save memory space, as confirmed by djns99. The comment "reuse the same pointers to save space" reflects this intentional behavior.

Applied to files:

  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_deepgemm.py
🧬 Code graph analysis (1)
tensorrt_llm/_torch/modules/fused_moe/fused_moe_deepgemm.py (1)
tensorrt_llm/quantization/utils/fp8_utils.py (2)
  • align (24-25)
  • ceil_div (10-21)
⏰ 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 (1)
tensorrt_llm/_torch/modules/fused_moe/fused_moe_deepgemm.py (1)

488-505: Workspace allocation switch to get_empty looks good (once helpers are fixed).

Shapes and dtypes are preserved; cache keys are distinct per workspace. No functional concerns after addressing the helper fixes above.

Please sanity-check that the largest required sizes across typical shapes are:

  • workspace_0: num_experts * m_max * max(hidden_size, intermediate_size)
  • workspace_1: num_experts * m_max * max(2*intermediate_size, hidden_size)
  • workspace_sf: num_experts * (align(ceil_div(fp8_dim, group_size), 4) // 4) * align(m_max, 4)

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17266 [ run ] completed with state SUCCESS
/LLM/release-1.1.0rc2/L0_MergeRequest_PR pipeline #9 completed with status: 'FAILURE'

@HuiGao-NV
Copy link
Collaborator Author

/bot run --stage-list="B200_PCIe-PyTorch-2,GB200-PyTorch-1" --add-multi-gpu-test --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17299 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17299 [ run ] completed with state SUCCESS
/LLM/release-1.1.0rc2/L0_MergeRequest_PR pipeline #13 (Partly Tested) completed with status: 'SUCCESS'

@HuiGao-NV
Copy link
Collaborator Author

/bot run --only-multi-gpu-test --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17351 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17351 [ run ] completed with state SUCCESS
/LLM/release-1.1.0rc2/L0_MergeRequest_PR pipeline #17 (Partly Tested) completed with status: 'FAILURE'

@HuiGao-NV HuiGao-NV force-pushed the reuse_buffer_in_deepgemm_moe branch from 0c0dc9d to 33428f9 Compare September 2, 2025 22:38
@HuiGao-NV
Copy link
Collaborator Author

Every pipeline is green, however the stage shows as red. Retest it.

@HuiGao-NV
Copy link
Collaborator Author

/bot run --only-multi-gpu-test --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17416 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17416 [ run ] completed with state SUCCESS
/LLM/release-1.1.0rc2/L0_MergeRequest_PR pipeline #28 (Partly Tested) completed with status: 'FAILURE'

@HuiGao-NV
Copy link
Collaborator Author

/bot run --disable-multi-gpu-test

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17448 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17448 [ run ] completed with state FAILURE
/LLM/release-1.1.0rc2/L0_MergeRequest_PR pipeline #32 (Partly Tested) completed with status: 'FAILURE'

@HuiGao-NV
Copy link
Collaborator Author

/bot run --disable-multi-gpu-test

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17461 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17461 [ run ] completed with state FAILURE
/LLM/release-1.1.0rc2/L0_MergeRequest_PR pipeline #36 (Partly Tested) completed with status: 'FAILURE'

@HuiGao-NV
Copy link
Collaborator Author

/bot run --disable-multi-gpu-test --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17469 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17469 [ run ] completed with state SUCCESS
/LLM/release-1.1.0rc2/L0_MergeRequest_PR pipeline #39 (Partly Tested) completed with status: 'FAILURE'

@HuiGao-NV
Copy link
Collaborator Author

/bot run --stage-list "B200_PCIe-PyTorch-1"

@HuiGao-NV
Copy link
Collaborator Author

/bot run --stage-list="B200_PCIe-PyTorch-1"

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17581 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17581 [ run ] completed with state SUCCESS
/LLM/release-1.1.0rc2/L0_MergeRequest_PR pipeline #53 (Partly Tested) completed with status: 'SUCCESS'

… by cudagraph pool

Signed-off-by: Hui Gao <huig@nvidia.com>
Signed-off-by: Hui Gao <huig@nvidia.com>
Signed-off-by: Hui Gao <huig@nvidia.com>
Signed-off-by: Hui Gao <huig@nvidia.com>
Signed-off-by: Hui Gao <huig@nvidia.com>
@HuiGao-NV HuiGao-NV force-pushed the reuse_buffer_in_deepgemm_moe branch from 0cb5a4e to b398e7c Compare September 4, 2025 03:55
@HuiGao-NV
Copy link
Collaborator Author

/bot skip --comment "multi-gpu and single gpu tests all pass"

@HuiGao-NV HuiGao-NV enabled auto-merge (squash) September 4, 2025 04:08
@litaotju litaotju disabled auto-merge September 4, 2025 04:08
@litaotju litaotju merged commit 80e1f9e into NVIDIA:release/1.1.0rc2 Sep 4, 2025
4 of 5 checks passed
@tensorrt-cicd
Copy link
Collaborator

PR_Github #17612 [ ] completed with state FAILURE
Not allowed on merged PR

HuiGao-NV added a commit to HuiGao-NV/TensorRT-LLM that referenced this pull request Sep 16, 2025
… by cudagraph pool (NVIDIA#7457)

Signed-off-by: Hui Gao <huig@nvidia.com>
@HuiGao-NV HuiGao-NV deleted the reuse_buffer_in_deepgemm_moe branch September 19, 2025 03:53
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