Inferensys

Glossary

Fused MoE Kernels

Fused MoE kernels are highly optimized GPU kernels that combine the routing logic, token permutation, and sparse matrix multiplications of multiple experts into a single, efficient operation to minimize memory movement and kernel launch overhead.
Developer demonstrating multi-agent tool use, agent tool selection interface on laptop, casual tech demo moment.
INFERENCE OPTIMIZATION

What are Fused MoE Kernels?

Fused MoE kernels are highly optimized GPU operations that combine the disparate computational steps of a Mixture of Experts layer into a single, efficient kernel launch.

A Fused MoE Kernel is a custom, low-level GPU program that executes the entire conditional computation of a Mixture of Experts (MoE) layer—including the gating network calculation, token routing, expert selection, and the subsequent sparse matrix multiplications—as a single, monolithic operation. This fusion eliminates the overhead of launching multiple smaller kernels and drastically reduces intermediate data movement between GPU memory and registers, which is a major bottleneck. The result is a significant reduction in router latency and a substantial increase in throughput for MoE model inference.

These kernels are engineered to handle the sparse activation pattern intrinsic to MoE models, where only a top-k selection of experts processes each token. By fusing operators, they efficiently manage the all-to-all communication of tokens between experts and the batched computation on non-contiguous memory blocks. This optimization is critical for realizing the theoretical efficiency of sparse models like Mixtral or Switch Transformers, making them viable for low-latency production serving in engines such as vLLM.

INFERENCE OPTIMIZATION

Key Benefits of Fused MoE Kernels

Fused MoE kernels are highly optimized GPU operations that combine the routing, permutation, and sparse computation steps of a Mixture of Experts layer into a single, efficient launch. This fusion directly targets the primary bottlenecks in sparse model inference.

01

Minimized Kernel Launch Overhead

In a naive implementation, a Mixture of Experts forward pass requires launching multiple separate GPU kernels: one for the gating network, one to permute/sort tokens by expert, and several for the sparse matrix multiplications of each expert. Each kernel launch incurs significant latency from driver scheduling and setup. A fused kernel executes this entire sequence as one monolithic operation, eliminating this serial overhead and drastically reducing scheduler contention on the GPU.

02

Reduced Global Memory Traffic

The most significant performance gain comes from eliminating intermediate writes and reads to high-bandwidth memory (HBM). Without fusion, the outputs of each step (router scores, token permutation indices, intermediate expert outputs) must be written to global memory and then read by the next kernel. This memory-bound process is a major bottleneck. A fused kernel keeps these intermediate tensors in fast on-chip registers or shared memory, performing the entire computation in a single pass and dramatically cutting HBM traffic, which is often the limiting factor for throughput.

03

Optimal Load Balancing & Utilization

Fused kernels allow for sophisticated, warp-level load balancing that is impossible with separate kernels. They can:

  • Dynamically distribute the variable workload of sparse expert matrices across streaming multiprocessors (SMs).
  • Implement fine-grained synchronization (e.g., warp-level primitives) to handle the irregular computation graph where different experts process different numbers of tokens.
  • This leads to near-ideal GPU utilization, hiding latency and ensuring all compute units are actively processing the sparse computation, not waiting on memory or other warps.
04

Elimination of Costly Permutation Operations

A core step in MoE is gathering tokens assigned to the same expert from scattered memory locations for efficient batched computation. A separate all-to-all communication or a sort/permute kernel is typically required. In a fused design, this gather/scatter logic is embedded within the kernel's indexing arithmetic. Tokens are logically routed and processed in-place or with minimal, coordinated data movement, avoiding the launch of a dedicated, memory-intensive permutation kernel. This is critical for performance in expert parallelism scenarios across multiple GPUs.

05

Enhanced Support for Dynamic Shapes

Modern inference serving uses continuous batching, where requests of varying sequence lengths are combined into a single batch. In MoE, this results in a highly irregular workload per expert. Fused kernels are uniquely suited to this dynamism because their internal logic (e.g., using parallel prefix sums for workload assignment) can adapt to variable token counts per expert at runtime without recompilation or suboptimal padding. This provides consistent low latency in production serving systems like vLLM with MoE support.

06

Reduced Framework & Python Overhead

From a systems perspective, a single fused kernel call simplifies the execution graph, reducing pressure on the framework's (e.g., PyTorch's) dispatcher and Python interpreter. Instead of managing dependencies and launches for many small ops, the runtime schedules one heavyweight, efficient kernel. This reduces CPU overhead and context switching, which is vital for achieving high queries per second (QPS) in server environments. It also simplifies integration into compiler stacks like TorchInductor or OpenAI's Triton.

KERNEL ARCHITECTURE

Naive vs. Fused MoE Implementation

A comparison of the computational and memory characteristics between a standard, multi-kernel MoE implementation and a single, optimized fused kernel.

Feature / MetricNaive Implementation (Multi-Kernel)Fused Kernel Implementation

Kernel Launch Overhead

High (multiple launches per layer)

Low (single launch per layer)

Global Memory Accesses

High (explicit loads/stores between ops)

Minimal (data stays in registers/SRAM)

Intermediate Tensor Storage

Required (routing scores, permuted inputs)

Eliminated (fused operations)

All-to-All Communication Pattern

Explicit (separate collective op)

Implicit (fused within kernel)

Token Permutation

Explicit sort/scatter before GEMM

Fused indexing within GEMM

Expert GEMM Execution

Separate kernel per expert group

Batched, warpspecialized GEMM in one kernel

Peak Theoretical FLOP/s Utilization

60-75%

90%

Latency for Top-2 Routing (8 Experts)

~1500 µs

< 500 µs

