Contents

Foundation Model Engineering

Manuscript updated (UTC) · Chapter source on GitHub · Cite this chapter (RIS)

On this page

5.3 Expert Parallelism

A router selects Expert 42 for a token on GPU 0, but Expert 42’s weights live on GPU 1. The arithmetic is local to the expert; moving the right token there and returning its result is the distributed problem. Expert Parallelism (EP) assigns different experts to different devices. Routing decisions therefore become a communication schedule.

For a hypothetical layer with 256 experts of 2 billion parameters each, FP16/BF16 weights occupy 256×2⋅109×2=1.024256 \times 2\cdot10^9 \times 2=1.024 TB in decimal units. Eight devices with 192 GB each provide 1.536 TB in aggregate. Raw expert weights fit that sum, but this does not establish a feasible training layout: add other layers, activations, gradients, optimizer state, temporary/communication buffers, checkpoint and evaluation overhead. Sharding and recomputation change these terms separately.

Tensor parallelism (TP) splits an expert’s matrices; EP places different experts. They can be combined, and both can skip unselected experts. For 256 experts on eight EP ranks, a simple assignment places Experts 0–31 on rank 0 and 32–63 on rank 1. Each rank owns only part of the weight set, but may receive an unequal share of tokens.


1. The Anatomy of Expert Parallelism

In a standard Transformer block within an MoE model, the self-attention mechanism is typically dense. Therefore, attention layers are processed using standard Data Parallelism or Tensor Parallelism. In a simple DP/TP layout, a rank holds a replica or a TP shard of the attention weights and processes its assigned tokens; sequence/context sharding adds further partitioning choices.

At the MoE feed-forward layer, a token may need an expert on another rank. The expert ownership map determines its destination.

For this top-1 dispatcher, each token takes three steps. Rows whose expert is on the same rank stay local.

  1. The Dispatch Phase (All-to-All): Each rank groups its token rows by the rank that owns the chosen expert and sends each group to its owner.
  2. The Compute Phase: Each rank receives the tokens routed to its local experts. Token counts can differ across ranks and across experts on the same rank.
  3. The Combine Phase (All-to-All): Each expert sends its outputs back to the source ranks. Each source restores its original token order before the next layer.

Read the timeline, not just the arrows. In a simplified window with 4 ms of communication and 3 ms of independent local computation, perfect scheduling can hide at most 3 ms of that communication. At least 1 ms remains exposed even before resource contention. Expert computation that needs the received tokens cannot start before those tokens arrive.


2. Engineering the Dispatcher

The core operation powering Expert Parallelism is the All-to-All collective communication primitive. Unlike an All-Reduce (where tensors are summed) or an All-Gather (where tensors are concatenated), an All-to-All is effectively a distributed matrix transpose. Every rank sends a different slice of data to every other rank.

For this variable-size implementation, every rank must know how many rows it will receive from each source before allocating the output and calling all_to_all_single. A count exchange supplies that information. Other dispatchers can use padded fixed-capacity layouts or different communication protocols; a separate count exchange is not a universal requirement of EP. API semantics below were checked against PyTorch 2.15 documentation as of 2026-11-18. [3]

Follow six tokens through two ranks

Suppose rank 0 owns Experts 0–1 and rank 1 owns Experts 2–3. Rank 0 starts with expert IDs [2, 0, 3, 2]; rank 1 starts with [1, 3]. The table counts token rows, not bytes:

Source rankRows for destination 0Rows for destination 1
013
111

Rank 0’s send counts are [1, 3], while its receive counts are the first column, [1, 1]. Rank 1 receives [3, 1]: four token rows. Expert IDs must use the same permutation and splits as the states. Local expert identity is the received global ID modulo two in this particular contiguous ownership layout.

If each state has 4,096 BF16 values, it occupies 8,192 bytes. Four rows cross between ranks (three from 0→1, one from 1→0), so dispatch carries 32 KiB of cross-rank state payload. Returning equal-width outputs adds another 32 KiB. IDs, counts, protocol overhead and any backward pass are separate. Top-k routing adds one assignment per chosen expert; local assignments still need expert work but do not cross this rank boundary.

