Phase 04/Algorithmic speedups/Mixture-of-experts inference
PHASE 04 · Algorithmic speedups

Mixture-of-experts inference

0%
9 h6 subtopics3 lessons · 1 required
In plain English

A normal language model makes every word pass through every part of its brain. A mixture-of-experts model instead keeps many specialist sub-networks (the experts) and a small gatekeeper (the router) that sends each word to only two or eight of them. Think of a hospital where each patient sees two relevant specialists instead of every doctor on staff. The hospital can employ far more specialists than any patient visits, so the model can be enormous while the work per word stays small. The catch for serving is organisational. Patients must be sorted and walked to the right offices, popular specialists get queues while others sit idle, and when the specialists are spread across several buildings (GPUs) the walking itself takes time. This topic is about making that sorting, balancing and walking fast.

Why it matters

Most frontier open models (Mixtral, DeepSeek-V3, Qwen3-MoE, Llama 4) are MoE, so serving them is now ordinary work. MoE changes the roofline (weights read per step depend on batch size), adds a routing and dispatch step that needs its own kernels, and introduces expert parallelism with all-to-all communication and load-imbalance problems that dense models never had.

Hiring signal

Cerebras lists tuning "tensor and expert parallelism" among the model-serving behaviours its GPU inference engineers own and names experience optimizing mixture-of-experts models as a preferred qualification; Baseten's kernel roles put mixture-of-experts routing beside GEMM and attention as the core kernels to write.

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, CoreWeave, Databricks, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Explain top-k routing, capacity factor, token dropping and auxiliary load-balancing losses and how they shape inference behaviour.
  • Implement an MoE layer with a naive per-token loop and with a sorted grouped-GEMM dispatch, verify equivalence and measure the speedup.
  • Derive the expected number of experts activated per decode step as a function of batch size and show how it changes the memory-bound roofline.
  • Describe expert parallelism, all-to-all dispatch and combine, and expert placement and replication for load balance.
  • Measure real routing imbalance on a small MoE model and explain its throughput consequences.

Key concepts

Router (gate)
A small linear layer plus softmax that scores each token against every expert; the top-k scores pick the experts and weight their outputs.
Top-k routing
Each token is processed by k of E experts (Mixtral uses 2 of 8, DeepSeek-V3 uses 8 of 256 plus a shared expert).
Active versus total parameters
FLOPs per token follow the active parameters (the k experts touched), while memory to store the model follows the total.
Capacity factor and token dropping
A per-expert buffer limit; tokens routed beyond it are dropped or overflow to a second choice, trading quality for predictable shapes.
Load-balancing loss
A training-time auxiliary loss that pushes the router toward uniform expert usage; inference inherits whatever imbalance remains.
Grouped GEMM
Sorting tokens by expert and running one batched matmul over variable-sized groups, instead of a Python loop over experts.
Expert parallelism (EP)
Placing different experts on different GPUs; tokens travel to their experts with an all-to-all before and after the expert MLPs.
All-to-all dispatch and combine
The two collective operations that move tokens to expert GPUs and bring results back; latency-sensitive at small batch.
Expert placement and replication
Choosing which GPU hosts which expert and duplicating hot experts so no single GPU becomes the straggler for every step.
Shared expert
An always-on expert every token visits (DeepSeek, Qwen), which behaves like a dense MLP for roofline purposes.

Subtopics

  1. 1. MoE layer anatomy

    Router scores, top-k selection and renormalisation, expert MLPs, weighted combine; where the MoE replaces the dense MLP in the block and what shapes flow through it.

  2. 2. Dispatch kernels

    Sort tokens by expert, compute group offsets, grouped or batched GEMM, scatter back; the vLLM fused_moe Triton kernel and the padding-versus-grouping trade-off.

  3. 3. Roofline for MoE decode

    Expected experts touched per step grows with batch; at batch 1 only k experts are read, at large batch nearly all, so the memory-bound advantage over a dense model shrinks as batch grows.

  4. 4. Expert parallelism and communication

    EP versus TP for expert weights, all-to-all cost model, overlapping communication with computation, DeepEP-style low-latency kernels for decode.

  5. 5. Load imbalance in production

    Hot experts and stragglers, measuring per-expert token counts from real traffic, expert replication and rebalancing, and capacity-based dropping at inference time.

  6. 6. Memory and quantization for MoE

    Total parameters dominate GPU memory; expert weights are the first target for INT4/FP8 and for CPU or SSD offload at small batch.

Resources

