A Mixture-of-Experts (MoE) is a sparse model that holds many experts, and each token activates only a few of them. A model thus grows its parameters without growing its compute cost per token. Expert parallelism, now standard in large language models, is the parallelism technique that distributes the experts across GPUs. Each MoE needs two transfers: the dispatch sends each token to the accelerators that hold the relevant experts, and the combine sums the expert outputs for a given token and communicates that result to the GPU that initiated the dispatch. The following picture illustrates expert parallelism of an MoE layer with 4 experts on 2 GPUs:

Green marks the first GPU and blue the second. No token is routed to the faded experts. \(W_g\) are the weights of the router, \(k\) the number of experts per token, \(A_e\) and \(B_e\) the weights of expert \(e\), \(O\) their hidden size and \(\phi\) the activation function. The picture writes \(E\) for the embedding size \(H\), and \(N\) for the number of experts \(E\).

These transfers are typically collectives, which are synchronous: every rank, i.e. device, waits for the data of the others, therefore the slowest rank sets the pace. According to COMET, the dispatch and the combine communication takes on average 47% of the execution time of popular MoE models, and is a major overhead. The usual techniques to overcome this bottleneck overlap the communication of a micro-batch (a subset of the input tokens) with the computation of another micro-batch.

Each SM has two types of units at once: matrix units for matrix multiplications (GEMMs, MatMuls), and vector units for elementwise work and data movement. An MoE layer runs as a chain of operation, alternating between matrix and vector units, depending on the operation. The following picture illustrates the computation workflow of an MoE layer across the three units:

The eight stages of the fused MoE layer, in dependency order, each on the resource that runs it: matrix multiplications on the matrix units (purple), all other computation on the vector units (green), and both collectives on the network (orange). The blue frame holds the experts. route computes the routing of the tokens, and dispatch sends them to their experts. group orders the received tokens by expert, and the experts run two MatMul stages, with the activation (SwiGLU) activation between them. reduce scales each expert output by its routing weight and sums the outputs of each token, and combine returns them.

Megakernels and kernel fusion

A conventional layer runs as a sequence of kernels. Each kernel loads its inputs from the GPU High Bandwidth Memory (HBM), executes some computation on the Streaming Multiprocessors (SMs, blocks) of the GPU, and writes its outputs back.While HBM has a capacity of several GBs, the SMs hold a shared/block/local memory of circa 256KB. Kernel fusion merges this sequence into one kernel. The intermediate results then stay in the SMs’ local memory, and only the final output is written to the HBM, reducing the overhead of HBM/SM memory load-store. For this to be possible, the communication required (if any), is also performed from the SM. Thus, a megakernel is a set of computation and communication operations that run into one large (mega) kernel. As examples, Look Ma, No Bubbles writes a megakernel by hand for the decode of a small language model, and Mirage Persistent Kernel compiles a model into one.

Pipelining and three-way overlap

During training and the prefill stage of inference, the batch is large enough to split into micro-batches. A micro-batch typically uses one resource at a time, as its stages are sequential. Tokens have independent computation. Thus, the megakernel can therefore run several micro-batches at the same time, with no global barrier: top overlap matrix computation, vector computation and communication, execution follows a pipelining strategy, where each stage waits only on the previous stage of its own micro-batch. The matrix units, the vector units and the switch can then work on different micro-batches at the same time. This three-way overlap is illustrated in the following timeline:

Pipelined execution of four micro-batches (mb 0 to 3) during prefill. Each micro-batch has three rows, one per resource, colored as in the stages above. A microbatch step uses all matrix and all vector units, so no two purple and no two green boxes overlap.

This reduces the overall runtime, due to the required large MatMul operations. Prefill is therefore compute-bound.

During inference decode, each step adds one or a few tokens per sequence, so the batch is too small to split into micro-batches. The matrix multiplications shrink to skinny ones that still read the weights of every expert from global memory. The collective communication sit on the critical path, and the compute must wait while the network works. A decode step is thus bound by memory and latency, not by compute. At a larger scale, MegaScale-Infer runs the attention and the experts on separate GPUs, so that many attention GPUs send larger batches to each expert.