CPU lab. Each token selects one expert. All ranks use the same state width and dtype. An expert ID is a torch.long on the same device as its state. Four experts are split into two contiguous pairs. The lab follows the forward dispatch and the return trip. A training system also needs routing weights for top-k, a capacity policy, gradients through communication, and failure recovery. [1]

Download the CPU lab (expert_dispatch.py)

Read the dispatch, return path, and three test cases
"""Trace top-1 expert dispatch and the return trip on two local CPU/Gloo ranks.

Foundation Model Engineering, section 5.3
English: https://sungeuns.github.io/foundation-model-engineering/chapter-5/expert-parallelism/#expert-dispatch-lab
Korean: https://sungeuns.github.io/foundation-model-engineering/ko/chapter-5/expert-parallelism/#expert-dispatch-lab

Run: torchrun --standalone --nproc-per-node=2 expert_dispatch.py
Tested on Linux with CPU PyTorch 2.15.0. All inputs are defined below.
"""
from datetime import timedelta
import os

import torch
import torch.distributed as dist


class ExpertParallelDispatcher:
    def __init__(self, ep_group, num_total_experts):
        self.ep_group = ep_group
        self.world_size = dist.get_world_size(ep_group)
        self.rank = dist.get_rank(ep_group)
        if num_total_experts <= 0 or num_total_experts % self.world_size:
            raise ValueError("Each rank must own the same positive number of experts.")
        self.local_experts = num_total_experts // self.world_size

    def dispatch(self, hidden_states, expert_indices):
        """Send one state row and one global expert ID per token to its owner."""
        destinations = expert_indices // self.local_experts
        permutation = torch.argsort(destinations, stable=True)

        # Each rank sends a row of the count matrix and receives a column.
        send_counts = torch.bincount(destinations, minlength=self.world_size)
        recv_counts = torch.empty_like(send_counts)
        dist.all_to_all_single(recv_counts, send_counts, group=self.ep_group)
        sends, receives = send_counts.tolist(), recv_counts.tolist()

        received = hidden_states.new_empty((sum(receives), hidden_states.size(1)))
        received_ids = expert_indices.new_empty(sum(receives))
        for output, payload in ((received, hidden_states), (received_ids, expert_indices)):
            dist.all_to_all_single(
                output, payload[permutation], output_split_sizes=receives,
                input_split_sizes=sends, group=self.ep_group,
            )
        return received, received_ids % self.local_experts, receives, permutation, sends

    def combine(self, outputs, receives, permutation, sends):
        """Reverse the splits, then scatter the sorted rows into their source slots."""
        returned = outputs.new_empty((sum(sends), outputs.size(1)))
        dist.all_to_all_single(
            returned, outputs, output_split_sizes=sends, input_split_sizes=receives,
            group=self.ep_group,
        )
        restored = torch.empty_like(returned)
        restored[permutation] = returned
        return restored


def run_case(dispatcher, assignments):
    rank = dispatcher.rank
    expert_ids = torch.tensor(assignments[rank], dtype=torch.long)
    # The first coordinate identifies the source token. A second coordinate
    # checks that we move a whole state row, including when the rank has zero rows.
    tokens = torch.arange(len(expert_ids), dtype=torch.float32) + 100 * rank + 1
    states = torch.stack((tokens, tokens + 0.5), dim=1)
    received, local_ids, receives, permutation, sends = dispatcher.dispatch(states, expert_ids)
    global_ids = rank * dispatcher.local_experts + local_ids

    # Construct the expected arrivals independently from the ownership map.
    expected_arrivals = [
        (100 * source + index + 1, expert)
        for source, experts in enumerate(assignments)
        for index, expert in enumerate(experts)
        if expert // dispatcher.local_experts == rank
    ]
    received_tokens = received[:, 0].int().tolist()
    assert list(zip(received_tokens, global_ids.tolist())) == expected_arrivals
    torch.testing.assert_close(received[:, 1], received[:, 0] + 0.5, rtol=0, atol=0)

    # A distinct offset for each expert makes routing errors visible.
    outputs = received + 1000 * global_ids[:, None]
    restored = dispatcher.combine(outputs, receives, permutation, sends)
    torch.testing.assert_close(restored, states + 1000 * expert_ids[:, None], rtol=0, atol=0)
    return (
        f"rank {rank}: send={sends} receive={receives}\n"
        f"  received tokens={received_tokens} experts={global_ids.tolist()}\n"
        f"  source tokens={tokens.int().tolist()} restored values={restored[:, 0].int().tolist()}"
    )


