Large Language ModelsInference & Performance Optimization

How do you optimize expert-parallel communication and load balancing for low-latency Mixture-of-Experts (MoE) LLM inference?

Question 296 of 309 · Updated

On this page

1. Why this problem matters#

A Mixture-of-Experts (MoE) model does not activate every feed-forward expert for every token. A router selects a small subset—often top-1 or top-2—from a larger expert pool. This reduces active computation relative to a dense model with a comparable total parameter count. But it creates a distributed-systems problem: the selected experts may live on different GPUs, and tokens must travel to those GPUs before the expert computation can run.

Expert parallelism (EP) shards experts across GPUs. For each MoE layer, an EP execution commonly performs two communication phases:

  1. Dispatch: route token activations and routing metadata from source ranks to the ranks that own the selected experts.
  2. Combine: return expert outputs to the originating ranks and combine them using the router's weights.

The expert MLPs may be fast while the dispatch, synchronization, queueing, or combine phases dominate end-to-end latency. This is especially important during autoregressive decode: each request contributes relatively few new tokens per step, so fixed communication and launch costs can matter more than total bytes transferred.

The optimization problem is therefore not simply “use a faster network.” It is to coordinate routing, expert placement, communication backend, topology, compute overlap, and workload shape without breaking model semantics or exhausting GPU memory.

This lesson focuses on inference-time expert-parallel execution. It is distinct from the basic MoE architecture explanation and the MoE training-instability question already in the curriculum.

2. A small numerical example#

Suppose a model has 64 routed experts distributed across 8 GPUs. Each GPU owns 8 experts. A token chooses its top-2 experts.

For a batch containing 128 tokens:

  • There are 128 token representations before routing.
  • Top-2 routing creates 256 token-to-expert assignments.
  • Some assignments target experts on the local GPU; others must cross the inter-GPU fabric.
  • After each expert processes its assigned tokens, the results are returned and combined.

Assume, purely for illustration, that each token activation has 4,096 values stored in BF16. One activation is:

LaTeX

If all 256 assignments were remote, the raw activation payload sent for dispatch would be about 2 MiB, before metadata, protocol buffers, alignment, and return traffic. In practice, the local/remote split and communication implementation change this number.

Now consider a decode step with only 8 new tokens. There are just 16 top-2 assignments. The payload is much smaller, but the operation may still need routing metadata, synchronization, kernel launches, and collective coordination. A communication path optimized for large payload throughput may perform poorly for this tiny message regime.

Key distinction: prefill and decode can need different expert-parallel communication strategies. Prefill usually exposes more tokens and can benefit from throughput-oriented dispatch. Decode often has smaller per-step token counts and is more sensitive to fixed latency.

3. Understand the EP execution path#

A simplified MoE layer follows this sequence:

  1. Compute router scores for each token.
  2. Select the top-k experts and their routing weights.
  3. Group or permute token activations by destination expert/rank.
  4. Exchange token data and metadata across EP ranks.
  5. Run the selected expert MLPs.
  6. Return expert outputs to the source ranks.
  7. Undo the permutation and combine outputs using routing weights.

The dispatch and combine are not interchangeable with ordinary tensor-parallel all-reduce. All-to-all-style communication moves different token subsets to different destinations. A rank may send different amounts of data to every other rank, and the traffic matrix changes with the router's decisions.

An implementation can also split the work into local and remote paths, fuse permutation with communication, or use a specialized device-initiated communication kernel. The exact path depends on the framework, backend, GPU generation, and network topology.

When diagnosing latency, measure each stage separately. A single end-to-end tokens-per-second number cannot tell you whether the bottleneck is router computation, token permutation, communication, expert GEMMs, synchronization, or an overloaded expert.

4. Choose the parallelism layout before tuning kernels#

Expert parallelism is one dimension of distributed execution, not a universal replacement for tensor or data parallelism.

  • Tensor parallelism (TP) splits individual matrix operations across GPUs. It can be useful when dense attention or other large layers need to be distributed.
  • Expert parallelism (EP) distributes experts so that tokens travel to the ranks that own the selected experts.
  • Data parallelism (DP) replicates model execution to process independent requests or batches.
  • Real deployments often combine these dimensions.

