Skip to content

Conversation

@tcherckez-nvidia
Copy link
Collaborator

@tcherckez-nvidia tcherckez-nvidia commented Dec 25, 2025

Summary by CodeRabbit

  • Refactor

    • Restructured Mixture of Experts (MoE) weight handling for improved consistency and simplified weight format support.
    • Enhanced checkpoint loading mechanisms with new state-dict hooks for per-expert weight decomposition.
  • Tests

    • Added comprehensive unit tests for MoE checkpoint loading behavior.
    • Removed deprecated MoE operation tests.

✏️ 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: Tal Cherckez <127761168+tcherckez-nvidia@users.noreply.github.com>
@tcherckez-nvidia tcherckez-nvidia requested a review from a team as a code owner December 25, 2025 08:00
@tcherckez-nvidia
Copy link
Collaborator Author

/bot run

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 25, 2025

📝 Walkthrough

Walkthrough

This pull request refactors MoE (Mixture of Experts) weight handling from dual-format support (stacked/Llama4 weights) to a unified per-expert-list approach. The changes remove stacked weight format code paths, introduce state-dict split hooks for decomposing stacked weights on load, and update MLP construction, fusion logic, and sharding operations accordingly.

Changes

Cohort / File(s) Summary
Core MoE Logic
tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/torch_moe.py
Removed stacked weight format handling and related gating logic. Updated MLP construction to consistently use per-expert weight lists, choosing between gated MLP (W1, W2, W3) and simple two-layer MLP (W_up, W_down) based on is_gated_mlp. Simplified docstrings to reflect per-expert-only approach and clarified routing behavior for apply_routing_on_input.
MoE Fusion & Transformation
tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py
Introduced two state-dict split hooks (_bmm_moe_gate_up_split_hook, _bmm_moe_down_split_hook) to decompose stacked BMM MoE weights into per-expert tensors during load. Refactored _insert_fused_moe_ops to handle both Llama4-style pre-stacked weights and per-expert weight lists via hooks and parameter registration. Added dtype casting and routing-on-input logic. Unified per-node processing with _process_moe_node function.
Sharding Transformation
tensorrt_llm/_torch/auto_deploy/transform/library/sharding.py
Removed _transform_bmm_moe_weight_param, _canonicalize_node_args, and _insert_sharded_moe_stacked functions to eliminate stacked weight handling. Reworked _insert_sharded_moe to assume per-expert weight lists, added local partitioning logic (get_partition) for sharding, and simplified MoE-type inference in detect_ep_shard. Added dead-code elimination and cleanup of temporary attributes.
Unit Tests
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_ad_moe_op.py
Removed import of reference_bmm_moe_torch and deleted test_bmm_based_moe_op_run(dtype) test function, consolidating test coverage to remove BMM-based MoE path testing. Other MoE tests remain unaffected.
New Hook Tests
tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_bmm_moe_hooks.py
Added comprehensive unit test suite covering _bmm_moe_gate_up_split_hook and _bmm_moe_down_split_hook behavior, including stacked weight decomposition, per-expert tensor shape validation, module prefix handling, and end-to-end integration flow. Tests validate tensor contents and transpositions against Llama4 format fixtures.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description contains only the template boilerplate without any actual implementation details, rationale, test coverage, or solution explanation. Fill in the Description section explaining what was changed and why; provide Test Coverage section with relevant test names; complete other checklist items as applicable.
Docstring Coverage ⚠️ Warning Docstring coverage is 68.97% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: standardizing the MoE weights interface by removing dual-format handling and implementing a unified per-expert-list approach.
✨ 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: 3

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/auto_deploy/custom_ops/fused_moe/torch_moe.py (1)

127-149: Inconsistent dtype casting between gated and non-gated MLP paths.

The gated MLP path (lines 134-136) explicitly casts input to weight dtype with inp.to(W1.dtype) and inp.to(W3.dtype), but the non-gated MLP path (line 145) does not perform any dtype casting. This inconsistency could cause dtype mismatch errors when using the non-gated path with mixed precision weights.

🔎 Proposed fix - add dtype casting to non-gated path
     else:
         # Standard per-expert list format with simple MLP
         def make_mlp(i: int):
             W_up = w1_weight[i]  # (I, H)
             W_down = w2_weight[i]  # (H, I)
-            return lambda inp: F.linear(torch_act_fn(F.linear(inp, W_up)), W_down)
+            return lambda inp: F.linear(torch_act_fn(F.linear(inp.to(W_up.dtype), W_up)), W_down)

         mlps = [make_mlp(i) for i in range(len(w1_weight))]
