-
Notifications
You must be signed in to change notification settings - Fork 1.8k
DO NOT REVIEW YET #8954
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
DO NOT REVIEW YET #8954
Conversation
Signed-off-by: Neta Zmora <[email protected]>
Signed-off-by: Neta Zmora <[email protected]>
📝 WalkthroughWalkthroughThis PR introduces Relu² activation support and FP8 quantization infrastructure for mixture-of-experts (MoE) operations. Changes span kernel implementations, C++ runners, and PyTorch bindings, adding new Changes
Sequence Diagram(s)sequenceDiagram
participant Caller as PyTorch Caller
participant PyOps as torch_custom_ops.py
participant MoeRunner as MoERunner
participant Dispatch as moe_dispatch
participant Kernel as CUTLASS Kernel
Caller->>PyOps: fused_moe(..., activation_type=Relu2)
PyOps->>PyOps: Convert activation_type to enum
PyOps->>MoeRunner: __init__(activation_type=Relu2)
MoeRunner->>MoeRunner: Store self.activation_type
MoeRunner->>Dispatch: forward(activation_type=Relu2)
rect rgb(200, 220, 255)
note right of Dispatch: Activation Dispatch
Dispatch->>Dispatch: Switch on activation_type
alt activation_type == Relu2
Dispatch->>Kernel: Select Relu2 Kernel
else activation_type == Swiglu (default)
Dispatch->>Kernel: Select Swiglu Kernel
else Other
Dispatch->>Kernel: Select Corresponding Kernel
end
end
Kernel->>Kernel: Apply Relu2 (ReLU + Square)
Kernel-->>Dispatch: Output
Dispatch-->>MoeRunner: Result
MoeRunner-->>PyOps: Result
PyOps-->>Caller: Output Tensor
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes
Areas requiring extra attention:
Possibly related PRs
Suggested reviewers
Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 7
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
cpp/tensorrt_llm/thop/moeOp.cpp (2)
331-355: Block invalid enum values; align INT8 WOQ dim check with gated/ungated activations.
- Casting int64_t → ActivationType without validation can pass an out‑of‑range value that later indexes activation tables in kernels. Add a guard.
- For mUseINT8WoqPerChannel, the inter-size check always enforces “×2” (GLU). It should mirror the new gated/ungated logic used below.
Apply:
- ActivationType base_activation_type = activation_type.has_value() - ? static_cast<ActivationType>(activation_type.value()) - : ActivationType::Swiglu; + ActivationType base_activation_type = ActivationType::Swiglu; + if (activation_type.has_value()) + { + auto act = static_cast<ActivationType>(activation_type.value()); + switch (act) + { + case ActivationType::Gelu: + case ActivationType::Relu: + case ActivationType::SiLu: + case ActivationType::Swiglu: + case ActivationType::Geglu: + case ActivationType::SwigluBias: + case ActivationType::Relu2: + case ActivationType::Identity: + base_activation_type = act; + break; + default: + TORCH_CHECK(false, "Invalid activation_type value: ", activation_type.value()); + } + } @@ - if (mUseINT8WoqPerChannel) - { - // Note: The weight shape for INT8 weight only quantization is different, e.g., fc2_expert_weights: - // [num_experts, inter_size, hidden_size] - TORCH_CHECK(fc1_expert_weights.sizes()[2] == fc2_expert_weights.sizes()[1] * mInnerDimMultiplier * 2, - "fc1_expert_weights inter size must be 2 times fc2_expert_weights inter size."); - } + if (mUseINT8WoqPerChannel) + { + // INT8 weight-only uses [num_experts, inter_size, hidden_size] for fc2. + auto const expect_mul = isGatedActivation(base_activation_type) ? 2 : 1; + TORCH_CHECK( + fc1_expert_weights.sizes()[2] == fc2_expert_weights.sizes()[1] * mInnerDimMultiplier * expect_mul, + expect_mul == 2 + ? "fc1_expert_weights inter size must be 2x fc2_expert_weights inter size for gated activations." + : "fc1_expert_weights inter size must equal fc2_expert_weights inter size for ungated activations."); + }Based on learnings.
286-316: Duplicate bias-validation block.The fc1/fc2 bias validation appears twice back‑to‑back; drop one to avoid redundant checks and noisy errors.
Apply:
- if (fc1_expert_biases.has_value() || fc2_expert_biases.has_value()) - { - CHECK_INPUT(fc1_expert_biases.value(), mOutputDtype); - CHECK_INPUT(fc2_expert_biases.value(), mOutputDtype); - TORCH_CHECK(fc1_expert_biases.value().dim() == 2, "fc1_expert_biases must be 2D."); - TORCH_CHECK(fc2_expert_biases.value().dim() == 2, "fc2_expert_biases must be 2D."); - TORCH_CHECK(fc1_expert_weights.sizes()[0] == fc1_expert_biases.value().sizes()[0], - "fc1_expert_weights and fc1_expert_biases must have the same number of experts."); - TORCH_CHECK(fc2_expert_weights.sizes()[0] == fc2_expert_biases.value().sizes()[0], - "fc2_expert_weights and fc2_expert_biases must have the same number of experts."); - TORCH_CHECK(fc1_expert_biases.value().sizes()[1] == fc1_expert_weights.sizes()[1], - "fc1_expert_biases should match fc1_expert_weights output shape."); - TORCH_CHECK(fc2_expert_biases.value().sizes()[1] == fc2_expert_weights.sizes()[1], - "fc2_expert_biases should match fc2_expert_weights output shape."); - }cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_template_dispatch.h (1)
949-958: Relu2 activation still hard-fails at runtime
ActivationType::Relu2is now threaded all the way from the Python API and we introduce a CUTLASS functor for it, yet this switch still raises"Relu2 is not supported.". Any attempt to exercise the new activation will immediately throw here, so the feature cannot work. Please wire this case to the actual Relu² epilogue (or the appropriate adaptor) instead of throwing so that the new activation behaves correctly.
🧹 Nitpick comments (2)
cpp/tensorrt_llm/thop/moeOp.cpp (1)
729-742: Profiler hardcodes Swiglu; consider threading selected activation.mProfiler->init uses ActivationType::Swiglu regardless of the actual activation. For non‑gated/Relu2 runs this can skew workspace/tactic selection.
Pass the resolved base_activation_type into runGemmProfile (API change), or infer gated vs. ungated from dims to set the activation used for profiling. Based on learnings.
cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cu (1)
2310-2312: Relu2 added: guard against enum/dispatch drift.The dispatch uses an array indexed by static_cast(ActivationType). If enum order diverges from this array, you’ll pick the wrong kernel or OOB-index on invalid values.
- Prefer a switch on activation_type.activation_type with a default that TLLM_CHECK(false, …). Compilers will turn this into a jump table; safer than positional arrays.
- If keeping the array, add a compile-time/static size guard tied to an enum sentinel (e.g., kNumActivations) and validate input at call sites (see moeOp.cpp comments).
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (9)
cpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/thread/fused_activations.h(1 hunks)cpp/tensorrt_llm/kernels/cutlass_kernels/include/common.h(1 hunks)cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_template_dispatch.h(1 hunks)cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cu(1 hunks)cpp/tensorrt_llm/thop/moeOp.cpp(6 hunks)tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.py(4 hunks)tensorrt_llm/_torch/custom_ops/torch_custom_ops.py(9 hunks)tensorrt_llm/_torch/modules/fused_moe/routing.py(1 hunks)tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py(1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh}: Namespace closing braces must include a trailing comment with the namespace name (e.g., '} // namespace foo').
Prefer const or constexpr variables over #define for constants.
Declare variables that are not modified after initialization as const.
Avoid magic literals in code; except for 0, nullptr, true, false. Use named constants for comparisons and logic.
Use Allman brace style for formatting.
Place the semicolon of an empty for/while loop on a new line.
Bodies of switch/while/do-while/for must be compound statements (brace-delimited), and if/else must always be followed by brace-delimited statements.
Type names (e.g., classes) must be CamelCase starting with an uppercase letter (e.g., FooBar).
Local variables, methods, and namespaces use lowerCamelCase (e.g., localFooBar).
Non-magic-number global variables that are non-static and not in an anonymous namespace must be lowerCamelCase prefixed with 'g' (e.g., gDontUseGlobalFoos).
Non-magic-number globals that are static or in an anonymous namespace use lowerCamelCase prefixed with 's' (e.g., sMutableStaticGlobal).
Locally visible static variables use lowerCamelCase with 's' prefix (e.g., static std::once_flag sFlag).
Private/protected member variables use 'm' prefix with CamelCase (e.g., mNbFooValues). Public members may omit, but 'm' is encouraged for clarity.
Constants (enums, global constants, static constants, and function-scope magic/literal constants) use uppercase SNAKE_CASE with 'k' prefix (e.g., kDIGIT_NUM).
Function-scope constants that are not magic numbers or literals are named like non-constant variables (e.g., bool const pass = a && b).
If macros are necessary, name them in UPPER_SNAKE_CASE (e.g., FOO_VERSION) and prefer constants over #define.
Use LLVM clang-format; wrap lines at a maximum of 120 columns; use '// clang-format off/on' sparingly with justification.
Use smart pointers for heap allocations; prefer unique_ptr for sole ownership, shared_ptr for shared...
Files:
cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_template_dispatch.hcpp/tensorrt_llm/kernels/cutlass_kernels/include/common.hcpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cucpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/thread/fused_activations.hcpp/tensorrt_llm/thop/moeOp.cpp
**/*.{cpp,cxx,cc,cu,h,hpp,hh,hxx,cuh}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
C++ filenames should be lowerCamelCase (first letter lowercase) and must be case-insensitive unique within a compilation target.
Files:
cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_template_dispatch.hcpp/tensorrt_llm/kernels/cutlass_kernels/include/common.hcpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cucpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/thread/fused_activations.hcpp/tensorrt_llm/thop/moeOp.cpp
**/*.{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:
cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_template_dispatch.hcpp/tensorrt_llm/kernels/cutlass_kernels/include/common.hcpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cucpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/thread/fused_activations.htensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.pytensorrt_llm/_torch/custom_ops/torch_custom_ops.pytensorrt_llm/_torch/modules/fused_moe/routing.pycpp/tensorrt_llm/thop/moeOp.cpptests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
**/*.{h,hpp,hh,hxx}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Document new class interfaces and function prototypes with Doxygen; use //! for single-line and //!< for members.
Files:
cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_template_dispatch.hcpp/tensorrt_llm/kernels/cutlass_kernels/include/common.hcpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/thread/fused_activations.h
**/*.{h,hpp,hh,hxx,cpp,cxx,cc}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.{h,hpp,hh,hxx,cpp,cxx,cc}: Prefer anonymous namespaces over 'static' for internal linkage of functions.
All templates (class/function/member/static) must be instantiated at least once; non-POD classes should have private data members.
Files:
cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_template_dispatch.hcpp/tensorrt_llm/kernels/cutlass_kernels/include/common.hcpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/thread/fused_activations.hcpp/tensorrt_llm/thop/moeOp.cpp
**/*.{h,hpp,hh,hxx,cuh}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Use include guards named 'TRTLLM_<FILE_NAME_IN_CAPS_WITH_UNDERSCORES>_H' (no leading or trailing underscore; directory names excluded).
Files:
cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_template_dispatch.hcpp/tensorrt_llm/kernels/cutlass_kernels/include/common.hcpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/thread/fused_activations.h
**/*.{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:
cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_template_dispatch.hcpp/tensorrt_llm/kernels/cutlass_kernels/include/common.hcpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cucpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/thread/fused_activations.htensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.pytensorrt_llm/_torch/custom_ops/torch_custom_ops.pytensorrt_llm/_torch/modules/fused_moe/routing.pycpp/tensorrt_llm/thop/moeOp.cpptests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.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/auto_deploy/custom_ops/fused_moe/trtllm_moe.pytensorrt_llm/_torch/custom_ops/torch_custom_ops.pytensorrt_llm/_torch/modules/fused_moe/routing.pytests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
🧠 Learnings (22)
📓 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: venkywonka
Repo: NVIDIA/TensorRT-LLM PR: 6029
File: .github/pull_request_template.md:45-53
Timestamp: 2025-08-27T17:50:13.264Z
Learning: For PR templates in TensorRT-LLM, avoid suggesting changes that would increase developer overhead, such as converting plain bullets to mandatory checkboxes. The team prefers guidance-style bullets that don't require explicit interaction to reduce friction in the PR creation process.
Learnt from: djns99
Repo: NVIDIA/TensorRT-LLM PR: 7104
File: cpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/fusion/sm90_visitor_scatter.hpp:399-417
Timestamp: 2025-08-21T21:48:35.135Z
Learning: CUTLASS extensions in TensorRT-LLM (located under cpp/tensorrt_llm/cutlass_extensions/) are designed to integrate with and extend functionality in the external CUTLASS repository. When analyzing these extensions, their consumers and functionality wiring may exist in the CUTLASS codebase rather than within TensorRT-LLM itself.
📚 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:
cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_template_dispatch.hcpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cutensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.pycpp/tensorrt_llm/thop/moeOp.cpp
📚 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:
cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_template_dispatch.hcpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cucpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/thread/fused_activations.h
📚 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:
cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_template_dispatch.hcpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cucpp/tensorrt_llm/thop/moeOp.cpp
📚 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:
cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_template_dispatch.hcpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cu
📚 Learning: 2025-08-21T02:41:10.565Z
Learnt from: djns99
Repo: NVIDIA/TensorRT-LLM PR: 7104
File: cpp/tensorrt_llm/kernels/cutlass_kernels/include/moe_gemm_kernels.h:141-145
Timestamp: 2025-08-21T02:41:10.565Z
Learning: In TensorRT-LLM MOE GEMM kernels (cpp/tensorrt_llm/kernels/cutlass_kernels/include/moe_gemm_kernels.h), the stride_act and stride_weight pointers in TmaWarpSpecializedGroupedGemmInput are intentionally declared as void* rather than typed pointers because the actual stride type is determined at runtime based on factors like the swap_ab flag and layout decisions. This runtime type determination makes compile-time type safety impossible, so void* is the correct approach.
Applied to files:
cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_template_dispatch.h
📚 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:
cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_template_dispatch.htensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.pytests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.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:
cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_template_dispatch.htensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.pycpp/tensorrt_llm/thop/moeOp.cpptests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
📚 Learning: 2025-08-21T21:48:35.135Z
Learnt from: djns99
Repo: NVIDIA/TensorRT-LLM PR: 7104
File: cpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/fusion/sm90_visitor_scatter.hpp:399-417
Timestamp: 2025-08-21T21:48:35.135Z
Learning: CUTLASS extensions in TensorRT-LLM (located under cpp/tensorrt_llm/cutlass_extensions/) are designed to integrate with and extend functionality in the external CUTLASS repository. When analyzing these extensions, their consumers and functionality wiring may exist in the CUTLASS codebase rather than within TensorRT-LLM itself.
Applied to files:
cpp/tensorrt_llm/kernels/cutlass_kernels/include/common.hcpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/thread/fused_activations.h
📚 Learning: 2025-08-08T05:06:31.596Z
Learnt from: sklevtsov-nvidia
Repo: NVIDIA/TensorRT-LLM PR: 3294
File: cpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/fusion/sm90_visitor_scatter.hpp:36-36
Timestamp: 2025-08-08T05:06:31.596Z
Learning: CUTLASS extension files (under cpp/tensorrt_llm/cutlass_extensions/) follow CUTLASS coding style conventions, including using #pragma once instead of TRTLLM_ prefixed header guards, even though they are .hpp files.
Applied to files:
cpp/tensorrt_llm/kernels/cutlass_kernels/include/common.hcpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/thread/fused_activations.h
📚 Learning: 2025-08-08T05:10:38.906Z
Learnt from: sklevtsov-nvidia
Repo: NVIDIA/TensorRT-LLM PR: 3294
File: cpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/fusion/sm90_visitor_scatter.hpp:0-0
Timestamp: 2025-08-08T05:10:38.906Z
Learning: The ScaledAccPerRowBiasPerColScaleScatter fusion in CUTLASS extensions (cpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/fusion/sm90_visitor_scatter.hpp) is specifically designed for per-column scaling factors only, so it uses a fixed Stride<_0,_1,int64_t> rather than conditional stride logic.
Applied to files:
cpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/thread/fused_activations.h
📚 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/trtllm_moe.pytests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_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:
tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_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/trtllm_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:
tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_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:
tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.pycpp/tensorrt_llm/thop/moeOp.cpptests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.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/auto_deploy/custom_ops/fused_moe/trtllm_moe.py
📚 Learning: 2025-09-02T13:42:44.885Z
Learnt from: pcastonguay
Repo: NVIDIA/TensorRT-LLM PR: 7455
File: tensorrt_llm/_torch/pyexecutor/py_executor.py:1852-1860
Timestamp: 2025-09-02T13:42:44.885Z
Learning: In MPI communication within TensorRT-LLM pipeline parallelism, different communication types (tokens, logits, termination sync) must use disjoint tag namespaces to avoid message routing collisions when using the same source/destination patterns.
Applied to files:
cpp/tensorrt_llm/thop/moeOp.cpp
📚 Learning: 2025-07-28T17:06:08.621Z
Learnt from: moraxu
Repo: NVIDIA/TensorRT-LLM PR: 6303
File: tests/integration/test_lists/qa/examples_test_list.txt:494-494
Timestamp: 2025-07-28T17:06:08.621Z
Learning: In TensorRT-LLM testing, it's common to have both CLI flow tests (test_cli_flow.py) and PyTorch API tests (test_llm_api_pytorch.py) for the same model. These serve different purposes: CLI flow tests validate the traditional command-line workflow, while PyTorch API tests validate the newer LLM API backend. Both are legitimate and should coexist.
Applied to files:
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
📚 Learning: 2025-09-09T09:40:45.658Z
Learnt from: fredricz-20070104
Repo: NVIDIA/TensorRT-LLM PR: 7645
File: tests/integration/test_lists/qa/llm_function_core.txt:648-648
Timestamp: 2025-09-09T09:40:45.658Z
Learning: In TensorRT-LLM test lists, it's common and intentional for the same test to appear in multiple test list files when they serve different purposes (e.g., llm_function_core.txt for comprehensive core functionality testing and llm_function_core_sanity.txt for quick sanity checks). This duplication allows tests to be run in different testing contexts.
Applied to files:
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
📚 Learning: 2025-08-06T13:58:07.506Z
Learnt from: galagam
Repo: NVIDIA/TensorRT-LLM PR: 6487
File: tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py:1-12
Timestamp: 2025-08-06T13:58:07.506Z
Learning: In TensorRT-LLM, test files (files under tests/ directories) do not require NVIDIA copyright headers, unlike production source code files. Test files typically start directly with imports, docstrings, or code.
Applied to files:
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
📚 Learning: 2025-08-11T20:09:24.389Z
Learnt from: achartier
Repo: NVIDIA/TensorRT-LLM PR: 6763
File: tests/integration/defs/triton_server/conftest.py:16-22
Timestamp: 2025-08-11T20:09:24.389Z
Learning: In the TensorRT-LLM test infrastructure, the team prefers simple, direct solutions (like hard-coding directory traversal counts) over more complex but robust approaches when dealing with stable directory structures. They accept the maintenance cost of updating tests if the layout changes.
Applied to files:
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
🧬 Code graph analysis (7)
cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_template_dispatch.h (3)
tensorrt_llm/_torch/custom_ops/torch_custom_ops.py (1)
ActivationType(31-40)cpp/tensorrt_llm/kernels/cutlass_kernels/include/common.h (1)
ActivationType(23-36)tensorrt_llm/_torch/modules/fused_moe/routing.py (1)
ActivationType(158-167)
cpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/thread/fused_activations.h (1)
cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cu (3)
T(1950-1954)T(1966-1970)T(1981-1987)
tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.py (2)
tensorrt_llm/_torch/custom_ops/torch_custom_ops.py (2)
ActivationType(31-40)fused_moe(144-250)tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/triton_moe.py (1)
_quantize_fp8(547-551)
tensorrt_llm/_torch/custom_ops/torch_custom_ops.py (3)
cpp/tensorrt_llm/kernels/cutlass_kernels/include/common.h (1)
ActivationType(23-36)tensorrt_llm/_torch/modules/fused_moe/routing.py (1)
ActivationType(158-167)tensorrt_llm/_torch/autotuner.py (2)
AutoTuner(514-1173)get(545-548)
tensorrt_llm/_torch/modules/fused_moe/routing.py (2)
tensorrt_llm/_torch/custom_ops/torch_custom_ops.py (1)
ActivationType(31-40)cpp/tensorrt_llm/kernels/cutlass_kernels/include/common.h (1)
ActivationType(23-36)
cpp/tensorrt_llm/thop/moeOp.cpp (2)
cpp/tensorrt_llm/kernels/cutlass_kernels/include/moe_gemm_kernels.h (1)
isGatedActivation(248-252)cpp/tensorrt_llm/kernels/internal_cutlass_kernels/include/moe_gemm_kernels.h (1)
isGatedActivation(239-243)
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py (2)
tensorrt_llm/_torch/custom_ops/torch_custom_ops.py (2)
ActivationType(31-40)fused_moe(144-250)tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.py (1)
trtllm_quant_fp8moe_fused(80-194)
🪛 Ruff (0.14.3)
tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.py
34-34: Avoid specifying long messages outside the exception class
(TRY003)
40-40: Avoid specifying long messages outside the exception class
(TRY003)
42-42: Avoid specifying long messages outside the exception class
(TRY003)
65-65: Unused function argument: mlp_style
(ARG001)
66-66: Unused function argument: act_fn
(ARG001)
89-89: Unused function argument: w3_input_scale
(ARG001)
92-92: Unused function argument: w3_weight_scale
(ARG001)
168-168: Avoid specifying long messages outside the exception class
(TRY003)
175-175: Avoid specifying long messages outside the exception class
(TRY003)
177-177: Avoid specifying long messages outside the exception class
(TRY003)
200-200: Unused function argument: selected_experts
(ARG001)
201-201: Unused function argument: routing_weights
(ARG001)
202-202: Unused function argument: w1_weight
(ARG001)
203-203: Unused function argument: w2_weight
(ARG001)
204-204: Unused function argument: w3_weight
(ARG001)
205-205: Unused function argument: w1_input_scale
(ARG001)
206-206: Unused function argument: w2_input_scale
(ARG001)
207-207: Unused function argument: w3_input_scale
(ARG001)
208-208: Unused function argument: w1_weight_scale
(ARG001)
209-209: Unused function argument: w2_weight_scale
(ARG001)
210-210: Unused function argument: w3_weight_scale
(ARG001)
211-211: Unused function argument: mlp_style
(ARG001)
212-212: Unused function argument: act_fn
(ARG001)
tensorrt_llm/_torch/custom_ops/torch_custom_ops.py
284-284: Unused function argument: activation_type
(ARG001)
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
222-222: Unpacked variable w3_weight_dequantized is never used
Prefix it with an underscore or any other dummy variable pattern
(RUF059)
⏰ 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
| torch::optional<int64_t> const& activation_type, torch::optional<int64_t> const& unpadded_hidden_size, | ||
| torch::optional<int64_t> const& num_valid_tokens, torch::optional<torch::Tensor> const& out_tensor) | ||
| { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
API change: ensure Python bindings/tests pass activation_type consistently.
New optional args added (activation_type, unpadded_hidden_size, num_valid_tokens, out_tensor). Please verify torch bindings and call sites are updated for ordering/defaults to avoid silent arg shifts.
Run to locate call sites and confirm argument ordering:
🏁 Script executed:
#!/bin/bash
set -euo pipefail
fd -a 'torch_custom_ops.py|routing.py|test_trtllm_moe.py' -tl |
xargs -I{} bash -c 'echo ">>> {}"; nl -ba "{}" | sed -n "1,999p" | rg -n "run_moe\(|run_moe_min_latency\(" -n -C2'Length of output: 0
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Find the moeOp.cpp file and surrounding context
echo "=== Finding moeOp.cpp ==="
fd -t f 'moeOp\.cpp'
# Search for runMoe function calls and definitions
echo -e "\n=== runMoe function definitions ==="
rg -n 'void runMoe\(|runMoe_impl\(' --type=cpp -C3
# Search for runMoe calls in Python files
echo -e "\n=== Python calls to run_moe ==="
fd -t f -e py . | xargs rg -n 'run_moe\(|run_moe_min_latency\(' -C2
# Search for torch binding registration related to moe
echo -e "\n=== Torch binding registration ==="
rg -n 'TORCH_LIBRARY.*moe|\.def.*run_moe' --type=cpp -C2Length of output: 14071
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Get the full function signatures at the specified lines
echo "=== runMoe signature (lines 250-280) ==="
sed -n '250,280p' cpp/tensorrt_llm/thop/moeOp.cpp
echo -e "\n=== runMoeMinLatency signature (lines 550-580) ==="
sed -n '550,580p' cpp/tensorrt_llm/thop/moeOp.cpp
# Get the Python call at torch_custom_ops.py line 241
echo -e "\n=== Python call in torch_custom_ops.py (lines 235-250) ==="
sed -n '235,250p' tensorrt_llm/_torch/custom_ops/torch_custom_ops.py
# Check one of the trtllm_gen_custom_ops calls
echo -e "\n=== trtllm_gen_custom_ops.py call (lines 119-135) ==="
sed -n '119,135p' tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py
# Check moe_op_cutlass.py call
echo -e "\n=== moe_op_cutlass.py call (lines 194-205) ==="
sed -n '194,205p' tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_cutlass.pyLength of output: 6340
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Search all Python files for calls to run_moe or run_moe_min_latency
echo "=== All run_moe and run_moe_min_latency calls ==="
rg -n 'run_moe\(|run_moe_min_latency\(' --type=py -B2 -A8 | head -150
# Check if there's a signature definition in Python bindings
echo -e "\n=== Python method signatures in moe_op_cutlass.py ==="
sed -n '200,250p' tensorrt_llm/_torch/modules/fused_moe/ops/moe_op_cutlass.py
# Check runMoeMinLatency signature
echo -e "\n=== runMoeMinLatency signature (full) ==="
rg -n 'torch::Tensor runMoeMinLantency\(' --type=cpp -A15Length of output: 17595
Critical: Missing activation_type parameter in moe_op_cutlass.py call.
The C++ runMoe signature at line 251-265 expects 26 parameters ending with (profile_ids, activation_type, unpadded_hidden_size, num_valid_tokens, out_tensor). However, the Python wrapper call at moe_op_cutlass.py:196-203 is missing activation_type, causing all subsequent arguments to shift left by one position:
Currently passes (incorrect): ..., min_latency_mode, self.gemm_tactics, unpadded_hidden_size, tuner_num_tokens, None
Should pass (correct): ..., min_latency_mode, self.gemm_tactics, activation_type, unpadded_hidden_size, tuner_num_tokens, None
The torch_custom_ops.py:241-248 call correctly includes all four new optional parameters. Update moe_op_cutlass.py line 202 to add activation_type before unpadded_hidden_size.
🤖 Prompt for AI Agents
In cpp/tensorrt_llm/thop/moeOp.cpp around lines 262-264 and moe_op_cutlass.py
around lines 196-203 (specifically line 202), the Python wrapper call is missing
the activation_type argument which shifts all subsequent parameters left; update
the call at moe_op_cutlass.py:202 to insert activation_type before
unpadded_hidden_size so the argument list matches the C++ signature (...,
min_latency_mode, self.gemm_tactics, activation_type, unpadded_hidden_size,
tuner_num_tokens, None), and ensure activation_type is obtained from the correct
source (e.g., self.activation_type or passed into the function) and has the
expected optional/torch-compatible type.
| ActivationType base_activation_type = activation_type.has_value() | ||
| ? static_cast<ActivationType>(activation_type.value()) | ||
| : ActivationType::Swiglu; | ||
| if (swiglu_alpha.has_value()) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Same enum‑validation needed here.
Mirror the activation_type validation added in runMoe to prevent invalid values in min‑latency path.
Apply:
- ActivationType base_activation_type = activation_type.has_value()
- ? static_cast<ActivationType>(activation_type.value())
- : ActivationType::Swiglu;
+ ActivationType base_activation_type = ActivationType::Swiglu;
+ if (activation_type.has_value()) {
+ auto act = static_cast<ActivationType>(activation_type.value());
+ switch (act) {
+ case ActivationType::Gelu:
+ case ActivationType::Relu:
+ case ActivationType::SiLu:
+ case ActivationType::Swiglu:
+ case ActivationType::Geglu:
+ case ActivationType::SwigluBias:
+ case ActivationType::Relu2:
+ case ActivationType::Identity:
+ base_activation_type = act; break;
+ default:
+ TORCH_CHECK(false, "Invalid activation_type value: ", activation_type.value());
+ }
+ }| x_q_fp8 = _quantize_fp8(x2d, w1_input_scale) | ||
|
|
||
| # Scales are stored in float32 | ||
| w1_weight_scale = w1_weight_scale.to(torch.float32) | ||
| w2_weight_scale = w2_weight_scale.to(torch.float32) | ||
| w1_input_scale = w1_input_scale.to(torch.float32) | ||
| w2_input_scale = w2_input_scale.to(torch.float32) | ||
|
|
||
| # Prepare quant_scales for TensorRT-LLM FP8 format: | ||
| # [gemm1_dequant_scale, gemm2_act_quant_scale, gemm2_dequant_scale, gemm1_input_dequant_scale] | ||
| # For gated MLP: | ||
| # - gemm1_dequant_scale: w1_weight_scale * w1_input_scale (combined for w1 and w3) | ||
| # - gemm2_act_quant_scale: 1 / w2_input_scale | ||
| # - gemm2_dequant_scale: w2_weight_scale * w2_input_scale | ||
| # - gemm1_input_dequant_scale: w1_input_scale | ||
|
|
||
| # Compute combined scales | ||
| gemm1_dequant = (w1_weight_scale * w1_input_scale).contiguous().squeeze() | ||
| gemm2_act_quant = (1.0 / w2_input_scale).contiguous().to(torch.float32) # [E] | ||
| gemm2_dequant = (w2_weight_scale * w2_input_scale).contiguous().squeeze() | ||
| gemm1_input_dequant = w1_input_scale.contiguous() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Avoid broadcasting mismatch when quantizing inputs
x2d is [num_tokens, hidden_size], while w1_input_scale is documented and passed as [num_experts], so _quantize_fp8(x2d, w1_input_scale) throws “The size of tensor a (…) must match the size of tensor b (…)” as soon as you have more than one expert. The CUTLASS kernel expects the activations to be quantized already, but that scale must be per token (or scalar), not per expert. Please restructure the quantization so you either (a) accept pre-quantized inputs and skip this step, or (b) postpone activation quantization until after tokens are dispatched per expert so the shapes align. Right now the path hard-crashes for real FP8 configs.(docs.flashinfer.ai)
🤖 Prompt for AI Agents
In tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.py around
lines 121-141, the call _quantize_fp8(x2d, w1_input_scale) fails when
w1_input_scale is per-expert ([num_experts]) while x2d is [num_tokens,
hidden_size]; remove or defer this quantization and instead perform activation
quantization after tokens are dispatched per-expert (or accept pre-quantized
inputs). Concretely: do not call _quantize_fp8 with a per-expert scale here;
either (A) trust callers to provide x2d already FP8 and skip quantization, or
(B) postpone quantizing activations until after the dispatcher splits tokens to
experts and apply _quantize_fp8 with the matching per-expert scale for each
expert’s token slice (or collapse scale to a scalar/per-token shape if
intended). Also ensure the prepared quant_scales (gemm1_dequant,
gemm2_act_quant, gemm2_dequant, gemm1_input_dequant) are computed from the same
scale convention you choose (per-expert vs scalar) and have shapes that match
the kernels.
| def dynamic_per_tensor_fp8_quant(x: torch.tensor) -> tuple[torch.tensor, torch.tensor]: | ||
| fp8_traits_max = FLOAT8_E4M3_MAX | ||
| fp8_traits_min = -FLOAT8_E4M3_MAX | ||
| fp8_max = torch.tensor(fp8_traits_max).float() | ||
| one = torch.tensor(1.0).float() | ||
|
|
||
| x_max = x.abs().max().float() | ||
| scale = x_max / fp8_max | ||
| iscale = one / scale | ||
| out = (x.float() * iscale).clamp(fp8_traits_min, fp8_traits_max).to(FP8_DTYPE) | ||
| return out, scale.view((1,)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Guard zero-scale to avoid NaNs
If x is all zeros, scale becomes 0 and iscale becomes inf, producing FP8 NaNs when you clamp and cast. The reproducer is simply routing zero activations, which is a valid MoE scenario. Please short-circuit the zero norm case before the reciprocal (e.g., return zeros with scale 1.0) and keep the tensors on the correct device.(reddit.com)
Apply this diff:
- scale = x_max / fp8_max
- iscale = one / scale
- out = (x.float() * iscale).clamp(fp8_traits_min, fp8_traits_max).to(FP8_DTYPE)
- return out, scale.view((1,))
+ if x_max == 0:
+ scale = one.to(x.device)
+ out = torch.zeros_like(x, dtype=FP8_DTYPE)
+ return out, scale.view((1,))
+ scale = x_max / fp8_max
+ iscale = one.to(x.device) / scale
+ out = (x.float() * iscale).clamp(fp8_traits_min, fp8_traits_max).to(FP8_DTYPE)
+ return out, scale.view((1,))🤖 Prompt for AI Agents
In
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
around lines 19 to 29, the dynamic_per_tensor_fp8_quant function can produce
inf/NaN when x is all zeros because scale becomes 0 and we take its reciprocal;
guard that by checking x_max == 0 (respecting device and dtype), and in that
case return a zero tensor of the same shape and device cast to FP8_DTYPE and a
scale tensor set to 1.0 on the same device and dtype (shape (1,)), otherwise
compute scale and iscale as before; ensure all created tensors (fp8_max, one,
returned zeros, and scale) are on x.device to avoid device-mismatch errors.
| mask = selected_experts == expert_id | ||
| if not mask.sum(): | ||
| continue |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix ambiguous tensor truthiness check
On CUDA, if not mask.sum(): raises “Boolean value of Tensor with more than one value is ambiguous”. Swap this for an explicit scalar check (e.g., if not mask.any().item():).(iifx.dev)
Apply this diff:
- if not mask.sum():
+ if not mask.any().item():
continue📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| mask = selected_experts == expert_id | |
| if not mask.sum(): | |
| continue | |
| mask = selected_experts == expert_id | |
| if not mask.any().item(): | |
| continue |
🤖 Prompt for AI Agents
In
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
around lines 80 to 82, the code uses an ambiguous tensor truthiness check `if
not mask.sum():` which fails on CUDA; change it to perform an explicit scalar
check such as evaluating the boolean via `.any().item()` or checking
`.sum().item() == 0` (e.g., `if not mask.any().item():`) so the condition uses a
Python bool rather than a multi-element Tensor.
| w31_scales = torch.empty(num_experts, 2, dtype=otype).cuda() | ||
| w2_scales = torch.empty(num_experts, 1, dtype=otype).cuda() | ||
|
|
||
| w31_dequantized = gen_tensor(w31_shape, otype) | ||
| w2_dequantized = gen_tensor(w2_shape, otype) | ||
| for expert_id in range(num_experts): | ||
| w31 = cast_to_representable(gen_tensor(w31_shape[1:], otype, scale=0.1)) | ||
| w2 = cast_to_representable(gen_tensor(w2_shape[1:], otype, scale=0.09)) | ||
|
|
||
| w31_quant, s31 = dynamic_per_tensor_fp8_quant(w31) | ||
| w2_quant, s2 = dynamic_per_tensor_fp8_quant(w2) | ||
|
|
||
| w31_weight.data[expert_id].copy_(w31_quant) | ||
| w2_weight.data[expert_id].copy_(w2_quant) | ||
| w31_scales.data[expert_id].copy_(s31) | ||
| w2_scales.data[expert_id].copy_(s2) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Align FP8 scale writes with tensor shape
w31_scales[expert_id] has length 2 but s31 is shape (1,), so copy_ blows up with a size mismatch the first time you hit the loop. Initialize both entries explicitly (e.g., fill_ with the scalar) so the broadcast matches the allocation.
Apply this diff:
- w31_scales.data[expert_id].copy_(s31)
+ w31_scales.data[expert_id].fill_(s31.item())🤖 Prompt for AI Agents
In
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
around lines 175 to 190, the test writes FP8 scales into w31_scales[expert_id]
(length 2) using s31 (shape (1,)) which causes a size-mismatch on copy_; change
the write so the two entries are set explicitly — either expand or repeat the
scalar to length 2 before copying, or use a scalar-fill (e.g., fill_ or
repeat()/expand() on s31) so the destination shape matches the source; apply the
same approach for any other scale tensors with mismatched dimensions (w2_scales
is length 1 so copy is fine).
| assert trtllm_test_output is not None | ||
| # torch.testing.assert_close(ad_test_output, trtllm_test_output, rtol=1e-6, atol=1e-6) | ||
|
|
||
| if diff.max() > 1e-1: | ||
| print("diff: " + "-" * 20) | ||
| print(f"{diff[:10]}") | ||
| print("test_output: " + "-" * 20) | ||
| print(f"{ad_test_output[:10]}") | ||
| print("ref_output: " + "-" * 20) | ||
| print(f"{ref_output[:10]}") | ||
| torch.testing.assert_close(ref_output, ad_test_output, rtol=1e-1, atol=1e-1) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actually validate torch.ops.trtllm.fused_moe
The test never checks trtllm_test_output; it only asserts the auto-deploy wrapper matches the reference and merely ensures the fused op returns something non-null. Please restore an equality check (with the same relaxed tolerance if needed) so we catch regressions in the C++ op. Without this, the test misses the code path the PR is extending.
Apply this diff:
- assert trtllm_test_output is not None
- # torch.testing.assert_close(ad_test_output, trtllm_test_output, rtol=1e-6, atol=1e-6)
+ torch.testing.assert_close(
+ ad_test_output, trtllm_test_output, rtol=1e-1, atol=1e-1
+ )🤖 Prompt for AI Agents
In
tests/unittest/_torch/auto_deploy/unit/singlegpu/custom_ops/test_trtllm_moe.py
around lines 291 to 301, the test only asserts trtllm_test_output is non-null
but never compares the fused C++ op output against the reference; reintroduce an
equality check to validate torch.ops.trtllm.fused_moe by calling
torch.testing.assert_close(trtllm_test_output, ref_output, rtol=1e-1, atol=1e-1)
(or the previously commented ad_test_output vs trtllm_test_output check) so the
fused op output is directly compared with the reference using the same relaxed
tolerances, placed before the existing final assertion and keeping the
diagnostic diff/print block as-is.
| return (x / scale).clamp(FP8_MIN, FP8_MAX).to(torch.float8_e4m3fn) | ||
|
|
||
|
|
||
| @torch.library.custom_op("auto_deploy::trtllm_quant_fp8moe_fused", mutates_args=()) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: The op name looks a bit too long...
| return torch.empty_like(x) | ||
|
|
||
|
|
||
| # Todo: refactor this repeating code block |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We can use some TRTLLM kernels to do this quantization, e.g. torch.ops.tensorrt_llm.static_quantize_e4m3_per_tensor
| from enum import IntEnum | ||
|
|
||
|
|
||
| # Copied from csrc/nv_internal/tensorrt_llm/kernels/cutlass_kernels/include/common.hExpand commentComment on line R76Code has comments. Press enter to view. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Comments seems off..
| Unspecified = 5. | ||
|
|
||
|
|
||
| class ActivationType(IntEnum): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Duplicate code? Maybe just use the torch_custom_ops one.
| w2_dequantized.data[expert_id].copy_(torch.mul(w2_quant.to(dtype=otype), s2)) | ||
|
|
||
| routing_weights, selected_experts = compute_routing(router_logits, top_k) | ||
| ref_output = compute_with_experts( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We can probably reuse the torch op auto_deploy::torch_moe
Summary by CodeRabbit
Release Notes
New Features
Tests
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.
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 thestage-listparameter 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.mdand the
scripts/test_to_stage_mapping.pyhelper.kill
killKill all running builds associated with pull request.
skip
skip --comment COMMENTSkip 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-pipelineReuse 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.