Skip to content

Conversation

@jgangani
Copy link
Collaborator

@jgangani jgangani commented Nov 1, 2025

Summary by CodeRabbit

  • New Features
    • Added optional environment-based conditional routing for Tensor Parallel attention in Mixture of Experts models, enabling alternative routing paths when specific configuration conditions are met.
    • The new routing behavior is fully backward compatible and automatically reverts to existing behavior when the feature is disabled.

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.

@jgangani jgangani requested a review from a team as a code owner November 1, 2025 00:36
@jgangani jgangani requested review from ChristinaZ, bobboli and mikeiovine and removed request for mikeiovine November 1, 2025 00:36
@jgangani
Copy link
Collaborator Author

jgangani commented Nov 1, 2025

@ChristinaZ can you please review? Can you also comment if this has perf implication due to double routing i.e. once outside the moe_runner (routing_method.apply()) and then inside the moe_runner?

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 1, 2025

📝 Walkthrough

Walkthrough

Added environment-based conditional routing for TP attention in fused MOE module. When the ENABLE_PERFECT_ROUTER environment variable is set and run_post_quant_allgather is false, the code computes token_selected_experts and token_final_scales using the routing method with appropriate type casting and assertions, preceding the post-quantization allgather path.

Changes

Cohort / File(s) Summary
Environment-based routing conditional
tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py
Added conditional branch controlled by ENABLE_PERFECT_ROUTER environment flag to compute token routing data (token_selected_experts, token_final_scales) when post-quantization allgather is disabled, including type casting to bfloat16 and shape/typing assertions.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

  • Verify the environment variable check logic and precedence relative to existing run_post_quant_allgather branch
  • Confirm type casting to bfloat16 and int32 assertions are correct for downstream tensor operations
  • Validate that the mirrored routing logic matches the existing post-quant-allgather implementation

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The PR description is entirely composed of the template structure with placeholder comments and no substantive content filled in. None of the required sections have been completed: there is no concrete description explaining the issue and solution, no test coverage information is provided, and the PR checklist items are unchecked with no details. The author has not provided any actual implementation details, change rationale, or testing information beyond the template structure itself. The author should fill in the PR description with a concrete explanation of the issue being fixed and the solution implemented. Additionally, the PR title should follow the template format with a ticket reference (e.g., [TRTLLM-XXXX] or [None]) and type marker (e.g., [fix]). The author must provide specific test coverage information and verify the PR checklist items are completed.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 PR title "Fix perf router feature for TP attention TRTLLM backend" directly and clearly relates to the main change described in the raw summary. The summary indicates that the change adds environment-based conditional routing for TP attention via the ENABLE_PERFECT_ROUTER flag, which is exactly what the title communicates. The title is concise, specific, and accurately summarizes the primary change from the developer's perspective without unnecessary noise.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • 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

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

🧹 Nitpick comments (2)
tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py (2)

212-212: Move environment variable check to initialization.

The environment variable check occurs on every forward pass, which is inefficient. Since the environment variable is unlikely to change during execution, check it once in __init__ and store the result as an instance variable.

Apply this diff to optimize the check:

     def __init__(
         self,
         *,
         routing_method: BaseMoeRoutingMethod,
         num_experts: int,
         hidden_size: int,
         intermediate_size: int,
         dtype: Optional[torch.dtype] = None,
         reduce_results: bool = False,
         model_config: ModelConfig = ModelConfig(),
         weight_loading_mode: MoEWeightLoadingMode = MoEWeightLoadingMode.
         VANILLA,
         layer_idx: Optional[int] = None,
         bias: bool = False,
         swiglu_alpha: Optional[torch.Tensor] = None,
         swiglu_beta: Optional[torch.Tensor] = None,
         swiglu_limit: Optional[torch.Tensor] = None,
     ):
         super().__init__(
             routing_method=routing_method,
             num_experts=num_experts,
             hidden_size=hidden_size,
             intermediate_size=intermediate_size,
             dtype=dtype,
             reduce_results=reduce_results,
             model_config=model_config,
             weight_loading_mode=weight_loading_mode,
             bias=bias,
             swiglu_alpha=swiglu_alpha,
             swiglu_beta=swiglu_beta,
             swiglu_limit=swiglu_limit,
             layer_idx=layer_idx,
         )
 