Implementation Complexity

Moderate (modular, easier to debug)

High (requires low-level CUDA/GPU expertise)

FUSED MOE KERNELS

Frameworks and Implementations

Fused MoE kernels are highly optimized GPU kernels that combine the routing logic, token permutation, and the sparse matrix multiplications of multiple experts into a single, efficient operation to minimize memory movement and kernel launch overhead.

01

Core Optimization: Kernel Fusion

The primary goal of a fused MoE kernel is to eliminate the performance cost of launching multiple separate GPU kernels and moving intermediate data between global memory and registers. A naive implementation executes distinct steps:

  • Compute router scores and perform top-k selection.
  • Permute and gather tokens based on routing decisions.
  • Launch separate GEMM (General Matrix Multiply) kernels for each expert's activated weight block.
  • Scatter the results back to the original token order.

A fused kernel combines these steps into one monolithic CUDA kernel. This reduces kernel launch latency, minimizes global memory traffic by keeping data in faster cache hierarchies (L1/L2, shared memory), and allows for more aggressive compiler optimizations across the entire operation.

02

Sparse Block-Sparse GEMM

At the heart of the fused kernel is an optimized sparse matrix multiplication. Unlike a dense GEMM that computes over an entire matrix, an MoE layer only multiplies by the weight blocks of the top-k selected experts.

Key implementation techniques include:

  • Block-Sparse Representation: Expert weights are stored in contiguous blocks. The kernel uses a lookup table of pointers to these blocks, indexed by the router's output.
  • Warp-Level Specialization: Different warps (groups of 32 threads) within a CUDA block are assigned to compute on different experts or token groups, enabling fine-grained parallelism.
  • Hierarchical Reduction: Partial results from processing different token-expert assignments are efficiently reduced within shared memory before being written to the final output tensor.

This approach avoids the overhead of a generic sparse linear algebra library, which is not optimized for the specific, structured sparsity pattern of MoE routing.

03

In-Memory Token Permutation

A major bottleneck in MoE is the data movement required to group tokens by their assigned expert for efficient computation (the "all-to-all" step in distributed settings). A fused kernel optimizes this by performing the permutation in-place within GPU registers and shared memory.

Instead of writing intermediate tensors to global memory, the kernel:

  1. Loads a tile of input tokens and their routing assignments.
  2. Uses warp shuffle instructions and shared memory buffers to locally reorder the tile so that tokens destined for the same expert are contiguous.
  3. Feeds this reordered data directly into the subsequent block-sparse GEMM steps.

This eliminates separate gather/scatter kernels and their associated memory read/write cycles, significantly reducing latency, especially for smaller batch sizes.

04

Integration in Major Frameworks

Fused MoE kernels are implemented as custom operators within leading inference and training systems:

  • vLLM: Integrates fused MoE kernels (e.g., for Mixtral models) within its PagedAttention scheduler, allowing for efficient memory management and continuous batching of MoE requests.
  • NVIDIA TensorRT-LLM: Provides highly optimized fused MoE plugins for NVIDIA GPUs, leveraging Tensor Cores and advanced CUDA features for maximum throughput.
  • PyTorch: Can utilize custom torch.autograd.Function implementations or leverage the Triton compiler (e.g., via triton.language) to write high-performance fused MoE kernels in Python-like syntax.
  • DeepSpeed: Its MoE implementation includes optimized kernels for training, handling the complexities of expert parallelism and gradient synchronization.
05

Performance Impact & Metrics

The use of fused kernels directly targets the inference latency and throughput pillars. Benchmarks on models like Mixtral 8x7B show substantial improvements:

  • Kernel Launch Overhead: Reduction from launching 5-10+ kernels per MoE layer to just 1 or 2.
  • Memory Bandwidth: Can reduce global memory transactions by 30-50% for the MoE operation by fusing load/compute/store phases.
  • End-to-End Latency: Can improve latency per token by 1.5x to 2x for the MoE layers, which are often the computational bottleneck in these models.

These optimizations are critical for achieving low-latency, high-throughput serving, making large MoE models viable for production use cases.

06

Design Challenges & Trade-offs

Building a robust fused MoE kernel involves navigating several engineering challenges:

  • Variable Workload: The number of tokens assigned to each expert varies dynamically per request and batch. The kernel must handle this load imbalance without thread divergence causing performance cliffs.
  • Expert Capacity: Must efficiently implement the capacity factor logic, handling tokens that exceed an expert's capacity (e.g., via buffering or a fallback path).
  • Numerical Precision: Support for mixed precision inference (FP16, BF16, INT8) requires separate kernel variants or dynamic precision selection.
  • Hardware Generality: Writing a kernel that performs well across different GPU architectures (e.g., Ampere, Hopper) and memory hierarchies is complex. Often, multiple kernel variants are maintained for different scenarios (e.g., small vs. large batch size).
FUSED MOE KERNELS

Frequently Asked Questions

Fused MoE kernels are a critical low-level optimization for efficiently executing Mixture of Experts models. These FAQs address their core mechanisms, performance impact, and implementation considerations.

A fused MoE kernel is a highly optimized GPU kernel that combines the discrete computational steps of a Mixture of Experts layer—token routing, permutation, and the sparse matrix multiplications for multiple experts—into a single, cohesive operation. It works by first computing the gating scores for all tokens in a batch, then using those scores to gather the tokens assigned to each expert into contiguous memory blocks. Finally, it performs a batched matrix multiplication using only the weight matrices of the activated experts, writing the results directly back to the correct output positions. This fusion minimizes intermediate memory writes and kernel launch overhead, which are significant bottlenecks in a naive implementation that launches separate kernels for routing and each expert's computation.

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.