A layout that looks balanced by GPU count can still be poor if it crosses a slow topology boundary. For example, placing experts across GPUs connected by high-bandwidth NVLink is not equivalent to spreading the same experts across nodes connected by a network fabric. The cost of a remote token assignment depends on the path it takes.

Before changing EP degree, record:

  • GPU count per node and GPU-to-GPU connectivity.
  • NVLink/NVSwitch domains and cross-node network bandwidth/latency.
  • Which ranks host attention and expert layers.
  • EP, TP, and DP group sizes.
  • Expert count, top-k, hidden dimension, activation dtype, and MoE layer count.
  • Whether the deployment is prefill-heavy, decode-heavy, or mixed.

Do not assume that increasing the number of EP ranks always improves performance. More ranks can reduce per-GPU expert weight residency, but they can also increase communication fan-out, synchronization, and network contention.

5. Match the communication backend to the workload#

There is no universally best all-to-all backend. The backend must match token count, message size, topology, and latency objective.

A practical starting point is to distinguish two regimes:

High-throughput regime

  • Often associated with prefill or large batches.
  • More tokens are available to amortize setup and synchronization.
  • Larger transfers can benefit from bandwidth-efficient aggregation and pipelining.
  • A throughput-oriented communication kernel may be appropriate.

Low-latency regime

  • Often associated with decode and small per-step batches.
  • Fixed costs, synchronization, and launch overhead become important.
  • A low-latency dispatch/combine path may outperform a high-bandwidth path even if its peak throughput is lower.

Current vLLM expert-parallel deployment documentation exposes multiple all-to-all backends and describes DeepEP high-throughput and low-latency modes for different serving phases. It also documents other options for particular topologies and hardware. Treat these as implementation choices to benchmark, not as universal performance rankings.

DeepEP provides expert-parallel communication kernels for dispatch and combine, including high-throughput and low-latency paths. Its newer EPv2 interface unifies these paths and supports scale-up and scale-out domains. It is important to verify the exact release and API used by your installed runtime: experimental branches, older V1 interfaces, and newer V2 interfaces are not automatically interchangeable.

A simple backend selection experiment#

For each representative workload:

  1. Hold model weights, batch composition, token lengths, EP layout, and request mix constant.
  2. Warm up every backend and exclude compilation or initialization from steady-state timing.
  3. Measure dispatch, expert compute, combine, and end-to-end latency.
  4. Repeat at several token counts, including small decode batches and larger prefill batches.
  5. Record p50, p95, and p99 latency, tokens per second, GPU utilization, and network utilization.
  6. Re-run under realistic concurrent traffic to expose contention.

Select by the actual service objective. A backend that wins at 4,096 tokens per step may lose at 16 tokens per step.

6. Understand all-to-all traffic and topology#

For each EP rank, build or sample a traffic matrix:

LaTeX

This matrix helps answer questions that aggregate bandwidth hides:

  • Are a few destination ranks receiving most of the tokens?
  • Are remote transfers crossing node boundaries?
  • Is traffic concentrated on a small number of network links?
  • Does one rank become a hotspot because popular experts are colocated?
  • Does the pattern change between prefill and decode?

The total bytes transferred are not enough to predict latency. A traffic pattern with the same total byte count can have very different completion times if one destination receives a disproportionate share or if many senders contend for the same receiver.

Prefer placements that keep frequently co-selected or heavily used experts within favorable communication domains when the model/runtime supports a valid placement strategy. But do not optimize placement from a single prompt sample: routing distributions vary with data, language, domain, and generation phase.

Measure local versus remote token fractions and per-link utilization. If the same traffic pattern is slow only across nodes, the network topology or inter-node protocol may be the limiting factor. If it is slow within one node too, investigate kernel launch, synchronization, layout conversion, or GPU-side communication overhead.

7. Load balance experts, not just GPUs#