NCCL Kernel vs shmem fused communication

Kernel Fusion matters even more in a distributed layer. Typically, a collective communication library, such as NCCL, is two-sided: every rank takes part in each collective, which runs as a kernel of its own. Since the each NCCL call is a separate kernel launch from the host GPU, each call enforces a graph break that forces a hard stop on the fused kernel: the kernel must finish before the call, and a new kernel must start after it. Each call also pays a fixed cost for the launch and the handshake between the ranks, which only a large payload amortizes, so NCCL is built for bandwidth.

To avoid graph breaks due to NCCL communication, MegaKernels need to communicate from inside the kernels. This is possible with communication libraries such as SHMEM, which is one-sided: a kernel calls it from the device, and a rank puts data into, or gets it from, the memory of a peer, which takes no part in the transfer. These operations work on a symmetric heap, a memory region allocated at the same offset on every rank. One-way communication is provided by a workflow control based on put, get, signal and wait operations. Shmem operations start at once, from the SM, with no launch or handshake, so shmem is built for latency. In brief, small communication volumes are relayed faster by shmem, while large ones are communicated faster by NCCL:

To account for the limited storage in SMs and communication bandwidth vs latency trade-off, kernels are written at a fine-grained level of parallelism (e.g. SM tile, micro-batch), that overlaps computation and communication across microbatches, and instead of a few NCCL transfers of large payloads, they run thousands of small one-sided SHMEM transfers, which fits the payload range that makes shmem faster than NCCL.

Note that NVIDIA’s implementation of OpenSHMEM, NVSHMEM, also provides collectives at the device level, which a megakernel can call.

Dispatch-and-combine communication

Consider \(W\) compute ranks and an MoE layer of \(E\) experts, \(E/W\) on each rank. For a token \(x\) of width \(H\), the router computes the probabilities \(p(x)\) of all experts, and keeps the set \(\mathcal{T}(x)\) of the top-\(k\). The output of the layer is the weighted sum of the selected experts \(F_e\), given by:

\[\text{MoE}(x) = \sum_{e \in \mathcal{T}(x)} p_e(x) \, F_e(x) = \sum_{y=0}^{W-1} \sigma^y(x)\]

where \(\sigma^y(x)\) is the partial result of rank \(y\), i.e. the weighted sum of the selected experts that rank \(y\) holds. The combine must therefore sum the partial results on the rank that owns the token. We will call rank that initially dispatched a token the token rank and the ranks to whom that token were assigned the expert rank.

As an example, imagine \(W=3\) ranks \(P_0\), \(P_1\) and \(P_2\), each holding one token (A, B or C) and one expert (\(E_0\), \(E_1\) or \(E_2\)), with top-\(k=2\). Take the following routing table that maps each token from token ranks to the experts and the NPUs that hold them:

Token rank \(E_0\) on \(P_0\) \(E_1\) on \(P_1\) \(E_2\) on \(P_2\)
\(P_0\) A   A
\(P_1\)   B B
\(P_2\) C C  

Typically, one implements the dispatch-and-combine communication pairs with AllGather/ReduceScatter or AlltoAll/AlltoAll. Let’s look at the different dispatch-and-combine methods.

Dispatch-and-combine with AllGather-ReduceScatter (AGRS). AGRS sends all tokens to all ranks with an all-gather, and returns the results with a reduce-scatter. Each rank runs its experts on the tokens routed to them, and writes zero outputs (\(\emptyset\)) for the others:

AllGather-ReduceScatter through a switch that relays each packet, with the dispatch (All-Gather) on the left and the combine (Reduce-Scatter) on the right. \(A_0\) is token A sent to the expert rank \(P_0\), \(E_0(\text{AC}_0)\) the expert \(E_0\) of \(P_0\) processing tokens A and C, \(\sigma^y_t\) the partial sum of the expert outputs of \(P_y\) for token \(t\), \(\Sigma_t = \sigma^0_t + \sigma^1_t + \sigma^2_t\) their sum across all ranks, i.e. the final output of token \(t\), and \(\emptyset\) a token without output.

