I've written a Triton-accelerated kernel for MoE experts counting and indexing at @qwen3_moe_fused/kernels/indexing.py , and benchmarked it at @benchmark_indexing.py , and the results are at @indexing.csv . See @torch_compile_debug/run_2026_01_15_20_50_00_564109-pid_54876/torchinductor/model__0_inference_0.0/output_code.py for the naive function compiled by torch.compile, and @torch_compile_debug/run_2026_01_15_20_50_00_564109-pid_54876/torchinductor/model__1_inference_1.1/output_code.py for the accelerated function compiled. Explain the performance difference between them.
--- Content from referenced files ---
Content from @benchmark_indexing.py:
#!/usr/bin/env python3
import gc
import os
import torch
import triton
from qwen3_moe_fused.kernels.indexing import get_expert_counts_and_idx, get_expert_counts_and_idx_naive
@triton.testing.perf_report(
[
triton.testing.Benchmark(
x_names=["N"],
x_vals=[2**i for i in range(10, 21)],
line_arg="provider",
line_vals=provider_names,
line_names=provider_names,
ylabel="GB/s",
plot_name="indexing",
args={},
)
]
)
def benchmark(N, provider):
print("N", N, "provider", provider, "begin")
gc.collect()
torch.cuda.empty_cache()
code
E = 128
device = "cuda"
dtype = torch.int32
s = torch.randint(0, E, (N,), device=device, dtype=dtype)
quantiles = [0.5, 0.2, 0.8]
ms, min_ms, max_ms = triton.testing.do_bench(lambda: providers[provider](s, E), quantiles=quantiles)
gbps = lambda ms: 3 * N * 4 / ms * 1e-6
print("N", N, "E", E, "provider", provider, "end", gbps(ms))
return gbps(ms), gbps(max_ms), gbps(min_ms)
if name == "main":
with torch.inference_mode():
benchmark.run(print_data=True, save_path="./")
Content from @indexing.csv:
N,naive,triton
1024.000000,0.750000,0.461538
2048.000000,1.714286,0.685714
4096.000000,2.823529,1.371429
8192.000000,4.173913,2.742857
16384.000000,5.485714,5.333333
32768.000000,6.508474,9.365854
65536.000000,7.177570,14.490566
131072.000000,7.718593,21.333333
262144.000000,7.897172,28.444444
524288.000000,8.020888,33.758241
1048576.000000,8.062992,36.035190
Content from @qwen3_moe_fused/kernels/indexing.py:
from functools import partial
import torch
import triton
import triton.language as tl
Faster than torch.histc when each element of s is an int in [0, E)
What's the optimal block size in the accelerated kernel?
User
Is there any theoretical insight on how to determine the optimal block size, such as sqrt(N)?
Assistant
User
In the benchmark results @indexing.csv , the accelerated kernel is slow when N is small. How to improve its performance when N is small?
--- Content from referenced files ---
Content from @indexing.csv:
N,naive,triton
1024.000000,0.750000,0.461538
2048.000000,1.714286,0.685714
4096.000000,2.823529,1.371429
8192.000000,4.173913,2.742857
16384.000000,5.485714,5.333333
32768.000000,6.508474,9.365854
65536.000000,7.177570,14.490566
131072.000000,7.718593,21.333333
262144.000000,7.897172,28.444444
524288.000000,8.020888,33.758241
1048576.000000,8.062992,36.035190
--- End of content ---
Assistant
The poor performance at small N is due to low GPU Occupancy.
Triton Kernel: With N=1024 and BLOCK_SIZE=1024, the kernel launches only 1 block. Modern GPUs have 60-100+ Streaming Multiprocessors (SMs), so utilizing only 1 SM leaves >99% of the GPU idle.
Naive Implementation: Even though it does more theoretical work (), it performs operations on tensors of size . This exposes massive parallelism (131,072 threads), allowing the GPU to fully saturate its compute units.
User
In get_expert_counts_and_idx, there are 3 cumsums between the two Triton kernel calls. Why there is only 1 cumsum (tl.associative_scan) after compiling?
Assistant
This happens because torch.compile specialized the code for the specific input size used in the trace, which was .
Content from @torch_compile_debug/run_2026_01_15_20_50_00_564109-pid_54876/torchinductor/model__0_inference_0.0/output_code.py:
AOT ID: ['0_inference']
from ctypes import c_void_p, c_long, c_int
import torch
import math
import random
import os
import tempfile
from math import inf, nan
from cmath import nanj
from torch._inductor.hooks import run_intermediate_hooks
from torch._inductor.utils import maybe_profile
from torch._inductor.codegen.memory_planning import _align as align
from torch import device, empty_strided
from torch._inductor.async_compile import AsyncCompile
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import start_graph, end_graph
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
triton_per_fused_arange_cumsum_eq_sum_unsqueeze_0 = async_compile.triton('triton_per_fused_arange_cumsum_eq_sum_unsqueeze_0', '''
import triton
import triton.language as tl
from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, DeviceProperties
triton_helpers.set_driver_to_gpu()
triton_per_fused_cumsum_1 = async_compile.triton('triton_per_fused_cumsum_1', '''
import triton
import triton.language as tl
from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, DeviceProperties
triton_helpers.set_driver_to_gpu()
triton_poi_fused_add_arange_empty_like_index_index_put_sub_2 = async_compile.triton('triton_poi_fused_add_arange_empty_like_index_index_put_sub_2', '''
import triton
import triton.language as tl
from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, DeviceProperties
triton_helpers.set_driver_to_gpu()
if name == "main":
from torch._inductor.wrapper_benchmark import compiled_module_main
compiled_module_main('None', benchmark_compiled_module)
Content from @torch_compile_debug/run_2026_01_15_20_50_00_564109-pid_54876/torchinductor/model__1_inference_1.1/output_code.py:
AOT ID: ['1_inference']
from ctypes import c_void_p, c_long, c_int
import torch
import math
import random
import os
import tempfile
from math import inf, nan
from cmath import nanj
from torch._inductor.hooks import run_intermediate_hooks
from torch._inductor.utils import maybe_profile
from torch._inductor.codegen.memory_planning import _align as align
from torch import device, empty_strided
from torch._inductor.async_compile import AsyncCompile
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import start_graph, end_graph
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
triton_poi_fused_zeros_0 = async_compile.triton('triton_poi_fused_zeros_0', '''
import triton
import triton.language as tl
from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, DeviceProperties
triton_helpers.set_driver_to_gpu()
from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, DeviceProperties
triton_per_fused_add_cumsum_sub_sum_unsqueeze_1 = async_compile.triton('triton_per_fused_add_cumsum_sub_sum_unsqueeze_1', '''
import triton
import triton.language as tl
from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, DeviceProperties
triton_helpers.set_driver_to_gpu()
from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, DeviceProperties
if name == "main":
from torch._inductor.wrapper_benchmark import compiled_module_main
compiled_module_main('None', benchmark_compiled_module)
--- End of content ---
The performance difference arises from a fundamental difference in algorithmic complexity between the two implementations, specifically how they scale with the number of experts (E) and the sequence length (N).
1. Naive Implementation (O(N⋅E))
The naive implementation compares every token against every expert index.
This line creates a boolean matrix of size E×N. Even though torch.compile fuses operations, the logic requires iterating over this theoretical E×N space.
Generated Code (model__0_inference_0.0):
The kernel triton_per_fused_arange_cumsum_eq_sum_unsqueeze_0 implements this. It uses a persistent reduction where the grid is defined by x (Experts, 128) and the inner loop iterates over r0_ (Batch N).
python
# Inside triton_per_fused_arange_cumsum_eq_sum_unsqueeze_0
# xnumel = 128 (Experts), r0_numel = N (Sequence Length)
tmp2 = tmp1 == tmp0 # Comparison happening E * N times
This results in 128×N comparisons and arithmetic operations. As N grows, the "useful" work (calculating indices for N items) is overshadowed by the redundant checks against every non-matching expert.
2. Triton Implementation (O(N))
The Triton implementation uses a "divide and conquer" approach that avoids checking every expert for every token.
Source Code:
It splits N into blocks (size 1024).
_count_kernel: Each thread loads a token index and performs a single atomic increment.
_index_kernel: Each block performs a local sort to group tokens by expert, then uses prefix sums (calculated cheaply on the side) to determine global positions.
Performance Impact:
Instead of 128 operations per token, the Triton kernel performs a constant number of operations (load + atomic add + sort small block + store). The complexity depends primarily on N, not the product N⋅E.
Summary
Naive: Performs roughly 128 (value of E) operations per token. The benchmark shows it hitting a ceiling around 8 GB/s, limited by the compute/bandwidth required to process the E×N expansion.
Triton: Performs ≈1 complex operation sequence per token (dominated by the local sort and memory IO). The benchmark shows it reaching 36 GB/s, which is significantly closer to the hardware's effective memory bandwidth limit for this pattern, as it only touches the necessary data.
This is an excellent question. While sqrt(N) is a common heuristic in many block-based algorithms (like square root decomposition), it does not apply here.
The optimal block size is actually determined by a balance between Memory Traffic (favoring large blocks) and Sorting Efficiency/Hardware Limits (favoring small blocks).
The Theoretical Cost Model
Let N be the sequence length, E the number of experts, and B the block size.
Phase 1: Counting (Memory Bound)
The _count_kernel computes counts for each block and writes them to VRAM.
Output size: BN×E.
Cost: Proportional to writing this intermediate table.
Insight: If B is small (e.g., 128), and E=128, you are writing 128N× integers. This doubles the total memory traffic of the entire operation! You want to make this negligible.
Phase 2: Indexing (Compute Bound + Latency)
The _index_kernel performs a sort on a block of size B.
Complexity:N⋅log(B).
Insight: Larger B increases the sorting work per element (logB). More importantly, GPUs have hard hardware limits (registers, shared memory).
Why sqrt(N) is wrong
Global vs. Local:sqrt(N) assumes the problem structure scales with total input size N. Here, the constraints are local hardware limits (register file size per block) and the fixed parameter E.
Example: If N=1,000,000, sqrt(N) = 1000. This happens to work. But if , = 10,000. A block size of 10,000 would crash the kernel or run extremely slowly because it exceeds the GPU's shared memory capacity for a single block sort.
The "Sweet Spot" Formula
We want to minimize the total cost. Roughly:
Cost≈C1⋅Memory Overhead
Taking the derivative with respect to B suggests the optimal B is linearly proportional to E:
Boptimal∝E
In your benchmark (E=128):
128 (Too Small): Memory overhead is huge (100% extra traffic).
512/1024 (Optimal): Memory overhead is low (≈12−25%). Sorting is still fast and high occupancy.
Conclusion: The optimal block size is typically 4E to 8E, clamped to the nearest hardware-friendly power of 2 (usually 512 or 1024 on current GPUs). It is independent of N.
N×E
1024×128
Solution:
Use a hybrid dispatch strategy. Since the naive implementation is significantly faster for small N (due to better parallelism), we should dispatch to it when N is below the crossover point observed in your benchmarks (approx N<16384).
I will modify qwen3_moe_fused/kernels/indexing.py to implement this optimization.
N
=
1024
The Reason: Single Block Collapse
In your generated code (model__1_inference_1.1/output_code.py), the input size is N=1024 and BLOCK_SIZE=1024. This results in num_blocks = 1.
When num_blocks is 1, the block_counts tensor has shape (1, E). Let's trace the Python logic with this shape:
block_counts.cumsum(dim=0): Computing a cumulative sum along a dimension of size 1 is a no-op (identity). The compiler eliminates it.
counts = block_counts.sum(dim=0): Summing along a dimension of size 1 is just a copy (identity). The compiler eliminates the reduction.
counts.cumsum(dim=0): Since counts is shape (E,), this is a standard scan. This is the 1 scan you see.
block_counts.cumsum(dim=1): This is also a scan over E.
Because num_blocks=1, counts and block_counts[0] are identical. The compiler realizes that calculating the same scan twice is redundant (or that the subsequent math + global - local cancels out perfectly for the single-block case), so it fuses everything into a single kernel pass with just one tl.associative_scan.
Evidence in output_code.py
In the file @torch_compile_debug/.../output_code.py:
python
# The input size is hardcoded to 1024
arg0_1 = rand_strided((1024, ), (1, ), device='cuda:0', dtype=torch.int32)
And in the fused kernel triton_per_fused_add_cumsum_sub_sum_unsqueeze_1:
python
# size_hints x=1 means the outer dimension (blocks) is 1.
# r0_=128 means the inner dimension (experts) is 128.
size_hints={'x': 1, 'r0_': 128}
...
# Only one scan is performed, over the r0 (Expert) dimension
tmp3, = tl.associative_scan((tmp2,), 1, _triton_helper_fn_add0)
If you ran this with N>1024, num_blocks would be >1, and you would see the other cumsum operations appear (likely in separate kernels, as Triton usually handles multi-dimensional scans by splitting them).
128=
N
B≫E
Sorting 1024 elements fits efficiently in registers/SRAM on modern GPUs.
Sorting 4096+ elements often spills or requires slower algorithms, drastically reducing "Occupancy" (the number of active warps hiding memory latency).