Equal numbers of experts per GPU do not guarantee equal work per GPU.

Suppose four ranks each own four experts. During one interval, the expert token counts are:

RankToken counts per local expertTotal assignments
090, 85, 80, 75330
125, 20, 18, 1780
222, 21, 20, 1780
320, 19, 18, 1774

The rank totals are very uneven even though each rank owns the same number of experts. Rank 0 may determine the layer's completion time while the other ranks wait.

Useful metrics include:

  • Tokens per expert and per rank.
  • Maximum-to-average expert load ratio.
  • Per-rank expert GEMM time.
  • Queueing time before expert compute.
  • Dispatch and combine completion skew.
  • The fraction of steps where one rank is the straggler.

One simple balancedness measure is:

LaTeX

A value near 1 indicates a more even token distribution; a low value indicates a hot expert. This is a diagnostic, not a complete performance score: experts can differ in shape, placement, or compute cost, and a balanced token count can still hide communication hotspots.

8. Use expert-parallel load balancing carefully#

An expert-parallel load balancer can redistribute expert placement across ranks, and some systems support redundant expert copies. If a frequently selected expert is replicated, its work can be spread across multiple GPUs rather than forcing all its tokens through one copy.

A typical feedback loop is:

  1. Collect expert token counts over a representative window.
  2. Identify persistently overloaded experts and overloaded ranks.
  3. Choose a placement or replication plan.
  4. Transfer expert weights to the new or redundant slots.
  5. Update routing/placement metadata consistently across ranks.
  6. Continue serving and measure whether the new placement improves tail latency and throughput.
  7. Rebalance again only when the expected gain exceeds the cost and disruption.

The decision must account for more than token count. Replication consumes GPU memory, weight transfers consume bandwidth, and frequent placement changes can destabilize execution. If expert weights or quantization scales are not copied correctly, inference results can be wrong. Placement changes must be coordinated so that every rank agrees on the mapping used for dispatch and combine.

vLLM documents an Expert Parallel Load Balancer (EPLB) that collects load statistics and periodically redistributes expert mappings. Its configuration includes a measurement window, rebalance interval, balancedness logging, and redundant expert count. The documentation also warns that redundant experts consume GPU memory, which can reduce memory available for the KV cache.

Practical rule: rebalance persistent skew, not random short-lived fluctuations. Use a sufficiently representative window, cap the amount of replication, and compare the value of additional expert capacity against the KV-cache capacity it displaces.

9. Overlap communication with computation#

The next major optimization is to avoid treating communication and compute as completely serial stages.

Potential overlap opportunities include:

  • Running shared-expert computation while routed tokens are being dispatched.
  • Starting expert GEMMs for ready groups while other groups are still arriving.
  • Overlapping return communication for completed expert groups with compute for other groups.
  • Using separate streams or device-side communication mechanisms where the runtime supports correct synchronization.

Overlap is not free. It can increase SM contention, memory pressure, queueing, and synchronization complexity. A communication kernel that consumes many SMs may slow down the expert GEMMs it is supposed to overlap. A strategy that works for large prefill batches may not work for small decode batches.

Recent research on distributed MoE serving finds that the best computation-communication overlap strategy depends on model shape, EP degree, input length, and hardware. This reinforces a key production principle: profile the complete workload and choose overlap granularity by configuration rather than enabling every overlap flag blindly.

Measure whether overlap actually reduces the critical path. If communication and compute overlap in a trace but total layer latency does not fall, the system may be limited by another serial stage or resource contention.

10. Reduce the bytes and work in the communication path#

There are several possible optimizations, each with trade-offs:

Activation dtype

  • Lower-precision activation exchange can reduce communication volume.
  • Confirm that the communication format is supported by the backend and compatible with expert kernels.
  • Validate output quality and numerical stability; do not assume quantized communication is lossless.

Fused permutation and communication

  • Token grouping, permutation, packing, and communication setup can create extra kernels and intermediate buffers.
  • Fusing compatible operations can reduce launch and memory traffic overhead.
  • Ensure the fused path preserves token ordering, expert IDs, and routing weights.

