Skip to content

Conversation

@nzmora-nvidia
Copy link
Collaborator

@nzmora-nvidia nzmora-nvidia commented Dec 18, 2025

The trtllm (cutlass) fp8 moe operator performs W3+W1 fusion (concat) during inference and we want to move this fusion to the model optimization time.

Summary by CodeRabbit

Release Notes

  • API Changes

    • Updated MoE fusion function signatures: consolidated weight parameters into fc1_expert_weights and fc2_expert_weights with new quantization scale arguments for improved consistency and flexibility.
  • Chores

    • Added VSCode Python debugger support for development workflows.

✏️ Tip: You can customize this high-level summary in your review settings.

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

  • Update tava architecture diagram if there is a significant design change in PR.

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

Signed-off-by: Neta Zmora <[email protected]>
Signed-off-by: Neta Zmora <[email protected]>
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 18, 2025

📝 Walkthrough

Walkthrough

Refactors MOE weight and scale parameter signatures from per-weight naming (w1/w2/w3) to FC layer naming (fc1/fc2) across custom operators, FX graph transformation, and tests. Updates internal argument handling, weight stacking helpers, and quantization logic to use the new parameter names. Adds VSCode debugger support in worker startup.

Changes

Cohort / File(s) Change Summary
MOE Custom Ops and Tests
tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.py, tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
Renamed trtllm_moe_fused() and trtllm_quant_fp8_moe_fused() function signatures, replacing per-weight arguments (w1_weight, w2_weight, w3_weight, and associated input/weight scales) with consolidated FC layer arguments (fc1_expert_weights, fc2_expert_weights, fc1_act_scale, fc1_dequant_scale, fc2_act_scale_reciprocal, fc2_dequant_scale). Updated fake registration functions and quantization logic to match new parameter names and handle mlp_style conditional branching.
FP8 MOE Library Transformation
tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py
Refactored _stack_fp8_moe_weights() with new internal helpers: _register_parameter(), get_param_or_buffer(), _extract_op_args(), _stack(), _prepare_args_cutlass_format(), and _prepare_args_triton_format(). Centralizes weight/scale extraction, stacking, and backend-specific argument preparation for both Cutlass and Triton paths. Replaces direct parameter access with robust parameter-vs-buffer handling via FX graph queries. Adds dtype consistency checks and incremental fusion with proper parameter registration and retrieval.
Worker Debugger Support
tensorrt_llm/executor/worker.py
Adds VSCode Python debugger initialization in worker_main() for rank 0 processes: transfers VSCODE_DEBUGPY_ADAPTER_ENDPOINTS to DEBUGPY_ADAPTER_ENDPOINTS environment variable, starts debugpy listener on ephemeral port, and waits for client attachment before proceeding with standard initialization.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Areas requiring extra attention:

  • Parameter propagation consistency: Verify that fc1/fc2 weight and scale parameters are correctly mapped across custom ops, FX graph transformation, and test cases, particularly for mlp_style conditional branching (mlp vs. gated variants)
  • Weight stacking logic: Review new helper functions (_stack(), _prepare_args_cutlass_format(), _prepare_args_triton_format()) in fused_moe.py for correct tensor stacking, dtype alignment, and quantization scale handling
  • Test coverage: Ensure test cases properly exercise both mlp_style branches and validate correct weight/scale selection (w1_weight vs. w31_weight for fc1_expert_weights)
  • Quantization semantics: Confirm scale application changes (fc1_dequant_scale, fc2_act_scale_reciprocal) maintain correct FP8 quantization behavior across gated and standard MLP paths

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.27% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description check ⚠️ Warning PR description lacks critical required sections: missing detailed Description section explaining the issue and solution, missing Test Coverage section listing relevant tests, and PR Checklist items only partially completed. Complete the PR description with: (1) a detailed 'Description' section explaining why W3+W1 fusion should move to optimization time, (2) a 'Test Coverage' section listing specific test files and test cases that validate this refactor, and (3) verification of all PR Checklist items with proper documentation.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: refactoring AutoDeploy's FP8 MoE implementation to move weight fusion from inference to optimization time.
✨ 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: 0

