Pidoku

MoE Kernels: Grouped GEMM, Permutation, DeepGEMM

Module 25 Lesson 25.h 1h 25m Difficulty 5/5

Prerequisites 14.g, 14.h, 14.e, 25.e, 25.g


Before you start: words you need#

WordPlain meaning
Router / top-kThe small layer that scores every expert for each token and keeps the best k (14.g).
PermutationReordering token rows so that all rows going to the same expert are next to each other. Undoing it afterwards is the unpermutation.
Grouped GEMMOne kernel launch that runs many independent GEMMs (one per expert), each with its own size.
Contiguous layoutAll experts’ token rows concatenated along M in one tensor, each expert’s segment padded to the kernel’s block size.
Masked layoutOne fixed-capacity slot per expert, plus a count of how many rows in each slot are real. Shapes never change, which suits CUDA graphs.
Align block sizeThe step that counts tokens per expert, pads each count up to the GEMM’s block-M and writes the sorted row order.
Megakernel (Mega MoE)One kernel that does dispatch, both expert GEMMs, the activation and combine, overlapping communication and compute (25.j).

1. What is it?#

An MoE layer (14.g) turns into a short pipeline of kernels on each GPU (14.h listed them):

flowchart LR
  R["Router GEMM<br/>+ top-k"] --> A["Align / permute<br/>count, sort, pad"]
  A --> D["Dispatch<br/>(all-to-all under EP, 25.i)"]
  D --> G1["Grouped GEMM 1<br/>gate+up, SwiGLU epilogue"]
  G1 --> G2["Grouped GEMM 2<br/>down projection"]
  G2 --> C["Combine<br/>(all-to-all under EP)"]
  C --> U["Unpermute<br/>weighted sum of k results"]
  class R,A,U,G1,G2 compute
  class D,C io

This lesson is about the boxes’ insides: how tokens are reordered cheaply, how one launch runs 256 GEMMs of different sizes, why DeepGEMM has both a contiguous and a masked grouped GEMM, and how the whole layer collapses into one kernel in 2026’s designs.

Facts checked on 13 November 2026 (vLLM v0.32.0, DeepGEMM main, CUTLASS 4.8.1).


2. Why does it matter?#

The large open models of 2025–2026 (DeepSeek V3/V4, Kimi K2/K3, GLM-5, Qwen3 MoE, gpt-oss) are MoE. In them, expert GEMMs are most of the FLOPs and, in decode, most of the bytes. Three things make MoE kernels harder than dense GEMMs:

  • Ragged shapes. Each expert gets a different, data-dependent number of tokens every step. A kernel compiled for fixed shapes, or a CUDA graph captured for fixed shapes, must cope.
  • Tiny per-expert batches in decode. With 256 experts, top-8 routing and 64 tokens per GPU, each expert sees about 2 rows (section 4). Every expert with at least one token must still read all of its weights.
  • Many small kernels. Router, sort, pad, quantise, GEMM, activation, GEMM, unpermute: launch gaps and memory round trips between them can exceed the GEMM time at small batch.

3. Simple analogy#

A post office sorting room. Letters (tokens) arrive in random order, each addressed to up to eight departments (experts). The fast way is not to carry each letter to each department one at a time. Instead: count how many letters each department gets, give each department a tray of the right size (rounded up to a full tray, the block size), drop the letters into the trays in one pass, then let every department process its tray in parallel, and finally put each letter’s eight replies back together.

If a department’s tray holds 128 letters but gets 2, the tray is mostly air — and the department still had to open its whole filing cabinet (the expert weights) to answer.


4. Tiny example: how much of a grouped GEMM is padding?#

The program routes tokens to 256 experts with top-8 (with a mildly skewed router), then pads each expert’s rows up to the kernel’s block-M, as vLLM’s moe_align_block_size and DeepGEMM’s contiguous layout do.

Go
// moealign.go — route tokens to experts, then count what a grouped GEMM really computes
// once each expert's rows are padded to the kernel's block size (the "align block size" step).
package main

import (
	"fmt"
	"math"
	"math/rand"
)

const experts, topK = 256, 8 // DeepSeek-V3-style routing

