Skip to content
Inference Academy

MoE dispatch and a grouped GEMM in Triton

How a mixture-of-experts layer runs on a GPU without a loop over experts: route each token to its top-k experts, sort and pad the assignments so every block of rows belongs to one expert, then run one grouped GEMM launch that gathers token rows, multiplies by the right expert and fuses the routing weight. With the padding cost, why decode reads most experts' weights even at small batches, and how vLLM's fused MoE kernel extends the same idea.

By

Key takeaways

  • Looping over experts in Python means one small matmul per expert and a host sync to find each expert's tokens. A grouped GEMM does all experts in one launch.
  • The trick is the alignment step: sort the (token, expert) assignments by expert and pad each expert's list to a multiple of the block size, so each block of rows needs only one expert's weights.
  • Padding costs at most block_m - 1 rows per expert, which matters at decode, where most experts get only a token or two.
  • Even small decode batches touch most experts: with 64 experts and top-6 routing, 16 tokens hit about 51 distinct experts on average, so the layer reads most of its weights.
  • Fuse what you can: the gather of token rows, the routing weight and, in production kernels, the activation between the two expert matmuls.
28 min · verified 2026-111 animated diagramHands-on labPro
Share

Goal: run a mixture-of-experts layer's expert matmul in one kernel launch, and understand the dispatch step that makes it possible.

You need: the Triton matmul lesson and mixture of experts for why MoE models work the way they do. The code is gpu_kernels/moe.py in the companion repository.