🧹 Nitpick comments (3)
tensorrt_llm/executor/worker.py (1)

247-256: Consider adding timeout and clarifying TODOs.

The debugging helper will block rank 0 indefinitely until a debugger connects. This could cause confusing hangs if the environment variable is accidentally left set in production.

Consider:

  1. Adding a timeout parameter to debugpy.wait_for_client() to prevent indefinite blocking
  2. Resolving the TODOs:
    • Is debugpy.listen(0) necessary? (The VSCode docs suggest it is required before wait_for_client())
    • Should this use env parameter in MpiPoolExecutor instead of runtime env manipulation?
  3. Adding a log message to indicate that the worker is waiting for debugger attachment
🔎 Suggested improvements
     if mpi_rank() == 0 and "VSCODE_DEBUGPY_ADAPTER_ENDPOINTS" in os.environ:
         # cf. https://github.com/microsoft/vscode-python-debugger/blob/f64b217c4d2445f7f55255b102de1d94c19cf450/bundled/scripts/noConfigScripts/debugpy#L4
         os.environ["DEBUGPY_ADAPTER_ENDPOINTS"] = os.environ[
             "VSCODE_DEBUGPY_ADAPTER_ENDPOINTS"]
-        # TODO: is listen() needed?
-        # TODO: Could use 'env' in MpiPoolExecutor instead (and if-env-contains-vscode...)
         import debugpy
         debugpy.listen(0)
+        logger.info("Rank 0 waiting for VSCode debugger to attach...")
-        debugpy.wait_for_client()
+        debugpy.wait_for_client()  # listen() is required before wait_for_client()
tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py (2)

1281-1292: Consider explicit error handling for invalid parameter/buffer targets.

The get_param_or_buffer function could raise various exceptions if the target doesn't exist as either a parameter or buffer. While this may be acceptable if the caller guarantees valid targets, explicit error handling would make debugging easier.

🔎 Suggested improvement
 def get_param_or_buffer(target):
     """Get parameter or buffer by target name."""
     try:
         return gm.get_parameter(target)
     except AttributeError:
         # It's a buffer, not a parameter
-        parts = target.rsplit(".", 1)
-        if len(parts) == 2:
-            mod = gm.get_submodule(parts[0])
-            return getattr(mod, parts[1])
-        else:
-            return getattr(gm, target)
+        try:
+            parts = target.rsplit(".", 1)
+            if len(parts) == 2:
+                mod = gm.get_submodule(parts[0])
+                return getattr(mod, parts[1])
+            else:
+                return getattr(gm, target)
+        except (AttributeError, KeyError) as e:
+            raise RuntimeError(f"Could not find parameter or buffer '{target}'") from e

1458-1463: Good runtime validation for scale consistency.

The assertions ensure that all experts use the same input scales, which is a critical assumption since only the first element ([0]) is used in subsequent computations. This catches configuration errors early.

However, consider whether these should be runtime assertions or validation checks that provide more actionable error messages:

🔎 Alternative validation approach
-        assert torch.all(w1_input_scale_stacked[0] == w1_input_scale_stacked), (
-            "All w1 scales should have the same value."
-        )
-        assert torch.all(w2_input_scale_stacked[0] == w2_input_scale_stacked), (
-            "All w2 scales should have the same value."
-        )
+        if not torch.all(w1_input_scale_stacked[0] == w1_input_scale_stacked):
+            raise ValueError(
+                f"All fc1 input scales must be identical across experts. "
+                f"Got scales: {w1_input_scale_stacked}"
+            )
+        if not torch.all(w2_input_scale_stacked[0] == w2_input_scale_stacked):
+            raise ValueError(
+                f"All fc2 input scales must be identical across experts. "
+                f"Got scales: {w2_input_scale_stacked}"
+            )
📜 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 f02782a and ae8b30a.

