Skip to content
Merged
Changes from 15 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
0cc6825
Add spark to microbenchmarks
bkryu Apr 6, 2026
0fb4db3
CUTLASS MoE
bkryu Apr 7, 2026
a94b434
Tune
bkryu Apr 7, 2026
2770a20
Fix
bkryu Apr 7, 2026
866dbbc
computeStrides optimize
bkryu Apr 7, 2026
175b4c8
computeStrides optimize
bkryu Apr 7, 2026
1b3e421
Skip memset
bkryu Apr 7, 2026
9bc0e0b
Cleanup
bkryu Apr 7, 2026
b3d96ab
Perf tune
bkryu Apr 7, 2026
2324fb3
revert perf tune
bkryu Apr 7, 2026
626fed1
Perf Tune v2 -- Flatten N-dim padding
bkryu Apr 7, 2026
f7eb890
Merge branch 'main' into bench_spark
bkryu Apr 7, 2026
527ede3
Merge branch 'main' into bench_spark
bkryu Apr 7, 2026
3ab2921
Port optimizations from TRTLLM
bkryu Apr 7, 2026
e9224bf
Merge branch 'main' into bench_spark
bkryu Apr 8, 2026
b5d140b
pre-commit
bkryu Apr 8, 2026
451befd
Address comments
bkryu Apr 8, 2026
a33b48c
Reduce unnecessary diffs from comments
bkryu Apr 8, 2026
5d268c5
Merge branch 'main' into bench_spark
bkryu Apr 8, 2026
580664b
Skip N-padding
bkryu Apr 9, 2026
85ceb8a
NAN fill testing for removing the N-padding
bkryu Apr 9, 2026
37dc223
remove the 0xFF poison memsets
bkryu Apr 9, 2026
45f97f0
Merge branch 'main' into bench_spark
bkryu Apr 9, 2026
6436f8e
Poison with 0xff AFTER kernel to make sure poisoning works
bkryu Apr 9, 2026
a22ce59
Undo poisoning
bkryu Apr 9, 2026
e7bc590
Address comments -- replace PDL PTX instruction to CUDA API
bkryu Apr 9, 2026
cabf9cd
Merge branch 'main' into bench_spark
bkryu Apr 9, 2026
6f36003
Poison K-dim for validation
bkryu Apr 10, 2026
ab0068c
Remove the poisoned K-dim padding
bkryu Apr 10, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 84 additions & 82 deletions csrc/fused_moe/cutlass_backend/cutlass_fused_moe_kernels.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The early exit for gemm_m == 0 is placed before the initialization of int4_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.

Copy link
Copy Markdown
Collaborator Author

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.


if (layout_info1.int4_groupwise_params.enabled) {
layout_info1.int4_groupwise_params.shape.problem_shapes[expert] =
TmaWarpSpecializedGroupedGemmInput::INT4GroupwiseParams::ProblemShapeInt::
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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;
Expand All @@ -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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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);
}
}
}
Expand All @@ -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 = [&]() {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Comment thread
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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

critical

There is a critical unit mismatch in the merged activation loop for FP4/MXFP8. loop_elems is calculated in units of VecSize (16 or 32), but the loop body indexes gemm_result_vec and output_vec using elem_index as if it were in units of ACTIVATION_ELEM_PER_THREAD (8).

For example, if inter_size is 1024 and VecSize is 16, loop_elems will be 64. The loop will only iterate 64 times, processing elements 0-511 (since gemm_result_vec[elem_index] accesses 8 elements), leaving the second half of the columns unprocessed. Furthermore, the padding check elem_index >= num_elems_in_col compares values with different units (units of VecSize vs units of 8), leading to incorrect branching between compute and padding logic. This logic needs to be corrected to ensure all elements are processed and indexing is consistent.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Expand Down Expand Up @@ -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;
Expand All @@ -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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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);
}
}
}
Expand All @@ -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 = [&]() {
Expand Down Expand Up @@ -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 =
Expand Down
Loading