AGRS does not depend on the routing, so each rank knows in advance what it sends (all tokens to all GPUs) and what it receives (all expert outputs, or zero for unrelated experts, from all GPUs). However, every token goes to every rank, so AGRS moves up to \(W\) times more data than needed. Each rank also issues \(W\) operations per collective.

Dispatch-and-combine with All-to-alls. The all-to-all (A2A) is the selective alternative to AGRS. It sends each token only to the ranks that hold its experts: a token whose experts lie on \(d\) distinct ranks is relayed \(d\) times. Its combine is the reverse all-to-all, followed by a sum of all expert rank results by the the token GPU (the owner of each token):

All-to-All through a switch that relays each packet, with the dispatch on the left and the combine on the right, in the notation of AllGather-ReduceScatter. Each rank sends a message to every rank, an empty one (\(\emptyset\), dotted) when it has no data for it.

The cost of the selective send is that message sizes depend on the routing, so each receiver must learn how much data it gets from each sender. Therefore, it usually requires an extra all-to-all of the counts beforehand, as in the distributed implementation of the MoE post.

Since each rank must relay to \(W\) ranks (even if zero tokens), \(W^2\) transfers cross the switch per collective. The all-to-all also adds two stages that AGRS does not need: a pack operation before the dispatch must lay out a copy of each token per destination, and a global reduce after the combine sums the partial results of each token on its owner.

For more advanced implementations, Multi-Head LatentMoE avoids the all-to-all of the counts: it splits each token into sub-tokens, each with its own small MoE, and sends them before the routing, so that every rank sends and receives the same amount of data. Across nodes, the hierarchical all-to-all of DeepSpeed-MoE exchanges the data inside each node first, which cuts the number of hops.

In-Network Computing

In-network computing (INC) moves the computation of some collectives from the sending and receiving ranks into the switch. In 2016, SHArP offloaded the reductions of MPI collectives into the switches of an InfiniBand network. NVLink SHARP now brings the same capabilities to the NVIDIA switches. An INC switch reduces the bandwidth that these collectives need, by performing the underlying disptch multicast and combine sum reduction on the switch. However, the INC switches on the market implement the all-gather, the all-reduce and the reduce-scatter collectives, not all-to-all.

Dispatch-and-combine with INC AllGather-ReduceScatter. Applied to AGRS, INC turns the all-gather into a multicast, and the reduce-scatter into a sum in the switch:

INC AllGather-ReduceScatter, with INC All-Gather on the left and INC Reduce-Scatter on the right, following the same notation and routing as AGRS. As an example: \(\sigma^0_{A\emptyset C}\) is the partial sums of \(P_0\) for the tokens A and C, with no output for B. The INC switch adds the partial sums into \(\Sigma_0\) and relayes it to \(P_0\).

Each rank now sends each token once rather than \(W\) times, and receives one sum per token rather than \(W\) partial results, with one operation per collective (insead of \(W\) per rank). This cuts the bandwidth that each rank needs. However, each rank still receives every token, whether its experts need it or not. Despite this, the bandwidth gains make it worth to have INC AGRS runs in many production systems.

Dispatch-and-combine with INC All-to-alls. No switch on the market implements an INC all-to-all. The implementation is challenging but feasible. Instead of a ring/mesh algorithm, Bruck’s algorithm or \(W^2\) point-to-point transfers through a regular switch, the INC all-to-all is one collective call done in three steps:

  1. each rank sends all its data to the INC switch in one transfer, with the offset of each recipient’s part;
  2. the switch groups the data by recipient; and
  3. it selectively sends each rank its data.

Think of it as an INC all-gather in which each rank selective send and receives the related tokens (on dispatch) and expert results (on combine). Despite the bandwidth/relays reduction, this methods still has two drawbacks. On the dispatch, each token is sent once per recipient, i.e. several duplicates of the same token are relayed. On the combine, the ranks send their partial results \(\sigma^y\), which is later summed onto \(\Sigma_t\) by the recipient ranks (a step that the INC reduce-scatter avoids by delivering the final output \(\Sigma_t\) of each token rank directly).