📒 Files selected for processing (4)
  • tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.py (3 hunks)
  • tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py (3 hunks)
  • tensorrt_llm/executor/worker.py (1 hunks)
  • tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: Code developed for TensorRT-LLM should conform to Python 3.8+
Indent Python code with 4 spaces. Do not use tabs
Always maintain the namespace when importing in Python, even if only one class or function from a module is used
Python files should use snake_case naming: some_file.py
Python classes should use PascalCase naming: class SomeClass
Python functions and methods should use snake_case naming: def my_awesome_function():
Python local variables should use snake_case naming: my_variable = ...
Python variable names that start with a number should be prefixed with 'k': k_99th_percentile = ...
Python global variables should use upper snake_case with prefix 'G': G_MY_GLOBAL = ...
Python constants should use upper snake_case naming: MY_CONSTANT = ...
Avoid shadowing variables declared in an outer scope in Python
Initialize all externally visible members of a Python class in the constructor
For Python interfaces that may be used outside a file, prefer docstrings over comments
Python comments should be reserved for code within a function, or interfaces that are local to a file
Use Google style docstrings in Python for classes and functions, which can be parsed by Sphinx
Python attributes and variables can be documented inline with type and description
Avoid using reflection in Python when functionality can be easily achieved without reflection
When using try-except blocks in Python, limit the except to the smallest set of errors possible
When using try-except blocks in Python to handle multiple possible variable types (duck-typing), keep the body of the try as small as possible, using the else block for logic

Files:

  • tensorrt_llm/executor/worker.py
  • tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
  • tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.py
  • tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py
