Expert parallelism: move the tokens, not the experts
Expert parallelism gives each GPU a slice of the MoE experts and sends every token to the GPU that owns its expert with two all-to-alls per layer. A walk through the Qwen3-Omni MoE implementation in LMMs Engine.
The memory problem MoE creates
A Mixture-of-Experts (MoE) layer replaces the single feed-forward block of a transformer with many smaller ones, the experts, plus a router: a linear layer that scores every expert for every token. Each token goes through only its top-K experts. The walkthrough uses the Qwen3-Omni MoE text decoder: 60 experts per MoE layer, top-4 routing. Each expert is a SwiGLU block with three matrices: gate_proj and up_proj of shape [intermediate, hidden] and down_proj of shape [hidden, intermediate].
The compute per token is small, because 4 of 60 experts run. The memory is not small, because all 60 experts must be somewhere. With the walkthrough’s example sizes (hidden 7168, intermediate 18944), one layer of experts is billion values, about 97 GB in fp32. In plain data parallelism every GPU holds that full copy.
Expert parallelism (EP) splits the experts over a group of GPUs. With EP = 4, GPU 0 owns experts 0–14, GPU 1 owns 15–29, and so on. A token that needs expert 20 travels to GPU 1. Expert memory per GPU becomes of the total.
One MoE layer on one GPU
EP is a change to the data path of a normal MoE forward. So first, the single-GPU path that the Qwen3-Omni code runs:
- Flatten the hidden states to
[T, hidden]. With rmpad (padding removed) they already are. - Router:
softmax(gate(x))over 60 experts, keep the top 4, renormalise the 4 weights to sum to 1. - Flatten the choices to
T·Kslots and sort them by expert id with a stable argsort. Stable means equal ids keep their token order, so the layout is deterministic. histccounts the tokens per expert. These counts are the split sizes.- Expand each hidden state K times, gather the rows in sorted order, split by the counts, and call
experts(*splits). Each expert does one batched matmul on its contiguous slice. - Multiply each output row by its routing weight (permuted with the same index) and
scatter_addthe K copies back into their token.
animation
The MoE forward on 4 tokens
Press Next to advance one line of code. Hover a cell to follow one token copy through every step.
Everything that EP adds happens inside step 5, between the gather and the expert call, and again right after the expert call. The experts still receive one slice per expert. Only now the slices hold rows that came from other GPUs.
Split the experts, move the tokens
Stack, then shard. The original model keeps the experts in an nn.ModuleList. The EP code first replaces it with one module that holds three 3D parameters: gate_proj and up_proj of shape [60, 18944, 7168] and down_proj of shape [60, 7168, 18944]. One tensor per projection can be sharded in one call. The sharding uses DTensor, PyTorch’s distributed tensor: a tensor that looks whole in code but whose pieces live on several devices. distribute_tensor(param, ep_mesh, [Shard(0)]) splits dimension 0, the expert dimension, over the EP ranks. With EP = 4, GPU 1 physically stores [15, 18944, 7168], and its local index 0 is global expert 15.
In the forward, the expert module calls .to_local() on each DTensor. This unwraps the local shard with no communication, so gate_proj[idx] is a plain array access. Indexing the DTensor itself could trigger an all-gather of the full tensor.
Hooks do the moving. A ParallelStyle attaches three functions to the expert module: _partition_fn shards the parameters, _input_fn dispatches tokens before the experts run, and _output_fn combines them after. The hooks exist only when ep_degree > 1. The MoE forward checks isinstance(self.experts.gate_proj, DTensor) to pick the path. With EP it passes the sorted rows and the counts to the experts and lets the hook do the rest. Without EP it splits the rows locally.
Dispatch has two collectives:
- The counts per expert are reshaped to
[ep_world_size, experts_per_rank]and summed per owner. This gives how many rows this GPU sends to each GPU. Anall_gather_objectshares these lists, so each GPU also learns how many rows it receives from each peer. torch.distributed.all_to_allwith those uneven split sizes then sends the rows. Each GPU gives a different chunk to each other GPU and gets a different chunk from each.
Combine is the same all_to_all with the two split lists swapped, so every row returns to the GPU that owns its token. Then step 6 above (weights and scatter_add) runs locally as before.
animation
Dispatch and combine on 4 GPUs
Press Play, or Step through the seven phases. Reseed draws a new routing.
Rows arrive in sender order
all_to_all keeps sender order. GPU 0 receives everything from GPU 0 first, then from GPU 1, and so on. Inside each chunk the rows are sorted by expert, but across chunks expert 0’s rows are scattered. The experts need the opposite layout: all of expert 0’s rows, then all of expert 1’s.
The fix is a permutation computed from the count matrix num_tokens_per_expert_group, where entry [s, j] is the number of rows from sender s for local expert j. The walkthrough’s vectorised recipe:
# offsets of each (sender, expert) block in the received buffer, sender-major
offsets = cumsum(counts.flatten()) - counts.flatten()
counts_t, offsets_t = counts.T.flatten(), offsets.view(S, J).T.flatten() # expert-major
starts = cumsum(counts_t) - counts_t
perm = repeat_interleave(offsets_t, counts_t) \
+ (arange(total) - repeat_interleave(starts, counts_t))
routed = routed[perm] # now grouped by expert; split by counts.sum(0)
playground
From sender order to expert order
Click cells in the count matrix. Watch the received buffer, the permutation lines and the indices change.
Click a cell to add a row (0–3, then back to 0). This is num_tokens_per_expert_group as GPU 0 sees it.
After the experts run, _output_fn writes output[perm] = output.clone(), which puts each result back at the position it arrived in. Only then does the combine all-to-all run, so the reverse split sizes match the data. Without the permute, each expert would need a scatter step during its compute.
The busiest GPU sets the pace
Each GPU computes the rows it received, and the combine all-to-all cannot finish until the slowest GPU is done. So the step time follows the most loaded GPU, not the average one. The walkthrough’s example: if one expert gets 1000 tokens and another gets 50, the GPU with the second expert is mostly idle.
The router decides the load. If it favours a few experts, their owners get more rows. The walkthrough’s remedy is an auxiliary load-balancing loss: the squared gap between each expert’s share of tokens and , averaged over experts and added to the main loss with weight 0.01.
playground
Skew the router, watch the load
Move the skew slider. Switch EP between 2 and 4. Hover a bar for its count.
The same piece also counts traffic. A dispatched row is one hidden vector: 7168 values, 14 KB in bf16. The code expands each token K = 4 times before the dispatch, so the all-to-all moves T·K rows, and with balanced routing a fraction of them leaves the GPU. The combine moves the same amount back.
EP inside FSDP2: a 2D mesh
Qwen3-Omni is multimodal. The vision encoder, the audio encoder and the attention blocks of the text decoder have no experts. They use only FSDP2, PyTorch’s fully sharded data parallelism built on DTensor, which shards each parameter over the data-parallel ranks, all-gathers it before use and reduce-scatters its gradient. Only the MoE blocks of the text decoder get EP.
To combine the two, the code builds a 2D device mesh of shape (world / EP, EP) with the dimension names dp_shard_mod_ep and dp_shard_in_ep; the second also has the alias ep. For 8 GPUs and EP = 2 the mesh is [[0, 1], [2, 3], [4, 5], [6, 7]]. Each row is one EP group: GPU 0 holds experts 0–29 and GPU 1 holds 30–59, and GPUs 2, 4 and 6 hold the same experts as GPU 0.
The expert modules get their own FSDP2 settings: mesh dp_shard_mod_ep and a shard_placement_fn that returns Shard(1). So an expert weight is Shard(0) over the EP ranks (which experts) and Shard(1) over the DP ranks (which rows of each expert). All other modules use the plain dp mesh with the default Shard(0). Both use bf16 parameters, fp32 gradient reduction and reshard_after_forward=True.
calculator
Who holds which slice
Pick an EP degree and switch FSDP2. Click a GPU in the mesh to see its slice, its peers and its memory.
Gradients take the forward path in reverse. Autograd runs the combine all-to-all backward (rows go to the expert owners), the expert backward runs locally, and the dispatch all-to-all backward returns the input gradients to the token owners. The expert weight gradients are DTensors with the same placement as the weights, and FSDP2 reduce-scatters them over the DP column.
The setup order matters: (1) stack the experts, (2) save the full state dict, (3) apply EP, (4) apply FSDP2, (5) load the full state dict into the sharded model with fsdp2_load_full_state_dict.
Memory first, speed second
The walkthrough is direct about this: EP is a memory optimisation. It does not run a token through its experts faster. Each token still visits 4 experts. Now part of that visit crosses the network twice.
For traffic, the walkthrough estimates about 470 MB of all-to-all per MoE layer for 32,768 tokens per GPU, and about 15 GB per forward pass over 32 MoE layers. That estimate counts each token once. The code sends K copies, so read it as a lower bound. To keep the cost down, the walkthrough lists three measures: it overlaps the all-to-all with expert compute, it counts with histc and sorts with a stable argsort (no communication), and it removes padding (rmpad) before the communication, which it estimates saves 30–50% of the volume.
The gain is in what fits. The walkthrough’s illustrative comparison for one GPU versus EP = 4 (it gives no measurement setup):
| Metric | Single GPU | EP = 4 |
|---|---|---|
| Per-token latency | 50 ms | 55 ms (+10%) |
| Max batch size | 2 | 8 |
| Tokens per second | 40 | 145 (3.6×) |
So EP makes sense when the model does not fit, when larger batches help, when the GPUs have a fast interconnect (NVLink, InfiniBand) and when throughput matters more than latency. It makes little sense when the model already fits with the batch you want, on PCIe-only links, or at very small batch sizes where the communication dominates.
Training versus generation
How much work each expert gets depends on how many tokens one forward pass holds. In training with teacher forcing, every position of every sequence routes at once: 4 × 2048 = 8,192 tokens, so on average tokens per expert. Each expert runs a large matmul, and the all-to-all cost is spread over many rows.
At decode time a forward pass holds one new token. It reaches 4 of 60 experts (6.7%), and each active expert multiplies a single row. With EP = 4, each GPU then exchanges about one row per layer, and the communication overhead is large next to the compute. The walkthrough’s batched-inference example (4 prefills and 4 decodes, 60 tokens in all) brings the mean back to 4 tokens per expert. That is why continuous batching and speculative decoding matter for MoE serving.
playground
Tokens per expert across workloads
Drag along the chart, use the arrow keys, or pick a preset.