// route returns how many token copies each expert receives, with a mildly skewed router.
func route(tokens int, rng *rand.Rand) []int {
	weight := make([]float64, experts)
	total := 0.0
	for e := range weight {
		weight[e] = 1 / math.Pow(float64(e+1), 0.3) // some experts are more popular
		total += weight[e]
	}
	counts := make([]int, experts)
	for t := 0; t < tokens; t++ {
		chosen := map[int]bool{}
		for len(chosen) < topK {
			r, e := rng.Float64()*total, 0
			for ; r > weight[e]; e++ {
				r -= weight[e]
			}
			chosen[e] = true
		}
		for e := range chosen {
			counts[e]++
		}
	}
	return counts
}

func main() {
	rng := rand.New(rand.NewSource(1))
	fmt.Println("tokens  block-M  useful rows  padded rows  wasted  busiest/mean expert")
	for _, tokens := range []int{64, 512, 8192} {
		counts := route(tokens, rng)
		busiest := 0
		for _, c := range counts {
			busiest = max(busiest, c)
		}
		mean := float64(tokens*topK) / experts
		for _, block := range []int{16, 64, 128} {
			padded := 0
			for _, c := range counts {
				padded += (c + block - 1) / block * block // each expert's segment rounded up
			}
			useful := tokens * topK
			fmt.Printf("%6d  %7d  %11d  %11d  %5.0f%%  %8.1fx\n",
				tokens, block, useful, padded, 100*float64(padded-useful)/float64(padded),
				float64(busiest)/mean)
		}
	}
}
tokens  block-M  useful rows  padded rows  wasted  busiest/mean expert
    64       16          512         3472     85%       5.0x
    64       64          512        13888     96%       5.0x
    64      128          512        27776     98%       5.0x
   512       16         4096         5840     30%       3.4x
   512       64         4096        16384     75%       3.4x
   512      128         4096        32768     88%       3.4x
  8192       16        65536        67488      3%       3.6x
  8192       64        65536        73344     11%       3.6x
  8192      128        65536        80896     19%       3.6x
  • Prefill (8,192 tokens): padding costs 3–19 %, depending on block-M. A large block-M is still worth it for reuse (25.e).
  • Decode (64–512 tokens): almost all padded rows are air. In the memory-bound regime that wasted arithmetic is cheap; what is not cheap is that every touched expert’s weights are read. That is why decode MoE kernels use small block-M (16 or swap A/B, 25.e), FP4/FP8 weights (25.g), and wide EP so each GPU owns fewer experts (14.e).
  • Imbalance (busiest expert 3–5× the mean in this router model) sets the tail of every grouped GEMM, and under EP, the step time of every GPU (14.h’s EPLB).

5. Technical explanation#

Routing kernels#

The router GEMM is tiny ([tokens × hidden] × [hidden × experts]); the work is in top-k with group constraints (DeepSeek’s “pick the top 4 of 8 groups, then the top 8 experts within them”) and score normalisation. Engines ship fused kernels for it (vLLM’s topk_softmax_kernels.cu, grouped_topk_kernels.cu, topk_softplus_sqrt_kernels.cu), because a chain of PyTorch top-k ops is a dozen launches.

Permutation without moving data#

Two designs:

  1. Index-based (no physical permute). moe_align_block_size counts tokens per expert, computes padded offsets with a prefix sum, and writes sorted_token_ids (row order) and expert_ids (one per block-M tile). The Triton fused_moe kernel then gathers A rows through sorted_token_ids as it loads them and scatters results back, multiplying by the router weight in the epilogue. No permuted copy of the activations is ever materialised. This is vLLM’s and SGLang’s portable default.
  2. Physical permute. Copy rows into expert order (often fused with FP8/FP4 quantisation and, under EP, with the dispatch all-to-all — DeepEP writes received tokens directly in expert-major layout), run a grouped GEMM on contiguous segments, then unpermute and reduce. Faster GEMM (TMA-friendly contiguous loads) for one extra pass.

Grouped GEMM designs#