**/*.{cpp,h,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

All TensorRT-LLM Open Source Software code should contain an NVIDIA copyright header that includes the year of its latest meaningful modification

Files:

  • tensorrt_llm/executor/worker.py
  • tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
  • tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.py
  • tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py
🧠 Learnings (12)
📓 Common learnings
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.
Learnt from: Fridah-nv
Repo: NVIDIA/TensorRT-LLM PR: 7227
File: tensorrt_llm/_torch/auto_deploy/utils/quantization_utils.py:94-100
Timestamp: 2025-08-27T16:22:10.695Z
Learning: When there are inconsistent operator detection methods (like custom_op() vs target_op()), removing one method and standardizing on the other is often cleaner than supporting both methods simultaneously.
📚 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:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
  • tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.py
  • tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py
📚 Learning: 2025-11-14T11:22:03.729Z
Learnt from: nzmora-nvidia
Repo: NVIDIA/TensorRT-LLM PR: 9163
File: tensorrt_llm/_torch/auto_deploy/custom_ops/quant.py:107-113
Timestamp: 2025-11-14T11:22:03.729Z
Learning: In TensorRT-LLM AutoDeploy custom ops, when adding hardware capability checks to select between kernel implementations (e.g., cuBLAS vs. CUDA kernel), use descriptive variable names that identify the specific GPU architectures or families being targeted (e.g., `is_blackwell_geforce_or_ada`) rather than generic names like `enable_cuda_core`. This makes it clear that the code is selecting an implementation path based on hardware capabilities, not enabling/disabling hardware features.

Applied to files:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
  • tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.py
📚 Learning: 2025-08-21T02:39:12.009Z
Learnt from: djns99
Repo: NVIDIA/TensorRT-LLM PR: 7104
File: cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cu:1475-1480
Timestamp: 2025-08-21T02:39:12.009Z
Learning: The min latency mode functionality in TensorRT-LLM MOE kernels (cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cu) is deprecated and no longer being maintained/updated, as confirmed by djns99. Bug reports and optimization suggestions for the computeStridesTmaWarpSpecializedLowLatencyKernel and related min latency code paths should be deprioritized.

Applied to files:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
  • tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.py
  • tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.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:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
  • tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.py
  • tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py
📚 Learning: 2025-10-20T16:54:09.824Z
Learnt from: nvchenghaoz
Repo: NVIDIA/TensorRT-LLM PR: 8469
File: tensorrt_llm/_torch/auto_deploy/custom_ops/rms_norm.py:6-6
Timestamp: 2025-10-20T16:54:09.824Z
Learning: In tensorrt_llm/_torch/auto_deploy/custom_ops/rms_norm.py, the import `from ...modules.mamba.layernorm_gated import _layer_norm_fwd` is correct and should not be changed to modules.fla.layernorm_gated. The _layer_norm_fwd function exists in both modules/mamba/layernorm_gated.py and modules/fla/layernorm_gated.py, but the mamba version is the intended implementation for this use case.

Applied to files:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
  • tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.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:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
  • tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py
📚 Learning: 2025-10-20T17:09:21.560Z
Learnt from: nvchenghaoz
Repo: NVIDIA/TensorRT-LLM PR: 8469
File: tensorrt_llm/_torch/auto_deploy/transform/library/rms_norm.py:180-182
Timestamp: 2025-10-20T17:09:21.560Z
Learning: In tensorrt_llm/_torch/auto_deploy/transform/library/rms_norm.py, the _gated_rmsnorm_replacement function does not need to cast the output of torch.ops.auto_deploy.torch_rmsnorm_gated back to the input dtype, even though the custom op returns fp32. The dtype handling is managed elsewhere or the fp32 output is acceptable for downstream consumers.

Applied to files:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
📚 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:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
  • tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.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:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
  • tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.py
📚 Learning: 2025-08-19T03:35:20.866Z
Learnt from: djns99
Repo: NVIDIA/TensorRT-LLM PR: 6915
File: cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cu:4616-4626
Timestamp: 2025-08-19T03:35:20.866Z
Learning: In the MOE profiler TMA workspace preparation (cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cu), the overlapping of TMA WS regions for NONE and FINALIZE variants is deliberate design to save memory space, as confirmed by djns99. The comment "reuse the same pointers to save space" reflects this intentional behavior.

Applied to files:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
  • tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py
📚 Learning: 2025-10-20T17:07:18.745Z
Learnt from: nvchenghaoz
Repo: NVIDIA/TensorRT-LLM PR: 8469
File: tensorrt_llm/_torch/auto_deploy/models/patches/nemotron_h.py:98-116
Timestamp: 2025-10-20T17:07:18.745Z
Learning: In NemotronH models (tensorrt_llm/_torch/auto_deploy/models/patches/nemotron_h.py), the gate (self.gate) returns topk_indices and topk_weights that are already in the correct shape to be passed directly to torch_ops.auto_deploy.torch_moe without needing to reshape them when hidden_states is flattened.

Applied to files:

  • tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py
🧬 Code graph analysis (4)
tensorrt_llm/executor/worker.py (1)
tensorrt_llm/_utils.py (1)
  • mpi_rank (527-534)
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py (1)
tensorrt_llm/_torch/modules/fused_moe/configurable_moe.py (1)
  • w2_weight (1046-1048)
tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.py (1)
tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/triton_moe.py (1)
  • _quantize_fp8 (643-647)
tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py (3)
tensorrt_llm/module.py (1)
  • register_parameter (186-190)
tensorrt_llm/_torch/auto_deploy/utils/node_utils.py (2)
  • extract_op_args (535-572)
  • is_op (198-221)
tensorrt_llm/functional.py (1)
  • stack (1961-2007)
🪛 Ruff (0.14.8)
tensorrt_llm/executor/worker.py

253-253: Import for debugpy found

(T100)


254-254: Trace found: debugpy.listen used

(T100)


255-255: Trace found: debugpy.wait_for_client used

(T100)

tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.py

230-230: Unused function argument: fc1_expert_weights

(ARG001)


231-231: Unused function argument: fc2_expert_weights

(ARG001)


232-232: Unused function argument: fc1_act_scale

(ARG001)


233-233: Unused function argument: gemm1_dequant

(ARG001)


234-234: Unused function argument: gemm2_act_quant

(ARG001)


235-235: Unused function argument: gemm2_dequant

(ARG001)

tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py

1330-1330: Avoid specifying long messages outside the exception class

(TRY003)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Pre-commit Check
🔇 Additional comments (10)
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py (1)

415-425: LGTM! Test correctly reflects the new fc1/fc2 parameter naming.

The test properly exercises the mlp_style-driven selection of fc1_expert_weights and uses the new scale parameter names (fc1_act_scale, fc1_dequant_scale, fc2_act_scale_reciprocal, fc2_dequant_scale) that align with the refactored API.

tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.py (4)

128-155: LGTM! Docstring accurately describes the refactored API.

The updated documentation clearly explains the FC1/FC2 layer semantics, weight shapes, and the distinction between gated_mlp and mlp styles. The notes about precomputed scale arguments are helpful for understanding the optimization.


212-214: LGTM! Contiguous memory layout ensures kernel compatibility.

Calling .contiguous() on fc2_expert_weights before passing to the TensorRT-LLM kernel is appropriate, as CUTLASS kernels typically require contiguous memory layouts.


230-238: LGTM! Fake registration correctly matches the updated API.

The fake implementation's signature matches the real function, and it appropriately validates mlp_style and act_fn before returning a dummy tensor. The Ruff warnings about unused arguments are expected for fake implementations and can be safely ignored.


119-124: Add assertions to validate all scale tensor shapes before use.

Lines 177-178 only assert that fc1_dequant_scale and fc2_dequant_scale are 1D tensors. However, fc1_act_scale and fc2_act_scale_reciprocal are also used as scale parameters without shape validation. Add assertions to verify fc1_act_scale is 1D (per docstring at line 146) and fc2_act_scale_reciprocal is 1D before they are used in _quantize_fp8 at line 163 and assembled into quant_scales at line 179.

⛔ Skipped due to learnings
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.
tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py (5)

1312-1315: LGTM! Clean weight stacking implementation.

The _stack helper efficiently stacks weights from the parameter list and ensures contiguous memory layout, which is essential for kernel compatibility.


1317-1366: LGTM! Cutlass format argument preparation is well-structured.

The function correctly:

  1. Handles both gated_mlp (concatenates w3+w1) and mlp (uses w1 only) styles
  2. Precomputes scale combinations to avoid runtime overhead
  3. Registers stacked tensors with unique keys
  4. Builds the argument tuple within the proper graph insertion context

The precomputed scales match the documentation in trtllm_moe.py.


1418-1421: Good optimization: pre-filtering matched nodes.

Creating a list of matched nodes upfront (line 1418-1420) before iterating is more efficient than checking is_op for every node in the graph. This avoids redundant checks during the loop.


1494-1503: LGTM! Proper cleanup after transformation.

The code correctly:

  1. Replaces the old node with the new fused node
  2. Erases the old node from the graph
  3. Eliminates dead code after all nodes are processed
  4. Deletes unused submodules/parameters

This cleanup strategy is appropriate for the transformation and matches the pattern in _insert_fused_moe_ops.


1479-1483: Ensure Triton backend supports all mlp_style variants or add validation.

The code prepares arguments differently for Cutlass (trtllm) vs Triton backends. However, the Triton backend (torch.ops.auto_deploy.triton_quant_fp8_moe) only supports mlp_style=="mlp" and will raise NotImplementedError for gated_mlp. The _prepare_args_triton_format() function should either validate that only supported styles are passed or ensure the backend can handle all variants that the Cutlass path supports.

@nzmora-nvidia
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29034 [ run ] triggered by Bot. Commit: 61ea54f

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29034 [ run ] completed with state SUCCESS. Commit: 61ea54f
/LLM/main/L0_MergeRequest_PR pipeline #22255 completed with status: 'FAILURE'

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

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.

2 participants