🧹 Nitpick comments (4)
tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py (1)

51-51: Consider adding strict=True to zip() for safety.

Since w1_keys and w3_keys should always have the same length as the number of experts, adding strict=True would catch any mismatch early.

🔎 Proposed fix
-        for w1_key, w3_key, w1, w3 in zip(w1_keys, w3_keys, w1_experts, w3_experts):
+        for w1_key, w3_key, w1, w3 in zip(w1_keys, w3_keys, w1_experts, w3_experts, strict=True):
tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_bmm_moe_hooks.py (1)

12-27: Consider parameterizing fixtures for broader coverage.

The fixtures use fixed dimensions. While the parameterized tests in the class cover different configurations, the standalone fixtures (gate_up_stacked_weight, down_stacked_weight) could benefit from parameterization if they're meant to be used more broadly.

tensorrt_llm/_torch/auto_deploy/transform/library/sharding.py (1)

1448-1448: Cosmetic: Ambiguous multiplication sign in comment.

The comment uses × (Unicode multiplication sign) instead of x. While this doesn't affect functionality, it could cause issues with some editors or search tools.

🔎 Proposed fix
-    for i in range(len(scale_names) * 3):  # 3 layers (w1, w2, w3) × #scale_names per layer
+    for i in range(len(scale_names) * 3):  # 3 layers (w1, w2, w3) x #scale_names per layer
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_ad_moe_op.py (1)

65-104: Remove setup_bmm_moe_test fixture as it is unused.

The setup_bmm_moe_test function (lines 65–104) is no longer called anywhere in the codebase after the removal of test_bmm_based_moe_op_run. Delete this function to eliminate dead code.

📜 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 182b3eb and 0e9e674.

📒 Files selected for processing (5)
  • tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/torch_moe.py
  • tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py
  • tensorrt_llm/_torch/auto_deploy/transform/library/sharding.py
  • tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_ad_moe_op.py
  • tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_bmm_moe_hooks.py
🧰 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:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_bmm_moe_hooks.py
  • tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_ad_moe_op.py
  • tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/torch_moe.py
  • tensorrt_llm/_torch/auto_deploy/transform/library/sharding.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:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_bmm_moe_hooks.py
  • tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_ad_moe_op.py
  • tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/torch_moe.py
  • tensorrt_llm/_torch/auto_deploy/transform/library/sharding.py
  • tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py
🧠 Learnings (10)
📓 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.
📚 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_ad_moe_op.py
📚 Learning: 2025-08-27T16:22:10.695Z
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.

Applied to files:

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

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_ad_moe_op.py
  • tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/torch_moe.py
  • tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py
📚 Learning: 2025-08-20T07:43:36.447Z
Learnt from: ChristinaZ
Repo: NVIDIA/TensorRT-LLM PR: 7068
File: cpp/tensorrt_llm/kernels/moeTopKFuncs.cuh:169-172
Timestamp: 2025-08-20T07:43:36.447Z
Learning: In TensorRT-LLM MOE kernels, when processing up to 128 experts across 32 threads, each thread handles at most 4 experts (N < 5 constraint), where N represents candidates per thread rather than total system capacity.

Applied to files:

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

  • tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/torch_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:

  • tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/torch_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/custom_ops/fused_moe/torch_moe.py
  • tensorrt_llm/_torch/auto_deploy/transform/library/fused_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:

  • tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/torch_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:

  • tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/torch_moe.py
🧬 Code graph analysis (3)
tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_bmm_moe_hooks.py (1)
tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py (2)
  • _bmm_moe_down_split_hook (56-77)
  • _bmm_moe_gate_up_split_hook (24-53)
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_ad_moe_op.py (1)
tests/unittest/_torch/helpers.py (1)
  • reference_moe_torch (96-121)
tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py (2)
tensorrt_llm/_torch/auto_deploy/utils/node_utils.py (3)
  • is_op (219-242)
  • extract_op_args (557-594)
  • shape (920-923)
tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/torch_moe.py (1)
  • torch_moe (90-149)
🪛 Ruff (0.14.10)
tensorrt_llm/_torch/auto_deploy/transform/library/sharding.py

1448-1448: Comment contains ambiguous × (MULTIPLICATION SIGN). Did you mean x (LATIN SMALL LETTER X)?

(RUF003)

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

27-27: Unused function argument: args

(ARG001)


51-51: zip() without an explicit strict= parameter

Add explicit value for parameter strict=

(B905)


59-59: Unused function argument: args

(ARG001)


76-76: zip() without an explicit strict= parameter

Add explicit value for parameter strict=