DesignGroups differ inHow the kernel knowsUsed by
CUTLASS ptr-array grouped GEMMM, N, K and pointersarrays of pointers and problem shapes on the device; TMA descriptors updated per group in the kernelCUTLASS (KernelPtrArrayTmaWarpSpecialized…), FlashInfer, TRT-LLM
DeepGEMM M-grouped contiguousonly M (N, K fixed)each expert’s segment aligned to block-M; one tensor; a per-row expert indexprefill, training forward
DeepGEMM M-grouped maskedonly the valid Mfixed [experts × capacity × K] tensor + masked_m countsdecode with CUDA graphs, fed by DeepEP low-latency
Triton fused_moeM per expertsorted_token_ids / expert_ids from align-block-sizevLLM and SGLang defaults

Why both contiguous and masked? In prefill, the CPU can know (or cheaply learn) how many tokens each expert got, and a contiguous tensor wastes only the per-expert padding. In decode under CUDA graphs, shapes are frozen at capture time and the CPU never sees the per-expert counts; the masked layout gives every expert a fixed slot of the maximum size, and the kernel skips the invalid rows using the device-side masked_m. DeepGEMM’s README describes exactly this pairing with DeepEP’s low-latency dispatch output.

Scheduling a grouped GEMM. A persistent kernel (25.e) walks a flattened list of (expert, m-tile, n-tile) work items. Because N and K are equal across experts, DeepGEMM can reuse one TMA descriptor for B with an expert offset, and rasterise tiles so that the same expert’s weight tiles stay in L2. With ptr-array grouped GEMMs, the kernel must also rewrite TMA descriptors when it moves to a new group; CUTLASS 4.8 lists faster “device-side TMA descriptor updates” (staged through shared memory) for exactly this.

Fusions that matter#

  • Gate and up in one GEMM (weights concatenated), with SwiGLU in the epilogue and FP8/FP4 quantisation of the result for the down projection (25.g).
  • Router weight multiply in the down-projection epilogue, so unpermute is a plain sum.
  • Shared expert (always active) run concurrently on another stream or folded into the grouped GEMM as an extra group.
  • Dispatch + quantise: DeepEP and FlashInfer’s all-to-all quantise to FP8 while sending, halving bytes on the wire.

2026: the whole layer in one kernel#

DeepGEMM’s Mega MoE (April 2026, extended September 2026) “fuses and overlaps EP dispatch, linear 1 and linear 2 (FP8×FP4 or FP8×FP8), SwiGLU, and EP combine into a single mega-kernel, overlapping NVLink communication and tensor core computation” (its README). It needs PyTorch ≥ 2.9 symmetric memory, weights transformed once into its layout, and inputs copied into its symmetric buffer. vLLM v0.32.0 has a deep_gemm_mega_moe.py backend, and TensorRT-LLM has CuTe DSL “mega MoE” kernels for Blackwell and Rubin. The idea is the megakernel of 25.j applied to one layer: no launch gaps, no HBM round trips between stages, and communication hidden under the expert GEMMs.

How vLLM organises it#

vLLM’s MoE code is a modular kernel: a FusedMoEPrepareAndFinalize object (quantise, dispatch, combine — swappable among DeepEP, pplx, FlashInfer, NIXL EP, …) and a FusedMoEExperts object (the grouped GEMMs — Triton, DeepGEMM, CUTLASS, FlashInfer, Marlin, AITER, FlyDSL on ROCm). That is why the same model can run with many kernel combinations, chosen from the quantisation and hardware (18.j, 14.h).


6. Under the hood: align-block-size on the GPU#

input:  topk_ids [T, k]   (expert id per token copy), block_M
1. histogram:   one pass, shared-memory atomics per expert          → counts[E]
2. pad:         padded[e] = ceil(counts[e] / block_M) * block_M
3. scan:        offsets = exclusive_prefix_sum(padded)              → total_padded
4. scatter:     for each copy (t, j): pos = offsets[e] + atomicAdd(cursor[e], 1)
                sorted_token_ids[pos] = t*k + j     (padding slots get a sentinel = T*k)
5. per tile:    expert_ids[pos / block_M] = e

