Sparse Expert Layers: Routing and Cross-Device Sharding
Machine LearningModel answerLast updated
Describe how a sparse top-k expert feed-forward layer processes a token batch, and how placing experts on different devices changes communication, balance, and memory.
Your team wants to scale a transformer's parameter count without scaling per-token compute at the same rate, and is considering replacing the dense feed-forward block with a sparse expert layer.
Explain how such a layer works and how its experts are spread across accelerators. Follow one batch of tokens from the moment it enters the layer until the layer's output is produced.
Assumptions. Use a feed-forward expert layer with top-k routing as your running example. The number of experts, the value of k, the capacity policy, and the hardware layout are not given, so choose concrete values and state them.
Your answer should cover:
- The architecture: what an expert is, what the router computes, and how the outputs are merged.
- The device-level view: how experts are partitioned, and what data moves between devices.
- What happens when some experts receive more tokens than they can handle.
- Auxiliary losses or mechanisms that keep usage balanced.
- Communication and memory costs, and how the answer differs for training throughput versus serving latency.
- Common failure modes and trade-offs.
You may want to ask yourself: are all experts on one device or spread out? Can a token visit more than one expert? Is the target training throughput or serving latency?
Hints
Hint 1
Keep two ideas apart: the model definition (router, experts, weighted sum) and the system layout (which device holds which expert). The second is what creates the communication pattern.
Hint 2
Think of the layer as a pipeline: score tokens, pick top-k experts, send tokens to the devices holding those experts, compute, send results back, then combine with the router weights. Count how many all-to-all exchanges that implies.
Hint 3
Tokens are not spread evenly by default. Consider what a fixed capacity per expert does to overloaded experts, which auxiliary signal nudges the router toward balance, and how stragglers affect step time.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Setup and choices
I will use a layer with E = 64 experts, top-k = 2, replacing the dense FFN in every second transformer block. Each expert is a normal FFN (two linear layers with a nonlinearity). Attention, embeddings, and norms stay dense. Experts are sharded across 8 devices (8 experts each), combined with data parallelism for the dense parts.
Architecture: what one layer computes
For a token vector x:
- Router. A small linear layer produces E logits:
logits = x · W_r. A softmax gives probabilitiesp. - Top-k selection. Keep the k = 2 largest entries. Renormalize their weights so they sum to 1 (a common choice).
- Expert compute. Run
xthrough only those two experts. - Combine. Output is
y = w1·E_i(x) + w2·E_j(x), a weighted sum.
Total parameters grow roughly with E, but per-token FLOPs grow with k. With E = 64 and k = 2, the FFN parameter count is about 64x a dense FFN while per-token FFN compute is about 2x. That is the point of sparsity: capacity decoupled from compute. Note that memory is not decoupled; all experts must be stored.
Device view: expert parallelism
In expert parallelism (EP), each device owns a disjoint subset of experts. Tokens, however, start out sharded by data parallelism, so a token on device A may need an expert on device B.
Trace of one forward pass through the layer:
- Route locally. Each device runs the router on its own tokens and gets expert assignments.
- Permute and pack. Tokens are sorted/grouped by destination expert (and thus destination device).
- All-to-all dispatch. Each device sends each token copy (k copies per token) to the owning device. Message size per device is about
tokens_per_device × k × d_model × bytes. - Local expert compute. Each device runs its experts on the tokens it received, ideally as grouped or batched GEMMs.
- All-to-all combine. Outputs go back to the originating devices.
- Unpermute and weight. Results are scattered back to original token order and multiplied by the router weights, then summed.
So each MoE layer costs two all-to-alls forward and two backward. The backward pass also routes gradients to the same experts along the reverse path. Router gradients flow through the selected weights, not through the discrete selection.
Rough numbers: with 4096 tokens per device, k = 2, d_model = 4096, bf16, each dispatch moves about 4096 × 2 × 4096 × 2 bytes ≈ 67 MB per device. Across dozens of MoE layers that traffic is significant, so interconnect bandwidth (NVLink inside a node, network across nodes) often dominates.
Load imbalance and capacity
Routers tend to collapse: a few experts get most tokens, they train faster, and the router favors them further. Consequences are idle devices, stragglers (the layer waits for the busiest device), and wasted capacity.
Capacity factor. To keep tensor shapes static, each expert gets a buffer of
capacity = capacity_factor × (tokens × k / E)
with a factor such as 1.25. Tokens beyond capacity are handled by an overflow policy:
- Drop: the token skips the expert; the residual connection carries it through. Cheap, but hurts quality if frequent.
- Reroute: send to the next-best expert with room.
- Dropless: variable-size grouped GEMMs process everything, avoiding drops at the cost of irregular shapes and possible stragglers.
Trade-off: a higher capacity factor means fewer drops but more padding and compute plus larger messages.
Keeping usage balanced
- Auxiliary load-balancing loss. For each expert, take
f_i(fraction of tokens routed to it) andP_i(mean router probability for it). Addα · E · Σ f_i · P_ito the loss, with α around 0.01. It is minimized when usage is uniform. - Router z-loss to keep logits small and stabilize training.
- Noise or jitter on router logits early in training for exploration.
- Bias-based balancing: adjust a per-expert bias to steer selection without adding gradient interference.
- Monitor per-expert token counts and drop rates as first-class metrics.
Memory and parallelism interplay
- Experts dominate parameter memory, so EP shards them; optimizer state shards with them.
- Dense layers are replicated (or sharded with FSDP/ZeRO) across the data-parallel group. The gradients for expert parameters only need reduction across replicas of the same expert, so the process groups differ for dense and expert weights. Mixing them up is a common bug.
- EP can combine with tensor parallelism inside an expert when a single expert is too big, and with pipeline parallelism across layers.
- Activation memory grows with the k token copies and capacity padding.
Training vs serving
- Training cares about throughput: large batches amortize all-to-all, overlap communication with compute (e.g., chunk the batch and pipeline dispatch with expert GEMMs), and tolerate some drops.
- Serving cares about latency: small batches mean few tokens per expert, so GEMMs are inefficient and all-to-all latency (not bandwidth) dominates. Dropping is usually undesirable, so use dropless or generous capacity. Hot experts can be replicated, and placement can use observed routing statistics. All weights still need to fit in aggregate memory, which makes MoE memory-heavy to serve even though compute is cheap.
Trade-offs and common mistakes
- Saying MoE reduces memory: it reduces compute per token, not memory.
- Forgetting that k copies of each token travel, not one.
- Ignoring the straggler effect: step time is set by the most loaded device.
- Using one gradient reduction group for both expert and dense parameters.
- Treating the balance loss weight as free: too high hurts quality by forcing uniform routing, too low allows collapse.
- Evaluating with different capacity or routing noise than training without realizing it changes outputs.
- Assuming drops are harmless; track drop rate, especially for rare or long-context inputs.
Summary
A sparse expert layer routes each token to k of E experts and sums their weighted outputs. Expert parallelism puts different experts on different devices, turning the layer into route, all-to-all dispatch, local expert compute, all-to-all combine. The practical difficulties are communication cost, load balance (handled with capacity limits, overflow policy, and auxiliary losses), and the fact that all expert weights must still live in memory.