Honest limits. This kernel implements one linear layer per expert to keep the dispatch in view; a real expert is an MLP with two matmuls and an activation. The alignment step uses a short Python loop over experts, which real engines replace with a kernel (vLLM's moe_align_block_size). Tested for correctness in the Triton interpreter on a CPU; no timings here.

#The problem

For each of TT tokens, a router scores EE experts; each token goes to its top kk, and its output is the weighted sum of those experts' outputs:

yt=∑j=1kgt,j xtWet,jy_t = \sum_{j=1}^{k} g_{t,j} \, x_t W_{e_{t,j}}

where et,je_{t,j} is the token's jj-th expert and gt,jg_{t,j} its routing weight (the softmax probabilities of the chosen experts, renormalised to sum to one; models differ in this detail).

The obvious implementation loops over experts: find the tokens assigned to expert ee, gather them, multiply, scatter back. With 64 experts that is 64 small matmuls, 64 launches, and a host synchronisation for each nonzero() that finds the tokens. At decode, where each expert gets one or two tokens, almost all of the time is overhead.

#The plan: align, then one grouped GEMM

flowchart LR
  R[Router logits<br/>T x E] --> TK[top-k + renormalise<br/>ids, weights: T x k]
  TK --> AL[Align: sort the T*k assignments<br/>by expert, pad each to BLOCK_M]
  AL --> SI[sorted_ids<br/>+ expert id per block]
  X[x: T x K] --> GG
  W[W: E x K x N] --> GG
  SI --> GG[Grouped GEMM<br/>one program per row block<br/>x column block]
  TK --> GG
  GG --> O[out: T*k x N<br/>already weighted]
  O --> C[Sum each token's<br/>k rows: T x N]

Alignment. Number the T⋅kT \cdot k assignments 0,1,…0, 1, \dots (assignment aa belongs to token a/ka / k). Sort them by expert. Pad each expert's list up to a multiple of BLOCK_M with a sentinel value T⋅kT \cdot k. Record, for each block of BLOCK_M rows, which expert it belongs to. Now every block of rows needs exactly one expert's weights, and the kernel never needs to look anything up beyond its own block.

The grouped GEMM. One program per (row block, column block). It reads its expert, loads its block's assignment ids, turns them into token ids (id // top_k), gathers those rows of xx (masking the padding), multiplies by that expert's weight tile, scales each row by its routing weight, and stores into the assignment's own output row. A final sum over each token's kk rows gives the layer output.

gpu_kernels/moe.py · MIT licensed, on GitHub

python
"""Mixture-of-experts dispatch and a grouped GEMM in Triton.

Steps, for T tokens, E experts and top_k experts per token:
  1. route:    softmax over router logits, keep the top_k, renormalise their weights.
  2. align:    sort the T * top_k (token, expert) assignments by expert and pad each expert's
               list to a multiple of BLOCK_M, so every block of rows belongs to one expert.
  3. grouped GEMM: one program per (row block, column block). It reads which expert its block
               belongs to, gathers those tokens' rows of x, multiplies by that expert's weight
               and scales by the routing weight (fused), writing one output row per assignment.
  4. combine:  sum each token's top_k rows.

A real expert is an MLP (two grouped GEMMs with an activation between); one linear layer per
expert keeps the dispatch logic in view. Runs on a GPU, or on a CPU with TRITON_INTERPRET=1.
"""
import torch
import triton
import triton.language as tl


def route(router_logits, top_k):
    probs = torch.softmax(router_logits.float(), dim=-1)
    weights, ids = probs.topk(top_k, dim=-1)                 # [T, top_k]
    return weights / weights.sum(dim=-1, keepdim=True), ids


def align_by_expert(topk_ids, num_experts, block_m):
    """Returns sorted_ids (padded with the sentinel T*top_k) and one expert id per block of rows."""
    flat = topk_ids.reshape(-1)
    sentinel = flat.numel()
    order = torch.argsort(flat, stable=True)                 # assignment indices grouped by expert
    counts = torch.bincount(flat, minlength=num_experts)
    padded = (counts + block_m - 1) // block_m * block_m
    sorted_ids = torch.full((int(padded.sum()),), sentinel, dtype=torch.int32, device=flat.device)
    expert_of_block = torch.repeat_interleave(torch.arange(num_experts, device=flat.device), padded // block_m)
    starts = torch.cumsum(counts, 0) - counts
    dst = torch.cumsum(padded, 0) - padded
    for e in range(num_experts):                             # small loop over experts; real engines use a kernel
        c = int(counts[e])
        sorted_ids[int(dst[e]): int(dst[e]) + c] = order[int(starts[e]): int(starts[e]) + c].to(torch.int32)
    return sorted_ids, expert_of_block.to(torch.int32)


@triton.jit
def _grouped_gemm_kernel(x_ptr, w_ptr, out_ptr, sorted_ids_ptr, expert_ptr, weight_ptr,
                         num_assign, N, K, top_k,
                         stride_xt, stride_we, stride_wk, stride_out,
                         BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr):
    pid_m = tl.program_id(0)
    pid_n = tl.program_id(1)
    expert = tl.load(expert_ptr + pid_m)

    rows = tl.load(sorted_ids_ptr + pid_m * BLOCK_M + tl.arange(0, BLOCK_M))   # assignment ids
    valid = rows < num_assign                                                  # padding rows are skipped
    token = rows // top_k                                                      # assignment -> token
    rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    rk = tl.arange(0, BLOCK_K)

    acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
    for k0 in range(0, K, BLOCK_K):
        kk = k0 + rk
        a = tl.load(x_ptr + token[:, None] * stride_xt + kk[None, :],
                    mask=valid[:, None] & (kk[None, :] < K), other=0.0)
        b = tl.load(w_ptr + expert * stride_we + kk[:, None] * stride_wk + rn[None, :],
                    mask=(kk[:, None] < K) & (rn[None, :] < N), other=0.0)
        acc += tl.dot(a, b)

    gate = tl.load(weight_ptr + rows, mask=valid, other=0.0)                   # fused routing weight
    acc = acc * gate[:, None]
    tl.store(out_ptr + rows[:, None] * stride_out + rn[None, :], acc.to(out_ptr.dtype.element_ty),
             mask=valid[:, None] & (rn[None, :] < N))


def moe_linear(x, w, router_logits, top_k, block_m=16, block_n=64, block_k=32):
    """x: [T, K], w: [E, K, N], router_logits: [T, E]. Returns [T, N]."""
    T, K = x.shape
    E, _, N = w.shape
    weights, ids = route(router_logits, top_k)
    sorted_ids, expert_of_block = align_by_expert(ids, E, block_m)
    out = torch.zeros((T * top_k, N), dtype=x.dtype, device=x.device)
    flat_weights = weights.reshape(-1).to(x.dtype).contiguous()
    grid = (expert_of_block.numel(), triton.cdiv(N, block_n))
    _grouped_gemm_kernel[grid](x, w, out, sorted_ids, expert_of_block, flat_weights,
                               T * top_k, N, K, top_k,
                               x.stride(0), w.stride(0), w.stride(1), out.stride(0),
                               BLOCK_M=block_m, BLOCK_N=block_n, BLOCK_K=block_k)
    return out.view(T, top_k, N).sum(dim=1)


def moe_reference(x, w, router_logits, top_k):
    weights, ids = route(router_logits, top_k)
    out = torch.zeros((x.shape[0], w.shape[2]), dtype=torch.float32, device=x.device)
    for e in range(w.shape[0]):
        tok, slot = (ids == e).nonzero(as_tuple=True)
        if tok.numel():
            out[tok] += weights[tok, slot][:, None] * (x[tok].float() @ w[e].float())
    return out.to(x.dtype)

The rest is Pro

Keep reading this full lab

Pro unlocks this full lab, including 1 animated diagram, every advanced lesson, the hands-on labs and completion certificates.

One year

$25

365 days, no auto-renewal

Lifetime Best value

$75

pay once, keep it forever

7-day refund, no questions asked. One payment, no auto-renewal.Compare plansHave a licence key?

Sandip MaityBuilt by Sandip Maity, who runs self-hosted LLM inference in production.

Not ready? Keep learning free

Or follow the free roadmap →

Not ready? Take the free 5-day email course

One short email a day for five days, each built on a free lesson, then the occasional new lesson or offer. Unsubscribe in one click.

Still to come in this lab

  1. Walking through the details
  2. Padding and why decode is expensive
  3. Testing
  4. How production kernels extend this
  5. What you can now do
  6. Common mistakes
  7. Exercise
  8. Going deeper

You will be able to answer

  • Why sort the assignments by expert before the GEMM?
  • An MoE layer has 64 experts and routes each token to 6. A decode batch has one token. How many experts' weights are read?
  • Where is the routing weight applied in this kernel, and why there?