All of it runs in one or two small kernels (vLLM has a special variant for small batches with few experts). The sentinel lets the GEMM skip padded rows on load and store. Note step 4’s atomics: the order of tokens within an expert is nondeterministic, which is harmless for the GEMM but matters if you need bitwise reproducibility (28.c).


7. Performance implications#

  • Decode MoE is weight-bandwidth-bound. Time ≈ (experts touched on this GPU × bytes per expert) ÷ HBM bandwidth. Kernel tricks that do not reduce bytes (bigger tiles, better MMA utilisation) do not help; FP4 weights, wider EP and fewer touched experts do (14.e).
  • Prefill MoE is compute-bound with modest padding; it behaves like a large GEMM with a tail from the busiest expert.
  • Launch count matters at small batch. A naive MoE layer is 8–12 kernels. At decode, fusing to 3–4 (or one megakernel) can be worth 10–30 % of MoE time; measure with Nsight Systems’ gaps.
  • Imbalance is a kernel problem too. Even on one GPU, the busiest expert’s tiles finish last. Persistent schedulers that interleave experts, and EPLB’s replicas, shorten the tail.

8. Production implications#

  • Read the start-up log for the MoE backend (14.h). Falling back from a DeepGEMM/CUTLASS/FlashInfer path to Triton for an FP4 or FP8 model can cost a large factor.
  • CUDA graphs need masked or fixed-capacity layouts for decode. Capacity is a memory and padding trade-off: size it from observed per-expert maxima, not the average.
  • Extra installs. DeepGEMM and DeepEP are separate packages with CUDA, NCCL and PyTorch version floors (DeepEP V2.5 needs NCCL ≥ 2.32.3 and PyTorch ≥ 2.10). Bake them into the image and test version changes like kernel changes (25.l).
  • Tune per model. Triton fused_moe uses per-shape config files (block sizes, warps, stages) in vllm/model_executor/layers/fused_moe/configs/; a new model or GPU without a config falls back to defaults that can be far from optimal. vLLM ships a benchmark script to generate them.

9. Common mistakes#

  1. Physically permuting activations in a separate kernel when the GEMM could gather rows itself.
  2. Using block-M = 128 for decode. Over 95 % of rows are padding; weight reads already dominate.
  3. Contiguous layout under CUDA graphs: the per-expert counts change every step, so the graph’s shapes are wrong.
  4. Ignoring the shared expert in the timeline; it is a dense GEMM that can overlap with dispatch.
  5. Unfused SwiGLU and quantisation between the two expert GEMMs.
  6. Benchmarking with a uniform router. Real routers are skewed; the busiest expert sets the time.
  7. Assuming determinism: atomics in align and in combine change summation order between runs.

10. Hands-on exercise#

  1. Change the Go program’s skew exponent from 0.3 to 0 (uniform) and 0.8. How do padding and the busiest/mean ratio change? Add a count of experts touched per step and estimate decode MoE time on an H200 for a DeepSeek-V3-sized layer at FP8 (about 44 MB per expert for gate+up+down).
  2. In vLLM, run benchmarks/kernels/benchmark_moe.py for a Qwen3-MoE or DeepSeek shape with and without a tuned config. Report the speedup per batch size.
  3. With DeepGEMM on an H100 or B200, compare m_grouped_fp8_gemm_nt_contiguous and m_grouped_fp8_gemm_nt_masked at the same total rows. Where does the masked version waste time?
  4. Profile one MoE layer of a decode step in Nsight Systems and count kernels and gaps.

11. Interview questions#

  1. Walk through the kernels of one MoE layer on one GPU, with and without expert parallelism.
  2. What does moe_align_block_size produce, and how does the GEMM use it?
  3. Contiguous versus masked grouped GEMM: what problem does each solve?
  4. Why is decode MoE time nearly independent of how well the GEMM uses the tensor cores?
  5. What does a ptr-array grouped GEMM need that a normal GEMM does not (think TMA descriptors)?
  6. What does Mega MoE fuse, and what does it require from the runtime?
  7. A new MoE model is 2× slower per token than a dense model with the same active parameters. Where do you look?

12. Further reading#

Checked on 13 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in