KEMBAR78
[https://nvbugs/5392414] [fix] For release 1.0 cherry pick. Add customized default routing method by ChristinaZ · Pull Request #7068 · NVIDIA/TensorRT-LLM · GitHub
Skip to content

Conversation

@ChristinaZ
Copy link
Collaborator

@ChristinaZ ChristinaZ commented Aug 20, 2025

Summary by CodeRabbit

  • New Features
    • Added a default MoE routing operator available via torch.ops.trtllm.default_moe_routing_op returning (indices, values).
    • DefaultMoeRoutingMethod now accepts force_enable_pytorch_op to switch to a pure PyTorch path.
  • Performance
    • Introduced a new CUDA MoE routing kernel with optional pre-softmax top‑k, improving latency for small expert counts (<=128) and small top‑k (<=8).
    • Top‑k selection gains a fast path in the runtime, with automatic fallback to the PyTorch implementation for larger sizes.
  • Chores
    • Build system updated to use the new routing implementation.

Description

This is the same commit of PR #6818.
Just cherry pick it to the release 1.0.

Test Coverage

GitHub Bot Help

/bot [-h] ['run', 'kill', 'skip', 'reuse-pipeline'] ...

Provide a user friendly way for developers to interact with a Jenkins server.

Run /bot [-h|--help] to print this help message.

See details below for each supported subcommand.

run [--reuse-test (optional)pipeline-id --disable-fail-fast --skip-test --stage-list "A10-PyTorch-1, xxx" --gpu-type "A30, H100_PCIe" --test-backend "pytorch, cpp" --add-multi-gpu-test --only-multi-gpu-test --disable-multi-gpu-test --post-merge --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" --detailed-log --debug(experimental)]

Launch build/test pipelines. All previously running jobs will be killed.

--reuse-test (optional)pipeline-id (OPTIONAL) : Allow the new pipeline to reuse build artifacts and skip successful test stages from a specified pipeline or the last pipeline if no pipeline-id is indicated. If the Git commit ID has changed, this option will be always ignored. The DEFAULT behavior of the bot is to reuse build artifacts and successful test results from the last pipeline.

--disable-reuse-test (OPTIONAL) : Explicitly prevent the pipeline from reusing build artifacts and skipping successful test stages from a previous pipeline. Ensure that all builds and tests are run regardless of previous successes.

--disable-fail-fast (OPTIONAL) : Disable fail fast on build/tests/infra failures.

--skip-test (OPTIONAL) : Skip all test stages, but still run build stages, package stages and sanity check stages. Note: Does NOT update GitHub check status.

--stage-list "A10-PyTorch-1, xxx" (OPTIONAL) : Only run the specified test stages. Examples: "A10-PyTorch-1, xxx". Note: Does NOT update GitHub check status.

--gpu-type "A30, H100_PCIe" (OPTIONAL) : Only run the test stages on the specified GPU types. Examples: "A30, H100_PCIe". Note: Does NOT update GitHub check status.

--test-backend "pytorch, cpp" (OPTIONAL) : Skip test stages which don't match the specified backends. Only support [pytorch, cpp, tensorrt, triton]. Examples: "pytorch, cpp" (does not run test stages with tensorrt or triton backend). Note: Does NOT update GitHub pipeline status.

--only-multi-gpu-test (OPTIONAL) : Only run the multi-GPU tests. Note: Does NOT update GitHub check status.

--disable-multi-gpu-test (OPTIONAL) : Disable the multi-GPU tests. Note: Does NOT update GitHub check status.

--add-multi-gpu-test (OPTIONAL) : Force run the multi-GPU tests in addition to running L0 pre-merge pipeline.

--post-merge (OPTIONAL) : Run the L0 post-merge pipeline instead of the ordinary L0 pre-merge pipeline.

--extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" (OPTIONAL) : Run the ordinary L0 pre-merge pipeline and specified test stages. Examples: --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx".

--detailed-log (OPTIONAL) : Enable flushing out all logs to the Jenkins console. This will significantly increase the log volume and may slow down the job.

--debug (OPTIONAL) : Experimental feature. Enable access to the CI container for debugging purpose. Note: Specify exactly one stage in 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.

…topk for trt backend

Signed-off-by: Christina Zhang <83400082+ChristinaZ@users.noreply.github.com>
@ChristinaZ ChristinaZ requested a review from byshiue August 20, 2025 03:01
@ChristinaZ ChristinaZ requested a review from a team as a code owner August 20, 2025 03:01
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 20, 2025

📝 Walkthrough

Walkthrough

Introduces a new custom MoE routing kernel and utilities, removes the legacy implementation, integrates a fast-path TopK for small sizes, adjusts SM90 programmatic-launch gating, switches Torch op wiring to the new kernel, adds a new default routing Torch operator, and updates Python routing to choose between custom op and PyTorch path.

Changes

Cohort / File(s) Summary
New custom MoE routing + utilities
cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu, cpp/tensorrt_llm/kernels/customMoeRoutingKernels.h, cpp/tensorrt_llm/kernels/moeTopKFuncs.cuh
Adds templated MoE routing CUDA kernel with optional pre-topk softmax, warp-level top-k reduction utilities, runtime launcher with variant dispatch, and new header exposing DoSoftmaxBeforeTopK template.
Remove legacy MoE routing
cpp/tensorrt_llm/kernels/renormMoeRoutingKernels.cu
Deletes previous MoE routing kernel, top-k helpers, launcher, and explicit instantiations.
TopK kernel fast path and API adjustments
cpp/tensorrt_llm/kernels/topkLastDim.cu
Adds small-size MoE top-k kernel path (len≤128, k≤8), introduces nextPowerOfTwo, switches to Thrust iterators, standardizes IdxT, updates standalone_stable_radix_11bits signature, and dispatches to the new fast path when applicable.
PDL gating updated to SM90
cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingKernel.cuh, cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingLlama4.cu
Replaces PDL_PROFILE-based guards with CUDA_ARCH >= 900 for programmatic launch trigger sections; no API changes.
Torch op switch and new default op
cpp/tensorrt_llm/thop/CMakeLists.txt, cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp
Replaces renorm op TU with customMoeRoutingOp.cpp, routes to new kernel header, adds DoSoftmaxBeforeTopK templating, keeps renorm_moe_routing_op wrapper, and introduces default_moe_routing_op with Torch registration.
Python integration and routing selection
tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py, tensorrt_llm/_torch/modules/fused_moe/routing.py
Registers fake op for trtllm::default_moe_routing_op; updates DefaultMoeRoutingMethod to optionally force PyTorch path or select PyTorch when experts>128 or top_k>8; otherwise invokes custom op; adds apply_pytorch method.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant Routing as DefaultMoeRoutingMethod
  participant TorchOp as torch.ops.trtllm.default_moe_routing_op
  participant CppOp as customMoeRoutingOp.cpp
  participant KernLaunch as invokeRenormMoeRouting<..., DoSoftmaxBeforeTopK>
  participant CUDA as customMoeRoutingKernel<<<>>>()

  User->>Routing: apply(router_logits)
  alt force_enable_pytorch_op or experts>128 or top_k>8
    Routing->>Routing: apply_pytorch()\nsoftmax + torch.topk
    Routing-->>User: (topk_indices, topk_values)
  else small-size path
    Routing->>TorchOp: default_moe_routing_op(router_logits, top_k)
    TorchOp->>CppOp: dispatch by dtype
    CppOp->>KernLaunch: select variant (experts, top_k)\nDoSoftmaxBeforeTopK=true
    KernLaunch->>CUDA: launch kernel
    CUDA-->>KernLaunch: write outputs
    KernLaunch-->>CppOp: (indices, values)
    CppOp-->>TorchOp: (indices, values)
    TorchOp-->>Routing: (indices, values)
    Routing-->>User: (topk_indices, topk_values)
  end
  note over KernLaunch,CUDA: Runtime selects MaxNumExperts/TopK specializations via nextPowerOfTwo.
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Suggested labels

SW Architecture

Suggested reviewers

  • byshiue
  • MatthiasKohl
  • rosenrodt
  • nv-guomingz
  • pcastonguay
  • yizhang-nv

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ 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 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.

@byshiue
Copy link
Collaborator

byshiue commented Aug 20, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15858 [ run ] triggered by Bot

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

Caution

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

⚠️ Outside diff range comments (3)
cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingKernel.cuh (1)

247-250: Fix incorrect stride-alignment check for local experts (mask uses log2 value, not (1<<log2)-1).

Current code uses (localExpertIdx & params.mLocalExpertsStrideLog2) == 0, which is only correct when mLocalExpertsStrideLog2 == 0 or 1. For mLocalExpertsStrideLog2 > 1, it misclassifies indices like 5 with stride 4 (log2=2), since 5 & 2 == 0 even though 5 is not multiple of 4. This can route tokens to non-local experts and corrupt local histograms/offsets.

Replace the bit test with a proper mask (1 << log2) - 1.

Apply the following changes:

@@
-        auto isLocalExpert = localExpertIdx >= 0 && localExpertIdx < localExpertExtent
-            && (localExpertIdx & params.mLocalExpertsStrideLog2) == 0;
+        int32_t const strideMask = (1 << params.mLocalExpertsStrideLog2) - 1;
+        bool const isLocalExpert = localExpertIdx >= 0 && localExpertIdx < localExpertExtent
+            && ((localExpertIdx & strideMask) == 0);
@@
-        auto isLocalExpert = localExpertIdx >= 0 && localExpertIdx < localExpertExtent
-            && (localExpertIdx & params.mLocalExpertsStrideLog2) == 0;
+        int32_t const strideMask = (1 << params.mLocalExpertsStrideLog2) - 1;
+        bool const isLocalExpert = localExpertIdx >= 0 && localExpertIdx < localExpertExtent
+            && ((localExpertIdx & strideMask) == 0);
@@
-        auto isLocalExpert = localExpertIdx >= 0 && localExpertIdx < localExpertExtent
-            && (localExpertIdx & params.mLocalExpertsStrideLog2) == 0;
+        int32_t const strideMask = (1 << params.mLocalExpertsStrideLog2) - 1;
+        bool const isLocalExpert = localExpertIdx >= 0 && localExpertIdx < localExpertExtent
+            && ((localExpertIdx & strideMask) == 0);
@@
-            auto isLocalExpert = localExpertIdx >= 0 && localExpertIdx < localExpertExtent
-                && (localExpertIdx & params.mLocalExpertsStrideLog2) == 0;
+            int32_t const strideMask = (1 << params.mLocalExpertsStrideLog2) - 1;
+            bool const isLocalExpert = localExpertIdx >= 0 && localExpertIdx < localExpertExtent
+                && ((localExpertIdx & strideMask) == 0);
@@
-            auto isLocalExpert = localExpertIdx >= 0 && localExpertIdx < localExpertExtent
-                && (localExpertIdx & params.mLocalExpertsStrideLog2) == 0;
+            int32_t const strideMask = (1 << params.mLocalExpertsStrideLog2) - 1;
+            bool const isLocalExpert = localExpertIdx >= 0 && localExpertIdx < localExpertExtent
+                && ((localExpertIdx & strideMask) == 0);

Optional follow-up (to avoid duplication across kernels): introduce a tiny helper and use it at call sites:

// Place near other helpers in this file
__host__ __device__ inline bool isLocalExpertIdx(
    int32_t globalExpertIdx, int32_t localExpertsStartIdx, int32_t localExpertsStrideLog2, int32_t localExpertExtent)
{
    int32_t const localExpertIdx = globalExpertIdx - localExpertsStartIdx;
    int32_t const strideMask = (1 << localExpertsStrideLog2) - 1;
    return (localExpertIdx >= 0) && (localExpertIdx < localExpertExtent) && ((localExpertIdx & strideMask) == 0);
}

Then use:
bool const isLocalExpert = isLocalExpertIdx(scoreIdx.idx, params.mLocalExpertsStartIdx, params.mLocalExpertsStrideLog2, localExpertExtent);

Also applies to: 402-405, 464-467, 631-634, 719-723

cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp (2)

39-41: Bug: outputs allocated on “current” CUDA device instead of router_logits.device().

Allocating with device(torch::kCUDA) can place outputs on a different GPU than router_logits in multi-GPU setups, leading to device mismatch or invalid stream launches. Allocate on router_logits.device().

Apply this fix:

-    th::Tensor topk_values = th::empty({num_tokens, topk}, th::dtype(torch::kFloat32).device(torch::kCUDA));
-    th::Tensor topk_indices = th::empty({num_tokens, topk}, th::dtype(torch::kInt32).device(torch::kCUDA));
+    auto out_device = router_logits.device();
+    th::Tensor topk_values = th::empty({num_tokens, topk}, th::dtype(torch::kFloat32).device(out_device));
+    th::Tensor topk_indices = th::empty({num_tokens, topk}, th::dtype(torch::kInt32).device(out_device));

42-43: Guard the current device before stream use and allocations.

Without a device guard, launching on a stream for router_logits’ device while the current device differs can cause runtime errors. Guarding also makes allocations deterministic if any future code uses current device defaults.

Apply this change:

-    auto stream = at::cuda::getCurrentCUDAStream(router_logits.get_device());
+    at::cuda::CUDAGuard device_guard{router_logits.device()};
+    auto stream = at::cuda::getCurrentCUDAStream(router_logits.get_device());
♻️ Duplicate comments (1)
cpp/tensorrt_llm/kernels/topkLastDim.cu (1)

1535-1552: Duplicate implementation of nextPowerOfTwo.

This function is duplicated from customMoeRoutingKernels.cu. As mentioned in the review of that file, consider moving this to a common utility header.

🧹 Nitpick comments (12)
tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py (1)

535-541: Additive fake op looks correct; consider deduplicating with renorm’s fake.

The new fake returns the right shapes/dtypes and mirrors the renorm variant. Minor: you can DRY the two fakes to a shared helper to avoid divergence.

Apply this refactor to reduce duplication:

@@
-    @torch.library.register_fake("trtllm::renorm_moe_routing_op")
-    def _(router_logits, topk):
-        num_tokens = router_logits.shape[0]
-        sz = (num_tokens, topk)
-        return router_logits.new_empty(
-            sz, dtype=torch.int32), router_logits.new_empty(sz,
-                                                            dtype=torch.float32)
+    def _fake_moe_routing(router_logits, topk):
+        num_tokens = router_logits.shape[0]
+        sz = (num_tokens, topk)
+        return router_logits.new_empty(sz, dtype=torch.int32), router_logits.new_empty(sz, dtype=torch.float32)
+
+    @torch.library.register_fake("trtllm::renorm_moe_routing_op")
+    def _(router_logits, topk):
+        return _fake_moe_routing(router_logits, topk)
@@
-    @torch.library.register_fake("trtllm::default_moe_routing_op")
-    def _(router_logits, topk):
-        num_tokens = router_logits.shape[0]
-        sz = (num_tokens, topk)
-        return router_logits.new_empty(
-            sz, dtype=torch.int32), router_logits.new_empty(sz,
-                                                            dtype=torch.float32)
+    @torch.library.register_fake("trtllm::default_moe_routing_op")
+    def _(router_logits, topk):
+        return _fake_moe_routing(router_logits, topk)
cpp/tensorrt_llm/kernels/customMoeRoutingKernels.h (2)

2-2: Copyright header year.

Using 2025 is acceptable for new headers; ensure consistency across the newly added/updated kernel files in this PR.


26-29: Prefer const-correct input pointer in the launcher API.

The API takes InputT* for routerLogits, but the op treats router logits as read-only. Making it InputT const* clarifies intent and avoids forcing callers to request mutable pointers.

Proposed signature change:

-template <typename InputT, typename OutputT, typename IdxT, bool DoSoftmaxBeforeTopK>
-void invokeRenormMoeRouting(InputT* routerLogits, OutputT* topkValues, IdxT* topkIndices, int64_t const numTokens,
+template <typename InputT, typename OutputT, typename IdxT, bool DoSoftmaxBeforeTopK>
+void invokeRenormMoeRouting(InputT const* routerLogits, OutputT* topkValues, IdxT* topkIndices, int64_t const numTokens,
     int64_t const numExperts, int64_t const topK, cudaStream_t const stream);

If you take this, adjust the .cu implementation and the call sites to use data_ptr() instead of mutable_data_ptr().

tensorrt_llm/_torch/modules/fused_moe/routing.py (1)

67-75: Centralize dispatch thresholds for CUDA kernels
To keep Python logic in sync with the C++ TORCH_CHECK limits (num_experts ≤ 128, top_k ≤ 8), introduce module‐level constants—e.g.:

# tensorrt_llm/_torch/modules/fused_moe/routing.py
MAX_EXPERTS_FOR_CUDA = 128
MAX_TOPK_FOR_CUDA     = 8

Then update both apply implementations to use these constants:

  • DefaultMoeRoutingMethod.apply (currently lines 67–75)
  • RenormalizeMoeRoutingMethod.apply (currently lines 117–125)

Also add a comment linking back to the checks in customMoeRoutingOp.cpp, for example:

// Enforced in customMoeRoutingOp.cpp: TORCH_CHECK(topk <= 8 && num_experts <= 128)

Optional: extend existing unit tests to cover cases where num_experts > MAX_EXPERTS_FOR_CUDA and top_k > MAX_TOPK_FOR_CUDA, ensuring both the PyTorch fallback and the CUDA path are exercised.

cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp (1)

48-66: Const-correctness and pointer access.

Inputs are read-only; prefer passing const pointers to the kernel and using data_ptr() over mutable_data_ptr(). This also avoids implying in-place modification of router_logits.

If you adopt the header change to take InputT const*, update calls like:

-        tk::invokeRenormMoeRouting<float, float, int32_t, DoSoftmaxBeforeTopK>(
-            reinterpret_cast<float*>(router_logits.mutable_data_ptr()),
+        tk::invokeRenormMoeRouting<float, float, int32_t, DoSoftmaxBeforeTopK>(
+            router_logits.data_ptr<float>(),
             reinterpret_cast<float*>(topk_values.mutable_data_ptr()),
             reinterpret_cast<int32_t*>(topk_indices.mutable_data_ptr()), num_tokens, num_experts, topk, stream);

Repeat similarly for bfloat16 and half.

cpp/tensorrt_llm/kernels/moeTopKFuncs.cuh (2)

115-121: Consider providing a more descriptive macro name.

The macro TOPK_SWAP is very generic and could potentially conflict with other macros in the codebase. Consider using a more specific name that indicates its purpose within the topk reduction context.

Apply this diff to use a more descriptive name:

-#define TOPK_SWAP(I, J)                                                                                                \
+#define TOPK_REDUCTION_SWAP(I, J)                                                                                      \
     {                                                                                                                  \
         auto pairMin = min(topK[I].compValIdx, topK[J].compValIdx);                                                    \
         auto pairMax = max(topK[I].compValIdx, topK[J].compValIdx);                                                    \
         topK[I].compValIdx = pairMax;                                                                                  \
         topK[J].compValIdx = pairMin;                                                                                  \
     }

And update all usages accordingly:

-        TOPK_SWAP(0, 1);
+        TOPK_REDUCTION_SWAP(0, 1);

193-194: Complex ternary operator could benefit from clarification.

The ternary expression on Line 193 is correct but complex. Consider adding a comment to explain the logic: when updating (update == true) and we're at the last element (nn == N - 1), we replace it with minValue to prepare for the next iteration.

Add a clarifying comment:

 #pragma unroll
         for (int nn = 0; nn < N; ++nn)
         {
+            // When updating: shift all elements left by one, and fill the last position with minValue
             topK[nn] = update && nn == N - 1 ? RedType{minValue, idx[nn]} : update ? topK[nn + 1] : topK[nn];
         }
cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu (3)

44-47: Redundant conditional check in calcSoftmax.

The condition score >= maxScore on Line 47 is redundant since maxScore is initialized to -INFINITY, making the condition always true for any valid score.

Simplify the code:

     T maxScore = T{-INFINITY};
     if (laneIdx < NumTopExperts)
     {
-        maxScore = score >= maxScore ? score : maxScore;
+        maxScore = score;
     }

231-232: Improve error message for kernel selection failure.

The error message "Can not find corresponding kernel instance" doesn't provide enough context about what configuration failed.

Provide more informative error message:

-        TLLM_CHECK_WITH_INFO(kernelInstance != nullptr, "Can not find corresponding kernel instance.");
+        TLLM_CHECK_WITH_INFO(kernelInstance != nullptr, 
+            "Cannot find kernel instance for maxNumExperts=" + std::to_string(maxNumExperts) + 
+            ", maxNumTopExperts=" + std::to_string(maxNumTopExperts));

168-185: Consolidate nextPowerOfTwo in common math utilities

The nextPowerOfTwo helper is currently defined in multiple places (and risks bit-level inconsistency):

  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu (lines 168–185)
  • cpp/tensorrt_llm/kernels/topkLastDim.cu (around line 1535)
  • cpp/tensorrt_llm/thop/thUtils.h / thUtils.cpp
  • cpp/tensorrt_llm/plugins/common/gemmPluginProfiler.h

To DRY-up the code, please:

  • Add an inline __host__ __device__
    int nextPowerOfTwo(int) implementation to
    cpp/tensorrt_llm/common/mathUtils.h
    (in namespace tensorrt_llm::common).
  • Replace the local definitions in each .cu/.h file with
    #include "cpp/tensorrt_llm/common/mathUtils.h"
    and call the shared utility.
  • Remove the duplicated implementations from those modules.

This will centralize the logic and prevent divergence.

cpp/tensorrt_llm/kernels/topkLastDim.cu (2)

1564-1565: Consider extracting the max length calculation.

The pattern nextPowerOfTwo(len) < 32 ? 32 : nextPowerOfTwo(len) ensures a minimum of 32, but it calls nextPowerOfTwo twice. Consider computing it once.

-    uint32_t max_len = nextPowerOfTwo(len) < 32 ? 32 : nextPowerOfTwo(len);
+    uint32_t power_of_two_len = nextPowerOfTwo(len);
+    uint32_t max_len = power_of_two_len < 32 ? 32 : power_of_two_len;

1569-1612: Consider using a lookup table for kernel selection.

The nested switch statements for kernel selection could be simplified using a lookup table or a more compact approach.

Consider refactoring to use a template-based approach or lookup table to reduce code duplication:

+template<int MaxLen, int MaxTopK>
+struct KernelSelector {
+    static constexpr auto value = &moe_topk::moe_topk_kernel<InputT, OutputT, IdxT, MaxLen, MaxTopK>;
+};
+
+template<typename InputT, typename OutputT, typename IdxT>
+auto selectKernel(uint32_t max_len, uint32_t moe_topk) {
+    // Use a 2D lookup table or similar structure
+    // This is a sketch - actual implementation would need proper template metaprogramming
+}
📜 Review details

Configuration used: .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 fae43e7 and 59d1a58.

📒 Files selected for processing (11)
  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu (1 hunks)
  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.h (2 hunks)
  • cpp/tensorrt_llm/kernels/moeTopKFuncs.cuh (1 hunks)
  • cpp/tensorrt_llm/kernels/renormMoeRoutingKernels.cu (0 hunks)
  • cpp/tensorrt_llm/kernels/topkLastDim.cu (13 hunks)
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingKernel.cuh (2 hunks)
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingLlama4.cu (0 hunks)
  • cpp/tensorrt_llm/thop/CMakeLists.txt (1 hunks)
  • cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp (5 hunks)
  • tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py (1 hunks)
  • tensorrt_llm/_torch/modules/fused_moe/routing.py (1 hunks)
💤 Files with no reviewable changes (2)
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingLlama4.cu
  • cpp/tensorrt_llm/kernels/renormMoeRoutingKernels.cu
🧰 Additional context used
📓 Path-based instructions (6)
**/*.py

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+
Python indentation: 4 spaces, no tabs
Maintain module namespace in imports (from package.subpackage import foo; then use foo.SomeClass())
Python file names use snake_case
Python class names use PascalCase
Python functions/methods and local variables use snake_case; variables starting with a number get k_ prefix (e.g., k_99th_percentile)
Global variables use G_ prefixed UPPER_SNAKE_CASE (e.g., G_MY_GLOBAL)
Constants use UPPER_SNAKE_CASE in Python
Avoid shadowing variables from outer scopes in Python
Initialize all externally visible members of a Python class in init
Prefer docstrings for interfaces used outside a file; comments for local code
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes/variables inline with short docstrings
Avoid reflection when simple alternatives exist (e.g., prefer explicit parameters over dict(**locals()))
In try/except, catch the narrowest exceptions possible
For duck-typing with try/except, keep try body minimal and put logic in else

Files:

  • tensorrt_llm/_torch/modules/fused_moe/routing.py
  • tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,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/routing.py
  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.h
  • tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingKernel.cuh
  • cpp/tensorrt_llm/kernels/moeTopKFuncs.cuh
  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu
  • cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp
  • cpp/tensorrt_llm/kernels/topkLastDim.cu
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}: In C++, close namespaces with a comment naming the namespace (e.g., } // namespace foo)
Prefer const/constexpr variables over #define for constants
Declare variables const if not modified after initialization
Use Allman brace style in C++
C++ filenames use lowerCamelCase and must be case-insensitively unique within a build target
C++ type names use UpperCamelCase
Local variables, methods, and namespaces use lowerCamelCase
Global non-static variables not in anonymous namespace use gPrefix lowerCamelCase (e.g., gExample)
Static globals or globals in anonymous namespaces use sPrefix lowerCamelCase
Locally visible static variables start with 's' (e.g., static std::once_flag sFlag;)
Member variables use mPrefix lowerCamelCase; public members may omit but are encouraged to use 'm'
Constants (enums, global/static/function-scope magic numbers) use kPREFIXED_UPPER_SNAKE (e.g., kDIGIT_NUM)
If macros are unavoidable, use UPPER_SNAKE_CASE (prefer constants over #define)
Constructor parameter that conflicts with a public member name gets trailing underscore (foo_)
Literal suffixes should be uppercase (e.g., 1234L not 1234l)
C++: use spaces only; indent 4 spaces
Run clang-format (LLVM style) before submitting; wrap lines at 120 characters
If formatting must be bypassed, use // clang-format off/on around the section
Prefer smart pointers; use unique_ptr for sole ownership, shared_ptr for shared; weak_ptr only in exceptional cases
Do not use deprecated pre-C++11 smart pointers
Use C++ style comments; avoid C comments except special inline cases; prefer // single-line
Capitalize and punctuate full-sentence comments
Follow Doxygen rules: use //! for comments and //!< for members in C++
Disable code with #if/#endif and mnemonic conditions; avoid commented-out code; avoid dead code
Do not throw exceptions across library boundaries
Use least-forceful casts; avoid removing const/volatile; avoid C-style and functional casts (except constructors); p...

Files:

  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.h
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingKernel.cuh
  • cpp/tensorrt_llm/kernels/moeTopKFuncs.cuh
  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu
  • cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp
  • cpp/tensorrt_llm/kernels/topkLastDim.cu
**/*.{h,hpp,hxx,hh,cuh,cpp,cxx,cc,cu}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Parameter names must be consistent between declarations and definitions

Files:

  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.h
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingKernel.cuh
  • cpp/tensorrt_llm/kernels/moeTopKFuncs.cuh
  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu
  • cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp
  • cpp/tensorrt_llm/kernels/topkLastDim.cu
**/*.{h,hpp,hxx,hh,cuh}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Header files must use include guards named TRTLLM__H without underscores prefix/suffix (e.g., TRTLLM_FOO_BAR_HELLO_H)

Files:

  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.h
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingKernel.cuh
  • cpp/tensorrt_llm/kernels/moeTopKFuncs.cuh
**/*.{cpp,cxx,cc,cu}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu}: Avoid literal values except for 0, nullptr, true, false; use named constexpr for other literals
Place semicolon of empty for/while loop on a new line
Always use brace-delimited bodies for switch/while/do-for/if/else
Use inline C comments in argument lists when parameter meaning is unclear (e.g., /* checkForErrors = */ false)
Do not use assignment in subexpressions (e.g., if (x = y) ... is forbidden)
Switch on enums should enumerate all values and omit default to catch new values at compile time
Structure switch statements; prohibit fallthrough except between empty cases; each case ends with break or throw; return at end of case not allowed; put break inside braces for compound case
Prefer anonymous namespaces over static for internal linkage of functions
Every defined function must be called at least once (no unused methods)

Files:

  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu
  • cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp
  • cpp/tensorrt_llm/kernels/topkLastDim.cu
🧠 Learnings (3)
📓 Common learnings
Learnt from: sklevtsov-nvidia
PR: NVIDIA/TensorRT-LLM#3294
File: cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cu:1198-1209
Timestamp: 2025-08-08T22:03:40.707Z
Learning: In the CUTLASS MoE kernels (cpp/tensorrt_llm/cutlass_extensions), when `layout_info.fusion` is set to `TmaWarpSpecializedGroupedGemmInput::EpilogueFusion::FINALIZE`, the `router_scales` parameter must be non-null by design. The fused finalize kernel epilogue does not perform nullptr checks and requires valid router scales to function correctly. This is an implicit contract that callers must satisfy when enabling the FINALIZE fusion mode.
📚 Learning: 2025-08-08T22:03:40.707Z
Learnt from: sklevtsov-nvidia
PR: NVIDIA/TensorRT-LLM#3294
File: cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cu:1198-1209
Timestamp: 2025-08-08T22:03:40.707Z
Learning: In the CUTLASS MoE kernels (cpp/tensorrt_llm/cutlass_extensions), when `layout_info.fusion` is set to `TmaWarpSpecializedGroupedGemmInput::EpilogueFusion::FINALIZE`, the `router_scales` parameter must be non-null by design. The fused finalize kernel epilogue does not perform nullptr checks and requires valid router scales to function correctly. This is an implicit contract that callers must satisfy when enabling the FINALIZE fusion mode.

Applied to files:

  • cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingKernel.cuh
  • cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp
📚 Learning: 2025-08-14T15:36:37.576Z
Learnt from: MatthiasKohl
PR: NVIDIA/TensorRT-LLM#6904
File: cpp/tensorrt_llm/kernels/mlaKernels.cu:436-439
Timestamp: 2025-08-14T15:36:37.576Z
Learning: CUDA kernels prioritize performance and should avoid runtime bounds checking or conditional operations that cause branching/warp divergence. Input validation should be done at the host level before kernel launch, not per-thread in the kernel.

Applied to files:

  • cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingKernel.cuh
🧬 Code Graph Analysis (5)
tensorrt_llm/_torch/modules/fused_moe/routing.py (3)
cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/runner.h (2)
  • top_k (207-207)
  • num_experts (204-204)
tensorrt_llm/_torch/models/modeling_deepseekv3.py (2)
  • apply (339-344)
  • apply (404-406)
cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp (2)
  • default_moe_routing_op (80-83)
  • default_moe_routing_op (80-80)
tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py (2)
tensorrt_llm/_torch/custom_ops/torch_custom_ops.py (7)
  • _ (228-267)
  • _ (346-354)
  • _ (435-445)
  • _ (617-644)
  • _ (677-687)
  • _ (764-774)
  • _ (867-883)
tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py (2)
  • _ (276-319)
  • _ (542-565)
cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu (1)
cpp/tensorrt_llm/kernels/topkLastDim.cu (16)
  • T (153-161)
  • T (1183-1186)
  • void (213-273)
  • void (277-340)
  • void (387-479)
  • void (486-533)
  • void (540-559)
  • void (564-618)
  • void (621-698)
  • void (739-879)
  • void (960-992)
  • void (997-1075)
  • void (1078-1171)
  • void (1202-1244)
  • nextPowerOfTwo (1535-1552)
  • nextPowerOfTwo (1535-1535)
cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp (1)
cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu (2)
  • invokeRenormMoeRouting (208-249)
  • invokeRenormMoeRouting (208-209)
cpp/tensorrt_llm/kernels/topkLastDim.cu (1)
cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu (5)
  • void (71-99)
  • void (105-166)
  • T (42-68)
  • nextPowerOfTwo (168-185)
  • nextPowerOfTwo (168-168)
🔇 Additional comments (16)
cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingKernel.cuh (2)

381-387: Arch-gate PDL trigger to SM90+ looks correct; verify downstream consumer sync.

Moving the cudaTriggerProgrammaticLaunchCompletion() under #if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900)) is appropriate and avoids compiling PDL paths on pre-SM90 architectures. Keep this pattern.

Action: Please confirm the immediate consumer kernel of this trigger performs cudaGridDependencySynchronize() at entry (as you already do in routingIndicesHistogramKernel). The comment notes visibility is not guaranteed otherwise; the dependency sync in the consumer is the required mechanism for memory visibility across grids with PDL.


759-767: SM90 arch guard for final PDL trigger is good; ensure consumer executes dependency sync.

This mirrors the SM90 guard used earlier. Given the explicit comment that visibility isn’t guaranteed without a dependency sync, please double-check the consumer of this trigger executes cudaGridDependencySynchronize() (or an equivalent dependency-sync stage) before reading any producer-written buffers.

cpp/tensorrt_llm/thop/CMakeLists.txt (1)

84-84: Stale references cleared; new routing ops wired correctly

All checks passed—there are no leftover references to renormMoeRoutingOp.cpp, and both routing variants are implemented and exposed:

  • cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp
    • Defines and registers renorm_moe_routing_op and default_moe_routing_op.
  • tensorrt_llm/_torch/modules/fused_moe/routing.py
    • Invokes torch.ops.trtllm.default_moe_routing_op and renorm_moe_routing_op.
  • tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py
    • Registers fake bindings for both ops.
tensorrt_llm/_torch/modules/fused_moe/routing.py (2)

54-58: Constructor extension is fine; defaults keep backward compatibility.

Adding force_enable_pytorch_op with a safe default preserves prior behavior.


59-66: PyTorch fallback logic matches “Softmax -> TopK” semantics.

Casting to float before softmax/topk is correct for fp16/bf16 input. Returned dtypes align with downstream expectations (int32 indices, float32 scales).

cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp (3)

18-18: Include switch to customMoeRoutingKernels.h is expected.

Matches the new kernel launcher with DoSoftmaxBeforeTopK template parameter.


75-83: Wrappers for both routing modes are clear and minimal.

renorm_moe_routing_op => DoSoftmaxBeforeTopK=false, default_moe_routing_op => true. Clean separation.


98-108: Registration of the new Torch op is correct.

Dual TORCH_LIBRARY_FRAGMENT blocks for symbol defs and CUDA impls are fine. Naming and signatures match the Python fake registrations.

cpp/tensorrt_llm/kernels/moeTopKFuncs.cuh (3)

129-130: Empty implementation for Sort<1, RedType> specialization.

The run method for the single-element specialization is correctly empty since no sorting is needed for a single element.


51-58: LGTM! Efficient bit-packing implementation.

The makeCmpVal function correctly packs values and indices into a single comparison value using bit manipulation. The use of 65535 - idx for index priority ensures that smaller indices get higher priority, which is a clever implementation detail.


18-19: Fix the include guard name.

The include guard macro name doesn't match the coding guidelines. According to the project's coding standards, header guards should be named TRTLLM_<FILENAME>_H without underscores as prefix/suffix. The filename is moeTopKFuncs.cuh, so the guard should be TRTLLM_MOETOPKFUNCS_CUH.

Apply this diff to fix the include guard:

-#ifndef TRTLLM_MOETOPKFUNCS_CUH_H
-#define TRTLLM_MOETOPKFUNCS_CUH_H
+#ifndef TRTLLM_MOETOPKFUNCS_CUH
+#define TRTLLM_MOETOPKFUNCS_CUH

Also update the closing guard on Line 205:

-#endif // TRTLLM_MOETOPKFUNCS_CUH_H
+#endif // TRTLLM_MOETOPKFUNCS_CUH
⛔ Skipped due to learnings
Learnt from: CR
PR: NVIDIA/TensorRT-LLM#0
File: CODING_GUIDELINES.md:0-0
Timestamp: 2025-08-12T10:28:57.320Z
Learning: Applies to **/*.{h,hpp,hxx,hh,cuh} : Header files must use include guards named TRTLLM_<FILENAME>_H without underscores prefix/suffix (e.g., TRTLLM_FOO_BAR_HELLO_H)
Learnt from: sklevtsov-nvidia
PR: NVIDIA/TensorRT-LLM#3294
File: cpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/fusion/sm90_visitor_scatter.hpp:36-36
Timestamp: 2025-08-08T05:06:31.596Z
Learning: CUTLASS extension files (under cpp/tensorrt_llm/cutlass_extensions/) follow CUTLASS coding style conventions, including using #pragma once instead of TRTLLM_ prefixed header guards, even though they are .hpp files.
cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu (2)

251-254: LGTM! Clean instantiation macro.

The instantiation macro is well-structured and follows good practices for template instantiation.


108-117: LGTM! Well-structured kernel setup.

The kernel initialization correctly uses conditional types based on DoSoftmaxBeforeTopK and properly initializes thread indexing and cooperative groups.

cpp/tensorrt_llm/kernels/topkLastDim.cu (3)

1182-1198: LGTM! Well-implemented negative infinity specializations.

The negativeInfinity template function and its specializations for half and __nv_bfloat16 correctly provide type-specific negative infinity values using the appropriate CUDA constants.


1672-1682: LGTM! Smart routing decision for MOE vs stable radix.

The conditional routing to use the MOE top-k path for small inputs (len ≤ 128 and k ≤ 8) is a good optimization. The MOE path avoids workspace allocation for these small cases.


33-34: Iterator Replacement Verified and Consistent

I searched the entire cpp/ directory and confirmed there are no remaining uses of cub::CountingInputIterator or cub::TransformInputIterator—all iterator usages in topkLastDim.cu now rely on thrust::counting_iterator and thrust::transform_iterator. This change is localized and API-compatible. No further updates are needed.

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

Caution

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

⚠️ Outside diff range comments (2)
cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp (2)

31-37: Fix precondition order and add missing invariants for safety

You index sizes[0]/sizes[1] before verifying rank, and you don't guard CUDA device or topK bounds relative to num_experts. Reorder checks and add the missing guards.

Apply this diff:

-    auto data_type = router_logits.scalar_type();
-    auto input_size = router_logits.sizes();
-    int64_t num_tokens = input_size[0];
-    int64_t num_experts = input_size[1];
-    TORCH_CHECK(input_size.size() == 2, "router_logits must be a 2D Tensor");
-    TORCH_CHECK(topk <= 8, "topk should be smaller than or equal to 8 for now"); //@todo: remove this restriction later
-    TORCH_CHECK(num_experts <= 128, "expert number should be smaller than or equal to 128 for now");
+    TORCH_CHECK(router_logits.is_cuda(), "router_logits must be a CUDA tensor");
+    TORCH_CHECK(router_logits.dim() == 2, "router_logits must be a 2D Tensor");
+    auto input_size = router_logits.sizes();
+    int64_t num_tokens = input_size[0];
+    int64_t num_experts = input_size[1];
+    TORCH_CHECK(topk > 0, "topk must be >= 1");
+    TORCH_CHECK(topk <= num_experts, "topk must be <= num_experts");
+    TORCH_CHECK(topk <= 8, "topk should be smaller than or equal to 8 for now"); //@todo: remove this restriction later
+    TORCH_CHECK(num_experts <= 128, "expert number should be smaller than or equal to 128 for now");
+    auto data_type = router_logits.scalar_type();

39-43: Ensure output tensors are on the same device and force contiguous input

Avoid defaulting to the current CUDA device. Use the input tensor’s options to allocate outputs and make the input contiguous for the kernel’s strided indexing.

-    th::Tensor topk_values = th::empty({num_tokens, topk}, th::dtype(torch::kFloat32).device(torch::kCUDA));
-    th::Tensor topk_indices = th::empty({num_tokens, topk}, th::dtype(torch::kInt32).device(torch::kCUDA));
-
-    auto stream = at::cuda::getCurrentCUDAStream(router_logits.get_device());
+    auto logits = router_logits.contiguous();
+    auto fOpts = logits.options().dtype(torch::kFloat32);
+    auto iOpts = logits.options().dtype(torch::kInt32);
+    th::Tensor topk_values = th::empty({num_tokens, topk}, fOpts);
+    th::Tensor topk_indices = th::empty({num_tokens, topk}, iOpts);
+
+    auto stream = at::cuda::getCurrentCUDAStream(logits.get_device());
🧹 Nitpick comments (15)
cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingKernel.cuh (1)

381-387: Arch-based PDL gating switch looks correct; optionally restrict trigger to a single thread and add an #endif comment.

Compilation gating on SM90+ via CUDA_ARCH is the right direction. To avoid redundant programmatic-launch triggers from every thread, gate the trigger to a single elected thread. Also align the #endif style with the rest of the file.

Apply this diff:

-#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900))
-    if constexpr (KernelParams::UsePdl)
-    {
-        cudaTriggerProgrammaticLaunchCompletion();
-    }
-#endif
+#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900))
+    if constexpr (KernelParams::UsePdl)
+    {
+        // Trigger once per cluster to minimize redundant triggers.
+        if (clusterBlockRank == 0 && warpIdx == 0 && threadIdx.x == 0)
+        {
+            cudaTriggerProgrammaticLaunchCompletion();
+        }
+    }
+#endif // if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900))
tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py (1)

535-541: New fake op wiring looks correct and consistent with renorm_moe_routing_op.

  • Output shapes/dtypes align with the routing path expectations: (num_tokens, topk) int32 indices and float32 values.
  • Name matches the Torch op usage in routing.py.

Minor:

  • Consider factoring the duplicated body with renorm_moe_routing_op into a tiny helper to avoid drift.
  • Ensure the NVIDIA copyright header is present at the top of this Python file per repo guidelines.
tensorrt_llm/_torch/modules/fused_moe/routing.py (2)

54-58: Expose and document the new force_enable_pytorch_op in init.

The new switch is helpful for forcing the PyTorch path. Please add a brief docstring for the class (or the init signature) describing top_k and force_enable_pytorch_op to keep external usage self-explanatory.


67-75: Heuristic matches the CUDA fast-path constraints; keep thresholds in sync.

The gating (num_experts > 128 or top_k > 8) correctly routes large cases to the PyTorch path and small cases to the custom CUDA op. Please ensure this stays consistent with kernels/topkLastDim.cu fast-path constraints (len <= 128 and k <= 8). If those limits change, update this condition accordingly.

cpp/tensorrt_llm/kernels/customMoeRoutingKernels.h (1)

26-29: Template API change is reasonable; consider naming or docs to reflect the new toggle.

Adding DoSoftmaxBeforeTopK is the right abstraction. Since invokeRenormMoeRouting now also covers the “Default” flow (softmax-before-topk), consider documenting this in a brief comment or renaming in a future refactor to avoid confusion at call sites.

cpp/tensorrt_llm/kernels/topkLastDim.cu (4)

25-36: Add to use std::max in host code.

This TU uses max() in host code. Prefer std::max and include to avoid macro collisions.

Apply:

 #include "topkLastDim.h"
+#include <algorithm>
 #include <cooperative_groups.h>
 #include <cooperative_groups/reduce.h>

1323-1324: Use std::max for clarity and to avoid macro pitfalls.

Switch to std::max since this is host code and is now included.

Apply:

-    temp_storage_bytes = max(temp_storage_bytes, temp_storage_bytes_sort);
+    temp_storage_bytes = std::max(temp_storage_bytes, temp_storage_bytes_sort);

1452-1452: Use std::max here as well.

Apply:

-    temp_storage_bytes = max(temp_storage_bytes, temp_storage_bytes_sort);
+    temp_storage_bytes = std::max(temp_storage_bytes, temp_storage_bytes_sort);

1555-1618: Kernel dispatch table: minor cleanups and edge-case note.

  • Case 96 for max_len is unreachable with current nextPowerOfTwo() logic (it yields 32/64/128). Safe to remove or keep for readability, but it's dead code.
  • Param greater is unused in moe_reduce_topk; either wire it (if you add “small-K min” in future) or remove it to reduce confusion.
cpp/tensorrt_llm/kernels/moeTopKFuncs.cuh (4)

33-35: Verify architecture gating for redux.sync path

kTLLM_GEN_HAS_FAST_REDUX is tied to arch::is_major_v<10>. Please confirm this matches the first SM that supports redux.sync.max.u32 (SM90 on Hopper in practice). If not, gate on the correct SM to avoid illegal instruction on older GPUs.

Would you like me to update this to a helper constant like arch::hasFastRedux() and wire it to SM90+?


83-95: Use volatile inline asm for redux to prevent unwanted reordering

Minor but conventional; also documents that there are no memory side-effects.

-            asm("redux.sync.max.u32 %0, %1, 0xffffffff;\n" : "=r"(result) : "r"(compValIdx));
+            asm volatile("redux.sync.max.u32 %0, %1, 0xffffffff;\n" : "=r"(result) : "r"(compValIdx));

115-121: Avoid relying on unqualified min/max in device code

Unqualified min/max can be problematic depending on includes. Being explicit removes ambiguity.

-        auto pairMin = min(topK[I].compValIdx, topK[J].compValIdx);
-        auto pairMax = max(topK[I].compValIdx, topK[J].compValIdx);
+        auto pairMin = topK[I].compValIdx < topK[J].compValIdx ? topK[I].compValIdx : topK[J].compValIdx;
+        auto pairMax = topK[I].compValIdx < topK[J].compValIdx ? topK[J].compValIdx : topK[I].compValIdx;

169-173: Fix static_assert condition/message mismatch

N is the per-lane candidate count (= MaxNumExperts / 32); supported N is up to 4. The message currently says “<= 128” which is misleading here.

-    static_assert(N < 5, "Only support candidates number less than or equal to 128");
+    static_assert(N <= 4, "Only supports up to 4 candidates per lane (MaxNumExperts <= 128)");
cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu (2)

220-227: Unreachable CASE(96) branch

maxNumExperts is nextPowerOfTwo(numExperts) floored to at least 32, so values are 32/64/128. CASE(96) will never be selected.

Remove the CASE(96) branch to reduce confusion.


168-186: Deduplicate nextPowerOfTwo implementation

nextPowerOfTwo is already implemented in topkLastDim.cu. Prefer a single utility (header) to avoid divergence.

I can extract nextPowerOfTwo into a small header (e.g., kernels/topkUtils.cuh) and refactor both call sites to include it.

📜 Review details

Configuration used: .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 fae43e7 and 59d1a58.

📒 Files selected for processing (11)
  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu (1 hunks)
  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.h (2 hunks)
  • cpp/tensorrt_llm/kernels/moeTopKFuncs.cuh (1 hunks)
  • cpp/tensorrt_llm/kernels/renormMoeRoutingKernels.cu (0 hunks)
  • cpp/tensorrt_llm/kernels/topkLastDim.cu (13 hunks)
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingKernel.cuh (2 hunks)
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingLlama4.cu (0 hunks)
  • cpp/tensorrt_llm/thop/CMakeLists.txt (1 hunks)
  • cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp (5 hunks)
  • tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py (1 hunks)
  • tensorrt_llm/_torch/modules/fused_moe/routing.py (1 hunks)
💤 Files with no reviewable changes (2)
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingLlama4.cu
  • cpp/tensorrt_llm/kernels/renormMoeRoutingKernels.cu
🧰 Additional context used
📓 Path-based instructions (6)
**/*.py

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+
Python indentation: 4 spaces, no tabs
Maintain module namespace in imports (from package.subpackage import foo; then use foo.SomeClass())
Python file names use snake_case
Python class names use PascalCase
Python functions/methods and local variables use snake_case; variables starting with a number get k_ prefix (e.g., k_99th_percentile)
Global variables use G_ prefixed UPPER_SNAKE_CASE (e.g., G_MY_GLOBAL)
Constants use UPPER_SNAKE_CASE in Python
Avoid shadowing variables from outer scopes in Python
Initialize all externally visible members of a Python class in init
Prefer docstrings for interfaces used outside a file; comments for local code
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes/variables inline with short docstrings
Avoid reflection when simple alternatives exist (e.g., prefer explicit parameters over dict(**locals()))
In try/except, catch the narrowest exceptions possible
For duck-typing with try/except, keep try body minimal and put logic in else

Files:

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

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

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

Files:

  • tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py
  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.h
  • tensorrt_llm/_torch/modules/fused_moe/routing.py
  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingKernel.cuh
  • cpp/tensorrt_llm/kernels/moeTopKFuncs.cuh
  • cpp/tensorrt_llm/kernels/topkLastDim.cu
  • cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}: In C++, close namespaces with a comment naming the namespace (e.g., } // namespace foo)
Prefer const/constexpr variables over #define for constants
Declare variables const if not modified after initialization
Use Allman brace style in C++
C++ filenames use lowerCamelCase and must be case-insensitively unique within a build target
C++ type names use UpperCamelCase
Local variables, methods, and namespaces use lowerCamelCase
Global non-static variables not in anonymous namespace use gPrefix lowerCamelCase (e.g., gExample)
Static globals or globals in anonymous namespaces use sPrefix lowerCamelCase
Locally visible static variables start with 's' (e.g., static std::once_flag sFlag;)
Member variables use mPrefix lowerCamelCase; public members may omit but are encouraged to use 'm'
Constants (enums, global/static/function-scope magic numbers) use kPREFIXED_UPPER_SNAKE (e.g., kDIGIT_NUM)
If macros are unavoidable, use UPPER_SNAKE_CASE (prefer constants over #define)
Constructor parameter that conflicts with a public member name gets trailing underscore (foo_)
Literal suffixes should be uppercase (e.g., 1234L not 1234l)
C++: use spaces only; indent 4 spaces
Run clang-format (LLVM style) before submitting; wrap lines at 120 characters
If formatting must be bypassed, use // clang-format off/on around the section
Prefer smart pointers; use unique_ptr for sole ownership, shared_ptr for shared; weak_ptr only in exceptional cases
Do not use deprecated pre-C++11 smart pointers
Use C++ style comments; avoid C comments except special inline cases; prefer // single-line
Capitalize and punctuate full-sentence comments
Follow Doxygen rules: use //! for comments and //!< for members in C++
Disable code with #if/#endif and mnemonic conditions; avoid commented-out code; avoid dead code
Do not throw exceptions across library boundaries
Use least-forceful casts; avoid removing const/volatile; avoid C-style and functional casts (except constructors); p...

Files:

  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.h
  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingKernel.cuh
  • cpp/tensorrt_llm/kernels/moeTopKFuncs.cuh
  • cpp/tensorrt_llm/kernels/topkLastDim.cu
  • cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp
**/*.{h,hpp,hxx,hh,cuh,cpp,cxx,cc,cu}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Parameter names must be consistent between declarations and definitions

Files:

  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.h
  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingKernel.cuh
  • cpp/tensorrt_llm/kernels/moeTopKFuncs.cuh
  • cpp/tensorrt_llm/kernels/topkLastDim.cu
  • cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp
**/*.{h,hpp,hxx,hh,cuh}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Header files must use include guards named TRTLLM__H without underscores prefix/suffix (e.g., TRTLLM_FOO_BAR_HELLO_H)

Files:

  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.h
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingKernel.cuh
  • cpp/tensorrt_llm/kernels/moeTopKFuncs.cuh
**/*.{cpp,cxx,cc,cu}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu}: Avoid literal values except for 0, nullptr, true, false; use named constexpr for other literals
Place semicolon of empty for/while loop on a new line
Always use brace-delimited bodies for switch/while/do-for/if/else
Use inline C comments in argument lists when parameter meaning is unclear (e.g., /* checkForErrors = */ false)
Do not use assignment in subexpressions (e.g., if (x = y) ... is forbidden)
Switch on enums should enumerate all values and omit default to catch new values at compile time
Structure switch statements; prohibit fallthrough except between empty cases; each case ends with break or throw; return at end of case not allowed; put break inside braces for compound case
Prefer anonymous namespaces over static for internal linkage of functions
Every defined function must be called at least once (no unused methods)

Files:

  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu
  • cpp/tensorrt_llm/kernels/topkLastDim.cu
  • cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp
🧠 Learnings (2)
📚 Learning: 2025-08-08T22:03:40.707Z
Learnt from: sklevtsov-nvidia
PR: NVIDIA/TensorRT-LLM#3294
File: cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cu:1198-1209
Timestamp: 2025-08-08T22:03:40.707Z
Learning: In the CUTLASS MoE kernels (cpp/tensorrt_llm/cutlass_extensions), when `layout_info.fusion` is set to `TmaWarpSpecializedGroupedGemmInput::EpilogueFusion::FINALIZE`, the `router_scales` parameter must be non-null by design. The fused finalize kernel epilogue does not perform nullptr checks and requires valid router scales to function correctly. This is an implicit contract that callers must satisfy when enabling the FINALIZE fusion mode.

Applied to files:

  • cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingKernel.cuh
  • cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp
📚 Learning: 2025-08-14T15:36:37.576Z
Learnt from: MatthiasKohl
PR: NVIDIA/TensorRT-LLM#6904
File: cpp/tensorrt_llm/kernels/mlaKernels.cu:436-439
Timestamp: 2025-08-14T15:36:37.576Z
Learning: CUDA kernels prioritize performance and should avoid runtime bounds checking or conditional operations that cause branching/warp divergence. Input validation should be done at the host level before kernel launch, not per-thread in the kernel.

Applied to files:

  • cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingKernel.cuh
🧬 Code Graph Analysis (5)
tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py (1)
tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py (2)
  • _ (276-319)
  • _ (542-565)
tensorrt_llm/_torch/modules/fused_moe/routing.py (2)
tensorrt_llm/_torch/models/modeling_deepseekv3.py (2)
  • apply (339-344)
  • apply (404-406)
cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp (2)
  • default_moe_routing_op (80-83)
  • default_moe_routing_op (80-80)
cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu (1)
cpp/tensorrt_llm/kernels/topkLastDim.cu (16)
  • T (153-161)
  • T (1183-1186)
  • void (213-273)
  • void (277-340)
  • void (387-479)
  • void (486-533)
  • void (540-559)
  • void (564-618)
  • void (621-698)
  • void (739-879)
  • void (960-992)
  • void (997-1075)
  • void (1078-1171)
  • void (1202-1244)
  • nextPowerOfTwo (1535-1552)
  • nextPowerOfTwo (1535-1535)
cpp/tensorrt_llm/kernels/topkLastDim.cu (1)
cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu (5)
  • void (71-99)
  • void (105-166)
  • T (42-68)
  • nextPowerOfTwo (168-185)
  • nextPowerOfTwo (168-168)
cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp (1)
cpp/tensorrt_llm/kernels/customMoeRoutingKernels.cu (2)
  • invokeRenormMoeRouting (208-249)
  • invokeRenormMoeRouting (208-209)
🔇 Additional comments (6)
cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingKernel.cuh (1)

759-767: Limit PDL trigger to one thread and confirm host‐side gating

To avoid redundant device‐side triggers, update cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/RoutingKernel.cuh (lines 759–767) as follows:

 #if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900))
     // Trigger secondary kernel.
     // Note: this does not guarantee the visibility of prior writes unless the consumer executes a
     // dependency sync.
-    if constexpr (KernelParams::UsePdl)
-    {
-        cudaTriggerProgrammaticLaunchCompletion();
-    }
+    if constexpr (KernelParams::UsePdl)
+    {
+        // Trigger once per grid (block 0 / thread 0) to avoid redundant triggers.
+        if (blockIdx.x == 0 && threadIdx.x == 0)
+        {
+            cudaTriggerProgrammaticLaunchCompletion();
+        }
+    }
 #endif // if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900))

• The device‐side #if (__CUDA_ARCH__ >= 900) already prevents any PDL calls on SM < 90.
• I didn’t find any host‐side logic that disables UsePdl when targeting SM 8.x or earlier—please verify your kernel‐launch wrappers pass UsePdl=false for architectures below 9.0.

tensorrt_llm/_torch/modules/fused_moe/routing.py (1)

59-66: PyTorch path is correct for Default routing (Softmax -> TopK), with stable dtypes.

  • Casting to float32 for softmax improves numerical robustness.
  • Return order and dtypes match downstream expectations.

LGTM.

cpp/tensorrt_llm/thop/CMakeLists.txt (1)

84-84: Legacy routing source renormMoeRoutingOp.cpp fully removed
Confirmed no references to renormMoeRoutingOp.cpp in any CMakeLists.txt or elsewhere in the repo. Build now exclusively uses customMoeRoutingOp.cpp.

cpp/tensorrt_llm/kernels/customMoeRoutingKernels.h (1)

2-2: Updated copyright year is good.

Header shows 2025 which matches the current release cycle. No concerns here.

cpp/tensorrt_llm/kernels/topkLastDim.cu (1)

1672-1683: No ordering mismatch—both paths return sorted Top-K results

After inspecting both implementations:

  • reduceTopK (used by moe_reduce_topk) always emits the Top-K values in descending order.
  • standalone_stable_radix_11bits with sorted=true likewise produces a sorted output.

There’s no behavioral difference between the fast path and the radix fallback.

cpp/tensorrt_llm/thop/customMoeRoutingOp.cpp (1)

98-108: Operator registration looks correct

The new default_moe_routing_op is properly defined and bound for CUDA; keeping renorm_moe_routing_op for compatibility is good.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15858 [ run ] completed with state FAILURE
/LLM/release-1.0/L0_MergeRequest_PR pipeline #225 completed with status: 'FAILURE'

@ChristinaZ
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15900 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15900 [ run ] completed with state SUCCESS
/LLM/release-1.0/L0_MergeRequest_PR pipeline #234 completed with status: 'SUCCESS'
Pipeline passed with automatic retried tests. Check the rerun report for details.

@byshiue byshiue merged commit a875e50 into NVIDIA:release/1.0 Aug 21, 2025
7 checks passed
yuanjingx87 pushed a commit that referenced this pull request Aug 28, 2025
…mized default routing method (#7068)

Signed-off-by: Christina Zhang <83400082+ChristinaZ@users.noreply.github.com>
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Sep 5, 2025
…mized default routing method (NVIDIA#7068)

Signed-off-by: Christina Zhang <83400082+ChristinaZ@users.noreply.github.com>
Signed-off-by: Wangshanshan <30051912+dominicshanshan@users.noreply.github.com>
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Sep 5, 2025
…mized default routing method (NVIDIA#7068)

Signed-off-by: Christina Zhang <83400082+ChristinaZ@users.noreply.github.com>
Signed-off-by: Wangshanshan <30051912+dominicshanshan@users.noreply.github.com>
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Sep 6, 2025
…mized default routing method (NVIDIA#7068)

Signed-off-by: Christina Zhang <83400082+ChristinaZ@users.noreply.github.com>
Signed-off-by: Wangshanshan <30051912+dominicshanshan@users.noreply.github.com>
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Sep 6, 2025
…mized default routing method (NVIDIA#7068)

Signed-off-by: Christina Zhang <83400082+ChristinaZ@users.noreply.github.com>
Signed-off-by: Wangshanshan <30051912+dominicshanshan@users.noreply.github.com>
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Sep 7, 2025
…mized default routing method (NVIDIA#7068)

Signed-off-by: Christina Zhang <83400082+ChristinaZ@users.noreply.github.com>
Signed-off-by: Wangshanshan <30051912+dominicshanshan@users.noreply.github.com>
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.

3 participants