The Insights into DeepSeek-V3 paper mentions both limitations and emphasizes the efficiency opportunities: a dispatch that “resembles a small-scale multicast”, and a combine that could use in-network aggregation. Therefore, to tackle both drawbacks, two variants of the INC all-to-all can be implemented:

  • INC All-to-All-Dispatch: a variant of the INC all-to-all in which each sender sends each token once to the INC switch, however many ranks need it. The INC switch receives this single copy, reads its header, and multicasts the token to all ranks that need it;
  • INC All-to-All-Combine: a variant of the all-to-all in which the switch reduces the partial results of the ranks selectively. Unlike an all-reduce or a reduce-scatter, which reduce each value over all ranks, the All-to-all combine sums only the expert results across expert ranks that refer to each token rank. The INC switch then sends each token rank the final \(\Sigma\) once all partial results have been summed.

The following picture illustrated the INC All-to-all-dispatch and -combine MoE workflow:

Note that this method relays fewer transfers and requires less bandwidth than regular all-to-all or INC all-to-all. The pack and global reduce stages of the non-INC communication disappear too.

INC all-to-all Phased. The INC collectives can be acynchronous on the GPUs (fire-and-forget), but they are synchronous on the switch: the switch relays nothing until all \(W\) ranks have sent their data, and holds all of it meanwhile. This requires large storage on the switch, and later it holds back the computation of the ranks that wait for the data from the INC. As an optimization, a phased version of the INC All-to-All-Dispatch and the INC All-to-All-Combine can be done iteratively, in phases: instead of an all-to-INC-to-all, we can do \(W\) one-to-INC-to-many dispatches and \(W\) many-to-INC-to-one combines, ie one for each token rank. This way, the INC can process the ranks one at a time, in their order of arrival, and release the idle ranks sooner. Them benefits are:

  • memory: the switch holds the data of one phase (token rank) only, up to \(W\) times less, which allows larger batches or a switch with less memory;
  • overlap: the switch can communicate with some ranks while the others still compute, and spreads the traffic over time, rather than waiting for every rank before doing a broadcast that saturates the links.

The drawback is that, due to more relays through the switch, we increase latency, and this can possibly by meaningful on small communication payloads.

For further reading, In-Network Collective Operations reviews the obstacles of INC for AI workloads, such as low-precision data types and bitwise reproducibility.

Results

We implemented a MegaKernel with fused computation and communication, with pipeline parallelism of micro-batching, and three-way overlap of vector, cube and in-network compute. Fused/device communication was enabled by implementing the previous dispatch-and-combine methods for the INC all-to-all dispatch and combine and for the non-INC all-to-all use cases. The MoE MegaKernel was placed on the OLMoE-1B-7B model, running on vLLM. This model has 7 billion parameters, 1 billion active per token, and 16 MoE layers of \(E=64\) experts with top-\(k=8\) and \(H=2048\). We tested it on one node with \(W=4\) GPUs. A separate GPU simulated the INC switch.

We then benchmkarked three implementations of the MoE layer, each at its best micro-batch size (found with grid search):

  • Baseline: several compute kernels and NCCL communication kernels;
  • Fused without INC: a single kernel, with fused one-sided communication (shmem);
  • Fused with INC: the same single kernel, with fused INC communication (shmem).

Prefill ran one forward pass over 1k to 64k tokens per rank, and decode ran 32 steps of 1 to 64 sequences of 1024 tokens per rank. The runtime of the whole model is displayed below:

Prefill. Prefill moves large payloads, so its communication is bandwidth-bound. At 1k tokens, Fused without INC runs 1.78 times faster than Baseline, as fusion removes the overhead of kernel launches, and round trips to global memory of each stage. However, for large batch, the Fused without INC runtime approximates the baseline, due to being in a communication regime of high bandwitdh. Fused without INC is thus only 1.18 to 1.22 times faster from 16k tokens. However, Fused with INC is 1.65 to 1.94 times faster at every batch, as in-network computing also improves bandwidth.