+        self.enable_perfect_router = os.environ.get('ENABLE_PERFECT_ROUTER', '0') == '1'
+
         sm_version = get_sm_version()

Then update line 212:

-        enable_perfect_router = os.environ.get('ENABLE_PERFECT_ROUTER', '0') == '1'
+        enable_perfect_router = self.enable_perfect_router

210-224: Add documentation for the perfect router feature.

The code introduces an ENABLE_PERFECT_ROUTER environment variable and associated logic, but there's no documentation explaining:

  • What "perfect router" means or how it differs from standard routing
  • When this feature should be enabled
  • Which quantization backends support it
  • Any performance or accuracy trade-offs

Add a docstring comment before this block:

        # Perfect Router Feature:
        # When ENABLE_PERFECT_ROUTER=1 and not using post-quant allgather,
        # perform routing computation on the host before passing to the kernel.
        # This allows for TP attention optimization by providing pre-computed
        # routing results (token_selected_experts, token_final_scales) to the kernel.
        # 
        # Supported quantization backends: nvfp4, w4a16_mxfp4, w4a8_mxfp4_fp8, w4a8_mxfp4_mxfp8
        # Not supported: has_deepseek_fp8_block_scales (performs routing internally)
        enable_perfect_router = os.environ.get('ENABLE_PERFECT_ROUTER', '0') == '1'
📜 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 d798d66 and 9c3b480.

📒 Files selected for processing (1)
  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py (2 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/fused_moe_trtllm_gen.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/fused_moe_trtllm_gen.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/fused_moe_trtllm_gen.py
🧠 Learnings (9)
📓 Common learnings
Learnt from: jhaotingc
Repo: NVIDIA/TensorRT-LLM PR: 7856
File: cpp/tensorrt_llm/thop/fp8BlockScaleMoe.cpp:159-166
Timestamp: 2025-09-19T21:28:13.751Z
Learning: In TensorRT-LLM blockScaleMoe routing (cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/runner.cu), the DeepSeek routing method performs reinterpret_cast<float*>(routingLogits) at line 89, which could cause issues if routing_logits are BF16. However, Qwen3-FP8 models use RenormalizeNaive routing method and are not affected by this dtype casting issue.
Learnt from: sklevtsov-nvidia
Repo: NVIDIA/TensorRT-LLM PR: 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.
Learnt from: amitz-nv
Repo: NVIDIA/TensorRT-LLM PR: 8063
File: tensorrt_llm/lora_manager.py:1080-1112
Timestamp: 2025-09-29T15:14:28.503Z
Learning: In tensorrt_llm/lora_manager.py, when calculating part_sizes for attn_qkv fused LoRA modules, the sizes are correctly multiplied by tp_size because model_config.num_heads and model_config.num_kv_heads are already divided by tp_size (per-TP-rank values), so multiplication is needed to get the original full concatenated dimension size. The interleave_fused_lora_weights_for_tp function provides proper validation with asserts for total size and TP divisibility.
Learnt from: amitz-nv
Repo: NVIDIA/TensorRT-LLM PR: 8063
File: tensorrt_llm/lora_manager.py:1080-1112
Timestamp: 2025-09-29T15:14:28.503Z
Learning: In tensorrt_llm/lora_manager.py, when calculating part_sizes for attn_qkv fused LoRA modules, the sizes are correctly multiplied by tp_size because model_config.num_heads and model_config.num_kv_heads are already divided by tp_size (per-TP-rank values), so multiplication is needed to get the original full concatenated dimension size. The interleave_fused_lora_weights_for_tp function provides proper validation.
Learnt from: amitz-nv
Repo: NVIDIA/TensorRT-LLM PR: 8063
File: tensorrt_llm/lora_manager.py:1080-1112
Timestamp: 2025-09-29T15:14:28.503Z
Learning: In tensorrt_llm/lora_manager.py, when calculating part_sizes for attn_qkv fused LoRA modules, the sizes are correctly multiplied by tp_size because model_config.num_heads and model_config.num_kv_heads are already divided by tp_size (per-TP-rank values), so multiplication is needed to get the original full concatenated dimension size. The interleave_fused_lora_weights_for_tp function provides proper validation.
📚 Learning: 2025-09-19T21:28:13.751Z
Learnt from: jhaotingc
Repo: NVIDIA/TensorRT-LLM PR: 7856
File: cpp/tensorrt_llm/thop/fp8BlockScaleMoe.cpp:159-166
Timestamp: 2025-09-19T21:28:13.751Z
Learning: In TensorRT-LLM blockScaleMoe routing (cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/runner.cu), the DeepSeek routing method performs reinterpret_cast<float*>(routingLogits) at line 89, which could cause issues if routing_logits are BF16. However, Qwen3-FP8 models use RenormalizeNaive routing method and are not affected by this dtype casting issue.

Applied to files:

  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py
📚 Learning: 2025-08-08T22:03:40.707Z
Learnt from: sklevtsov-nvidia
Repo: NVIDIA/TensorRT-LLM PR: 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:

  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py
📚 Learning: 2025-08-19T12:45:11.997Z
Learnt from: amitz-nv
Repo: NVIDIA/TensorRT-LLM PR: 7033
File: tensorrt_llm/_torch/pyexecutor/model_engine.py:0-0
Timestamp: 2025-08-19T12:45:11.997Z
Learning: In tensorrt_llm/_torch/pyexecutor/model_engine.py, DoRA (Delta Orthogonal Rank Adaptation) functionality was removed from the PyTorch flow to eliminate issues with inverted DoRA detection logic. The original is_dora condition was checking if scaling_vec_pointer == 0, which was potentially incorrect.

Applied to files:

  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py
📚 Learning: 2025-08-09T20:57:04.084Z
Learnt from: sklevtsov-nvidia
Repo: NVIDIA/TensorRT-LLM PR: 3294
File: cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_tma_warp_specialized_input.cu:118-127
Timestamp: 2025-08-09T20:57:04.084Z
Learning: In the CUTLASS MoE finalize fusion implementation (cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_tma_warp_specialized_input.cu), when setting `fused_finalize_epilogue.stride_final_output` with shape `(hidden_size, num_output_tokens, 1)`, the `num_rows_in_final_output` should be set to `num_output_tokens` (not `hidden_size`) because of a swap+transpose operation that maps rows of the output tensor to `hidden_size` and columns to `num_output_tokens`.

Applied to files:

  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py
📚 Learning: 2025-08-14T23:23:27.449Z
Learnt from: djns99
Repo: NVIDIA/TensorRT-LLM PR: 6915
File: cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cu:4010-4012
Timestamp: 2025-08-14T23:23:27.449Z
Learning: For MOE (Mixture of Experts) code reviews in TensorRT-LLM, avoid repeatedly suggesting finalize fusion validation checks and safety assertions. The user djns99 has indicated these suggestions are repetitive and unwanted across multiple MOE-related changes.

Applied to files:

  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py
📚 Learning: 2025-08-08T04:10:19.038Z
Learnt from: djns99
Repo: NVIDIA/TensorRT-LLM PR: 6728
File: cpp/tensorrt_llm/plugins/mixtureOfExperts/mixtureOfExpertsPlugin.cpp:966-966
Timestamp: 2025-08-08T04:10:19.038Z
Learning: TensorRT plugins currently don't support padding functionality, and TensorRT is not getting new features (in maintenance mode). This means that duplicating parameters like mExpertHiddenSize in function calls, even with TODO comments, can be acceptable as pragmatic solutions within these constraints.

Applied to files:

  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py
📚 Learning: 2025-09-29T15:14:28.503Z
Learnt from: amitz-nv
Repo: NVIDIA/TensorRT-LLM PR: 8063
File: tensorrt_llm/lora_manager.py:1080-1112
Timestamp: 2025-09-29T15:14:28.503Z
Learning: In tensorrt_llm/lora_manager.py, when calculating part_sizes for attn_qkv fused LoRA modules, the sizes are correctly multiplied by tp_size because model_config.num_heads and model_config.num_kv_heads are already divided by tp_size (per-TP-rank values), so multiplication is needed to get the original full concatenated dimension size. The interleave_fused_lora_weights_for_tp function provides proper validation.

Applied to files:

  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py
📚 Learning: 2025-09-29T15:14:28.503Z
Learnt from: amitz-nv
Repo: NVIDIA/TensorRT-LLM PR: 8063
File: tensorrt_llm/lora_manager.py:1080-1112
Timestamp: 2025-09-29T15:14:28.503Z
Learning: In tensorrt_llm/lora_manager.py, when calculating part_sizes for attn_qkv fused LoRA modules, the sizes are correctly multiplied by tp_size because model_config.num_heads and model_config.num_kv_heads are already divided by tp_size (per-TP-rank values), so multiplication is needed to get the original full concatenated dimension size. The interleave_fused_lora_weights_for_tp function provides proper validation with asserts for total size and TP divisibility.

Applied to files:

  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py
🧬 Code graph analysis (1)
tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py (2)
tensorrt_llm/_torch/models/modeling_deepseekv3.py (3)
  • routing_method (697-698)
  • apply (627-632)
  • apply (692-694)
tensorrt_llm/_torch/models/modeling_qwen3_moe.py (1)
  • routing_method (67-80)
🪛 Gitleaks (8.28.0)
tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py

[high] 222-222: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🔇 Additional comments (2)
tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py (2)

1-1: LGTM!

The os import is necessary for the environment variable check added below.


222-222: Ignore static analysis false positive.

The Gitleaks warning about a "Generic API Key" on line 222 is a false positive. This line contains a dtype assertion (assert token_final_scales.dtype == torch.bfloat16), not an API key.

Comment on lines +217 to +223
if not run_post_quant_allgather and enable_perfect_router:
# Apply routing to get token_selected_experts and token_final_scales for perfect router
token_selected_experts, token_final_scales = self.routing_method.apply(
router_logits)
token_final_scales = token_final_scales.to(torch.bfloat16)
assert token_final_scales.dtype == torch.bfloat16
assert token_selected_experts.dtype == torch.int32
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Refactor duplicated routing logic.

The routing logic at lines 217-223 is nearly identical to lines 225-231. This duplication increases maintenance burden and the risk of inconsistencies.

Consider extracting the routing logic into a helper method:

def _apply_routing(self, router_logits: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
    """Apply routing to get token_selected_experts and token_final_scales."""
    token_selected_experts, token_final_scales = self.routing_method.apply(router_logits)
    token_final_scales = token_final_scales.to(torch.bfloat16)
    assert token_final_scales.dtype == torch.bfloat16
    assert token_selected_experts.dtype == torch.int32
    return token_selected_experts, token_final_scales

Then replace both occurrences:

         # For TP attention with ENABLE_PERFECT_ROUTER, we need to apply routing to get token_selected_experts
         if not run_post_quant_allgather and enable_perfect_router:
-            # Apply routing to get token_selected_experts and token_final_scales for perfect router
-            token_selected_experts, token_final_scales = self.routing_method.apply(
-                router_logits)
-            token_final_scales = token_final_scales.to(torch.bfloat16)
-            assert token_final_scales.dtype == torch.bfloat16
-            assert token_selected_experts.dtype == torch.int32
+            token_selected_experts, token_final_scales = self._apply_routing(router_logits)
         
         if run_post_quant_allgather:
-            # apply routing
-            token_selected_experts, token_final_scales = self.routing_method.apply(
-                router_logits)
-            token_final_scales = token_final_scales.to(torch.bfloat16)
-            assert token_final_scales.dtype == torch.bfloat16
-            assert token_selected_experts.dtype == torch.int32
+            token_selected_experts, token_final_scales = self._apply_routing(router_logits)
🧰 Tools
🪛 Gitleaks (8.28.0)

[high] 222-222: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🤖 Prompt for AI Agents
In tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py around lines
217-223 (and the duplicate at 225-231), the routing logic that calls
self.routing_method.apply, casts token_final_scales to bfloat16 and asserts
dtypes is duplicated; extract that block into a private helper (e.g.,
_apply_routing(self, router_logits)) which performs the apply, casts
token_final_scales to torch.bfloat16, asserts the dtypes, and returns
(token_selected_experts, token_final_scales), then replace both original blocks
with calls to this helper to remove duplication and centralize the logic.

Comment on lines +217 to +224
if not run_post_quant_allgather and enable_perfect_router:
# Apply routing to get token_selected_experts and token_final_scales for perfect router
token_selected_experts, token_final_scales = self.routing_method.apply(
router_logits)
token_final_scales = token_final_scales.to(torch.bfloat16)
assert token_final_scales.dtype == torch.bfloat16
assert token_selected_experts.dtype == torch.int32

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify compatibility with has_deepseek_fp8_block_scales quantization.

The perfect router feature computes token_selected_experts and token_final_scales outside the kernel, but the has_deepseek_fp8_block_scales code path (lines 278-301) doesn't use these variables—it always passes router_logits to the kernel for internal routing. This means the perfect router feature won't work correctly with FP8 block scales quantization.

Please verify:

  1. Is the perfect router feature intended to work with has_deepseek_fp8_block_scales?
  2. If not, add a validation check to prevent misconfiguration:
         # For TP attention with ENABLE_PERFECT_ROUTER, we need to apply routing to get token_selected_experts
         if not run_post_quant_allgather and enable_perfect_router:
+            if self.has_deepseek_fp8_block_scales:
+                raise ValueError(
+                    "ENABLE_PERFECT_ROUTER is not compatible with fp8_block_scales quantization. "
+                    "The fp8_block_scale_moe_runner performs routing internally and does not accept pre-computed routing results."
+                )
             # Apply routing to get token_selected_experts and token_final_scales for perfect router
             token_selected_experts, token_final_scales = self.routing_method.apply(
                 router_logits)


---

🏁 Script executed:

```shell
#!/bin/bash
# Locate and inspect the fused_moe_trtllm_gen.py file
find . -type f -name "fused_moe_trtllm_gen.py" 2>/dev/null | head -5

Length of output: 63


🏁 Script executed:

#!/bin/bash
# Show lines 210-240 of fused_moe_trtllm_gen.py to see perfect router context
fd "fused_moe_trtllm_gen.py" --type f --exec sed -n '210,240p' {} \;

Length of output: 1713


🏁 Script executed:

#!/bin/bash
# Show lines 270-310 of fused_moe_trtllm_gen.py to see has_deepseek_fp8_block_scales path
fd "fused_moe_trtllm_gen.py" --type f --exec sed -n '270,310p' {} \;

Length of output: 1718


🏁 Script executed:

#!/bin/bash
# Search for has_deepseek_fp8_block_scales definition and usage patterns
rg "has_deepseek_fp8_block_scales" -n -B2 -A2 --type py | head -50

Length of output: 4494


🏁 Script executed:

#!/bin/bash
# Search for fp8_block_scale_moe_runner to understand kernel interface
rg "fp8_block_scale_moe_runner|fp8BlockScaleMoe" -n -B2 -A2 | head -50

Length of output: 3948



---

🏁 Script executed:

```shell
#!/bin/bash
# Show broader context around perfect router and fp8 blocks (lines 200-350)
sed -n '200,350p' ./tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py

Length of output: 7137


🏁 Script executed:

#!/bin/bash
# Search for all uses of token_selected_experts and token_final_scales in the file
rg "token_selected_experts|token_final_scales" -n ./tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py

Length of output: 1403


🏁 Script executed:

#!/bin/bash
# Inspect the fp8_block_scale_moe_runner custom op implementation in detail
sed -n '553,620p' ./tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py

Length of output: 2203


Add validation to prevent incompatible perfect router + fp8 block scales configuration.

The perfect router feature (lines 217-224) pre-computes routing results for efficiency, but the fp8 block scales path (lines 278-301) performs routing internally via the kernel and ignores pre-computed results. These strategies are incompatible. The conditions that enable each are independent, creating a silent misconfiguration scenario.

         # For TP attention with ENABLE_PERFECT_ROUTER, we need to apply routing to get token_selected_experts
         if not run_post_quant_allgather and enable_perfect_router:
+            if self.has_deepseek_fp8_block_scales:
+                raise ValueError(
+                    "ENABLE_PERFECT_ROUTER is not compatible with fp8_block_scales quantization. "
+                    "The fp8_block_scale_moe_runner performs routing internally and does not accept pre-computed routing results."
+                )
             # Apply routing to get token_selected_experts and token_final_scales for perfect router
             token_selected_experts, token_final_scales = self.routing_method.apply(
                 router_logits)
🧰 Tools
🪛 Gitleaks (8.28.0)

[high] 222-222: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

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.

1 participant