(B905)


1169-1171: Avoid specifying long messages outside the exception class

(TRY003)


1179-1182: 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)
tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py (3)

100-119: LGTM - Clean refactoring of MoE node processing.

The extraction of the processing loop with immediate dead code elimination is a good pattern for managing GPU memory during large model transformations.


186-224: Dtype casting and routing logic look correct.

The dtype handling ensures activation dtype matches weight dtype for the fused kernel, and the apply_routing_on_input logic correctly substitutes ones_like to prevent double-application of routing weights.


996-1020: Good defensive validation for Llama4-shaped weights.

The shape validation ensures the BMM MoE pattern only matches tensors with the expected dimensional relationships before proceeding with the transformation.

tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_ad_moe_op.py (1)

4-4: Import change looks correct.

The import now correctly references only reference_moe_torch which is used by the remaining tests.

tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/torch_moe.py (1)

112-124: Docstring updates are clear and accurate.

The updated parameter documentation correctly describes the per-expert weight list format and the routing behavior options.

tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_bmm_moe_hooks.py (1)

1-249: Comprehensive test coverage for new BMM MoE hooks.

The test suite provides good coverage including:

  • Parameterized tests for various expert/dimension configurations
  • Content validation ensuring correct tensor splitting and transposition
  • Edge case handling for missing source keys
  • Module prefix handling
  • Integration test for the complete flow

Note: These tests confirm the hooks work without num_experts parameter, which indicates the partial() calls in fused_moe.py that pass num_experts are incorrect.

tensorrt_llm/_torch/auto_deploy/transform/library/sharding.py (4)

1401-1412: Clean partition helper with correct remainder handling.

The get_partition function correctly handles the case where num_experts % world_size != 0 by assigning remainder experts to the last rank.


1466-1470: Good cleanup of unused expert weights.

The code properly eliminates dead code and removes the unused expert weight attributes, which is important for memory management with large MoE models.


2448-2451: MLPType inference logic is straightforward.

The heuristic checking if args[5] (w3_weight/gate list) is non-empty to determine GATED_MLP vs MLP is clear and aligns with the per-expert weight list convention.


1414-1416: Code correctly handles uneven expert distribution; no action needed.

The code already explicitly accounts for cases where ep_size doesn't evenly divide num_experts. The get_partition function (lines 1406–1410) assigns remaining experts to the last rank via conditional logic. Similarly, the selected_experts sharding (lines 1383–1384) uses torch.ge for the last rank instead of torch.eq, correctly masking experts for the asymmetric case. The final_scales follow the same logic. Downstream all_reduce (line 1458) sums outputs across ranks, which is mathematically correct regardless of asymmetry.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29928 [ run ] triggered by Bot. Commit: 0e9e674

Signed-off-by: Tal Cherckez <127761168+tcherckez-nvidia@users.noreply.github.com>
@tcherckez-nvidia
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29935 [ run ] triggered by Bot. Commit: 90af55f

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29935 [ run ] completed with state SUCCESS. Commit: 90af55f
/LLM/main/L0_MergeRequest_PR pipeline #23024 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

Copy link
Collaborator

@greg-kwasniewski1 greg-kwasniewski1 left a comment

Choose a reason for hiding this comment

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

LGTM

Copy link
Member

@lucaslie lucaslie left a comment

Choose a reason for hiding this comment

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

Overall interface looks good!


# Now create get_attr nodes for each expert weight
# These must be created within the insertion context for proper graph ordering
with graph.inserting_before(output_node):
Copy link
Member

Choose a reason for hiding this comment

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

Let's insert them with the other get_attr nodes. The graph is usually sorted such that all input nodes appear first, then all the get_attr nodes, then all the compute nodes.

You can get the last get_attr node like this:

last_get_attr_node = graph.find_nodes(target="get_attr")[-1]

Comment on lines +1466 to +1471
gm.graph.eliminate_dead_code()
for expert in (
w_up_list_to_remove + w_down_list_to_remove + w_gate_list_to_remove + scales_to_remove
):
delattr(gm, expert.target)

Copy link
Member

Choose a reason for hiding this comment

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

why is this explicit clean up needed rather than using the generic utility in the outer call function?

Comment on lines +2450 to +2451
if args[5] and len(args[5]) > 0:
mlp_type = MLPType.GATED_MLP
Copy link
Member

Choose a reason for hiding this comment

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

why not use the argument that you now have for this?

Copy link
Member

Choose a reason for hiding this comment

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

can we now also remove torch_moe_dense_mlp ? I see it's still being used in mxfp4_moe.py

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