Repository navigation
perf: Optimize CUTLASS MoE helper kernels for small-batch decode workloads #3014
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
Changes from 15 commits
0cc6825
0fb4db3
a94b434
2770a20
866dbbc
175b4c8
1b3e421
9bc0e0b
b3d96ab
2324fb3
626fed1
f7eb890
527ede3
3ab2921
e9224bf
b5d140b
451befd
a33b48c
5d268c5
580664b
85ceb8a
37dc223
45f97f0
6436f8e
a22ce59
e7bc590
cabf9cd
6f36003
ab0068c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1260,6 +1260,16 @@ __global__ void computeStridesTmaWarpSpecializedKernel( | |
| layout_info2.swap_ab ? gemm2_n : gemm_m, layout_info2.swap_ab ? gemm_m : gemm2_n, | ||
| gemm2_k); | ||
|
|
||
| // Skip expensive stride/pointer/SF setup for experts with no assigned tokens. | ||
| // CUTLASS grouped GEMM skips zero-M problems after reading problem_shapes. | ||
| // For decode (1 token, top_k=8, 128 experts), this skips ~120 of 128 experts. | ||
| if (gemm_m == 0) { | ||
| #if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900)) | ||
| asm volatile("griddepcontrol.launch_dependents;"); | ||
| #endif | ||
| return; | ||
| } | ||
|
|
||
| if (layout_info1.int4_groupwise_params.enabled) { | ||
| layout_info1.int4_groupwise_params.shape.problem_shapes[expert] = | ||
| TmaWarpSpecializedGroupedGemmInput::INT4GroupwiseParams::ProblemShapeInt:: | ||
|
|
@@ -1471,15 +1481,14 @@ __global__ void expandInputRowsKernel( | |
| } | ||
|
|
||
| // Pad zeros in the extra SFs along the K dimension, we do this to ensure there are no nan | ||
| // values in the padded SF atom Use VecSize per thread since we are just writing out zeros so | ||
| // every thread can process a whole vector | ||
| // values in the padded SF atom | ||
| size_t padding_start_offset = hidden_size / VecSize + start_offset; | ||
| size_t padding_elems_in_col = padded_hidden_size / VecSize; | ||
| for (int64_t elem_index = padding_start_offset; elem_index < padding_elems_in_col; | ||
| elem_index += stride) { | ||
| writeSF<VecSize, VecSize>(num_tokens_before_expert, expert, /*source_row*/ -1, permuted_row, | ||
| elem_index, padded_hidden_size, fc1_act_sf_flat, | ||
| /* input_sf */ nullptr); // Pass nulltpr input_sf so we write 0 | ||
| writeSF<VecSize, VecSize>(num_tokens_before_expert, expert, /*source_row*/ -1, | ||
| permuted_row, elem_index, padded_hidden_size, fc1_act_sf_flat, | ||
| /* input_sf */ nullptr); | ||
| } | ||
| } else if constexpr (PRE_QUANT_AWQ) { | ||
| static_assert(!is_nvfp4 && !is_mxfp8, "NVFP4 and MXFP8 are not supported for AWQ"); | ||
|
|
@@ -1512,7 +1521,7 @@ __global__ void expandInputRowsKernel( | |
| #endif | ||
|
|
||
| // Pad zeros in the extra SFs along the N dimension, we do this to ensure there are no nan values | ||
| // in the padded SF atom | ||
| // in the padded SF atom. | ||
| if constexpr (is_nvfp4 || is_mxfp8) { | ||
| int64_t const start_offset = threadIdx.x; | ||
| int64_t const stride = EXPAND_THREADS_PER_BLOCK; | ||
|
|
@@ -1526,28 +1535,29 @@ __global__ void expandInputRowsKernel( | |
| : TmaWarpSpecializedGroupedGemmInput::MinNDimAlignmentMXFPX; | ||
| static_assert((min_num_tokens_alignment & (min_num_tokens_alignment - 1)) == 0, | ||
| "Min num tokens alignment must be a power of two"); | ||
| // Since we don't know a priori how much padding is needed we assume the max per expert | ||
| // NOTE: we don't use (min_num_tokens_alignment-1) to be able to do power of two divisions | ||
| int64_t num_padding_tokens = min_num_tokens_alignment * num_experts_per_node; | ||
|
|
||
| for (int64_t padding_token = blockIdx.x; padding_token < num_padding_tokens; | ||
| padding_token += gridDim.x) { | ||
| int64_t expert = padding_token / min_num_tokens_alignment; | ||
| // Iterate over experts (skipping empty ones) instead of over all potential padding slots. | ||
| // For decode with 8 active experts out of 128, this skips 120 experts entirely instead | ||
| // of iterating over 128*128=16384 slots with most being wasted. | ||
| // The (pad_row x K_element) work is flattened into a 1D loop so all threads participate. | ||
| // Without flattening, only padded_num_elems_in_col threads (e.g. 64) are active per | ||
| // pad_row iteration while the rest idle β wasting 75% of threads for hidden_size=2048. | ||
| for (int64_t expert = blockIdx.x; expert < num_experts_per_node; expert += gridDim.x) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can you try simply disabling this padding. It was pointed out that this might not be necessary since these weight columns should not impact any valid parts. The one catch is that if they are NaN this can propagate. We can fix that by skipping the OOB values in the activation function - currently all NVFP4/MXFP8 implementations use doActivationKernel afaik, so this should be straightforward
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We should add some tests memsetting the workspace buffer to NaN/Infinity to cover this
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Actually, this is just for the OOB values in the MMA tile, cutlass GEMM should already prevent this from propagating. We don't even need to make activation changes. Still should add test coverage though |
||
| int64_t num_tokens_before_expert = expert_first_token_offset[expert]; | ||
| int64_t num_tokens_after_expert = expert_first_token_offset[expert + 1]; | ||
| int64_t tokens_to_expert = num_tokens_after_expert - num_tokens_before_expert; | ||
| int64_t padding_to_expert = TmaWarpSpecializedGroupedGemmInput::alignToSfDim( | ||
| tokens_to_expert, min_num_tokens_alignment) - | ||
| tokens_to_expert; | ||
| int64_t expert_pad_idx = padding_token % min_num_tokens_alignment; | ||
| if (expert_pad_idx < padding_to_expert) { | ||
| for (int64_t elem_index = start_offset; elem_index < padded_num_elems_in_col; | ||
| elem_index += stride) { | ||
| writeSF<VecSize, VecSize>(num_tokens_before_expert, expert, /*source_row*/ -1, | ||
| num_tokens_after_expert + expert_pad_idx, elem_index, | ||
| padded_hidden_size, fc1_act_sf_flat, | ||
| /* input_sf */ nullptr); // Pass nulltpr input_sf so we write 0 | ||
| } | ||
| if (tokens_to_expert == 0) continue; | ||
| int64_t padded_tokens = TmaWarpSpecializedGroupedGemmInput::alignToSfDim( | ||
| tokens_to_expert, min_num_tokens_alignment); | ||
| int64_t num_pad_rows = padded_tokens - tokens_to_expert; | ||
| int64_t total_sf_writes = num_pad_rows * padded_num_elems_in_col; | ||
| for (int64_t work_idx = start_offset; work_idx < total_sf_writes; work_idx += stride) { | ||
| int64_t pad_idx = tokens_to_expert + work_idx / padded_num_elems_in_col; | ||
| int64_t elem_index = work_idx % padded_num_elems_in_col; | ||
| writeSF<VecSize, VecSize>(num_tokens_before_expert, expert, /*source_row*/ -1, | ||
| num_tokens_before_expert + pad_idx, elem_index, | ||
| padded_hidden_size, fc1_act_sf_flat, | ||
| /* input_sf */ nullptr); | ||
| } | ||
| } | ||
| } | ||
|
|
@@ -1568,18 +1578,14 @@ void expandInputRowsKernelLauncher( | |
| (std::is_same_v<ExpandedActivationsType, __nv_fp4_e2m1> && fc1_act_sf_flat) || | ||
| !use_per_expert_act_scale, | ||
| "Per-expert act scale for FC1 is only supported for NVFP4 activations"); | ||
| constexpr int64_t min_num_tokens_alignment = | ||
| std::is_same_v<ExpandedActivationsType, __nv_fp4_e2m1> | ||
| ? TmaWarpSpecializedGroupedGemmInput::MinNDimAlignmentNVFP4 | ||
| : TmaWarpSpecializedGroupedGemmInput::MinNDimAlignmentMXFPX; | ||
| int64_t num_padding_tokens = min_num_tokens_alignment * num_experts_per_node; | ||
| #else | ||
| int64_t num_padding_tokens = 0; | ||
| #endif | ||
|
|
||
| static int64_t const smCount = tensorrt_llm::common::getMultiProcessorCount(); | ||
| // Note: Launching 8 blocks per SM can fully leverage the memory bandwidth (tested on B200). | ||
| int64_t const blocks = std::min(smCount * 8, std::max(num_rows * k, num_padding_tokens)); | ||
| // The N-dim padding loop is now expert-driven and strides over experts with gridDim.x, so it | ||
| // works correctly with any grid size. No need to inflate the grid for padding work. | ||
| int64_t const blocks = std::min(smCount * 8, std::max(num_rows * k, | ||
| static_cast<int64_t>(num_experts_per_node))); | ||
| int64_t const threads = EXPAND_THREADS_PER_BLOCK; | ||
|
|
||
| auto func = [&]() { | ||
|
|
@@ -2058,7 +2064,8 @@ void doGatedActivation(ActivationOutputType* output, GemmOutputType const* gemm_ | |
|
|
||
| template <class T, class GemmOutputType, class ScaleBiasType, class ActFn, | ||
| TmaWarpSpecializedGroupedGemmInput::FpXBlockScalingType BlockScalingType> | ||
| __global__ void doActivationKernel(T* output, GemmOutputType const* gemm_result, | ||
| __global__ __launch_bounds__(ACTIVATION_THREADS_PER_BLOCK) | ||
| void doActivationKernel(T* output, GemmOutputType const* gemm_result, | ||
| float const* fp8_quant, ScaleBiasType const* bias_ptr, | ||
| bool bias_is_broadcast, int64_t const* expert_first_token_offset, | ||
| int num_experts_per_node, int64_t inter_size, | ||
|
|
@@ -2155,11 +2162,26 @@ __global__ void doActivationKernel(T* output, GemmOutputType const* gemm_result, | |
| assert(gated_off % ACTIVATION_ELEM_PER_THREAD == 0); | ||
| int64_t const gated_off_vec = gated_off / ACTIVATION_ELEM_PER_THREAD; | ||
|
|
||
| // For FP4/MXFP8: extend the loop to cover K-dim padding (writes zero SFs for padded columns). | ||
| // This merges K-dim padding into the main loop for better cache locality. | ||
| int64_t const loop_elems = (IsNVFP4 || IsMXFP8) | ||
| ? padded_inter_size / VecSize // cover both real elements and K-dim padding | ||
| : num_elems_in_col; | ||
| bool const do_k_padding = (IsNVFP4 || IsMXFP8) && (padded_inter_size > inter_size); | ||
|
|
||
| ActFn fn{}; | ||
| fn.alpha = gate_alpha; | ||
| fn.beta = gate_beta; | ||
| fn.limit = gate_limit; | ||
| for (int64_t elem_index = start_offset; elem_index < num_elems_in_col; elem_index += stride) { | ||
| for (int64_t elem_index = start_offset; elem_index < loop_elems; elem_index += stride) { | ||
| // K-dim padding region: write zero SF only (no activation compute) | ||
| if (do_k_padding && elem_index >= num_elems_in_col) { | ||
| writeSF<VecSize, VecSize>(num_tokens_before_expert, expert, /*source_row*/ -1, token, | ||
| elem_index, padded_inter_size, fc2_act_sf_flat, | ||
| /* input_sf */ nullptr); | ||
| continue; | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| } | ||
|
|
||
| auto fc1_value = | ||
| arrayConvert<GemmResultElem, ComputeElem>(gemm_result_vec[elem_index + gated_off_vec]); | ||
| if (bias_ptr) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There is a critical unit mismatch in the merged activation loop for FP4/MXFP8. For example, if
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good catch β you're absolutely right. The main loop indexes in units of ACTIVATION_ELEM_PER_THREAD (8) while the K-dim padding loop indexes in units of VecSize (16 for NVFP4). Merging them into a single loop with padded_inter_size / VecSize as the upper bound causes the main loop to under-iterate (48 iterations instead of 96 for inter_size=768), leaving half the columns unprocessed. The elem_index >= num_elems_in_col check also compares values in different units. Reverted to the original separate K-dim padding loop in the next commit. In practice, this merge was a no-op for the target workload anyway β Qwen3-30B-A3B has inter_size=768 which is already 128-aligned, so the K-dim padding loop executes zero iterations. The actual performance wins in this PR come from the N-dim padding restructuring and computeStrides changes, which are unaffected. |
||
|
|
@@ -2198,29 +2220,14 @@ __global__ void doActivationKernel(T* output, GemmOutputType const* gemm_result, | |
| output_vec[elem_index] = arrayConvert<ComputeElem, OutputElem>(post_act_val); | ||
| } | ||
| } | ||
|
|
||
| // Pad zeros in the extra SFs along the K dimension, we do this to ensure there are no nan | ||
| // values in the padded SF atom | ||
| if constexpr (IsNVFP4 || IsMXFP8) { | ||
| // Use VecSize per thread since we are just writing out zeros so every thread can process a | ||
| // whole vector | ||
| size_t padding_start_offset = inter_size / VecSize + start_offset; | ||
| size_t padding_elems_in_col = padded_inter_size / VecSize; | ||
| for (int64_t elem_index = padding_start_offset; elem_index < padding_elems_in_col; | ||
| elem_index += stride) { | ||
| writeSF<VecSize, VecSize>(num_tokens_before_expert, expert, /*source_row*/ -1, token, | ||
| elem_index, padded_inter_size, fc2_act_sf_flat, | ||
| /* input_sf */ nullptr); // Pass nulltpr input_sf so we write 0 | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900)) | ||
| asm volatile("griddepcontrol.launch_dependents;"); | ||
| #endif | ||
|
|
||
| // Pad zeros in the extra SFs along the N dimension, we do this to ensure there are no nan values | ||
| // in the padded SF atom | ||
| // in the padded SF atom. | ||
| if constexpr (IsNVFP4 || IsMXFP8) { | ||
| int64_t const start_offset = threadIdx.x; | ||
| int64_t const stride = ACTIVATION_THREADS_PER_BLOCK; | ||
|
|
@@ -2234,31 +2241,29 @@ __global__ void doActivationKernel(T* output, GemmOutputType const* gemm_result, | |
| : TmaWarpSpecializedGroupedGemmInput::MinNDimAlignmentMXFPX; | ||
| static_assert((min_num_tokens_alignment & (min_num_tokens_alignment - 1)) == 0, | ||
| "Min num tokens alignment must be a power of two"); | ||
| // Since we don't know a priori how much padding is needed we assume the max per expert | ||
| // NOTE: we don't (min_num_tokens_alignment-1) to have power of two divisions | ||
| int64_t num_padding_tokens = min_num_tokens_alignment * num_experts_per_node; | ||
|
|
||
| for (int64_t padding_token = blockIdx.x; padding_token < num_padding_tokens; | ||
| padding_token += gridDim.x) { | ||
| int64_t expert = padding_token / min_num_tokens_alignment; | ||
| // Iterate over experts (skipping empty ones) instead of over all potential padding slots. | ||
| // For decode with 8 active experts out of 128, this skips 120 experts entirely instead | ||
| // of iterating over 128*128=16384 slots with most being wasted. | ||
| // The (pad_row x K_element) work is flattened into a 1D loop so all threads participate. | ||
| // Without flattening, only padded_num_elems_in_col threads (e.g. 64) are active per | ||
| // pad_row iteration while the rest idle β wasting 75% of threads for inter_size=768. | ||
| for (int64_t expert = blockIdx.x; expert < num_experts_per_node; expert += gridDim.x) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As above, this padding can simply be skipped. In this case nothing should ever use it so it is safe to just ignore |
||
| int64_t num_tokens_before_expert = expert_first_token_offset[expert]; | ||
| int64_t num_tokens_after_expert = expert_first_token_offset[expert + 1]; | ||
| int64_t tokens_to_expert = num_tokens_after_expert - num_tokens_before_expert; | ||
| int64_t padding_to_expert = TmaWarpSpecializedGroupedGemmInput::alignToSfDim( | ||
| tokens_to_expert, min_num_tokens_alignment) - | ||
| tokens_to_expert; | ||
| int64_t expert_pad_idx = padding_token % min_num_tokens_alignment; | ||
| if (expert_pad_idx < padding_to_expert) { | ||
| for (int64_t elem_index = start_offset; elem_index < padded_num_elems_in_col; | ||
| elem_index += stride) { | ||
| // The SF buffer is padded to a multiple of MinNDimAlignment for each expert | ||
| // This means we can safely write to offset num_tokens_after_expert + padded_token, since | ||
| // the next expert will leave space for the padding | ||
| writeSF<VecSize, VecSize>(num_tokens_before_expert, expert, /*source_row*/ -1, | ||
| num_tokens_after_expert + expert_pad_idx, elem_index, | ||
| padded_inter_size, fc2_act_sf_flat, | ||
| /* input_sf */ nullptr); // Pass nulltpr input_sf so we write 0 | ||
| } | ||
| if (tokens_to_expert == 0) continue; | ||
| int64_t padded_tokens = TmaWarpSpecializedGroupedGemmInput::alignToSfDim( | ||
| tokens_to_expert, min_num_tokens_alignment); | ||
| int64_t num_pad_rows = padded_tokens - tokens_to_expert; | ||
| int64_t total_sf_writes = num_pad_rows * padded_num_elems_in_col; | ||
| for (int64_t work_idx = start_offset; work_idx < total_sf_writes; work_idx += stride) { | ||
| int64_t pad_idx = tokens_to_expert + work_idx / padded_num_elems_in_col; | ||
| int64_t elem_index = work_idx % padded_num_elems_in_col; | ||
| writeSF<VecSize, VecSize>(num_tokens_before_expert, expert, /*source_row*/ -1, | ||
| num_tokens_before_expert + pad_idx, elem_index, | ||
| padded_inter_size, fc2_act_sf_flat, | ||
| /* input_sf */ nullptr); | ||
| } | ||
| } | ||
| } | ||
|
|
@@ -2272,18 +2277,12 @@ void doActivation(T* output, GemmOutputType const* gemm_result, float const* fp8 | |
| QuantParams const& quant_params, bool use_per_expert_act_scale, | ||
| TmaWarpSpecializedGroupedGemmInput::ElementSF* fc2_act_sf_flat, bool enable_pdl, | ||
| cudaStream_t stream) { | ||
| #ifdef ENABLE_FP4 | ||
| constexpr int64_t min_num_tokens_alignment = | ||
| std::is_same_v<T, __nv_fp4_e2m1> ? TmaWarpSpecializedGroupedGemmInput::MinNDimAlignmentNVFP4 | ||
| : TmaWarpSpecializedGroupedGemmInput::MinNDimAlignmentMXFPX; | ||
| int64_t num_padding_tokens = min_num_tokens_alignment * num_experts_per_node; | ||
| #else | ||
| int64_t num_padding_tokens = 0; | ||
| #endif | ||
|
|
||
| static int64_t const smCount = tensorrt_llm::common::getMultiProcessorCount(); | ||
| // Note: Launching 8 blocks per SM can fully leverage the memory bandwidth (tested on B200). | ||
| int64_t const blocks = std::min(smCount * 8, std::max(expanded_num_tokens, num_padding_tokens)); | ||
| // The N-dim padding loop is now expert-driven and strides over experts with gridDim.x, so it | ||
| // works correctly with any grid size. No need to inflate the grid for padding work. | ||
| int64_t const blocks = std::min(smCount * 8, std::max(expanded_num_tokens, | ||
| static_cast<int64_t>(num_experts_per_node))); | ||
| int64_t const threads = ACTIVATION_THREADS_PER_BLOCK; | ||
|
|
||
| auto fn = [&]() { | ||
|
|
@@ -3952,7 +3951,10 @@ CutlassMoeFCRunner<T, WeightType, OutputType, InputType, BackBoneType, IsMXFPX, | |
| layout_info1.fpX_block_scaling_type = getScalingType(); | ||
| layout_info2.fpX_block_scaling_type = getScalingType(); | ||
|
|
||
| int const threads = std::min(1024, num_experts_per_node); | ||
| // Use a smaller block size to spread work across multiple SMs. Each thread handles one expert, | ||
| // so we only need num_experts_per_node threads total. With 1 warp per block, 128 experts | ||
| // yields 4 blocks across 4 SMs instead of 1 block on 1 SM. | ||
| int const threads = std::min(32, num_experts_per_node); | ||
| int const blocks = (num_experts_per_node + threads - 1) / threads; | ||
|
|
||
| auto* kernel_instance = | ||
|
|
||
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.
The early exit for
gemm_m == 0is placed before the initialization ofint4_groupwise_params.shape.problem_shapes(lines 1273-1285). CUTLASS grouped GEMM typically requires all problem shapes to be initialized, even for zero-M problems, to correctly traverse the problem list. Skipping this initialization for experts with no tokens may lead to undefined behavior or illegal memory accesses if the visitor reads uninitialized data from the problem shape buffer. Consider moving the early exit after all problem shape assignments.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.
Good point β moved the early exit after all problem shape assignments (both regular and int4_groupwise). CUTLASS's tile scheduler may read problem shapes for all experts to traverse the problem list, so they need to be fully initialized even for zero-M entries. The remaining work after the early exit (alpha scales, block scaling factors, strides, pointers) is only consumed by CUTLASS for experts it actually processes, so skipping those for zero-M experts is safe.