Skip to content

Conversation

xxi-nv
Copy link
Collaborator

@xxi-nv xxi-nv commented Sep 15, 2025

Summary by CodeRabbit

  • New Features
    • Runtime selection of MoE backend (Cutlass or DeepGemm), including FP8 block-scale support on newer GPUs.
    • Lazy initialization of the MoE operator after weights are ready.
    • Unified public API to import MoE operations.
  • Refactor
    • Replaced direct kernel calls with a pluggable MoE op interface; streamlined forward execution with proper dtype/scale handling.
    • Added attribute to preserve the original (unpadded) hidden size.
  • Tests
    • Added a 4-GPU FP8 blockwise WideEPMoE test covering multiple all-to-all methods and varying sequence lengths.

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.

@xxi-nv xxi-nv requested a review from a team as a code owner September 15, 2025 06:55
@xxi-nv xxi-nv requested review from hlu1, kaiyux and litaotju September 15, 2025 06:55
Copy link
Contributor

coderabbitai bot commented Sep 15, 2025

📝 Walkthrough

Walkthrough

Introduces a pluggable MoE operator layer with runtime selection (Cutlass vs DeepGemm), integrates it into WideEPMoE via a lazy moe_op_impl property, and refactors forward_chunk to call moe_op_impl.run_moe. Adds DeepGemm FP8 block-scales implementation, Cutlass-backed path, public ops API exports, and a new multi-GPU FP8 blockwise WideEPMoE unit test.

Changes

Cohort / File(s) Summary
MoE operator abstraction and selection
tensorrt_llm/_torch/modules/fused_moe/ops/moe_op.py
Adds abstract MoEOp with finalize_tactic/compute_moe/run_moe and MoEOpSelector to choose Cutlass or DeepGemm based on SM version and FP8 block-scales flag.
Cutlass MoE op
tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_cutlass.py
Implements CutlassMoEOp with AutoTuner/MoERunner tactic finalization and execution paths (standard and min-latency).
DeepGemm MoE op (FP8 block-scales)
tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_deepgemm.py
Implements DeepGemmMoEOp for GB200 FP8 blockwise; adds workspace management and grouped GEMM flow with routing, masking, gather, and finalize-scale.
Public ops API surface
tensorrt_llm/_torch/modules/fused_moe/ops/__init__.py
New ops package initializer exporting MoEOp, MoEOpSelector, CutlassMoEOp, DeepGemmMoEOp.
WideEPMoE integration
tensorrt_llm/_torch/modules/fused_moe/fused_moe_wide_ep.py
Adds lazy selection property moe_op_impl, unpadded_hidden_size attribute, and refactors forward_chunk to call moe_op_impl.run_moe with adjusted params and dtype/quant scale handling.
Unit tests
tests/unittest/_torch/modules/test_fused_moe.py
Adds multi-GPU FP8 blockwise WideEPMoE test comparing against DeepGemm reference across all-to-all method variants.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant W as WideEPMoE
  participant S as MoEOpSelector
  participant C as CutlassMoEOp
  participant D as DeepGemmMoEOp

  Note over W: forward_chunk
  W->>W: access moe_op_impl
  W->>S: select_op(self)
  alt has_fp8_block_scales && SM==100
    S-->>W: DeepGemmMoEOp instance
    W->>D: run_moe(input, weights, scales, ...)
    D->>D: finalize_tactic (no-op)
    D->>D: compute_moe (permute→GEMM1→act→GEMM2→gather→finalize)
    D-->>W: output
  else
    S-->>W: CutlassMoEOp instance
    W->>C: run_moe(input, weights, scales, ...)
    C->>C: finalize_tactic (tune gemm1/gemm2)
    C->>C: compute_moe (min-latency or standard)
    C-->>W: output
  end