Decode. Decode moves only a few tokens per rank and step, so its communication is latency-bound. Both fused kernels beat Baseline at every batch, for the same reasons as above. Fused without INC and Fused with INC have comparable runtimes as the bandwidth advantages of the INC are meaningless at such low payloads. Fused kernel run decode 1.56 to 1.91 times than baseline.

Prefill and decode. While the baseline benefits from large bandwidth (large payload prefills), and fused kernels benefit from low latency, only Fused with INC provides the bandwidth and latency improvements that make it run faster for prefill and decode. Thus, total runtime is consistently faster for Fused with INC compared to the other two implementations, at 1.66 to 1.91 times faster than Baseline.

Performance modeling to unseen networks

A measurement holds only for the network it ran on. And network efficiency is critical for MoEs. So ideally one should be able to create a network-based performance model that, given new network specifications - latency and bandwidth - is able to extrapolate the full model performance when running on the new network. This should be possible as long as one can estimate the runtime of the communication steps in the timeline, and respect: (1) the dispatch-and-combine stage dependencies, (2) cross-micro-batch dependencies, and (3) the rule of non-overlap of vector units or cube units in the same period of time.

The performance model we implemented starts by profiling the bytes \(B_i\) and duration \(d_i\) of each transfer \(i\). We noticed that not all communication relays are the same, as runtime depends on the context: the transport used (NCCL or shmem), the phase (prefill or decode), the collective stage (dispatch, combine), and the first/last/middle micro-batch. So we fit a latency, bandwidth and margin of error to each context with aBayesian linear regression with with Gaussian noise and a flat prior:

\[d_i = \alpha_c + \frac{b_i}{\beta_c} + \epsilon_i, \quad \epsilon_i \sim \mathcal{N}(0, \sigma_c^2), \quad b_i = \frac{B_i}{f_i}\]

where \(\alpha_c\) is the latency, \(\beta_c\) the bandwidth, and \(f_i\) the number of ports that the transfer spreads over: one on a compute rank, \(W\) on the INC device. This fitting has a closed-form solution. With the rows \(x_i^T = [1, \; b_i - \bar{b}]\) of the design matrix \(X\), the posterior of the weights is Gaussian, with mean and covariance given by:

\[m_N = (X^T X)^{-1} X^T d, \quad S_N = \hat{\sigma}_c^2 \, (X^T X)^{-1}\]

where \(\hat{\sigma}_c^2\) is the variance of the residuals over the \(n\) transfers of the context, \(\beta_c = 1/m_{N,2}\) and \(\alpha_c = \max(0, m_{N,1} - \bar{b}/\beta_c)\).

So we measured the current runtime per context, and inferred the projected (estimated) communication runtime on an arbitrary slower network (that communicates over the NIC) with 130 Gb/s bandwitdh and a latency of \(\alpha'=\alpha+2\) μs (ie 2 microseconds slower). The following plots draw a sample of a fitted communication context against its payload, one panel per transport.

This plot emphasizes some insights discussed before. The NCCL is optimized for bandwidth: it pays a large fixed cost per call, but communicates with a very large bandwidth. The shmem operations of Fused without INC are optimized for latency: they start fast, but the bandwidth across payloads is lower. So the NCCL overtakes the shmem runtime for payloads above 155 MiB. The transfers of shmem over INC have both the low latency and high bandwidth, so the NCCL never overtakes it. Those patterns are constant across the current network and the predicted NIC network performance (dashed line).

With the values of latency and bandwidth estimated per context on the new network, one can compute the estimated runtime of each communication block in the timeline, and replay those over the dependency graph of the model to compute the estimated the model runtime. In this example, we computed that Fused with INC is estimated to run up to 1.66 times faster than Baseline on the new network, against 1.66 to 1.91 times measured, with an uncertainty below 1.1%. Fused without INC is only predicted to have gains of up to 1.32x, way below the max 1.78x times measured in the current network.