huggingface/transformers · #49429
Expert-parallel implementations for `ep_dispatch_experts`: all-reduce at inference, all-to-all in training
docs/source/en/expert_parallelism.md38 + / 5 −
@@ -48,7 +48,40 @@ The expert forward rule in `ep_plan` selects how tokens reach the experts: | rule | mechanism | layout | | :--- | :--- | :--- | | `"moe_tp_experts"` with `"ep_router"` on the router | masking and all-reduce: every rank runs its local experts on the whole batch, the router masks the others, and an all-reduce combines the outputs | `ep_size=tp_size` |-| `"ep_dispatch_experts"` | [token dispatch](#token-dispatch): each rank keeps its own tokens and only exchanges the routed (token, expert) pairs with two all-to-all collectives | `ep_size` a multiple of `tp_size` that divides `fsdp_size * tp_size` |+| `"ep_dispatch_experts"` | whole experts per rank, reached through the implementation `ep_implementation` names, see [Choosing an implementation](#choosing-an-implementation) | `ep_size` a multiple of `tp_size` that divides `fsdp_size * tp_size` |++### Choosing an implementation++`"ep_dispatch_experts"` shards the experts once and picks how tokens reach them from the implementations registered in `EPImplementationInterface`, selected with `ep_implementation` in [`DistributedConfig`]:++| `ep_implementation` | advantages | disadvantages |+| :--- | :--- | :--- |+| `"all_to_all"`, see [token dispatch](#token-dispatch) | Works for any layout, including `ep_size > tp_size`. Only the routed tokens move. | Two all-to-all collectives and one host sync per layer, so it does not capture in a CUDA graph. |+| `"all_reduce"` | No tokens move and no host sync, so decode captures in a CUDA graph. | Requires `ep_size=tp_size`. Every rank runs its experts over the whole batch, so its cost grows with the batch. |+| `"auto"`, the default | Runs `"all_reduce"` at inference when the ranks of an expert group share one batch, and `"all_to_all"` otherwise. | Not always the fastest choice: a workload can benefit from a custom implementation, see [Adding an implementation](#adding-an-implementation). |++> [!NOTE]+> `ep_implementation` only chooses within the parallel sizes set in [`DistributedConfig`]. When the ranks of an expert group hold different batches, for example `tp_size=1` with `fsdp_size=ep_size`, `"all_to_all"` is the only implementation that applies.++### Adding an implementation++An implementation subclasses `EPImplementation` and registers under the name `ep_implementation` selects. It is built once per experts module, so it can keep state such as communication buffers. Calling it with the batch this rank holds, with global expert ids, returns the weighted expert output for each of its tokens. It runs this rank's experts with `experts_forward`, on the rows, local expert ids and weights it brought them.++```py+from transformers.distributed.expert_parallel import EPImplementation, EPImplementationInterface++class MyEP(EPImplementation):+ def __call__(self, hidden_states, top_k_index, top_k_weights):+ tokens, expert_ids, weights = ... # bring this rank's experts the rows routed to them+ expert_output = self.experts_forward(tokens, expert_ids, weights)+ return ... # the weighted expert output for each token of the batch this rank holds++EPImplementationInterface.register("my_ep", MyEP)+distributed_config = DistributedConfig(tp_size=1, fsdp_size=8, ep_size=8, ep_implementation="my_ep")+```++> [!NOTE]+> Gradients must reach every rank that holds a token, routing weights included, so wrap a collective that autograd does not differentiate in a `torch.autograd.Function`. > [!TIP] > `enable_expert_parallel=True` without `ep_size` is deprecated and emits a `FutureWarning`. It shards only the experts, like `ep_size=tp_size, tp_plan={}`.@@ -74,7 +107,7 @@ distributed_config = DistributedConfig( Providing a plan does not infer parallel sizes: set `tp_size` and `ep_size` explicitly. -Most MoE models default to `"ep_dispatch_experts"`. To use masking and all-reduce instead, set `ep_size=tp_size` and override both the router and the expert forward rules (the router module name depends on the model, e.g. `mlp.router` on gpt-oss):+Most MoE models default to `"ep_dispatch_experts"`, which already uses `"all_reduce"` at inference when `ep_size=tp_size`. To use masking and all-reduce in training too, set `ep_size=tp_size` and override both the router and the expert forward rules (the router module name depends on the model, e.g. `mlp.router` on gpt-oss): ```py distributed_config = DistributedConfig(@@ -91,7 +124,7 @@ Conversely, override the expert forward rule of a model whose plan uses masking ## Token dispatch -With token dispatch, each rank trains on its own part of the batch. At every MoE layer, a rank routes its tokens, sends each (token, expert) pair to the rank that owns the expert with an all-to-all, runs its local experts on what it receives, gets the results back with a second all-to-all and combines them with the routing weights. Only the routed activations and expert outputs travel, and no rank computes experts for tokens it does not own.+Token dispatch is the `"all_to_all"` implementation: each rank trains on its own part of the batch. At every MoE layer, a rank routes its tokens, sends each (token, expert) pair to the rank that owns the expert with an all-to-all, runs its local experts on what it receives, gets the results back with a second all-to-all and combines them with the routing weights. Only the routed activations and expert outputs travel, and no rank computes experts for tokens it does not own. ```py from transformers import AutoModelForCausalLM@@ -155,10 +188,10 @@ These configurations each use eight GPUs: | Configuration | Result | | :--- | :--- |-| `DistributedConfig(tp_size=4, fsdp_size=2, ep_size=4)` | Dispatch with TP groups of four, each slicing its batch in four (default plan); unless you specify a ep_plan to use the legacy masked EP |+| `DistributedConfig(tp_size=4, fsdp_size=2, ep_size=4)` | Each TP group of four shares one batch. Training dispatches tokens, each rank taking a quarter of the batch; inference uses `"all_reduce"`. A masked `ep_plan` uses masking and all-reduce throughout. | | `DistributedConfig(tp_size=1, fsdp_size=8, ep_size=4)` | Dispatch with an independent batch on each rank, no slicing, and experts FSDP-sharded across pairs of ranks. | | `DistributedConfig(tp_size=2, fsdp_size=4, ep_size=4)` | Dispatch with a TP pair per batch, each pair slicing its batch in two; two batches per expert group. |-| `DistributedConfig(tp_size=8, ep_size=8)` | Dispatch with every rank sharing one batch, sliced in eight, or masking and all-reduce for a masked plan. |+| `DistributedConfig(tp_size=8, ep_size=8)` | Every rank shares one batch. Training dispatches tokens, each rank taking an eighth of the batch; inference uses `"all_reduce"`. A masked `ep_plan` uses masking and all-reduce throughout. | > [!WARNING] > The [`Trainer`] does not account for token dispatch yet: batch and token counting assume the all-reduce layout, where the ranks of a TP group share a batch and `fsdp_size` data-parallel shards exist. Trainer support for dispatch comes in a follow-up.src/transformers/distributed/configuration_utils.py13 + / 3 −
@@ -63,13 +63,22 @@ class DistributedConfig: Number of devices for pipeline parallelism. If `None` and another parallel mode is set, defaults to 1. ep_size (`int`, *optional*): Number of devices owning distinct expert shards. Defaults to 1. Set it explicitly to enable EP. Must be- a multiple of `tp_size` and divide `fsdp_size * tp_size`. All-reduce expert plans require- `ep_size=tp_size`; token dispatch (`"ep_dispatch_experts"`) also allows `ep_size > tp_size`.+ a multiple of `tp_size` and divide `fsdp_size * tp_size`. `ep_size > tp_size` needs an+ `"ep_dispatch_experts"` rule with an `ep_implementation` that exchanges tokens, such as `"all_to_all"`. ep_plan (`dict[str, str]`, *optional*): Expert parallel sharding plan. Leave as `None` to use the model's predefined `base_model_ep_plan`. Pass a dictionary to override individual rules of that plan; unspecified rules are kept. Applied only when `ep_size > 1`, and its rules take precedence over `tp_plan` rules for the same modules. An- `"ep_dispatch_experts"` rule selects all-to-all token dispatch instead of router masking and all-reduce.+ `"ep_dispatch_experts"` rule lets `ep_implementation` pick how tokens reach the experts.+ ep_implementation (`str`, *optional*, defaults to `"auto"`):+ How an `"ep_dispatch_experts"` rule brings the experts their tokens. It names an `EPImplementation`+ registered in `EPImplementationInterface`:++ - `"all_to_all"` exchanges the routed tokens with all-to-all collectives.+ - `"all_reduce"` runs each rank's experts on the batch the EP group shares, and sums the outputs. It+ requires `ep_size == tp_size`.+ - `"auto"` runs `"all_reduce"` at inference when the EP group shares one batch, and `"all_to_all"`+ otherwise. """ tp_size: int | None = None@@ -84,6 +93,7 @@ class DistributedConfig: pp_size: int | None = None ep_size: int | None = None ep_plan: dict[str, str] | None = None+ ep_implementation: str = "auto" @property def efsdp_size(self) -> int:src/transformers/distributed/expert_parallel.py206 + / 121 −
@@ -16,10 +16,10 @@ from __future__ import annotations import contextlib-from collections.abc import Callable-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, NamedTuple from ..utils import logging+from ..utils.generic import GeneralInterface from ..utils.import_utils import is_torch_available, is_torch_distributed_available from .parallel_utils import ALL_PARALLEL_STYLES, _use_local_dtensor_params @@ -35,10 +35,11 @@ import torch if is_torch_distributed_available():+ from torch.distributed import all_to_all_single, get_process_group_ranks from torch.distributed._functional_collectives import all_to_all_single_autograd from torch.distributed.tensor import DTensor, Replicate, Shard, distribute_tensor - from .parallel_utils import _AllReduceBackward, _WaitTensor+ from .parallel_utils import _AllReduceBackward, _AllReduceForward, _WaitTensor class ExpertParallelLayer:@@ -171,9 +172,8 @@ def transform_output_post_forward(self, module, output, mesh): router_logits, router_scores, router_indices, *extra_outputs = output # Each rank's score gradient covers only its local experts' slots; sum the per-rank partials # before the mask (each slot has exactly one owning rank, so the sum is exact).- if torch.is_grad_enabled() and router_scores.requires_grad:- process_group = mesh.get_group() if mesh.ndim == 1 else mesh.get_group("tp")- router_scores = _AllReduceBackward.apply(router_scores, process_group)+ process_group = mesh.get_group() if mesh.ndim == 1 else mesh.get_group("tp")+ router_scores = _AllReduceBackward.apply(router_scores, process_group) non_local_mask = (router_indices // num_local_experts) != ep_rank router_scores = router_scores.masked_fill(non_local_mask, 0.0) router_indices = router_indices.masked_fill(non_local_mask, -1)@@ -197,15 +197,58 @@ def transform_output_post_forward(self, module, output, mesh): return output -class EpDispatchExpertsParallel(ExpertParallelLayer):+class EPImplementation:+ """+ How the experts of an `ep_dispatch_experts` module get their tokens. One instance is built per experts module when+ the plan is applied, so an implementation can keep state across forwards (communication buffers, a layout it+ reuses).++ Calling it with `(hidden_states, top_k_index, top_k_weights)`, the batch this rank holds (global expert ids),+ returns the weighted expert output for each of its tokens. It runs this rank's experts with `experts_forward`, on+ whatever rows, local expert ids and weights it brought them.++ Gradients must reach every rank that holds a token, routing weights included, so a collective that autograd does not+ differentiate has to be wrapped in a `torch.autograd.Function`.+ """++ # Set by implementations that only run when every rank of the EP group holds the same batch, e.g. `AllReduceEP`.+ needs_shared_batch = False++ def __init__(self, experts: nn.Module, ep_mesh: DeviceMesh, tp_mesh: DeviceMesh):+ self.experts_forward = experts.forward # the experts' own forward, on local expert ids+ self.num_local_experts = experts.num_experts+ self.ep_mesh = ep_mesh+ self.tp_mesh = tp_mesh+ # Every rank of the EP group holds the same batch when the EP group is the TP group.+ tp_ranks, ep_ranks = (get_process_group_ranks(mesh.get_group()) for mesh in (tp_mesh, ep_mesh))+ self.shares_batch = tp_ranks == ep_ranks+ if self.needs_shared_batch and not self.shares_batch:+ raise ValueError(+ f"{type(self).__name__} needs every rank of the expert group to hold the same batch (`ep_size == tp_size`)."+ )++ def __call__(self, hidden_states, top_k_index, top_k_weights):+ raise NotImplementedError+++class _AllToAllState(NamedTuple):+ top_k_weights: torch.Tensor+ order: torch.Tensor+ send_sizes: list[int]+ recv_sizes: list[int]+ num_tokens: int+++class AllToAllEP(EPImplementation): """- Dispatch disjoint TP token slices to the experts' owners, then replicate the combined output on TP.+ The ranks of a TP group keep disjoint slices of the batch they share, send each (token, expert) pair to the+ expert's rank with an all-to-all and get the results back with a second one, then gather the slices back over TP.+ The split sizes are read back to the host every layer, so it does not capture in a CUDA graph. - Example:- Let's say we have 8 experts [E0, E7] with DistributedConfig(tp_size=2, fsdp_size=4, ep_size=4). That imply:- - Since fsdp_size=4, we have 4 batches B denoted [B0, B3]- - Because we have tp_size=2, that means *both ranks share the same batch*- - efsdp = (fsdp_size * tp_size) / ep_size = 4 * 2 / 4 = 2+ Example: 8 experts [E0, E7] with DistributedConfig(tp_size=2, fsdp_size=4, ep_size=4):+ - fsdp_size=4: 4 batches [B0, B3]+ - tp_size=2: the 2 ranks of a TP group share one batch+ - efsdp_size = fsdp_size * tp_size / ep_size = 4 * 2 / 4 = 2 copies of each expert GPU 0 1 2 3 4 5 6 7 | | | | | | | |@@ -220,25 +263,35 @@ class EpDispatchExpertsParallel(ExpertParallelLayer): ep_size 0 1 2 3 0 1 2 3 efsdp_size [___________ 0 ___________] [___________ 1 ___________] - Assume token 1 in B0 chose E4, which lives on another rank, so it must travel by all-to-all. B0 sits on 2 ranks (cf diagram), so if both sent it, E4 would compute it twice.- We need to make sure that token 1 is in rank 0 range, so rank 0 sends it and rank 1 does not have it in its slice.+ The TP slicing keeps a token from being computed twice. Say token 1 of B0 picks E4, which lives on rank 2. B0 sits+ on ranks 0 and 1, so if both sent it, E4 would compute it twice: token 1 falls in rank 0's slice, so rank 0 sends it+ and rank 1 does not. """ - def should_use_local_tensors(self, module):- return True-- def _dispatch_tokens(- self,- hidden_states: torch.Tensor,- top_k_index: torch.Tensor,- num_local_experts: int,- ep_group,- ep_size: int,- ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, list[int], list[int]]:- """Send each selected (token, expert) pair to the rank that owns the expert.-- Also returns the sort order and the per-rank split sizes that `_combine_tokens` needs to reverse the exchange.- """+ def __call__(self, hidden_states, top_k_index, top_k_weights):+ tokens, expert_ids, weights, state = self._dispatch_tokens(hidden_states, top_k_index, top_k_weights)+ if tokens.shape[0] == 0:+ # Keep the empty rows connected to backward, so the reverse exchange and FSDP's reduction still run.+ expert_output = self.experts_forward(+ tokens.sum(dim=0, keepdim=True), expert_ids.new_zeros((1, 1)), weights.new_ones((1, 1))+ )[:0]+ else:+ expert_output = self.experts_forward(tokens, expert_ids, weights)+ return self._combine_tokens(expert_output, state)++ def _dispatch_tokens(self, hidden_states, top_k_index, top_k_weights):+ """Each (token, expert) pair to the expert's rank: the rows this rank's experts run on, their local expert ids+ and weights, and what `_combine_tokens` needs to bring the results back."""+ num_tokens = hidden_states.size(0)+ if self.tp_mesh.size() > 1:+ # Replicate -> Shard(0) is a local chunk (no communication); its backward all-gathers the row gradients.+ hidden_states, top_k_index, top_k_weights = (+ DTensor.from_local(t, self.tp_mesh, [Replicate()], run_check=False)+ .redistribute(self.tp_mesh, [Shard(0)])+ .to_local()+ for t in (hidden_states, top_k_index, top_k_weights)+ )+ ep_group, ep_size = self.ep_mesh.get_group(), self.ep_mesh.size() num_top_k = top_k_index.size(-1) # Sorting the selected pairs by expert groups them by owner rank, since each rank owns a contiguous range of@@ -247,109 +300,134 @@ def _dispatch_tokens( expert_ids = top_k_index.reshape(-1) order = torch.argsort(expert_ids) send_tokens = hidden_states[order // num_top_k]- send_counts = torch.zeros(num_local_experts * ep_size, dtype=torch.long, device=hidden_states.device)- send_counts = send_counts.scatter_add_(0, expert_ids, torch.ones_like(expert_ids)).view(- ep_size, num_local_experts- )+ send_counts = torch.zeros(self.num_local_experts * ep_size, dtype=torch.long, device=hidden_states.device)+ send_counts = send_counts.scatter_add_(0, expert_ids, torch.ones_like(expert_ids))+ send_counts = send_counts.view(ep_size, self.num_local_experts) recv_counts = torch.empty_like(send_counts)- torch.distributed.all_to_all_single(recv_counts, send_counts, group=ep_group)+ all_to_all_single(recv_counts, send_counts, group=ep_group) send_sizes, recv_sizes = torch.stack([send_counts.sum(dim=1), recv_counts.sum(dim=1)]).tolist() recv_tokens = all_to_all_single_autograd(send_tokens, recv_sizes, send_sizes, ep_group)- recv_expert_ids = torch.arange(num_local_experts, device=hidden_states.device).repeat(ep_size)+ # hand the experts the received rows, not the all-to-all's pending result (whose pointer is null until+ # waited on): https://github.com/huggingface/transformers/pull/49421+ recv_tokens = _WaitTensor.apply(recv_tokens)+ recv_expert_ids = torch.arange(self.num_local_experts, device=hidden_states.device).repeat(ep_size) recv_expert_ids = recv_expert_ids.repeat_interleave(recv_counts.reshape(-1), output_size=sum(recv_sizes))- return recv_tokens, recv_expert_ids, order, send_sizes, recv_sizes-- def _run_local_experts(- self,- experts_forward: Callable,- tokens: torch.Tensor,- expert_ids: torch.Tensor,- ) -> torch.Tensor:- """Run local experts with top-1 routing and unit weights; apply routing weights after combine."""- num_tokens = tokens.shape[0]- if num_tokens == 0:- # Keep the empty tokens connected to backward so the reverse all-to-all and FSDP reduction still run.- dummy = tokens.sum(dim=0, keepdim=True)- dummy_ids = torch.zeros((1, 1), dtype=expert_ids.dtype, device=tokens.device)- dummy_weights = torch.ones((1, 1), dtype=tokens.dtype, device=tokens.device)- return experts_forward(dummy, dummy_ids, dummy_weights)[:0]-- expert_ids = expert_ids.unsqueeze(-1)- weights = torch.ones_like(expert_ids, dtype=tokens.dtype)- return experts_forward(tokens, expert_ids, weights)-- def _combine_tokens(- self,- expert_output: torch.Tensor,- top_k_weights: torch.Tensor,- order: torch.Tensor,- send_sizes: list[int],- recv_sizes: list[int],- ep_group,- ) -> torch.Tensor:- """Return expert outputs to the token owners and combine them with routing weights."""- num_tokens, num_top_k = top_k_weights.shape+ recv_expert_ids = recv_expert_ids.unsqueeze(-1)+ # Experts run top-1 with unit weights; the routing weights are applied in `_combine_tokens`, on the sender.+ recv_weights = torch.ones_like(recv_expert_ids, dtype=recv_tokens.dtype)+ state = _AllToAllState(top_k_weights, order, send_sizes, recv_sizes, num_tokens)+ return recv_tokens, recv_expert_ids, recv_weights, state++ def _combine_tokens(self, expert_output, state):+ """The expert outputs back to the ranks that sent the tokens, weighted and summed per token.""" hidden_dim = expert_output.size(-1)- recv_out = all_to_all_single_autograd(expert_output, send_sizes, recv_sizes, ep_group)+ recv_out = all_to_all_single_autograd(+ expert_output, state.send_sizes, state.recv_sizes, self.ep_mesh.get_group()+ ) # Restore the original (token, top-k slot) order, then apply routing weights. token_outputs = torch.empty_like(recv_out)- token_outputs[order] = recv_out- token_outputs = token_outputs.view(num_tokens, num_top_k, hidden_dim)- return (token_outputs * top_k_weights.unsqueeze(-1)).sum(dim=1)-- def transform_inputs_pre_forward(self, module, args, kwargs, mesh, *, tp_mesh=None):- hidden_states, top_k_index, top_k_weights = args- if isinstance(hidden_states, DTensor):- hidden_states = hidden_states.to_local()- if isinstance(top_k_weights, DTensor):- top_k_weights = top_k_weights.to_local()- if tp_mesh is None or tp_mesh.size() == 1:- return (hidden_states, top_k_index, top_k_weights), kwargs- # TP ranks share the same batch, so keep only this rank's rows and each token is dispatched once.- # Replicate -> Shard(0) is a local chunk (no communication); its backward all-gathers the row gradients.- hidden_states = DTensor.from_local(hidden_states, tp_mesh, [Replicate()], run_check=False)- top_k_index = DTensor.from_local(top_k_index, tp_mesh, [Replicate()], run_check=False)- top_k_weights = DTensor.from_local(top_k_weights, tp_mesh, [Replicate()], run_check=False)-- hidden_states = hidden_states.redistribute(tp_mesh, [Shard(0)]).to_local()- top_k_index = top_k_index.redistribute(tp_mesh, [Shard(0)]).to_local()- top_k_weights = top_k_weights.redistribute(tp_mesh, [Shard(0)]).to_local()- return (hidden_states, top_k_index, top_k_weights), kwargs-- def transform_output_post_forward(self, module, output, mesh, *, tp_mesh=None, num_tokens=None):- if tp_mesh is None or tp_mesh.size() == 1:+ token_outputs[state.order] = recv_out+ token_outputs = token_outputs.view(*state.top_k_weights.shape, hidden_dim)+ output = (token_outputs * state.top_k_weights.unsqueeze(-1)).sum(dim=1)+ if self.tp_mesh.size() == 1: return output- # Shard(0) -> Replicate is one all-gather of the row slices, which also handles uneven and empty slices.- hidden_dim = output.size(-1)+ # Shard(0) -> Replicate is one all-gather of the row slices, uneven or empty ones too. output = DTensor.from_local(- output.contiguous(), tp_mesh, [Shard(0)], shape=(num_tokens, hidden_dim), stride=(hidden_dim, 1)+ output.contiguous(),+ self.tp_mesh,+ [Shard(0)],+ shape=(state.num_tokens, hidden_dim),+ stride=(hidden_dim, 1), ) return output.full_tensor() - def install_forward(self, module, ep_mesh, *, tp_mesh=None):- """Experts stay whole (Shard(0) on `ep_mesh`); `tp_mesh` is only the group of ranks holding the same batch."""- experts_forward = module.forward- ep_group, ep_size = ep_mesh.get_group(), ep_mesh.size() - def ep_forward(hidden_states, top_k_index, top_k_weights):- # Read the full token count before the pre hook slices the inputs across the batch replicas.- num_tokens = hidden_states.size(0)- (hidden_states, top_k_index, top_k_weights), _ = self.transform_inputs_pre_forward(- module, (hidden_states, top_k_index, top_k_weights), {}, ep_mesh, tp_mesh=tp_mesh+class AllReduceEP(EPImplementation):+ """+ When the EP group shares one batch (`ep_size == tp_size`): every rank runs its own experts on the whole batch,+ masking the routes to other ranks' experts (local id `num_local_experts`, weight 0), and an all-reduce sums the+ partial outputs. No tokens move and no split size is read back, so it captures in a CUDA graph; the masked routes+ still go through the experts' gather and elementwise passes, so its cost grows with the batch.++ Example: 4 experts on 2 ranks, top-2. Token t picks E1 (weight w1) and E2 (weight w2).++ GPU 0 1+ | |+ batch [====== B ======] [====== B ======] the same tokens on both ranks+ experts E0 E1 E2 E3+ top_k_index[t] [1, 2] [1, 2] global expert ids+ local index[t] [1, 2] [2, 0] 2 = not on this rank, masked+ top_k_weights[t] [w1, 0] [0, w2]+ expert output[t] w1 * E1(t) w2 * E2(t)+ after all-reduce w1 * E1(t) + w2 * E2(t) on both ranks+ """++ needs_shared_batch = True++ def __call__(self, hidden_states, top_k_index, top_k_weights):+ ep_group = self.ep_mesh.get_group()+ # Each rank backpropagates through its own experts only, so the gradients of the shared inputs it computes are+ # partial: sum them over the group (the forward all-reduce has an identity backward).+ hidden_states = _AllReduceBackward.apply(hidden_states, ep_group)+ top_k_weights = _AllReduceBackward.apply(top_k_weights, ep_group)+ off_rank = (top_k_index // self.num_local_experts) != self.ep_mesh.get_local_rank()+ local_index = torch.where(off_rank, self.num_local_experts, top_k_index % self.num_local_experts)+ expert_output = self.experts_forward(hidden_states, local_index, top_k_weights.masked_fill(off_rank, 0.0))+ return _AllReduceForward.apply(expert_output, ep_group)+++class AutoEP(EPImplementation):+ """+ The default: `AllReduceEP` at inference (gradients disabled) when the EP group shares one batch, and `AllToAllEP`+ in training and wherever the ranks hold different batches. At inference, the all-reduce never reads split sizes+ back to the host, so decode captures in a CUDA graph.+ """++ def __init__(self, experts: nn.Module, ep_mesh: DeviceMesh, tp_mesh: DeviceMesh):+ super().__init__(experts, ep_mesh, tp_mesh)+ self.all_to_all = AllToAllEP(experts, ep_mesh, tp_mesh)+ # Only built where it can run: an EP group whose ranks hold different batches has no all-reduce path.+ self.all_reduce = AllReduceEP(experts, ep_mesh, tp_mesh) if self.shares_batch else None++ def __call__(self, hidden_states, top_k_index, top_k_weights):+ if self.all_reduce is not None and not torch.is_grad_enabled():+ return self.all_reduce(hidden_states, top_k_index, top_k_weights)+ return self.all_to_all(hidden_states, top_k_index, top_k_weights)+++class EPImplementationInterface(GeneralInterface):+ """Registry of the `EPImplementation`s `DistributedConfig.ep_implementation` names. Add one with+ `EPImplementationInterface.register(name, cls)`."""++ _global_mapping = {"auto": AutoEP, "all_to_all": AllToAllEP, "all_reduce": AllReduceEP}+++class EpDispatchExpertsParallel(ExpertParallelLayer):+ """Whole experts per rank (`Shard(0)` on the EP mesh), reached through the `EPImplementation` that+ `DistributedConfig.ep_implementation` names in `EPImplementationInterface`."""++ def should_use_local_tensors(self, module):+ return True++ def install_forward(self, module, ep_mesh, *, tp_mesh, ep_implementation="auto"):+ """`tp_mesh` is the group of ranks holding the same batch (size 1 without TP)."""+ implementations = EPImplementationInterface()+ if ep_implementation not in implementations:+ raise ValueError(+ f"`ep_implementation={ep_implementation!r}` names no registered implementation: use one of "+ f"{', '.join(repr(name) for name in implementations)}, or register an `EPImplementation` "+ "with `EPImplementationInterface.register`." )- with self.context_around_forward(module, ep_mesh):- tokens, expert_ids, order, send_sizes, recv_sizes = self._dispatch_tokens(- hidden_states, top_k_index, module.num_experts, ep_group, ep_size- )- # hand the experts the received rows, not the all-to-all's pending result (whose pointer is null until- # waited on): https://github.com/huggingface/transformers/pull/49421- tokens = _WaitTensor.apply(tokens)- expert_output = self._run_local_experts(experts_forward, tokens, expert_ids)- output = self._combine_tokens(- expert_output, top_k_weights, order, send_sizes, recv_sizes, ep_group- ).to(hidden_states.dtype)+ implementation = implementations[ep_implementation](module, ep_mesh, tp_mesh) - return self.transform_output_post_forward(module, output, ep_mesh, tp_mesh=tp_mesh, num_tokens=num_tokens)+ def ep_forward(hidden_states, top_k_index, top_k_weights):+ if isinstance(hidden_states, DTensor):+ hidden_states = hidden_states.to_local()+ if isinstance(top_k_weights, DTensor):+ top_k_weights = top_k_weights.to_local()+ with self.context_around_forward(module, ep_mesh):+ output = implementation(hidden_states, top_k_index, top_k_weights)+ return output.to(hidden_states.dtype) module.forward = ep_forward return module@@ -383,9 +461,16 @@ def transform_output_post_forward(self, module, output, mesh, source=None): ALL_PARALLEL_STYLES.register("megamoe_experts", MoeTensorParalellMegaMoeExperts()) -def apply_expert_parallelism(model: nn.Module, ep_mesh: DeviceMesh, tp_mesh: DeviceMesh, plan: dict[str, str]):+def apply_expert_parallelism(+ model: nn.Module,+ ep_mesh: DeviceMesh,+ tp_mesh: DeviceMesh,+ plan: dict[str, str],+ ep_implementation: str = "auto",+): """- Shard experts on EP; use TP to split shared tokens and reconstruct outputs around dispatch.+ Shard experts on EP; `ep_dispatch_experts` modules reach them through the `EPImplementation` that+ `ep_implementation` names in `EPImplementationInterface`. """ modules = dict(model.named_modules()) parameters = dict(model.named_parameters())@@ -401,7 +486,7 @@ def apply_expert_parallelism(model: nn.Module, ep_mesh: DeviceMesh, tp_mesh: Dev module = modules[name] # Dispatch hooks need both meshes to redistribute tokens between TP and EP ranks. if style_name == "ep_dispatch_experts":- style.install_forward(module, ep_mesh=ep_mesh, tp_mesh=tp_mesh)+ style.install_forward(module, ep_mesh=ep_mesh, tp_mesh=tp_mesh, ep_implementation=ep_implementation) else: style.install_forward(module, ep_mesh) module._is_hooked = Truesrc/transformers/distributed/mixin.py3 + / 1 −
@@ -331,7 +331,9 @@ def maybe_distribute_model( elif "ep_dispatch_experts" in ep_plan.values(): # EP + DP with tp_size >= 1: the ranks of a TP group share the same batch. If we want a specific token, # we will have to slice the batch here in order to avoid computing tp_size times the same batch.- model = apply_expert_parallelism(model, ep_mesh, tp_mesh, ep_plan)+ model = apply_expert_parallelism(+ model, ep_mesh, tp_mesh, ep_plan, ep_implementation=distributed_config.ep_implementation+ ) if distributed_config.dp_size > 1: model = apply_fully_sharded_data_parallelism(model, mesh_manager, fsdp_plan, ep_plan)src/transformers/distributed/parallel_utils.py9 + / 0 −
@@ -117,8 +117,17 @@ class _AllReduceBackward(torch.autograd.Function): ranks), but the backward gradient is partial (each rank has 1/tp_size from its expert shard). We need to sum the partial gradients without dividing by world_size, which is what DTensor's Replicate backward does incorrectly.++ `apply` returns `x` as is when no gradient can flow: at inference the per-call overhead of an+ `autograd.Function` compounds across layers, e.g. in eager decode. """ + @classmethod+ def apply(cls, x, process_group):+ if torch.is_grad_enabled() and x.requires_grad:+ return super().apply(x, process_group)+ return x+ @staticmethod def forward(ctx, x, process_group): ctx.process_group = process_groupsrc/transformers/distributed/tensor_parallel.py2 + / 3 −
@@ -183,9 +183,8 @@ def transform_inputs_pre_forward(self, module, args, kwargs, mesh): # wrapping it as a DTensor. If its gradient is needed, synchronize the partial # input-gradient contributions explicitly. if is_local_input and getattr(module, "_hf_quantized_needs_local_tp", False):- if torch.is_grad_enabled() and x.requires_grad:- process_group = mesh.get_group() if mesh.ndim == 1 else mesh.get_group("tp")- x = _AllReduceBackward.apply(x, process_group)+ process_group = mesh.get_group() if mesh.ndim == 1 else mesh.get_group("tp")+ x = _AllReduceBackward.apply(x, process_group) return (x,) + args[1:], kwargs # DTensor path: handle regular training and layout redistribution.tests/expert_parallel/test_expert_parallel.py125 + / 7 −
@@ -13,11 +13,21 @@ # limitations under the License. from unittest.mock import patch +import pytest import torch+from parameterized import parameterized from torch.distributed.device_mesh import init_device_mesh+from torch.utils.checkpoint import checkpoint from transformers.distributed import expert_parallel-from transformers.distributed.expert_parallel import EpDispatchExpertsParallel+from transformers.distributed.expert_parallel import (+ AllReduceEP,+ AllToAllEP,+ AutoEP,+ EpDispatchExpertsParallel,+ EPImplementation,+ EPImplementationInterface,+) from transformers.distributed.parallel_utils import ALL_PARALLEL_STYLES from transformers.testing_utils import TestCasePlus, is_expert_parallel_test @@ -78,19 +88,127 @@ def test_dispatch_hands_experts_the_received_rows(self): it, and experts that launch kernels on raw pointers would read it: the dispatch waits before any experts run.""" run_distributed(world_size=2, backend="gloo")(_dispatch_hands_experts_the_received_rows)() + @parameterized.expand(+ [+ ("all_to_all", "train"),+ ("all_to_all", "inference"),+ ("all_reduce", "train"),+ ("all_reduce", "inference"),+ ("auto", "checkpoint"),+ ("auto", "reentrant_checkpoint"),+ ]+ )+ def test_ep_implementation_matches_one_process(self, ep_implementation, mode):+ """Each implementation gives the single-process output and input gradients, also under gradient checkpointing,+ where the reentrant mode runs `"auto"` without gradients first (all-reduce) and recomputes it with them+ (all-to-all)."""+ run_distributed(world_size=2, backend="gloo")(_ep_implementation_matches_one_process)(ep_implementation, mode)++ def test_auto_ep_picks_all_reduce_only_at_inference_on_a_shared_batch(self):+ run_distributed(world_size=2, backend="gloo")(_auto_ep_picks_all_reduce_only_at_inference_on_a_shared_batch)()++ def test_install_forward_checks_ep_implementation(self):+ """An unknown name and `"all_reduce"` without a shared batch are refused; a registered implementation runs."""+ run_distributed(world_size=2, backend="gloo")(_install_forward_checks_ep_implementation)()+ class _DummyExperts(torch.nn.Module):- def __init__(self):+ """Toy experts: expert `i` multiplies a token by `scales[i]` (1 by default, on 2 experts). The id `num_experts`+ marks a route to another rank's expert (`AllReduceEP` masks them that way) and adds nothing."""++ def __init__(self, scales=None): super().__init__()- self.num_experts = 2+ scales = torch.ones(2) if scales is None else scales+ self.num_experts = len(scales)+ # one extra scale of 0 for the id `num_experts`+ self.scales = torch.cat([scales, torch.zeros(1)]) - def forward(self, tokens, expert_ids, weights):- assert type(tokens) is torch.Tensor, type(tokens)- return tokens+ def forward(self, hidden_states, top_k_index, top_k_weights):+ assert type(hidden_states) is torch.Tensor, type(hidden_states)+ # each expert is a scalar, so a token's output is the token times the weighted sum of its experts' scales+ factor = (self.scales[top_k_index] * top_k_weights).sum(dim=-1, keepdim=True)+ return hidden_states * factor # Worker functions for the expert-parallel layer tests, spawned through `run_distributed`. def _dispatch_hands_experts_the_received_rows(rank): hidden_states = torch.arange(32.0).view(4, 8) + 100 * rank- experts = EpDispatchExpertsParallel().install_forward(_DummyExperts(), init_device_mesh("cpu", (2,)))+ mesh = init_device_mesh("cpu", (2, 1), mesh_dim_names=("ep", "tp"))+ experts = EpDispatchExpertsParallel().install_forward(_DummyExperts(), mesh["ep"], tp_mesh=mesh["tp"]) experts(hidden_states, torch.tensor([[0, 3], [1, 2], [2, 1], [3, 0]]), torch.ones(4, 2))+++def _install_forward_checks_ep_implementation(rank):+ mesh = init_device_mesh("cpu", (2, 1), mesh_dim_names=("ep", "tp"))+ ep_mesh, tp_mesh = mesh["ep"], mesh["tp"]+ # an unknown name, and `"all_reduce"` on ranks holding different batches+ for ep_implementation in ("fast", "all_reduce"):+ with pytest.raises(ValueError):+ EpDispatchExpertsParallel().install_forward(+ _DummyExperts(), ep_mesh, tp_mesh=tp_mesh, ep_implementation=ep_implementation+ )++ class Custom(EPImplementation):+ def __call__(self, hidden_states, top_k_index, top_k_weights):+ return hidden_states + 1++ with patch.dict(EPImplementationInterface._global_mapping, {"custom": Custom}):+ experts = EpDispatchExpertsParallel().install_forward(+ _DummyExperts(), ep_mesh, tp_mesh=tp_mesh, ep_implementation="custom"+ )+ torch.testing.assert_close(experts(torch.zeros(2, 4), None, torch.ones(2, 1)), torch.ones(2, 4))+++def _auto_ep_picks_all_reduce_only_at_inference_on_a_shared_batch(rank):+ mesh = init_device_mesh("cpu", (2, 1), mesh_dim_names=("ep", "tp"))+ ep_mesh, single = mesh["ep"], mesh["tp"]+ for tp_mesh, grad, all_reduce in ((ep_mesh, False, True), (ep_mesh, True, False), (single, False, False)):+ with (+ patch.object(AllReduceEP, "__call__") as all_reduce_call,+ patch.object(AllToAllEP, "__call__") as all_to_all_call,+ torch.set_grad_enabled(grad),+ ):+ AutoEP(_DummyExperts(), ep_mesh, tp_mesh)(None, None, None)+ assert (all_reduce_call.called, all_to_all_call.called) == (all_reduce, not all_reduce), (tp_mesh, grad)+++def _ep_implementation_matches_one_process(rank, ep_implementation, mode):+ """`ep_implementation` on 2 ranks gives the output and input gradients of all 4 experts on one process."""+ # 4 experts with distinct scales: rank 0 owns experts 0 and 1, rank 1 owns experts 2 and 3+ scales = torch.tensor([1.0, 2.0, 3.0, 4.0])+ # 4 tokens, top-2: every token picks one expert on each rank+ hidden_states = torch.arange(32.0).view(4, 8) / 10+ top_k_index = torch.tensor([[0, 3], [1, 2], [2, 0], [3, 1]])+ top_k_weights = torch.tensor([[0.6, 0.4], [0.7, 0.3], [0.5, 0.5], [0.9, 0.1]])+ grad_output = torch.linspace(-1, 1, 32).view(4, 8)++ def forward(experts, hidden_states, top_k_weights):+ # squared, so the backward needs the forward's output (under checkpointing, the recomputed one)+ return experts(hidden_states, top_k_index, top_k_weights).square()++ # expected: all 4 experts on one process+ expected_inputs = [t.clone().requires_grad_() for t in (hidden_states, top_k_weights)]+ expected = forward(_DummyExperts(scales), *expected_inputs)+ expected.backward(grad_output)++ # actual: the same batch through this rank's 2 experts, behind `ep_implementation`. Both ranks hold the batch+ # (the EP group is the TP group), so every implementation applies.+ mesh = init_device_mesh("cpu", (2,))+ experts = EpDispatchExpertsParallel().install_forward(+ _DummyExperts(scales[2 * rank : 2 * rank + 2]), mesh, tp_mesh=mesh, ep_implementation=ep_implementation+ )+ inputs = [t.clone().requires_grad_() for t in (hidden_states, top_k_weights)]+ if mode == "inference":+ with torch.no_grad():+ output = forward(experts, *inputs)+ elif mode == "train":+ output = forward(experts, *inputs)+ elif mode == "checkpoint":+ output = checkpoint(forward, experts, *inputs, use_reentrant=False)+ elif mode == "reentrant_checkpoint":+ output = checkpoint(forward, experts, *inputs, use_reentrant=True)++ torch.testing.assert_close(output, expected)+ if mode != "inference":+ output.backward(grad_output)+ torch.testing.assert_close([t.grad for t in inputs], [t.grad for t in expected_inputs])