Loading
sequenceDiagram
  autonumber
  participant D as DeepGemmMoEOp
  participant R as Routing/Permute
  participant G1 as Grouped GEMM1
  participant A as Act/Quant
  participant G2 as Grouped GEMM2
  participant G as Gather/Finalize

  D->>R: moe_permute_op(token_selected_slots)
  alt No tokens selected
    R-->>D: empty
    D-->>D: return zeros
  else
    R-->>D: masked structures
    D->>D: _get_deepgemm_workspace(...)
    D->>A: masked_index_copy_group_quant_fp8
    D->>G1: deepgemm_fp8_group_blockwise_gemm (w3_w1)
    G1-->>A: partial output
    A->>G2: apply SiLU-like + quant
    G2-->>D: expert outputs
    D->>G: triton_masked_index_gather → moe_finalize_scale_op
    G-->>D: output tensor
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • litaotju
  • kaiyux
  • QiJune
  • yuxianq

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The PR description is essentially the unfilled repository template with a one-line placeholder and lacks a substantive "Description" of the changes, explicit "Test Coverage" entries, and cherry-pick metadata (original commits/PR link), so it is largely incomplete and does not meet the repository's template requirements. The provided template text does not explain what was changed, why, or which tests exercise the new runtime paths (for example the new multi-GPU FP8 blockwise test referenced in the diff), nor does it note any CI or hardware requirements. Because these required sections are missing, the description check fails. Please replace the placeholder with a concise Description that summarizes what changed and why, list the relevant tests and how to run them (e.g., the added multi-GPU FP8 blockwise WideEPMoE test and any special hardware or GPU-count requirements), include cherry-pick metadata (original PR/commit IDs and link to #7423), and confirm PR checklist items such as CODEOWNERS, documentation, and CI expectations so reviewers can validate the change.
Docstring Coverage ⚠️ Warning Docstring coverage is 68.18% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The title includes the JIRA ticket and correctly identifies the primary change (adding support for FP8 block-wide expert partitions via a cherry-pick from PR #7423), so it is related to the changeset and conveys the main intent. It is slightly noisy and redundant (repeats "cherry-pick" and could be more concise), but it remains clear about the primary change.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
tests/unittest/_torch/modules/test_fused_moe.py (1)

1-6: Add NVIDIA Apache-2.0 header (2025).

Tests are source files too; add the standard 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.
 import pickle
 import sys
 from itertools import product
tensorrt_llm/_torch/modules/fused_moe/fused_moe_wide_ep.py (2)

1-12: Add NVIDIA Apache-2.0 header (2025).

Missing required header 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.
 import os
 from enum import IntEnum
 from typing import Dict, List, Optional, Tuple, Union

686-689: Incorrectly indexing output unconditionally; handle list-or-tensor.

DeepGemm path may return a Tensor (non-list). Always indexing breaks shape.

-        # Only in cutlass_min_latency_mode, the output is a list of tensors.
-        # Otherwise, the output should be unpacked as a single tensor.
-        final_hidden_states = final_hidden_states[0]
+        # Some backends return [tensor] while others return tensor.
+        if isinstance(final_hidden_states, list):
+            final_hidden_states = final_hidden_states[0]
🧹 Nitpick comments (12)
tensorrt_llm/_torch/modules/fused_moe/ops/moe_op.py (2)

110-120: Allow None for token_final_scales in run_moe signature.

Call sites can pass None (e.g., apply_router_weight_on_input path). Make the annotation Optional to match compute_moe.

-            token_selected_slots: torch.Tensor,
-            token_final_scales: torch.Tensor,
+            token_selected_slots: torch.Tensor,
+            token_final_scales: Optional[torch.Tensor],

210-220: Future-proof SM check: prefer >= 100 instead of == 100.

This avoids missing newer Blackwell SM revisions (e.g., 101/102).

-        is_blackwell = get_sm_version() == 100
+        is_blackwell = get_sm_version() >= 100
tensorrt_llm/_torch/modules/fused_moe/ops/__init__.py (1)

7-7: Sort all to satisfy Ruff RUF022.

Keep exports deterministic and linter-clean.

-__all__ = ['MoEOp', 'MoEOpSelector', 'CutlassMoEOp', 'DeepGemmMoEOp']
+__all__ = ['CutlassMoEOp', 'DeepGemmMoEOp', 'MoEOp', 'MoEOpSelector']
tests/unittest/_torch/modules/test_fused_moe.py (1)

661-665: Rename unused param to silence ARG001.

Prefix the per-rank job_id with underscore.

-def per_rank_test_fused_moe_alltoall_fp8_blockwise(job_id):
+def per_rank_test_fused_moe_alltoall_fp8_blockwise(_job_id):
tensorrt_llm/_torch/modules/fused_moe/fused_moe_wide_ep.py (2)

328-332: Future-proof SM check for DeepGemm FP8 block scales.

Use >= 100 to cover future SM100+ revisions.

-                if get_sm_version() == 100:
+                if get_sm_version() >= 100:
                     return DeepSeekFP8BlockScalesFusedMoEMethodDeepGemm()
                 else:
                     return DeepSeekFP8BlockScalesFusedMoEMethod()

417-419: Remove no-op branch.

This pass statement is dead code; drop it.

-        if not use_all_to_all or self.alltoall_method_type != AlltoallMethodType.MNNVL:
-            pass
+        # no-op
tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_cutlass.py (1)

162-173: Tighten exception messages.

Keep messages concise; avoids TRY003 and excess string concat.

-        if self.gemm_tactics is None or len(self.gemm_tactics) == 0:
-            raise RuntimeError(
-                "GEMM tactics have not been finalized. "
-                "Call finalize_tactic() before compute_moe() or use run_moe() instead."
-            )
+        if not self.gemm_tactics:
+            raise RuntimeError("GEMM tactics not finalized; call finalize_tactic() or run_moe().")
@@
-        if self.moe_runner is None:
-            raise RuntimeError(
-                "MoERunner has not been initialized. "
-                "Call finalize_tactic() before compute_moe() or use run_moe() instead."
-            )
+        if self.moe_runner is None:
+            raise RuntimeError("MoERunner not initialized; call finalize_tactic() or run_moe().")
tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_deepgemm.py (5)

61-73: Nit: avoid re-import; use cached self.fp8_utils.

You already cache fp8_utils in init. Prefer that over re-importing.

Apply:

-        import tensorrt_llm.quantization.utils.fp8_utils as fp8_utils
-
         # Get dimensions from module
-        hidden_size = module.hidden_size
-        intermediate_size = module.intermediate_size
+        fp8_utils = self.fp8_utils
+        hidden_size = module.hidden_size
+        intermediate_size = module.intermediate_size

181-182: Respect output_dtype in empty-path early return.

Keep dtype consistent with the configured output.

Apply:

-        if permuted_data_tensor.numel() == 0:
-            return torch.zeros_like(x)
+        if permuted_data_tensor.numel() == 0:
+            return torch.zeros_like(x, dtype=output_dtype)

274-292: Honor output_dtype and wire optional w2_bias into finalize.

  • Cast final output to output_dtype.
  • If w2_bias is provided, pass it to moe_finalize_scale_op to avoid losing bias.

Apply:

-        final_hidden_states = torch.ops.trtllm.moe_finalize_scale_op(
-            permuted_data_tensor,
-            None,  # biases (w2_bias could be added here if needed)
+        final_hidden_states = torch.ops.trtllm.moe_finalize_scale_op(
+            permuted_data_tensor,
+            w2_bias,
             token_final_scales,
             unpermuted_row_to_permuted_row_tensor,
             permuted_row_to_unpermuted_row_tensor,
             token_selected_slots,
             expert_first_token_offset_tensor,
             enable_alltoall,
             x.shape[0],  # num_rows
             x.shape[1],  # hidden_size
             unpadded_hidden_size,  # unpadded_hidden_size (may be different from hidden_size if padding was applied)
             module.routing_method.top_k if module else 1,  # experts_per_token
             expert_size_per_partition,  # num_experts_per_node
             tp_size,
             tp_rank,
             ep_size,
             ep_rank,
         )
+        if final_hidden_states.dtype != output_dtype:
+            final_hidden_states = final_hidden_states.to(output_dtype)

98-121: Multiple unused parameters; either use, prefix with _, or suppress.

Ruff flags: w3_w1_bias, w2_bias (if not wiring), output_dtype (if not casting), swizzled_input_sf, use_fused_finalize, tuner_num_tokens, tuner_top_k, kwargs. Keep signature parity with the base class, but silence lints by prefixing with _ or referencing in docstring/comments, or use them as suggested above.


74-96: Consider caching reusable workspaces by capacity to reduce allocations.

_per-call torch.empty of large buffers is expensive and fragments memory. Cache on self (or module) using a sizing heuristic keyed by (g, m_max, k_max) and reuse across forward passes.

Also applies to: 199-205, 216-218, 230-239, 249-251

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ddfe032 and d85d51e.

📒 Files selected for processing (6)
  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_wide_ep.py (10 hunks)
  • tensorrt_llm/_torch/modules/fused_moe/ops/__init__.py (1 hunks)
  • tensorrt_llm/_torch/modules/fused_moe/ops/moe_op.py (1 hunks)
  • tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_cutlass.py (1 hunks)
  • tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_deepgemm.py (1 hunks)
  • tests/unittest/_torch/modules/test_fused_moe.py (1 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/modules/fused_moe/ops/moe_op_deepgemm.py
  • tensorrt_llm/_torch/modules/fused_moe/ops/moe_op.py
  • tests/unittest/_torch/modules/test_fused_moe.py
  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_wide_ep.py
  • tensorrt_llm/_torch/modules/fused_moe/ops/__init__.py
  • tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_cutlass.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/modules/fused_moe/ops/moe_op_deepgemm.py
  • tensorrt_llm/_torch/modules/fused_moe/ops/moe_op.py
  • tests/unittest/_torch/modules/test_fused_moe.py
  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_wide_ep.py
  • tensorrt_llm/_torch/modules/fused_moe/ops/__init__.py
  • tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_cutlass.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/modules/fused_moe/ops/moe_op_deepgemm.py
  • tensorrt_llm/_torch/modules/fused_moe/ops/moe_op.py
  • tests/unittest/_torch/modules/test_fused_moe.py
  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_wide_ep.py
  • tensorrt_llm/_torch/modules/fused_moe/ops/__init__.py
  • tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_cutlass.py
🧠 Learnings (2)
📚 Learning: 2025-08-14T06:36:40.701Z
Learnt from: timlee0212
PR: NVIDIA/TensorRT-LLM#6886
File: tensorrt_llm/_torch/models/modeling_deepseekv3.py:0-0
Timestamp: 2025-08-14T06:36:40.701Z
Learning: In DeepSeek V3 model (tensorrt_llm/_torch/models/modeling_deepseekv3.py), the disagreement between AllReduce.__init__ guard and _compute_mlp_tp_size logic for MNNVL usage is expected by design. The AllReduce component and MLP TP-size computation intentionally use different criteria for MNNVL availability decisions.

Applied to files:

  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_wide_ep.py
📚 Learning: 2025-08-21T21:48:35.135Z
Learnt from: djns99
PR: NVIDIA/TensorRT-LLM#7104
File: cpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/fusion/sm90_visitor_scatter.hpp:399-417
Timestamp: 2025-08-21T21:48:35.135Z
Learning: CUTLASS extensions in TensorRT-LLM (located under cpp/tensorrt_llm/cutlass_extensions/) are designed to integrate with and extend functionality in the external CUTLASS repository. When analyzing these extensions, their consumers and functionality wiring may exist in the CUTLASS codebase rather than within TensorRT-LLM itself.

Applied to files:

  • tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_cutlass.py
🧬 Code graph analysis (6)
tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_deepgemm.py (4)
tensorrt_llm/_torch/modules/fused_moe/ops/moe_op.py (3)
  • MoEOp (17-174)
  • finalize_tactic (30-51)
  • compute_moe (54-104)
tensorrt_llm/_torch/modules/fused_moe/interface.py (1)
  • MoE (22-181)
tensorrt_llm/_torch/modules/fused_moe/fused_moe_deepgemm.py (5)
  • deepgemm_fp8_group_blockwise_gemm (298-336)
  • masked_index_copy_group_quant_fp8 (88-159)
  • preprocess_after_permute (259-294)
  • set_strides (339-345)
  • triton_masked_index_gather (194-215)
tensorrt_llm/quantization/utils/fp8_utils.py (1)
  • silu_and_mul_masked_post_quant_fwd (304-375)
tensorrt_llm/_torch/modules/fused_moe/ops/moe_op.py (2)
tensorrt_llm/_torch/modules/fused_moe/interface.py (2)
  • MoE (22-181)
  • has_deepseek_fp8_block_scales (127-130)
tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_deepgemm.py (1)
  • finalize_tactic (27-46)
tests/unittest/_torch/modules/test_fused_moe.py (7)
tensorrt_llm/_torch/modules/fused_moe/fused_moe_wide_ep.py (4)
  • AlltoallMethodType (30-38)
  • WideEPMoE (41-1023)
  • load_weights (1018-1023)
  • forward (726-878)
tensorrt_llm/_torch/modules/fused_moe/routing.py (1)
  • DefaultMoeRoutingMethod (184-210)
tensorrt_llm/mapping.py (1)
  • Mapping (32-513)
tensorrt_llm/quantization/utils/fp8_utils.py (1)
  • per_block_cast_to_fp8_e8m0 (54-79)
tests/unittest/_torch/helpers.py (1)
  • per_block_cast_to_fp8_e8m0 (55-68)
tensorrt_llm/models/modeling_utils.py (2)
  • QuantConfig (128-268)
  • quant_algo (547-548)
tensorrt_llm/_torch/modules/fused_moe/fused_moe_deepgemm.py (1)
  • DeepGemmFusedMoE (348-772)
tensorrt_llm/_torch/modules/fused_moe/fused_moe_wide_ep.py (3)
tensorrt_llm/_torch/modules/fused_moe/ops/moe_op.py (4)
  • MoEOp (17-174)
  • MoEOpSelector (177-220)
  • select_op (189-220)
  • run_moe (106-174)
tensorrt_llm/_torch/modules/fused_moe/quantization.py (2)
  • DeepSeekFP8BlockScalesFusedMoEMethod (604-737)
  • DeepSeekFP8BlockScalesFusedMoEMethodDeepGemm (740-781)
tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_cutlass.py (1)
  • run_moe (214-296)
tensorrt_llm/_torch/modules/fused_moe/ops/__init__.py (3)
tensorrt_llm/_torch/modules/fused_moe/ops/moe_op.py (2)
  • MoEOp (17-174)
  • MoEOpSelector (177-220)
tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_cutlass.py (1)
  • CutlassMoEOp (15-296)
tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_deepgemm.py (1)
  • DeepGemmMoEOp (15-296)
tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_cutlass.py (4)
tensorrt_llm/_torch/modules/fused_moe/ops/moe_op.py (4)
  • MoEOp (17-174)
  • finalize_tactic (30-51)
  • compute_moe (54-104)
  • run_moe (106-174)
tensorrt_llm/_torch/modules/fused_moe/interface.py (2)
  • MoE (22-181)
  • has_deepseek_fp8_block_scales (127-130)
tensorrt_llm/_torch/custom_ops/torch_custom_ops.py (1)
  • MoERunner (27-121)
tensorrt_llm/_torch/modules/fused_moe/fused_moe_wide_ep.py (1)
  • enable_alltoall (297-300)
🪛 Ruff (0.12.2)
tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_deepgemm.py

107-107: Unused method argument: w3_w1_bias

(ARG002)


109-109: Unused method argument: w2_bias

(ARG002)


111-111: Unused method argument: output_dtype

(ARG002)


115-115: Unused method argument: swizzled_input_sf

(ARG002)


118-118: Unused method argument: use_fused_finalize

(ARG002)


119-119: Unused method argument: tuner_num_tokens

(ARG002)


120-120: Unused method argument: tuner_top_k

(ARG002)


121-121: Unused method argument: kwargs

(ARG002)

tests/unittest/_torch/modules/test_fused_moe.py

661-661: Unused function argument: job_id

(ARG001)

tensorrt_llm/_torch/modules/fused_moe/ops/__init__.py

7-7: __all__ is not sorted

Apply an isort-style sorting to __all__

(RUF022)

tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_cutlass.py

130-130: Unused method argument: output_dtype

(ARG002)


137-137: Unused method argument: use_fused_finalize

(ARG002)


138-138: Unused method argument: tuner_num_tokens

(ARG002)


139-139: Unused method argument: tuner_top_k

(ARG002)


140-140: Unused method argument: kwargs

(ARG002)


164-167: Avoid specifying long messages outside the exception class

(TRY003)


170-173: Avoid specifying long messages outside the exception class

(TRY003)

⏰ 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 (6)
tensorrt_llm/_torch/modules/fused_moe/fused_moe_wide_ep.py (3)

96-98: LGTM: track unpadded_hidden_size.

Storing the original hidden size simplifies downstream op calls.


354-366: LGTM: lazy MoE op selection.

Property-based, cached instantiation avoids early imports and respects quant/hw.


664-681: LGTM: delegate to moe_op_impl with correct args.

Runtime selection + unified call is clean.

tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_deepgemm.py (3)

215-227: Validate quant_scales length to avoid IndexError/invalid kernel inputs.

Guard that quant_scales has both scales needed for (w3_w1, w2).

Apply:

         # Quantization parameters
         quant_scales: List[torch.Tensor],
@@
         """
         Compute MoE using DeepGemm op with block FP8 quantization.
@@
+        if quant_scales is None or len(quant_scales) < 2:
+            raise ValueError("quant_scales must provide at least [w3_w1_sfb, w2_sfb].")

If there is a non-quantized path where sfb is optional, confirm the DeepGemm wrapper supports None for sfb; otherwise this check is required.

Also applies to: 252-260


129-178: Check: moe_permute_op weight/scale args passed as None.

If DeepGemm path never needs permute-time weight/scale swizzling, this is fine. Otherwise, confirm parity with Cutlass path to avoid performance regressions.


190-196: Keep m_max aligned to 128 — this is valid.

fused_moe_deepgemm.py defines DEFAULT_BLOCK_SIZE_M = 256 but selects BLOCK_SIZE_M dynamically (uses DEFAULT when grid_m_size >= num_experts, otherwise BLOCK_SIZE_M = next_power_of_2(cdiv(total_tokens, num_experts))), so kernels can run with 128. moe_op_deepgemm also requests workspace with block=128 and then pads to 4 (TMA/tests require m % 4 == 0). No change required.

@xxi-nv xxi-nv force-pushed the supportFP8BlockWideEp_cherry-pick branch from d85d51e to 578b73b Compare September 16, 2025 01:16
@xxi-nv
Copy link
Collaborator Author

xxi-nv commented Sep 16, 2025

/blot run

@ziyixiong-nv
Copy link
Collaborator

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18689 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@xxi-nv
Copy link
Collaborator Author

xxi-nv commented Sep 16, 2025

/bot run

@kaiyux
Copy link
Member

kaiyux commented Sep 17, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18955 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@nv-guomingz nv-guomingz added the Cherry-pick It's a label that applies to Cherry-pick PR. label Sep 17, 2025
Signed-off-by: xxi <[email protected]>

	modified:   tensorrt_llm/_torch/modules/fused_moe/fused_moe_wide_ep.py
	new file:   tensorrt_llm/_torch/modules/fused_moe/moe_backend.py
	modified:   tests/unittest/_torch/modules/test_fused_moe.py

	modified:   tensorrt_llm/_torch/modules/fused_moe/fused_moe_wide_ep.py
	new file:   tensorrt_llm/_torch/modules/fused_moe/moe_backend.py
	modified:   tests/unittest/_torch/modules/test_fused_moe.py
Signed-off-by: xxi <[email protected]>

	modified:   tensorrt_llm/_torch/modules/fused_moe/fused_moe_wide_ep.py
	deleted:    tensorrt_llm/_torch/modules/fused_moe/moe_backend.py
	new file:   tensorrt_llm/_torch/modules/fused_moe/ops/__init__.py
	new file:   tensorrt_llm/_torch/modules/fused_moe/ops/moe_op.py
	new file:   tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_cutlass.py
	new file:   tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_deepgemm.py

	modified:   docs/source/deployment-guide/quick-start-recipe-for-deepseek-r1-on-trtllm.md
	modified:   tensorrt_llm/_torch/modules/fused_moe/fused_moe_wide_ep.py
	deleted:    tensorrt_llm/_torch/modules/fused_moe/moe_backend.py
	new file:   tensorrt_llm/_torch/modules/fused_moe/ops/__init__.py
	new file:   tensorrt_llm/_torch/modules/fused_moe/ops/moe_op.py
	new file:   tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_cutlass.py
	new file:   tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_deepgemm.py
@xxi-nv xxi-nv force-pushed the supportFP8BlockWideEp_cherry-pick branch from 578b73b to 94a52a3 Compare September 18, 2025 02:43
@xxi-nv xxi-nv requested a review from a team as a code owner September 18, 2025 02:43
@xxi-nv xxi-nv requested review from QiJune and chzblych September 18, 2025 02:43
@xxi-nv
Copy link
Collaborator Author

xxi-nv commented Sep 18, 2025

/bot run

2 similar comments
@ziyixiong-nv
Copy link
Collaborator

/bot run

@xxi-nv
Copy link
Collaborator Author

xxi-nv commented Sep 19, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19231 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@xxi-nv
Copy link
Collaborator Author

xxi-nv commented Sep 21, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19452 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@xxi-nv
Copy link
Collaborator Author

xxi-nv commented Sep 22, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19560 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@ziyixiong-nv ziyixiong-nv merged commit d471655 into NVIDIA:main Sep 23, 2025
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Cherry-pick It's a label that applies to Cherry-pick PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants