Skip to content

Conversation

@ChristinaZ
Copy link
Collaborator

@ChristinaZ ChristinaZ commented Sep 26, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Resolved inconsistencies in padding and routing across quantized MoE modes, improving stability in FP8 block-scale and mixed-precision configurations.
    • Corrected handling when distributed post-quantization gathering is enabled to avoid double-padding and ensure consistent input widths.
  • Improvements

    • Enhanced compatibility and accuracy by passing top-k routing data through quantized execution paths.
    • Streamlined logic for distributed quantization to reduce edge-case errors.
  • Tests

    • Re-enabled a previously skipped FP8 throughput test, increasing coverage.

Description

Fix the bug related to the fp8 post quant allgather for MoE TRTLLM backend

Test Coverage

pytest -s -o log_cli=true "tests/integration/defs/accuracy/test_llm_api_pytorch.py::TestDeepSeekR1::test_fp8_blockscale[throughput_mtp_trtllm]"

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.

Details

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.

@ChristinaZ ChristinaZ requested a review from a team as a code owner September 26, 2025 00:21
@ChristinaZ ChristinaZ requested review from QiJune and pengbowang-nv and removed request for QiJune September 26, 2025 00:21
@ChristinaZ ChristinaZ changed the title [https://nvbugs/5537738][fix] Add fp8 post quant allgather support [https://nvbugs/5537738][fix] Add fp8 post-quant allgather support Sep 26, 2025
@ChristinaZ
Copy link
Collaborator Author

/bot run

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 26, 2025

📝 Walkthrough

Walkthrough

Refactors fused MoE generation flow to simplify post-quant allgather gating, add explicit branches for DeepSeek FP8 and W4A16 MXFP4 (including conditional padding), adjust router/quantization inputs when allgather is enabled, and pass top-k routing data to FP8-related MoE runners. Removes a corresponding test waive entry.

Changes

Cohort / File(s) Summary of Changes
Fused MoE TRT-LLM generation logic
tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py
Simplified run_post_quant_allgather condition; added branches for has_deepseek_fp8_block_scales (no-op) and has_w4a16_mxfp4 with conditional padding; avoided double-padding when allgather active; routed router_logits/routing_bias as None when allgather active; passed topk_weights/topk_ids to FP8 and MXE2M1 runners.
Integration test waives
tests/integration/test_lists/waives.txt
Removed SKIP for accuracy/test_llm_api_pytorch.py::TestDeepSeekR1::test_fp8_blockscale[throughput_mtp_trtllm].

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Caller
  participant F as FusedMoE (gen)
  participant R as Router/Quant
  participant M as MoE Runner

  C->>F: forward(x, config, use_dp, parallel_size, ...)
  Note over F: Compute run_post_quant_allgather = use_dp && parallel_size>1

  alt has_w4a16_mxfp4
    F->>F: Compute pad_size from w3_w1_weight & x.shape[-1]
    alt pad needed AND NOT run_post_quant_allgather
      F->>F: Pad x (and related tensors)
    else No pad or allgather active
      Note over F: Preserve input width
    end
  else has_deepseek_fp8_block_scales
    Note over F: No-op branch for block scales
  end

  F->>R: Prepare routing/quantization
  alt run_post_quant_allgather == true
    Note over R: Post-quant allgather path
    F->>M: router_logits=None, routing_bias=None, topk_ids, topk_weights
  else run_post_quant_allgather == false
    F->>M: router_logits, routing_bias, topk_ids, topk_weights
  end

  alt FP8 (DeepSeek) or BF16 MXE2M1 path
    Note over M: Pass topk_ids/topk_weights to runner
  else Other modes
    Note over M: Standard execution
  end

  M-->>C: outputs
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
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 (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title clearly references the relevant NVBugs ID, correctly uses the “[fix]” type, and concisely summarizes adding FP8 post-quant allgather support, which is the primary change in this PR.
Description Check ✅ Passed The PR description follows the repository template by providing a clear “Description” of the bug fix, listing the specific test in “Test Coverage,” and including the standard “PR Checklist” and GitHub Bot Help sections, while leveraging the @coderabbitai summary marker for automated summary insertion.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

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

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

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

Please see the documentation for more information.

Example:

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

Please share your feedback with us on this Discord post.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

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

⚠️ Outside diff range comments (1)
tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py (1)

269-289: Pass float32 top‑k weights into DeepSeek FP8 runner

fp8_block_scale_moe_runner still reinterprets its top‑k weights buffer as float*. We now pass token_final_scales.to(torch.bfloat16) when run_post_quant_allgather is true, so the kernel consumes BF16 data via a float pointer, yielding corrupted gating probabilities and wrong expert activation. Keep token_final_scales in float32 for this path (and do so before the allgather to avoid mixed dtypes).

Apply:

-        token_selected_experts, token_final_scales = self.routing_method.apply(
-            router_logits)
-        token_final_scales = token_final_scales.to(torch.bfloat16)
+        token_selected_experts, token_final_scales = self.routing_method.apply(
+            router_logits)
+        if not self.has_deepseek_fp8_block_scales:
+            token_final_scales = token_final_scales.to(torch.bfloat16)

This keeps the DeepSeek FP8 path in float32 while preserving the BF16 downcast for other modes that require it. Based on learnings.

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

341-345: Remove redundant no‑op assignment

x = x inside the else adds noise without value. Please drop it.

Apply:

-            else:
-                x = x
📜 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 1eb6531 and 3983d93.

📒 Files selected for processing (2)
  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py (6 hunks)
  • tests/integration/test_lists/waives.txt (0 hunks)
💤 Files with no reviewable changes (1)
  • tests/integration/test_lists/waives.txt
🧰 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 (4)
📓 Common learnings
Learnt from: jhaotingc
PR: NVIDIA/TensorRT-LLM#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
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-09-19T21:28:13.751Z
Learnt from: jhaotingc
PR: NVIDIA/TensorRT-LLM#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-14T23:23:27.449Z
Learnt from: djns99
PR: NVIDIA/TensorRT-LLM#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-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:

  • 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/modules/fused_moe/interface.py (2)
  • has_deepseek_fp8_block_scales (290-293)
  • has_w4a16_mxfp4 (314-317)
tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py (1)
  • bf16_mxe2m1_block_scale_moe_runner (1355-1434)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Check PR Title Format
  • GitHub Check: Check PR Checklist Resolution
  • GitHub Check: Pre-commit Check

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20004 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@ChristinaZ
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20029 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@ChristinaZ
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20034 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

Signed-off-by: Christina Zhang <83400082+ChristinaZ@users.noreply.github.com>
@ChristinaZ
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20057 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@ChristinaZ
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20100 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@ChristinaZ ChristinaZ merged commit 95eac2c into NVIDIA:main Sep 28, 2025
5 checks passed
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Nov 1, 2025
…VIDIA#8008)

Signed-off-by: Christina Zhang <83400082+ChristinaZ@users.noreply.github.com>
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Nov 3, 2025
…VIDIA#8008)

Signed-off-by: Christina Zhang <83400082+ChristinaZ@users.noreply.github.com>
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Nov 3, 2025
…VIDIA#8008)

Signed-off-by: Christina Zhang <83400082+ChristinaZ@users.noreply.github.com>
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Nov 3, 2025
…VIDIA#8008)

Signed-off-by: Christina Zhang <83400082+ChristinaZ@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.

4 participants