# Is the MoE All-to-All an All-Gather Plus a Reduce-Scatter? *How the two all-to-alls of an MoE layer line up with the two halves of an all-reduce* If you read about expert parallelism for long enough, someone will tell you that the two all-to-alls in a Mixture-of-Experts (MoE) layer are equivalent to an all-gather and a reduce-scatter. You have probably also learned that an all-reduce is a reduce-scatter followed by an all-gather. Those are the same two operations, just in the opposite order, so it's natural to wonder whether the MoE version is really an all-reduce in disguise, or maybe something like a reduce followed by an all-gather. The short answer is that the claim is true, and its order is the right one: the all-gather happens before the experts, and the reduce-scatter happens after them. A reduce followed by an all-gather doesn't work, and that's true for the all-reduce as well as for the MoE layer. In this short write-up, I want to show why, first for the all-reduce and then for the MoE layer, with a small PyTorch simulation for each. At the end, we will look at what the swap costs, since "equivalent" here only means that every GPU ends up with the same numbers. (I'm reusing the notation from section 1.2 of my [article on multi-GPU communication](https://sleepy-capybara.vercel.app/multi-gpu-communication/), but everything you need is repeated here.) ## 1. Two Ways to Split an All-Reduce Let's start with the all-reduce, since that's where the reduce-scatter plus all-gather comes from. In an all-reduce, every GPU contributes a tensor of the same shape, and afterwards, every GPU holds the element-wise sum of all of them. To see what happens inside, it helps to cut the tensor of each GPU into one chunk per GPU. With 4 GPUs, the chunks are A, B, C and D, and we write A2 for chunk A as GPU 2 has it. The all-reduce has to leave ΣA = A0 + A1 + A2 + A3 on every GPU, and the same for ΣB, ΣC and ΣD. There are two standard ways to do this in two steps, as shown in Figure 1 below. ![Two ways to split an all-reduce into two steps](https://sleepy-capybara.vercel.app/stupid-questions/moe-all-to-all/figures/fig01_two_splits.png) *Figure 1: An all-reduce on 4 GPUs, split into a reduce-scatter and an all-gather (top), and into a reduce and a broadcast (bottom).* In the top half of Figure 1, the reduce-scatter sums each chunk across the GPUs but gives each GPU only one of the sums: GPU 0 gets ΣA, GPU 1 gets ΣB, and so on. Then, the all-gather copies the piece of each GPU to all the others, without adding anything. In the bottom half, the reduce adds everything up on a single GPU (GPU 0 here), so that GPU 0 holds all four sums and the other GPUs hold nothing. Then, the broadcast copies the tensor of GPU 0 to everyone. What makes each pair work is that the first step leaves the data in exactly the shape that the second step starts from. After a reduce-scatter, every GPU holds one finished piece, and an all-gather is the operation that starts from one piece per GPU. After a reduce, one GPU holds everything, and a broadcast is the operation that starts from one GPU. This is also why a reduce followed by an all-gather is not a way to split an all-reduce. After the reduce, GPUs 1 to 3 have nothing to contribute, so the all-gather would only collect the four sums of GPU 0 next to three empty pieces. (When people say "reduce" in this context, they often mean a reduce-scatter, and then the pair is just the one from the top half of Figure 1.) To make this concrete, below is a small simulation in PyTorch, where a "GPU" is just an entry in a Python list: ```python import torch P = 4 # GPUs; GPU g holds xs[g], cut into P chunks xs = [torch.randn(P, 3) for _ in range(P)] def reduce_scatter(xs): # GPU g gets the sum of chunk g return [sum(x[g] for x in xs) for g in range(P)] def all_gather(pieces): # every GPU gets every GPU's piece return [torch.stack(pieces) for _ in range(P)] def reduce(xs): # GPU 0 gets the sum, the others get nothing return [sum(xs)] + [None] * (P - 1) def broadcast(ys): # every GPU gets a copy of GPU 0's tensor return [ys[0].clone() for _ in range(P)] target = sum(xs) # what an all-reduce leaves on every GPU for out in (all_gather(reduce_scatter(xs)), broadcast(reduce(xs))): print(all(torch.allclose(o, target) for o in out)) # prints True twice ``` If we try `all_gather(reduce(xs))` instead, `torch.stack` fails because three of the four pieces are `None`, which is the same problem as above, just in code. ## 2. What the Two All-to-Alls in an MoE Layer Do Now, let's switch to the MoE layer. With expert parallelism, each GPU holds some of the experts in full, and each GPU starts out with the hidden states of its own tokens. The router picks a few experts for each token, and since these experts usually live on other GPUs, the tokens have to travel. This happens in two steps. In the first step, which is called dispatch, each token is copied to every GPU that holds one of its experts. In the second step, which is called combine, each expert output is multiplied by the router weight of that expert and sent back to the GPU that the token came from. There, the outputs for the token are added up. Both steps are all-to-alls, since every GPU sends something different to every other GPU. Let's use a toy example that is small enough to draw. We have 4 GPUs with one expert each (expert E0 on GPU 0, E1 on GPU 1, and so on), one token per GPU (token a on GPU 0, b on GPU 1, and so on), and 2 experts per token. Let's say that token a picks E1 and E2, b picks E0 and E1, c picks E2 and E3, and d picks E0 and E3. Similar to the chunks earlier, we write a1 for the output of expert E1 for token a, already multiplied by its router weight. This way, the output of the MoE layer for token a is Σa = a1 + a2. The top half of Figure 2 shows what each GPU holds after each step. ![The same MoE layer computed in two ways](https://sleepy-capybara.vercel.app/stupid-questions/moe-all-to-all/figures/fig02_moe_two_ways.png) *Figure 2: The same MoE layer on 4 GPUs, computed with two all-to-alls (top) and with an all-gather and a reduce-scatter (bottom). Each cell position belongs to one token, so the leftmost cell of each GPU is token a's.* As we can see in the top half of Figure 2, nothing is added during dispatch. The tokens are only copied, so that token a, for example, now sits on GPUs 1 and 2. All of the adding happens at the very end, when combine brings a1 and a2 back to GPU 0. ## 3. The Same Layer with an All-Gather and a Reduce-Scatter So, what does the bottom half of Figure 2 do differently? It replaces dispatch with an all-gather, which means that every GPU receives every token, whether it needs it or not. Each GPU then runs its expert on the tokens that picked it and writes zeros for all the other tokens. GPU 0, for example, ends up with b0 and d0, and with zeros in the places of a and c. At this point, it's worth comparing the "After experts" row with the "Before" row of Figure 1, because it's the same situation. Every GPU holds a partial result for every token, the final output of a token is the sum of these partial results over all GPUs, and each token belongs to exactly one GPU, just like chunk A belonged to GPU 0. This is exactly what a reduce-scatter expects as its input, so a reduce-scatter finishes the layer: GPU 0 receives a1 + a2 + 0 + 0 = Σa, and the other GPUs get the outputs for their own tokens in the same way. As a result, the last rows of the two halves of Figure 2 are identical. In other words, the dispatch all-to-all is an all-gather in which each GPU only receives the tokens it needs, and the combine all-to-all is a reduce-scatter in which the GPUs don't send the zeros. Note that the sum over the experts of a token, which combine has to compute anyway, is exactly the sum that the reduce-scatter computes. That's why the second step is a reduce-scatter and not just a scatter. This also answers the "reduce plus all-gather" question for the MoE layer. The gather has to come first, since the experts need the tokens before there is anything to add up. And the step after the experts has to be a reduce-scatter rather than a reduce, because each GPU only wants the outputs for its own tokens back, whereas a reduce would put the outputs for all tokens on one GPU. Below is the toy example as code, reusing the helpers from section 1. Here, the routing is random, and each GPU has 3 tokens instead of 1: ```python torch.manual_seed(0) T, D, K = 3, 8, 2 # tokens per GPU, hidden size, experts per token experts = [torch.nn.Linear(D, D) for _ in range(P)] # expert g on GPU g x = [torch.randn(T, D) for _ in range(P)] # the tokens on each GPU score = torch.randn(P, T, P).softmax(-1) # router scores, [GPU, token, expert] gate = score * (score >= score.topk(K, -1).values[..., -1:]) # 0 if not picked def all_to_all(sends): # sends[g][h] goes from GPU g to GPU h return [[sends[g][h] for g in range(P)] for h in range(P)] def moe_all_to_all(x): # dispatch: GPU g sends GPU e the tokens that picked expert e picked = gate > 0 sends = [[x[g][picked[g, :, e]] for e in range(P)] for g in range(P)] inbox = all_to_all(sends) # GPU e runs its expert on the tokens it received outs = [[experts[e](rows) for rows in inbox[e]] for e in range(P)] # combine: the outputs go back, and each home GPU adds them up back = all_to_all(outs) y = [torch.zeros(T, D) for _ in range(P)] for g in range(P): for e in range(P): rows = picked[g, :, e] y[g][rows] += gate[g, rows, e, None] * back[g][e] return y ``` The all-gather version is shorter, since there is no need to keep track of who sends what to whom: ```python def moe_all_gather(x): every = all_gather(x) # every GPU now holds all P*T tokens partial = [] for e in range(P): # GPU e: its expert's output, 0 for other tokens w = gate[..., e] # [GPU, token] y = torch.zeros(P, T, D) y[w > 0] = w[w > 0, None] * experts[e](every[e][w > 0]) partial.append(y) return reduce_scatter(partial) # GPU g: the sum of chunk g a, b = moe_all_to_all(x), moe_all_gather(x) print(all(torch.allclose(p, q, atol=1e-6) for p, q in zip(a, b))) # True ``` One thing I like about the all-gather version is that it doesn't care how the experts are split across the GPUs. If each GPU held a slice of every expert (tensor parallelism) instead of whole experts, each GPU would still end up with a partial result for every token, and the reduce-scatter would still finish the job. This is the gather and reduce-scatter that SGLang uses around a tensor-parallel MoE layer when DP attention is enabled (section 6.2 of the [multi-GPU article](https://sleepy-capybara.vercel.app/multi-gpu-communication/)). It is also what the default `allgather` token dispatcher in [Megatron-LM](https://github.com/NVIDIA/Megatron-LM/blob/54f18cd2195a0fc22c145268c9c1c193e9a3026e/megatron/core/transformer/moe/token_dispatcher.py#L236) does. It gathers the tokens along with the routing decisions, lets each GPU pick out the tokens for its own experts, writes the expert outputs back into a buffer with a row for every token, and reduce-scatters that buffer. ## 4. Where the Reduce-Scatter Plus All-Gather Shows Up There is one more place where the all-reduce order appears, and I suspect that it's behind a lot of the confusion. Let's write out the communication of two consecutive MoE layers that use the all-gather version, with the attention module of each layer running on the tokens of its own GPU (as with DP attention): ``` layer 1: attention all-gather experts reduce-scatter layer 2: attention all-gather experts reduce-scatter ``` If we read this from an all-gather to the next reduce-scatter, the two collectives wrap the experts, which is the view from section 3. But if we read across the boundary between the two layers, the reduce-scatter of layer 1 is followed by the all-gather of layer 2, with the attention module of layer 2 in between. If nothing ran in between, these two steps together would simply be an all-reduce, as in Figure 1. Megatron's sequence parallelism, introduced in the paper [Reducing Activation Recomputation in Large Transformer Models](https://arxiv.org/abs/2205.05198), uses exactly this. With plain tensor parallelism, the attention and feed-forward modules each end in an all-reduce. Sequence parallelism splits each of these all-reduces into its reduce-scatter and all-gather halves, so that the operations in between that work on each token separately, such as LayerNorm and dropout, only have to process and store 1/P of the tokens. So, both orders show up in practice, and they just put the brackets in different places. The all-gather plus reduce-scatter wraps the experts, and the reduce-scatter plus all-gather wraps whatever runs on the tokens of each GPU in between. ## 5. Same Result, Different Cost So far, "equivalent" has meant that every GPU ends up with the same numbers. However, the two versions move different amounts of data. With all-to-alls, a token only travels to the GPUs that hold one of its experts, and only those GPUs send something back. With an all-gather, every token travels to every GPU, and in the reduce-scatter, every GPU sends a partial result for every token, including all of the zeros. How big is the difference? That depends on how many different GPUs the experts of a token are spread over. For [GLM-5.3](https://huggingface.co/zai-org/GLM-5.3), which has 256 routed experts and picks 8 of them per token, we can compute the expected number if we assume that the router picks the 8 experts uniformly at random. (That's a simplification, since real routers prefer some experts over others, so I would treat the numbers below as a rough guide.) ```python from math import comb E, K = 256, 8 # GLM-5.3: 256 routed experts, 8 per token for P in (8, 16, 32, 64): # the chance that none of a GPU's E/P experts is among the K miss = comb(E - E // P, K) / comb(E, K) gpus = P * (1 - miss) # GPUs that need a copy of the token print(f"EP{P}: all-to-all {gpus:.1f}, all-gather {P}, {P / gpus:.1f}x") ``` This prints: ``` EP8: all-to-all 5.3, all-gather 8, 1.5x EP16: all-to-all 6.5, all-gather 16, 2.5x EP32: all-to-all 7.3, all-gather 32, 4.4x EP64: all-to-all 7.7, all-gather 64, 8.3x ``` With 8 GPUs, a token already needs to go to about 5 of them, so the all-gather only moves about 1.5 times as much data. In return, the all-gather and the reduce-scatter are plain NCCL collectives with a fixed size, so the GPUs don't have to exchange how many tokens each of them is going to send before the data can move. With 64 GPUs, on the other hand, a token still needs at most 8 of them, while the all-gather sends it to all 64, which is about 8 times as much data. This matches the [Megatron-LM MoE guide](https://github.com/NVIDIA/Megatron-LM/blob/54f18cd2195a0fc22c145268c9c1c193e9a3026e/megatron/core/transformer/moe/README.md), which recommends the `allgather` dispatcher for setups with little expert parallelism and a large number of experts per token, the `alltoall` dispatcher for regular expert parallelism, and [DeepEP](https://github.com/deepseek-ai/DeepEP) for expert parallelism across machines. ## 6. Summary To summarize: 1. An all-reduce can be split into a reduce-scatter followed by an all-gather, or into a reduce followed by a broadcast. A reduce followed by an all-gather doesn't work, since after the reduce, only one GPU holds any data. 2. In an MoE layer, dispatch can be replaced by an all-gather, after which each GPU only uses the tokens for its own experts, and combine can be replaced by a reduce-scatter, in which each GPU contributes zeros for the tokens it didn't process. The output is exactly the same. 3. The all-gather comes before the experts and the reduce-scatter after them. Across the boundary between two layers, the reduce-scatter and the next all-gather form the two halves of an all-reduce, which is what sequence parallelism builds on. 4. The all-gather version sends every token to every GPU instead of only to the ones that need it. For GLM-5.3, that's about 1.5 times as much data with 8 GPUs and about 8 times as much with 64. ## Sources - [Megatron-LM token dispatchers](https://github.com/NVIDIA/Megatron-LM/blob/54f18cd2195a0fc22c145268c9c1c193e9a3026e/megatron/core/transformer/moe/token_dispatcher.py) - [Megatron-LM MoE guide](https://github.com/NVIDIA/Megatron-LM/blob/54f18cd2195a0fc22c145268c9c1c193e9a3026e/megatron/core/transformer/moe/README.md) - [Reducing Activation Recomputation in Large Transformer Models](https://arxiv.org/abs/2205.05198) - [NCCL collective operations](https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/usage/collectives.html) - [GLM-5.3 model card](https://huggingface.co/zai-org/GLM-5.3) - [DeepEP](https://github.com/deepseek-ai/DeepEP)