KEMBAR78
[#5255][autodeploy] Update FuseAllreduceResidualRMSNorm to use pattern matcher utility; remove fuse_collective by Fridah-nv · Pull Request #7545 · NVIDIA/TensorRT-LLM · GitHub
Skip to content

Conversation

@Fridah-nv
Copy link
Collaborator

@Fridah-nv Fridah-nv commented Sep 4, 2025

Summary by CodeRabbit

  • Refactor
    • Switched to pattern-based fusion for all-reduce + residual + RMSNorm, improving reliability and coverage of fusions and consistent reporting of applied fusions.
  • Bug Fixes
    • Removed a conflicting collective fusion option from the default configuration to avoid unintended behavior.
    • Corrected selection of the dim-1 distributed reduce operator during sharding to improve compatibility and prevent execution errors.

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.

@Fridah-nv Fridah-nv self-assigned this Sep 4, 2025
@Fridah-nv Fridah-nv requested a review from a team as a code owner September 4, 2025 23:02
@Fridah-nv Fridah-nv marked this pull request as draft September 4, 2025 23:07
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 4, 2025

📝 Walkthrough

Walkthrough

Removed the fuse_collectives transform from the default config. Deleted the FuseCollectives transform implementation. Refactored FuseAllreduceResidualRMSNorm to use an ADPatternMatcher-based search/replace with a fused op. Updated sharding utils to call torch.ops.auto_deploy.torch_dist_all_reduce.default for dim-1 distribution.

Changes

Cohort / File(s) Summary
Config cleanup
tensorrt_llm/_torch/auto_deploy/config/default.yaml
Removed fuse_collectives entry from transforms (stage: post_load_fusion). Other transforms unchanged.
Collectives transform refactor
tensorrt_llm/_torch/auto_deploy/transform/library/collectives.py
Removed FuseCollectives transform and its registration. Rewrote FuseAllreduceResidualRMSNorm to use ADPatternMatcherPass with pattern/replacement helpers to fuse all_reduce + residual + RMSNorm into torch.ops.dist.fused_allreduce_residual_rmsnorm. Updated imports accordingly. Populates TransformInfo.num_matches from matcher results.
Sharding op resolution
tensorrt_llm/_torch/auto_deploy/utils/sharding_utils.py
Switched dim-1 distribution op from torch.ops.auto_deploy.torch_dist_all_reduce to torch.ops.auto_deploy.torch_dist_all_reduce.default. No signature or flow changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant GM as GraphModule
  participant PM as ADPatternMatcherPass
  participant Pat as AR+Res+RMSNorm Pattern
  participant Fused as torch.ops.dist.fused_allreduce_residual_rmsnorm

  GM->>PM: apply(pattern=Pat, dummy_args, scalar_workaround)
  PM->>GM: scan graph for matches
  Note over PM,GM: Find subgraph: all_reduce(x) -> add(residual) -> RMSNorm(weight, eps)
  PM->>Fused: replace matched subgraph with fused op call
  Fused-->>PM: fused node
  PM-->>GM: updated graph, report num_matches
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • suyoggupta
✨ 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: 0

🧹 Nitpick comments (8)
tensorrt_llm/_torch/auto_deploy/utils/sharding_utils.py (1)

1-1: Add required NVIDIA Apache-2.0 header.

Per repository guidelines, prepend the 2025 NVIDIA Apache-2.0 header to this file.

Apply this at file top:

+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#     http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
tensorrt_llm/_torch/auto_deploy/transform/library/collectives.py (7)

1-1: Add required NVIDIA Apache-2.0 header.

Please prepend the 2025 NVIDIA Apache-2.0 header.

+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#     http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.

19-21: De-duplicate the eps literal via a module constant.

0.1253 appears in multiple places; define once to keep pattern, replacement, and registration in sync.

-def _allreduce_residual_rmsnorm_pattern(
-    x: torch.Tensor, residual: torch.Tensor, weight: torch.Tensor, eps: float = 0.1253
-):
+RMSNORM_EPS_DEFAULT = 0.1253
+
+def _allreduce_residual_rmsnorm_pattern(
+    x: torch.Tensor, residual: torch.Tensor, weight: torch.Tensor, eps: float = RMSNORM_EPS_DEFAULT
+):

30-40: Use the op’s default overload explicitly for consistency.

Elsewhere in this PR we call .default; align here to avoid packet vs. overload mismatches in FX.

-    hidden_states = torch.ops.auto_deploy.torch_dist_all_reduce(x)
+    hidden_states = torch.ops.auto_deploy.torch_dist_all_reduce.default(x)

60-61: OK to instantiate a fresh matcher.

If this transform can run multiple times in a pipeline, consider guarding duplicate registrations (see next comment).


63-79: Harden registration: avoid dupe patterns and centralize eps.

  • Pass skip_duplicates=True to avoid re-registering on repeated transform runs.
  • Reuse RMSNORM_EPS_DEFAULT in dummy args and scalar_workaround.
-        dummy_args = [
+        dummy_args = [
             torch.randn(bsz, hidden, device="meta", dtype=torch.bfloat16),  # x
             torch.randn(bsz, hidden, device="meta", dtype=torch.bfloat16),  # residual
             torch.randn(hidden, device="meta", dtype=torch.bfloat16),  # weight
-            0.1253,  # eps
+            RMSNORM_EPS_DEFAULT,  # eps
         ]
@@
-        register_ad_pattern(
+        register_ad_pattern(
             search_fn=_allreduce_residual_rmsnorm_pattern,
             replace_fn=_allreduce_residual_rmsnorm_repl,
             patterns=patterns,
             dummy_args=dummy_args,
             op_ignore_types={torch.ops.aten.to.dtype: (torch.dtype,)},
-            scalar_workaround={"eps": 0.1253},
+            scalar_workaround={"eps": RMSNORM_EPS_DEFAULT},
+            skip_duplicates=True,
         )

80-81: Recompile after graph edits to materialize codegen.

Pattern pass mutates gm.graph; call dead-code elimination and recompile.

-        num_matches = patterns.apply(gm.graph)
+        num_matches = patterns.apply(gm.graph)
+        gm.graph.eliminate_dead_code()
+        gm.recompile()

43-47: Wrap torch.ops.dist.fused_allreduce_residual_rmsnorm in try/except to fall back to the Python implementation
This avoids hard failures on builds without the fused op:

 try:
     _FUSED_ARRN = torch.ops.dist.fused_allreduce_residual_rmsnorm
 except AttributeError:
     from ...distributed.trtllm import fused_allreduce_residual_rmsnorm as _FUSED_ARRN

 def _allreduce_residual_rmsnorm_repl(x: torch.Tensor, residual: torch.Tensor, weight: torch.Tensor, eps: float):
     return _FUSED_ARRN(x, residual, weight, eps)
📜 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 bddf183 and 71094e3.

📒 Files selected for processing (3)
  • tensorrt_llm/_torch/auto_deploy/config/default.yaml (0 hunks)
  • tensorrt_llm/_torch/auto_deploy/transform/library/collectives.py (3 hunks)
  • tensorrt_llm/_torch/auto_deploy/utils/sharding_utils.py (1 hunks)
💤 Files with no reviewable changes (1)
  • tensorrt_llm/_torch/auto_deploy/config/default.yaml
🧰 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/auto_deploy/utils/sharding_utils.py
  • tensorrt_llm/_torch/auto_deploy/transform/library/collectives.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/auto_deploy/utils/sharding_utils.py
  • tensorrt_llm/_torch/auto_deploy/transform/library/collectives.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/auto_deploy/utils/sharding_utils.py
  • tensorrt_llm/_torch/auto_deploy/transform/library/collectives.py
🧬 Code graph analysis (1)
tensorrt_llm/_torch/auto_deploy/transform/library/collectives.py (2)
tensorrt_llm/_torch/auto_deploy/utils/pattern_matcher.py (2)
  • ADPatternMatcherPass (61-67)
  • register_ad_pattern (99-182)
tensorrt_llm/_torch/auto_deploy/distributed/trtllm.py (1)
  • fused_allreduce_residual_rmsnorm (27-38)
⏰ 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/auto_deploy/utils/sharding_utils.py (1)

169-175: Fallback for torch_dist_all_reduce.default compatibility
Use a module‐scope fallback to avoid AttributeError in builds where the .default overload isn’t exposed, and manually verify its availability in your target environment.

Apply this diff at lines 169–175 of tensorrt_llm/_torch/auto_deploy/utils/sharding_utils.py:

-        1: (torch.ops.auto_deploy.torch_dist_all_reduce.default,),
+        1: (ALL_REDUCE_OP,),

Add near the top of the module:

# Fallback for op overloads that may not expose `.default`
ALL_REDUCE_OP = getattr(
    torch.ops.auto_deploy.torch_dist_all_reduce,
    "default",
    torch.ops.auto_deploy.torch_dist_all_reduce,
)

Request manual verification of the .default attribute in your build (e.g., dir(torch.ops.auto_deploy.torch_dist_all_reduce)) to ensure this change is necessary.

tensorrt_llm/_torch/auto_deploy/transform/library/collectives.py (4)

8-8: Import switch to pattern matcher looks good.


23-28: Docstring clarity is fine.

Return order is explicit; matches replacement’s tuple intent.


49-52: Transform registration retained; good.


83-85: TransformInfo wiring looks fine.

Consider setting has_valid_shapes=True if this transform does not rely on runtime shapes; otherwise leave as-is.

@Fridah-nv Fridah-nv force-pushed the user/fridah/pm-fusearrr branch from 71094e3 to ee93804 Compare September 4, 2025 23:26
@Fridah-nv Fridah-nv changed the title [#5255][autodeploy] Update FuseAllreduceResidualRMSNorm to use pattern matcher utility; remove fuse_collectives [None][autodeploy] Update FuseAllreduceResidualRMSNorm to use pattern matcher utility; remove fuse_collectives; closes #5255 Sep 4, 2025
@Fridah-nv Fridah-nv marked this pull request as ready for review September 4, 2025 23:32
@Fridah-nv Fridah-nv linked an issue Sep 4, 2025 that may be closed by this pull request
@Fridah-nv Fridah-nv force-pushed the user/fridah/pm-fusearrr branch from ee93804 to 33e098f Compare September 16, 2025 23:25
@Fridah-nv Fridah-nv force-pushed the user/fridah/pm-fusearrr branch 2 times, most recently from eebb455 to 701a6e3 Compare September 29, 2025 23:34
@lucaslie lucaslie changed the title [None][autodeploy] Update FuseAllreduceResidualRMSNorm to use pattern matcher utility; remove fuse_collectives; closes #5255 [#5255][autodeploy] Update FuseAllreduceResidualRMSNorm to use pattern matcher utility; remove fuse_collective Oct 3, 2025
@lucaslie lucaslie moved this from Backlog to In review in AutoDeploy Board Oct 3, 2025
Copy link
Member

@lucaslie lucaslie left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

…tcher

Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com>

fix fuse_allreduce_residual_rsmnode test

Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com>
Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com>

rm collective_fusion test

Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com>
Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com>
…rsmnorm failure for DeepSeek small build test

Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com>
Signed-off-by: Fridah-nv <201670829+Fridah-nv@users.noreply.github.com>

minor: update unit test

Signed-off-by: Fridah-nv <201670829+Fridah-nv@users.noreply.github.com>
Signed-off-by: Fridah-nv <201670829+Fridah-nv@users.noreply.github.com>
…agation

Signed-off-by: Fridah-nv <201670829+Fridah-nv@users.noreply.github.com>
Signed-off-by: Fridah-nv <201670829+Fridah-nv@users.noreply.github.com>
Signed-off-by: Fridah-nv <201670829+Fridah-nv@users.noreply.github.com>
@Fridah-nv Fridah-nv force-pushed the user/fridah/pm-fusearrr branch from 0e29fda to bc21976 Compare October 4, 2025 06:23
Signed-off-by: Fridah-nv <201670829+Fridah-nv@users.noreply.github.com>
@Fridah-nv
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20624 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20625 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20624 [ run ] completed with state ABORTED

@tensorrt-cicd
Copy link
Collaborator

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

@Fridah-nv
Copy link
Collaborator Author

/bot run

@Fridah-nv Fridah-nv enabled auto-merge (squash) October 4, 2025 21:56
@tensorrt-cicd
Copy link
Collaborator

PR_Github #20630 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@Fridah-nv
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20638 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@Fridah-nv Fridah-nv merged commit f6654f2 into NVIDIA:main Oct 5, 2025
5 checks passed
@github-project-automation github-project-automation bot moved this from In review to Done in AutoDeploy Board Oct 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Migrate other transformations to use torch._inductor pattern matcher

3 participants