Locality-aware placement

  • Keep more traffic within fast local links where possible.
  • Re-evaluate placement when the prompt mix or routing distribution changes.
  • Avoid concentrating hot experts on a single receiver.

Protocol and buffer design

  • Reuse communication buffers when the API permits safe reuse.
  • Avoid unnecessary host-device synchronization.
  • Make buffer sizing and registration compatible with peak token counts and concurrent requests.
  • Ensure the communication protocol handles empty destinations, variable split sizes, and uneven token counts.

These changes should be tested independently before combining them. Otherwise, a speedup or regression becomes difficult to attribute.

11. Prefill and decode need separate performance thinking#

A production server may serve both long prompts and token-by-token generation. The two phases create different EP communication patterns.

Prefill

  • Many prompt tokens can enter the MoE layer together.
  • Dispatch may move larger activation volumes.
  • Bandwidth, grouped expert GEMM efficiency, and overlap can dominate.
  • Throughput-oriented all-to-all paths may be attractive.

Decode

  • Each active sequence contributes a small number of new tokens per step.
  • The number of tokens can vary with active batch size and scheduling.
  • Fixed synchronization and dispatch overhead can dominate.
  • Tail latency and inter-token latency matter more than peak aggregate bandwidth.

A single backend and placement policy can still be used if it performs adequately, but do not assume it is optimal for both phases. If the serving framework supports phase-aware execution or separate prefill/decode pools, evaluate that architecture using end-to-end request latency and transfer overhead—not just isolated kernel benchmarks.

12. Numerical example: deciding whether to replicate a hot expert#

Assume one expert receives 400 token assignments in a measurement window while the median expert receives 100. Its rank is consistently the slowest.

You consider adding one redundant copy on another GPU.

Before replication:

  • Hot expert compute time: 2.0 ms.
  • Other expert work on the rank: 0.5 ms.
  • Communication and synchronization on the critical path: 0.8 ms.
  • Approximate critical path: 3.3 ms.

After replication, suppose assignments are split so each copy receives about 200 tokens. Expert compute falls to 1.0 ms per copy, but weight movement, dispatch complexity, and extra synchronization add 0.25 ms. The new critical path might be approximately 2.55 ms.

That would be a useful improvement if the measurements hold under real traffic. But suppose the redundant copy consumes 1.5 GiB and forces the server to reduce KV-cache capacity enough to lower its active batch size. The end-to-end service could become slower despite the faster MoE layer.

This is why expert balancing must be evaluated together with memory capacity, concurrency, and request-level latency.

13. Benchmark the system, not just the communication kernel#

Build a benchmark matrix across:

  • Prompt length and generated length.
  • Active decode batch size.
  • Prefill token count and decode token count.
  • EP degree and DP/TP combination.
  • Intra-node versus multi-node placement.
  • Communication backend and backend configuration.
  • Activation dtype and expert kernel implementation.
  • Balanced versus naturally skewed routing traffic.
  • Concurrent tenants and mixed request classes.

Record at least:

  • Time to first token (TTFT).
  • Inter-token latency (ITL), including p50, p95, and p99.
  • End-to-end request latency.
  • Output tokens per second and requests per second.
  • Dispatch, expert compute, and combine duration.
  • Per-rank and per-expert token counts.
  • Network throughput and link utilization.
  • GPU SM utilization, memory bandwidth, and memory headroom.
  • KV-cache occupancy, preemptions, and effective batch size.

Use identical prompts or controlled replay when comparing configurations. Warm up each configuration. Run enough repetitions to distinguish real improvements from noise. Report the exact model, runtime, backend version, GPU topology, and workload shape so that results can be reproduced.

A kernel-level speedup is not necessarily a serving-level speedup. The objective is to improve request-level SLOs and useful throughput without increasing error rate or reducing output quality.

14. Common failure modes#

Choosing a high-throughput backend for tiny decode batches. Peak bandwidth does not compensate for fixed synchronization and launch costs. Benchmark low-latency modes at realistic decode batch sizes.