paper
repo

Hands-on lessons

L1

Build an MoE layer with naive and grouped dispatch on CPU

CPU · your Macnotebook150 minrequired

Goal · A PyTorch MoE layer with top-2-of-8 routing implemented two ways, proven equivalent, with a timing comparison and a per-expert load histogram.

  1. 1Define MoE(d_model=512, d_ff=1024, E=8, k=2) with a router nn.Linear(d_model, E) and eight expert MLPs; initialise with a fixed seed.
  2. 2Implement forward_naive that loops over tokens, picks top-k experts with softmax-renormalised weights, and sums the weighted expert outputs.
  3. 3Implement forward_grouped that sorts token indices by expert id, computes group offsets, runs each expert once on its contiguous slice (or torch.bmm on padded groups), and scatters results back with index_add_.
  4. 4Assert torch.allclose(forward_naive(x), forward_grouped(x), atol=1e-5) on random x of 4,096 tokens.
  5. 5Time both on 4,096 tokens with 10 repeats and report the speedup; count the FLOPs of the MoE versus a dense MLP with the same total parameters.
  6. 6Record tokens routed per expert, plot the histogram, and compute the imbalance ratio max/mean; then add a capacity factor of 1.25 and count how many tokens would be dropped.
  7. 7Skew the router by adding a bias to one expert and repeat the imbalance and drop measurements.
Deliverable
A notebook with both implementations, the allclose assertion, the timing table, the histograms and the drop counts.
Check
allclose passes; forward_grouped is at least 2x faster than forward_naive at 4,096 tokens; the MoE uses about k/E of the dense-equivalent FLOPs per token (within 10 percent, ignoring the router).
L2

MoE decode roofline versus batch size

CPU · your Macnotebook60 minoptional

Goal · A plot of bytes read per decode step and predicted step time versus batch size for a Mixtral-8x7B-shaped model next to a dense model with the same active parameters.

  1. 1From the Mixtral config compute per-expert bytes, shared (attention plus embeddings) bytes and total bytes in FP16.
  2. 2Derive the expected number of distinct experts touched by B tokens with top-k of E experts, E * (1 - (1 - k/E)^B), and verify it with a Monte Carlo simulation of uniform routing.
  3. 3Compute bytes read per decode step for B in 1, 2, 4, 8, 16, 32, 64, 128 as shared bytes plus expected experts times per-expert bytes; do the same for a dense 13B-active-parameter model.
  4. 4Convert to step time on an H100 (3.35 TB/s) and plot both curves; mark the batch where the MoE loses most of its bandwidth advantage.
  5. 5Repeat with a skewed routing distribution (one expert takes 40 percent of tokens) and note how the expected experts touched changes.
Deliverable
A notebook with the formula, the Monte Carlo check and the two plots.
Check
At B 1 the MoE reads roughly k experts plus shared bytes; by B 64 with E 8 the expected experts touched exceeds 7.9; the Monte Carlo mean is within 2 percent of the formula.
L3

Measure routing imbalance in a real small MoE

CPU · your Macexperiment75 minoptional

Goal · Per-layer expert load histograms for google/switch-base-8 on 200 real sentences, with imbalance ratios and the fraction of tokens that would be dropped at a given capacity factor.

  1. 1pip install torch transformers datasets; load google/switch-base-8 and its tokenizer; take 200 sentences from a public text dataset.
  2. 2Register forward hooks on every router module to capture the chosen expert index per token.
  3. 3Run the sentences through the encoder (no generation needed) and accumulate tokens per expert per MoE layer.
  4. 4Plot one histogram per layer and compute max/mean imbalance for each; identify the hottest expert in the most imbalanced layer.
  5. 5Simulate expert parallelism with one expert per GPU and compute, per layer, the fraction of time the busiest GPU would be the straggler (max tokens divided by mean tokens).
  6. 6Write a paragraph on which replication or placement change you would make for this routing pattern.
Deliverable
A notebook with the per-layer histograms, the imbalance table and the paragraph.
Check
Imbalance ratios are reported for every MoE layer; at least one layer has a max/mean ratio above 1.5, and you name the expert responsible.

Build your own

Build your own MoE layer

PythonCPU · your Mac~9 h

A mixture-of-experts feed-forward layer in PyTorch on CPU, from a per-token loop to block-aligned grouped GEMM dispatch, with capacity factors, load-imbalance metrics and an expert-parallel traffic simulation.

The real thing: github.com/vllm-project/vllm/tree/main/vllm/model_executor/layers/fused_moe ↗