def main():
    if os.environ.get("WORLD_SIZE") != "2":
        raise SystemExit("Run: torchrun --standalone --nproc-per-node=2 expert_dispatch.py")
    torch.set_num_threads(1)
    dist.init_process_group("gloo", timeout=timedelta(seconds=30))
    try:
        dispatcher = ExpertParallelDispatcher(dist.group.WORLD, num_total_experts=4)
        cases = [
            ("six tokens", ([2, 0, 3, 2], [1, 3])),
            ("rank 0 has no input", ([], [0, 3])),
            ("rank 1 receives no tokens", ([0, 1], [0, 1])),
        ]
        for name, assignments in cases:
            summary = run_case(dispatcher, assignments)
            # Collect the two local reports solely to print them in rank order.
            reports = [None, None] if dispatcher.rank == 0 else None
            dist.gather_object(summary, reports, dst=0)
            if dispatcher.rank == 0:
                print(name, *reports, sep="\n", flush=True)
    finally:
        dist.destroy_process_group()


if __name__ == "__main__":
    main()

Save the file in any directory. With a Linux installation of PyTorch that includes Gloo, run this command in that directory. It starts two local CPU processes. The run below used PyTorch 2.15.0+cpu on 2026-11-25.

torchrun --standalone --nproc-per-node=2 expert_dispatch.py

In the six-token case, the first coordinate of each input row identifies its token. Expert ee adds 1000e1000e to both coordinates so you can trace its output. Rank 1 receives tokens [1, 3, 4, 102] for global experts [2, 3, 2, 3]. Follow token 3: it starts at rank 0, visits expert 3 on rank 1, and returns as 3003 to its original slot. Here are the first coordinates after the return trip:

Source rankOriginal token orderValues after dispatch, expert work and return
01, 2, 3, 42001, 2, 3003, 2004
1101, 1021101, 3102

The script also runs a case where rank 0 starts empty and one where rank 1 receives nothing. Both processes still enter the collectives in the same order. The checks compare both coordinates with the expected output for every source token.

Does sending a result back put it in the right slot?

Use the same three inputs as the CPU lab. Pick Six tokens, then Send back. Rank 0 already has all four of its results, yet the first row belongs to token 2. Select Restore order to see which value the next layer should read for token 1. The browser calculates the first coordinate of each row using the lab’s expert rule.

Stage

Read down each buffer in source order. Each row carries its token ID and the expert selected for it.

Rank 0Experts 0–1
Token IDExpertFirst coordinate
121
202
333
424
Rank 1Experts 2–3
Token IDExpertFirst coordinate
1011101
1023102

If rank 0 skips the final permutation, its first token gets 2 instead of 2001. The shape is still four rows by two coordinates. A shape check passes even though two tokens have each other’s results.


3. Advanced Optimizations: Overlapping and GroupGEMM

The CPU exercise checks row order. On a GPU, two other questions matter. How much of the transfer can run alongside independent computation? When an expert receives only a handful of tokens, how much time does its matrix product spend waiting for a kernel launch?

Shared-expert work and overlap