Assuming equal expert counts mean equal work. Router traffic is skewed. Inspect per-expert and per-rank token counts, not just placement counts.

Replicating experts too aggressively. Redundant weights consume GPU memory and can displace KV cache. Measure the impact on active concurrency.

Ignoring cross-node topology. A balanced expert map can still create expensive inter-node traffic. Measure the actual path and link utilization.

Enabling overlap without checking contention. Communication and expert GEMMs may compete for SMs or memory bandwidth. Verify that the critical path shrinks.

Benchmarking only synthetic uniform routing. Real prompts can produce skewed routing patterns. Include production-like traffic or replay representative router traces.

Rebalancing too frequently. Weight movement and metadata changes can cost more than the skew they fix. Use windows and hysteresis.

Measuring only tokens per second. A throughput gain can hide p99 ITL regressions or worse TTFT. Evaluate the full SLO set.

Changing multiple dimensions at once. If EP degree, backend, placement, dtype, and overlap all change together, it becomes impossible to identify the cause of a result. Change one dimension at a time, then validate the combined configuration.

15. A practical optimization workflow#

  1. Establish a baseline. Capture request-level latency, throughput, per-stage timing, expert skew, GPU memory, and network metrics.
  2. Classify the bottleneck. Decide whether the critical path is dispatch, expert compute, combine, synchronization, or a hotspot.
  3. Separate prefill and decode. Benchmark both at representative token counts and concurrency.
  4. Validate topology and EP layout. Confirm that ranks and experts map sensibly to NVLink and network domains.
  5. Compare communication backends. Use the same workload and warmup procedure; select by the service objective.
  6. Address persistent skew. Test expert placement or controlled redundant-expert balancing, while accounting for KV-cache memory.
  7. Test overlap and fusion. Measure resource contention and critical-path reduction.
  8. Validate correctness. Compare outputs, routing behavior, and numerical tolerances against a trusted baseline.
  9. Canary the configuration. Monitor TTFT, ITL, p99 latency, goodput, errors, GPU memory, and expert balancedness.
  10. Keep a rollback path. Preserve the previous backend, placement, and configuration until the new one is stable.

16. Production checklist#

  • [ ] EP, TP, and DP layout is documented and justified by the actual GPU topology.
  • [ ] Dispatch and combine are timed separately.
  • [ ] Prefill and decode have been benchmarked independently.
  • [ ] The all-to-all backend is selected using representative batch sizes.
  • [ ] Per-expert and per-rank token imbalance is monitored.
  • [ ] Expert replication or placement changes are bounded and coordinated.
  • [ ] Redundant expert memory is included in KV-cache capacity planning.
  • [ ] Communication/compute overlap has been measured for contention.
  • [ ] Mixed traffic and concurrent requests are included in evaluation.
  • [ ] p50/p95/p99 TTFT and ITL, goodput, errors, and output quality are checked.
  • [ ] Runtime, backend, topology, and model versions are recorded for reproducibility.
  • [ ] A rollback configuration is ready.

17. Key takeaways#

  • Expert parallelism moves routed token activations to the GPUs that own selected experts; dispatch and combine can become a major inference bottleneck.
  • Prefill and decode have different communication regimes. Large-batch throughput and small-batch latency require different measurements and may favor different backends.
  • Expert count per rank is not a reliable proxy for workload balance. Measure token load and completion skew.
  • Expert replication can reduce hot-expert bottlenecks, but it consumes memory that may otherwise hold KV cache.
  • Communication-compute overlap, fused dispatch, and topology-aware placement are useful only when they shorten the real critical path.
  • Optimize the complete serving objective—TTFT, ITL, tail latency, goodput, memory, and correctness—not a single communication microbenchmark.

The production decision is not “which all-to-all library is fastest?” It is “which combination of routing, placement, communication, overlap, and memory policy gives the best reliable serving performance for this model and traffic mix?”

Related questions

Explore other topics:Forward Deployed EngineeringDeep LearningRetrieval-Augmented GenerationAI Agents