Kernel Fusion for Tensor Parallelism and MoE Expert Sharding
Kernel fusion combines a sequence of kernels into a single kernel, so that the intermediate results stay in the memory of the streaming multiprocessors (SMs), without a round trip to the high bandwidth memory (HBM). Automatic fusion, such as the PyTorch compiler, which turns the layers of a model into fused Triton kernels, fuses computation only. On several GPUs, each collective communication causes a graph break, which splits the program into separate kernels, and the speedup of fusion shrinks. This post fuses the computation and the communication of the tensor parallelism of Megatron-LM, which needs a single collective per pair of linear layers, and of the expert sharding of Mixture-of-Experts layers.
Megatron-LM tensor parallelism
Megatron-LM splits the two blocks of a transformer layer, the attention and the feed-forward network (FFN), across \(G\) GPUs. The input \(X\) of each block holds \(B\) sequences of \(S\) tokens of size \(E\) (this \(B\) is not the weight matrix \(B\) below), and \(Z\) is its output.
The FFN has two linear layers. The first layer computes \(Y = \phi(XA + b_1)\), where \(\phi\) is the activation function, and the second one computes \(Z = YB + b_2\), optionally followed by \(\phi\). With \(X\) replicated on all GPUs, \(A\) split by columns and \(B\) by rows, each GPU computes \(O/G\) of the \(O\) columns of \(Y\) (the hidden dimension) and a partial sum of \(Z\) without any communication. A single all-reduce then adds up the partial sums, before \(b_2\) is added. This post implements the FFN. The following picture illustrates it on 2 GPUs, with the data of GPU 1 in green and the data of GPU 2 in blue:
The attention follows the same pattern, split by heads. With \(X\) replicated on all GPUs, each GPU computes the queries, keys and values of \(H/G\) of the \(H\) heads of size \(h\), and their attention scores, without any communication, as the heads are independent. Each GPU thus holds the columns of its heads in the attention output \(Y\). The output projection \(B\) is split by rows, so each GPU computes a partial sum of \(Z = YB\), and an all-reduce adds them up into \(Z\), which is the input \(X\) of the FFN. The following picture illustrates the attention:
The original formulation of Megatron-LM needs the input of each block replicated on all GPUs. Memory is an issue for large language models (LLMs), particularly as the sequence grows, so a variant combines tensor parallelism with data parallelism, by also splitting the input along the sequence dimension.
Sequence parallelism
Sequence parallelism gives each GPU \(S/G\) of the tokens of every sequence between the blocks, as in data parallelism. The FFN needs all the tokens and the attention the whole sequence, so an all-gather before each block gives every GPU all the tokens. The block then runs split as above, and a reduce-scatter after it adds up the partial sums and returns to each GPU the rows of its own tokens, as illustrated below:
The input and the output of each block are thus split instead of replicated, which divides their memory by \(G\). An all-gather and a reduce-scatter move as much data as one all-reduce, so the communication volume does not change.
Fusing the two linear layers
A regular implementation of the FFN launches one kernel per computation and one per communication operation. Each kernel loads its inputs from the HBM into the memory of the SMs and stores its outputs back, as displayed at the top of the timeline below:
A matrix multiplication (GEMM, for general matrix multiply) on a GPU is computed in tiles, i.e. small submatrices of the output. Each thread block, a group of threads that runs on one SM, computes a tile by iterating over the matching tiles of its inputs. The fused kernel keeps this tiling for the first layer. In this section, \(Y\), \(B\) and \(Z\) stand for the slices \(Y_g\) and \(B_g\) of one GPU \(g\) and for its partial sum \(Y_g B_g\).
The activation does not prevent the fusion, as it applies to each tile of \(Y\) on its own. However, the difficulty is the second matrix multiplication, which sums over the hidden dimension, and forces a naive implementation to dump into HBM the output of the first linear layer.
To avoid that HBM load/store and reduce runtime, we implemented a different algorithm: as soon as a tile \(Y_{i,j}\) is computed (with its bias and activation), it is multiplied by every tile in row \(j\) of \(B\). The products are added to the tiles in row \(i\) of \(Z\). When all tiles of \(Y\) are processed, \(Z\) holds the full product \(Y B\), and \(Y\) was never stored in global memory, as illustrated below:
Top: the regular execution computes all tiles of \(Y\), stores \(Y\) in global memory, and a second kernel computes \(Z\). Bottom: the fused kernel multiplies each tile of \(Y\) by a row of tiles of \(B\) and accumulates the results in a row of tiles of \(Z\).
There’s a small issue here. Many blocks add their products to the same tile of \(Z\) at the same time, so the additions must be atomic. However, blocking atomic additions quickly become a bottleneck. This can be overcome with PTX (assembly) instructions that allow for asynchronous tile reductions. These reductions overlap the next matrix multiplications in a ping-pong pattern. For each tile in the row of \(B\), the block computes the product, waits for the reduction of the previous product to complete, and issues the reduction of the current one. Thus, the latency of the accumulation is mostly hidden behind the computation of the next tile.
The kernel also needs to know when a tile of \(Z\) is complete. A per-tile counter, which each contributing block increments atomically, counts the contributions to the tile, and the block that makes the last contribution marks the tile as ready with a per-tile flag in global memory. Therefore, as soon as a tile has performed all accumulation, the all-reduce for that tile can now be done independently of the remaining tiles (still on flight).
Communication with block specialization
In a regular kernel, all SM blocks do the same work, and synchronize only at the end of the kernel. This requires a large communication sum-reduce step that holds execution until it’s done. To overcome that, we performed Block specialization that splits the blocks of the kernel into a group of compute blocks that run the fused matrix multiplications, and mark the tiles of \(Z\) as ready, and communication blocks that perform an all-reduce of every tile across GPUs when that give tilen is flagged as ready.
Thus, compute blocks never wait for communication, and communication blocks never run matrix multiplications. The price is that the matrix multiplications run on fewer SMs, which makes them slower, although we only need a few SMs reserved for communication on a GPU with 200+ SMs, so it is a marginal performance reduction. In return, the idle time disappears, the communication is done asynchronously. The following timeline illustrates this method:
An example on a GPU with 6 SMs. (a) Without block specialization, all SMs compute and then spin-wait before each band is all-reduced. (b) With block specialization, SM1 and SM2 all-reduce tiles iteratively, as soon as SM3 to SM6 have computed and flaggen them as ready.
Similar specializations exist at other levels. Inside a thread block, FlashAttention-3 uses warp specialization, where some warps load data while the others compute. Across the GPU, DeepSeek-V3 gives about 15% of the SMs to the communication of its Mixture-of-Experts layers.
Other kernels also fuse the collectives of tensor parallelism with the matrix multiplications, written by hand (FLUX, Punniyamurthy et al.) or by a compiler (TileLink, Triton-distributed). Without fusion, Centauri and Domino split them into smaller pieces that overlap across kernels.
Results
The fused kernel was compared to a baseline, a tuned implementation of the same FFN without fusion or block specialization, which uses the all-reduce of the NCCL. The benchmarks run FFNs with the dimensions of several LLMs available online, on 8 GPUs.
The fused kernel reduces the latency by 22% to 62% (a speedup of 1.3 to 2.6 times), roughly halves the memory of the activations, and shrinks the communication buffer from gigabytes to 32 KiB. The gains depend on the size of the FFN. Small FFNs gain the most, while large FFNs gain less, as the two matrix multiplications dominate their runtime so the possible communication improvements are reduced. The attention block, fused in the same way, gains a speedup of 20% to 30%.
Expert sharding
A main problem of expert parallelism in Mixture-of-Experts (MoE) layers is the load imbalance across experts. In 2025, the paper Accelerating MoE Model Inference with Expert Sharding proposed expert sharding, which splits every expert across all GPUs instead, as Megatron-LM splits the FFN. Each GPU holds a \(1/G\) share of the columns of the input matrix \(A_e\) and the matching rows of the output matrix \(B_e\) of every expert \(e\), and processes all the tokens of each expert with these slices. The partial outputs of all GPUs are then summed, so each expert is an FFN with Megatron-LM tensor parallelism. Sharding removes the load imbalance of expert parallelism: every GPU holds the same share of every expert and processes all the tokens, so all GPUs do the same amount of work, whatever the routing.
Expert sharding also uses an all-gather and a reduce-scatter, but splits the batch instead of the sequence. Each GPU runs the attention of its own sequences with all heads and all the attention weights, as in data parallelism, so the attention needs no communication. The dispatch is then an all-gather, which gives every GPU all the tokens, and the combine is a reduce-scatter, which sums the partial outputs and returns them to the GPUs of their tokens, as illustrated below:
\(W_g\) are the weights of the router, \(N\) the number of experts and \(k\) the number of experts per token. No token is routed to the faded experts.
However, this approach is typically not feasible. Expert sharding adds an extra communication overhead, as every GPU needs all the tokens, and the partial outputs must be summed across GPUs. But the fused kernel above makes this communication cheap, as its communication blocks sum the partial outputs one band at a time and overlap the computation.
In the benchmarks above, the expert FFNs are split across the 8 GPUs with expert sharding. The fused kernel reduces the latency by 55% and 62% for the two expert FFNs of DeepSeek V3, 45% for the experts of Llama 4 Scout and 42% for those of Mixtral 8×7B.