Shared experts are evaluated for all tokens, unlike the selected routed experts. They already appear in DeepSeek-V2; DeepSeek-V3 is not their origin. [4] V3 reports a particular computation/communication schedule and shared-expert layout, not a requirement that every EP system replicate a shared expert on every GPU. [2]

Locally available shared-expert work can overlap routed-token transport when its dependencies permit. Replication or sharding depends on the implementation. Measure exposed communication and contention for streaming multiprocessors (SMs) and memory bandwidth rather than adding isolated compute and transfer speeds.

Grouped matrix multiplication

Experts may receive very different numbers of tokens. Launching a separate small matrix multiplication for every nonempty expert can spend much of its time on launch and scheduling overhead. A grouped GEMM kernel schedules work from several matrix products together. It does not turn them into one mathematical matrix product or guarantee full GPU occupancy. Tile shapes, problem sizes, ordering, and scheduling overhead affect the result. The CUTLASS grouped scheduler documentation describes these mechanics; its current interface was checked as of 2026-11-18. [5]

Before optimizing, compare per-expert token counts, useful work, and dispatch/compute/combine durations under the same routing assignments. An average step time can hide a rank that determines the whole step’s completion time.


Summary and Next Steps

EP trades replicated expert storage for token transport and uneven work. Correctness does not require balanced routing, but usable throughput and bounded memory require a policy for skew. Sending 90% of tokens to one rank can make it a straggler or exceed its capacity; an OOM is a possible outcome, not a consequence determined by that percentage alone.

Before a distributed run, record the expert ownership map, top-k and capacity rules, precision, backend/topology, tensor shapes and collective order. Observe per-rank/per-expert token counts, dropped assignments, allocation high-water marks, nonfinite outputs, collective wait and useful throughput. Preserve reconstructable batch and routing identifiers. Abort on collective mismatch, nonfinite outputs or agreed memory/timeout limits; use a known-good dispatcher configuration and a tested checkpoint restore path. The example above implements none of those run-control decisions.

Next, 5.4 Collapsing & Load Balancing examines the trade-offs among capacity factors, dropping, and load-balancing objectives. They can bound a failure mode; they do not guarantee that a cluster will never fail.


Quizzes

Quiz 1: How do EP and TP interact with sparse activation? EP places different experts; TP shards a selected expert. Both can skip unselected experts. Choose their combination by measuring communication and available parallel work; neither guarantees linear scaling.

Quiz 2: Why does this dispatcher exchange counts, and must every EP implementation do so? This variable-size API needs receive split sizes and an allocated output tensor before payload transfer. Exchanging counts supplies that information; it is not proof that every backend uses RDMA or that a separate exchange is inevitable. A padded fixed-capacity protocol can make sizes known in advance, at the cost of wasted capacity.

Quiz 3: Does shared-expert work always hide All-to-All latency? No. Independent local computation can overlap transport, but dependencies, duration and resource contention determine how much communication remains exposed.

Quiz 4: In the two-rank example, why is rank 0’s receive-count vector [1, 1], not [1, 3]? The send vector is a row indexed by destination; the receive vector is the corresponding column indexed by source. Rank 0 receives one row from each source. Reusing its send counts would describe the wrong payload boundaries.

Quiz 5: Does a correct forward dispatch establish a working MoE trainer? No. The example restores source order for top-1. Training also needs gradients across communication, a capacity policy, optimizer and checkpoint state, and collective failure handling. A top-k router must additionally combine multiple weighted outputs per token. A small transport test cannot establish those properties or GPU throughput.


References

  1. Lepikhin, D., et al. (2020). GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding. arXiv:2006.16668.
  2. DeepSeek-AI. (2024). DeepSeek-V3 Technical Report. arXiv:2412.19437.
  3. PyTorch. Distributed communication package: all_to_all_single, version 2.15. Documentation.
  4. DeepSeek-AI. (2024). DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model. arXiv:2405.04434.
  5. NVIDIA CUTLASS. Grouped Kernel Schedulers. Documentation.