How you know a stage passes

Write tests/test_moe.py first. The oracle is a deliberately slow per-token Python loop over the top-k experts (stage 1). Every later stage must match it with torch.allclose (atol 1e-5) on seeded random weights for 8 experts, hidden 512, expert width 1024 and 4,096 tokens, and must satisfy an exact count or a timing ratio. A CLI `moe.py bench|imbalance|roofline` prints the numbers and writes CSV. Run `pytest -q`; a stage is done when its test passes and all earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/7
  1. 01router and the slow reference
    A linear router with softmax, top-k selection and renormalised weights, and a per-token loop that calls each chosen expert's FFN and sums the weighted outputs.
    test · Renormalised top-k weights sum to 1 for every token; with k equal to the number of experts the output equals a dense weighted sum of all experts to 1e-6; output shape equals input shape.
  2. 02sort-and-group dispatch
    Tokens are sorted by expert id, each expert runs one matmul over its contiguous slice, and results are scattered back and weighted.
    test · Matches stage 1 within 1e-5; the number of matmul calls equals the number of experts that received at least one token; at 4,096 tokens it is at least 5x faster than the loop.
  3. 03block-aligned grouped GEMM
    Each expert's token slice is padded to a multiple of a block size B (as vLLM's moe_align_block_size does) so a single batched matmul over [num_blocks, B, hidden] replaces the per-expert loop, with a block-to-expert map.
    test · Padded token count equals the sum over experts of ceil(n_e / B) * B for B in 16, 32, 64, asserted exactly; the output equals stage 2 for every B.
  4. 04capacity factor and dropped tokens
    Each expert accepts at most capacity_factor * tokens * k / num_experts tokens; overflow tokens skip the expert and pass through on the residual.
    test · With a seeded skewed router and capacity factor 1.0 the dropped count equals the formula you derive from the per-expert histogram; with capacity factor 2.0 nothing is dropped and the output equals stage 2; dropped tokens' outputs equal their inputs.
  5. 05load-imbalance metrics and the auxiliary loss
    `moe.py imbalance` reports per-expert load, max-over-mean ratio, coefficient of variation and the Switch Transformer load-balancing loss for a routing trace.
    test · For a uniformly random router over one million tokens the max-over-mean ratio is below 1.05; for the seeded skewed router it is above 2.0; the aux loss is lower for the uniform router, all asserted.
  6. 06the MoE decode roofline
    `moe.py roofline` computes bytes read per decode step as the union of experts touched by a batch, versus a dense layer of equal active parameters, for batch sizes 1 to 256.
    test · At batch 1 the expected number of unique experts equals k; for batch B the simulated unique-expert count is within 5 percent of E * (1 - (1 - k / E)^B) under uniform routing; the bytes-per-token curve is written to roofline.csv and plotted.
  7. 07expert-parallel traffic simulation
    Experts are assigned to D simulated devices and the dispatch computes the all-to-all token-count matrix, the most-loaded device and the fraction of tokens that stayed local.
    test · Total tokens sent across devices equals tokens * k minus local hits, asserted exactly; the test prints the busiest device and shows that placing the two hottest experts of the skewed router on different devices lowers the max device load.

Knowledge check

QWhy does an MoE model's advantage over a dense model shrink at large batch during decode?

At batch 1 only k experts' weights are read per step, but as more tokens join the step almost every expert gets at least one token, so nearly all expert weights are read and the step approaches the dense cost of the total parameters.

QWhat does a capacity factor do at inference time?

It caps tokens per expert to a fixed buffer so shapes are static; tokens beyond the cap are dropped or rerouted, which keeps kernels simple but can hurt quality under skewed routing.

QWhy is expert parallelism communication-heavy and what mitigates it?

Every MoE layer needs an all-to-all to send tokens to their experts' GPUs and another to bring results back; overlapping with compute, low-latency kernels and placing hot experts locally mitigate it.

QHow does a grouped GEMM dispatch differ from a loop over experts?

It sorts tokens by expert once and runs all expert matmuls as one kernel over variable-sized groups, removing per-expert launch overhead and idle time for lightly loaded experts.

Completion

  • All 6 subtopics marked done
  • All 1 required lessons done
  • All subtopics marked completed.
  • Lesson l1 notebook saved with the allclose assertion, the timing table and the load histogram.
  • Can sketch an MoE layer with expert parallelism across four GPUs and explain where the all-to-all and the imbalance costs appear.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →