Chapter 42
Mixture-of-Experts and Sparse Communication
On this page
- The MoE layer
- Dispatch through weighted return
- Capacity and overflow
- Load-balancing objectives
- Expert parallelism
- All-to-all cost
- Token packing and ordering
- Dispatch and combine are a sparse operator and its transpose
- Communication kernels are part of the compute schedule
- Expert replication
- Expert, data, and tensor group geometry
- MoE inference
- MoE failure and observability
- Design Exercises
- Worked Solutions
Mixture-of-experts models increase parameter capacity while activating only a subset per token. The systems cost moves from dense compute to routing, variable all-to-all traffic, expert memory, and load imbalance.
The MoE layer¶
For one token with top-2 routing, two selected experts execute and return outputs to its original owner for weighted combination. Expert dispatch and return may cross ranks; unselected experts still consume parameter storage.
For each token representation, a router scores experts and selects top k. The layer then:
- computes expert assignments and weights;
- counts tokens per destination expert;
- packs tokens into expert-contiguous buffers;
- dispatches tokens to expert owners, often with all-to-all;
- executes expert MLPs as grouped or batched GEMMs;
- sends outputs back to original token owners;
- combines selected expert outputs by routing weights.
Only selected experts compute for a token, but all expert parameters must reside somewhere. Total parameter count drives memory and checkpoint size; activated expert count drives most FLOPs; routing distribution drives communication and local GEMM shapes.
Dispatch through weighted return¶
examples/cross_layer.py gives an executable MoE ownership reference. Three scalar token values [2,4,8] route to experts f0(x)=2x and f1(x)=x+1; a third expert receives no tokens. The first token uses weights 0.75 and 0.25, the second uses expert 1, and the third uses expert 0. Dispatch loads are [2,2,0]; weighted return produces [3.75,5,16] in original token order.
The empty expert is legal. A dropped token is a different semantic event and needs an explicit overflow policy. Permuting receive order cannot permute final tokens: retain origin indices through packing, expert execution, and reverse routing. The reference rejects duplicate expert assignments and unnormalized gates so an accidental double contribution cannot look like valid dispatch.
Capacity and overflow¶
If T tokens are routed across E experts with top-1 routing, ideal load is T/E. A capacity factor c might allocate approximately:
Top-k routing increases total assignments. Real load is not uniform, so some experts can overflow while others idle. Possible policies include dropping overflow tokens, routing to a backup expert, increasing capacity and padding, or dynamically scheduling variable counts.
Dropping or rerouting changes model semantics and training. Padding preserves shape but wastes compute. Dynamic shapes improve useful work but complicate kernels, graphs, and collectives. State the policy in the model contract and report overflow by layer and data slice.
Load-balancing objectives¶
Auxiliary losses encourage balanced token counts and router probability mass. They improve system utilization but can oppose expert specialization. Router z-losses, noise, or regularization may stabilize training. The exact objectives belong to the training recipe, not an invisible runtime fix.
Balance has several levels:
- token count per expert;
- weighted compute per expert when ranks or experts differ;
- bytes per destination rank;
- maximum expert time on the critical path;
- balance over a step, accumulation window, and data domain.
Equal counts do not guarantee equal time if sequence packing, expert dimensions, quantization, or hardware differ.
Expert parallelism¶
An expert-parallel group partitions experts across ranks. Non-expert transformer layers may use data or tensor parallelism, while MoE layers enter expert-dispatch groups. Token ownership and expert ownership are different coordinates.
If a rank owns multiple experts, it sorts received tokens by local expert and executes a grouped GEMM. Very small expert batches underuse the accelerator. Combining tokens from multiple sequences or microbatches improves efficiency but may increase latency or saved activation memory.
Expert tensor parallelism can shard a single large expert. It lowers expert parameter bytes per rank but adds collectives inside expert computation, on top of dispatch traffic. Use it only when experts do not fit or local expert GEMMs are large enough.
All-to-all cost¶
All-to-all traffic is personalized: each source sends a different partition to every destination. Total token bytes may appear balanced while one destination or network link is hot. Fixed-size padded all-to-all is predictable but sends empty capacity; variable-size exchange requires counts and offsets and can create launch variation.
Measure:
- dispatch and combine bytes;
- per-source/destination matrix, not only total bytes;
- packing/unpacking time;
- arrival skew before the collective;
- maximum rank receive count;
- expert GEMM occupancy and tail;
- overlap with attention or other layers.
Hierarchical dispatch can first exchange within a node, aggregate by remote destination, then traverse the network. It reduces small cross-node messages but adds a local pack stage.
Token packing and ordering¶
Packing requires a histogram of assignments, prefix offsets, and scatter. Preserve original token identity so outputs return to the right sequence and position. For top-k, one token has multiple branch identities and combine weights.
Stable ordering may be needed for reproducibility or exact checkpoint replay. An unstable parallel sort can change floating accumulation order. Define whether results need bitwise identity or only distributional/numerical equivalence.
Padding, duplicate expert choices, masked tokens, and zero-token experts are edge cases. Test them directly; they often expose mismatched counts that hang all-to-all.
Dispatch and combine are a sparse operator and its transpose¶
Number each selected token-expert assignment by a, and retain token[a], expert[a], and routing weight w[a]. Dispatch is a gather D[a,:]=X[token[a],:], followed by a permutation into destination-rank and expert order. The permutation must carry assignment identity; expert outputs cannot be restored using token ID alone when a token selects multiple experts.
After expert computation and inverse permutation, combine is Y[t,:]=sum_(a:token[a]=t) w[a]*E[a,:]. Thus dE[a,:]=w[a]*dY[token[a],:] and dw[a]=dot(dY[token[a],:],E[a,:]). The input gradient sums the gradients returned by every selected expert. A last-writer-wins scatter is incorrect whenever top-k routing creates multiple assignments for one token.
Capacity filtering changes the assignment set before these equations are evaluated. Specify whether surviving weights are renormalized; if so, differentiation includes that normalization. Preserve deterministic assignment ordering if reproducible summation is required. For all-to-all-v style exchange, the send count from rank r to q must equal the receive count recorded by q from r; compare count matrices before diagnosing a payload hang.
Communication kernels are part of the compute schedule¶
Packing tokens, sending them, running grouped expert GEMMs, and combining results form a dependency graph. Reducing all-to-all time in isolation is not enough if communication kernels reserve SMs that the GEMMs need. Conversely, a transfer path that minimizes SM use can require larger buffers or a different transport protocol. Large training batches favor bandwidth amortization; small decode batches expose setup and tail latency.
The DeepEP repository, checked September 7, 2026, documents a V2 ElasticBuffer interface and NCCL Gin backend, while keeping NVSHMEM-based V1 behavior in legacy documentation. Its current description also identifies increased buffer consumption and distinguishes experimental features from the EP path. This matters when reading older optimization accounts: do not combine a V1 latency claim, a V2 API, and a third configuration's memory budget into an imaginary implementation. Pin the actual revision used in an experiment.
For an original example, four tokens choose two experts each: token 0 chooses [0, 1], token 1 [1, 2], token 2 [1, 3], and token 3 [0, 1]. The assignment counts are [2, 4, 1, 1], not the uniform expectation of two. Dispatch must retain each token's original index and routing weight. Combine scatters expert outputs back and sums both weighted contributions; sorting by expert without an inverse mapping corrupts results. If experts 1 and 3 share a rank, that rank receives five of eight assignments and can control latency even with perfect network bandwidth.
Overlap requires finer dependencies than “launch communication and compute together.” A GEMM can begin for a received expert tile when that tile is complete; combine can begin when an output tile is final. Do not reuse a dispatch buffer while its remote consumer is still reading it. The same ownership reasoning used for asynchronous CUDA buffers applies across ranks, with completion and failure now distributed.
DualPipe is a primary example of a bidirectional training pipeline designed around computation/communication overlap. It does not abolish dependencies or make every collective invisible. Sketch the actual forward, backward-input, backward-weight, and communication intervals, and include the activation/parameter memory required by the schedule. More overlap can lose when it displaces useful compute or makes the plan too memory-constrained.
Expert replication¶
Replicating a hot expert increases memory but splits its tokens across copies. A placement policy needs:
- expert popularity and variance by layer/domain;
- parameter bytes and load/eviction cost;
- routing distance and topology;
- consistency of replicated weights and optimizer state;
- deterministic mapping or acceptable stochasticity.
In training, replicas of one expert require gradient synchronization and consistent optimizer updates, creating another group. In inference, immutable weights simplify replication, but router-to-replica assignment affects cache locality and batching.
Dynamic expert migration during a step is rarely free. A slower-timescale placement controller can use recent routing histograms, move at safe boundaries, and keep a fallback copy until publication completes.
Expert, data, and tensor group geometry¶
Expert parallelism does not always multiply independently with data parallelism. Non-expert weights may be replicated across an expert group while expert weights are partitioned, so gradient groups differ by parameter class. Some systems fold expert and data axes to use the same devices differently in dense and sparse layers.
Draw group membership for:
- dense parameters and their gradient reductions;
- each expert's replicas or shards;
- router parameters;
- token dispatch and return;
- pipeline/context boundaries.
A single global "data parallel degree" is insufficient for an MoE checkpoint or optimizer.
MoE inference¶
Decode may provide only one token per active sequence. Per-expert batches become tiny and routing skew varies every iteration. The all-to-all latency can dominate even when experts are computationally cheap.
Serving strategies include larger continuous batches, expert replication, locality-aware request grouping, wide expert-parallel domains for capacity, and small local dispatch groups for latency. These goals conflict. Quantized expert weights reduce memory and load bandwidth but can make communication a larger fraction.
For strict token cadence, cap the work admitted to a group and protect against a rare hot-expert iteration. Report per-token tail latency by routed expert, not only average output tokens per second.
MoE failure and observability¶
Failure of one expert owner can invalidate the entire model replica unless another consistent copy exists. Recovery must restore expert placement, router version, optimizer ownership, and process groups together.
Operational dashboards should show expert load histograms, overflow, entropy, dispatch matrix, per-expert compute, routed-token quality slices, and replica placement. A routing collapse may first appear as network imbalance, then training instability.
Design Exercises¶
- Trace one token through distributed top-k expert routing and back.
- Compare padding, dropping, backup routing, and dynamic capacity on overflow.
- Why can balanced expert counts still produce an imbalanced step?
- Design expert parallel groups and gradient groups for a hybrid MoE model.
- When should a hot expert be replicated, and how is consistency maintained?
- Why is expert-parallel decode often harder than expert-parallel training?
Worked Solutions¶
1. Token path¶
The router produces expert IDs and weights. Counts and prefix offsets pack a token copy for each selected expert with original token identity. All-to-all sends each packed copy to the expert owner, which groups by local expert and runs the MLP. A return all-to-all restores source ownership; outputs are scattered to original positions and combined by routing weights. Counts, masks, top-k branches, and ordering must match at both transfers.
2. Overflow policies¶
Padding to fixed capacity gives predictable shapes but wastes compute and bandwidth. Dropping caps cost but changes model output and gradient. Backup routing preserves more tokens but changes specialization and can move the hot spot. Dynamic variable counts do useful work but create irregular collectives and kernels. Choose in the model/training contract, measure quality and tail performance, and expose overflow per layer and slice rather than hiding it in aggregate throughput.
3. Hidden imbalance¶
Experts may have equal counts but different token shapes, hardware, quantization, or branch multiplicity. Packing work, source-destination network paths, and arrival times can differ. One rank may own several simultaneously hot experts. Padding to maximum count also makes every rank pay for the worst destination. Profile per-expert compute, per-rank receive bytes, dispatch matrix, and arrival skew; count balance is only one indicator.
4. Group design¶
Give ranks explicit data, tensor, pipeline, context, and expert coordinates. Define separate gradient groups for dense parameters, router parameters, and each expert's replicas or shards. Define expert dispatch groups between token owners and expert owners, plus expert-TP groups if used. Map frequent dispatch within fast topology where possible and print ownership in checkpoints. Do not assume EP simply multiplies DP; parameter classes can have different replication geometry.
5. Expert replication¶
Replicate when a persistent hot expert sets the critical path and saved queue/dispatch time exceeds parameter memory, load, and synchronization cost. Place copies near token sources and split assignments using load-aware deterministic mapping. During training, reduce gradients across copies and apply identical optimizer updates; publish placement only at a safe boundary. During inference, immutable replicas simplify consistency, but version and quantization identity must match.
6. Decode difficulty¶
Training microbatches provide many tokens, creating larger expert GEMMs and amortizing all-to-all. Decode supplies roughly one token per sequence, so per-expert groups are tiny, skew changes each step, and two personalized collectives sit on token latency. Batching helps but conflicts with cadence and KV capacity. Expert replication and topology-aware grouping may be needed even when training used pure partitioning.