diff --git a/deepspeed/module_inject/auto_ep_config.py b/deepspeed/module_inject/auto_ep_config.py index 7289b92f0e7f..cafe9771f4cc 100644 --- a/deepspeed/module_inject/auto_ep_config.py +++ b/deepspeed/module_inject/auto_ep_config.py @@ -230,6 +230,10 @@ def validate_autoep_config( raise ValueError("overlap_weight_grad returns expert weight gradients from the DeepEP dispatch, which " f"has not been validated with ZeRO stage {zero_stage}. Use ZeRO stage 1 or 2, or " "leave overlap_weight_grad unset.") + if tp_size > 1: + raise ValueError("overlap_weight_grad returns expert weight gradients from the DeepEP dispatch, which " + "has not been validated with AutoEP+AutoTP folding (tensor_parallel.autotp_size=" + f"{tp_size}). Set tensor_parallel.autotp_size to 1, or leave overlap_weight_grad unset.") if not all( hasattr(torch._C, name) for name in ("_get_sm_carveout_experimental", "_set_sm_carveout_experimental")): diff --git a/deepspeed/module_inject/auto_ep_layer.py b/deepspeed/module_inject/auto_ep_layer.py index 4c9550da5938..aac7bc5597f4 100644 --- a/deepspeed/module_inject/auto_ep_layer.py +++ b/deepspeed/module_inject/auto_ep_layer.py @@ -962,13 +962,6 @@ def set_deepspeed_parallelism( raise ValueError('combine_impl="fused_weighted_sum" does not support folded tensor parallelism ' f"(tensor_parallel.autotp_size={folding_group_handles.spec.tp_size}). Set " 'tensor_parallel.autotp_size to 1, or leave combine_impl unset.') - if self.comm_backend == DEEPEP_BACKEND and folding_group_handles.spec.tp_size > 1: - # DeepEP's combine returns token-major rows, which folded TP's - # assignment-metadata restore can't consume. Refuse rather than - # silently fall back to a backend the job didn't ask for. - raise ValueError(f'comm_backend="{DEEPEP_BACKEND}" does not support folded tensor parallelism ' - f"(expert_tensor_parallel_size={folding_group_handles.spec.tp_size}). Set " - 'expert_tensor_parallel_size to 1, or comm_backend to "comm".') self.ep_group_name = folding_group_handles.ep_group_name self.ep_group = folding_group_handles.ep_group self.tp_group = folding_group_handles.tp_group @@ -1015,7 +1008,82 @@ def _assert_recompute_skip_contract(self) -> None: "gradient_checkpointing_kwargs={'use_reentrant': True}), so that nothing reads the skipped output. " "Leave skip_recompute_combine unset for other checkpointing.") - def _deepep_route(self, tokens: torch.Tensor, ro: "RouterOutput") -> torch.Tensor: + def _partition_assignments_over_tp(self, token_indices_sorted: torch.Tensor, top_scores_sorted: torch.Tensor, + expert_indices_sorted: torch.Tensor, *, num_tokens: int): + """Split the expert-sorted assignments across the TP folding group. + + Returns this peer's share of the assignments and the context that restores the full output. + """ + from deepspeed.moe.ep_tp_dispatch import ( + RoutedAssignmentPayload, + assignment_ordinals_by_expert, + assert_tp_payload_consistent, + partition_assignments, + ) + payload = RoutedAssignmentPayload( + token_indices=(token_indices_sorted // self.top_k).to(torch.long), + expert_indices=expert_indices_sorted.to(torch.long), + assignment_indices=assignment_ordinals_by_expert(expert_indices_sorted.to(torch.long)), + capacity_slots=(token_indices_sorted % self.top_k).to(torch.long), + combine_weights=top_scores_sorted if self.score_apply == "post" else torch.ones_like(top_scores_sorted), + drop_mask=torch.zeros_like(top_scores_sorted, dtype=torch.bool), + pad_mask=torch.zeros_like(top_scores_sorted, dtype=torch.bool), + input_splits=[0 for _ in range(self.ep_size)], + output_splits=[0 for _ in range(self.ep_size)], + extra={ + "destination_ranks": (expert_indices_sorted // self.num_local_experts).to(torch.long), + "top_scores": top_scores_sorted, + "num_tokens": torch.tensor(num_tokens, device=token_indices_sorted.device, dtype=torch.long), + }, + ) + if self.validate_folding_routing: + assert_tp_payload_consistent(payload, + tp_group=self.tp_group, + tp_size=self.folding_group_handles.spec.tp_size) + tp_rank = dist.get_rank(group=self.tp_group) + return partition_assignments(payload, + tp_group=self.tp_group, + tp_rank=tp_rank, + tp_size=self.folding_group_handles.spec.tp_size) + + def _partition_routing_over_tp(self, ro: "RouterOutput", *, num_tokens: int): + """The router output with the assignments other TP peers keep masked out, for DeepEP. + + DeepEP takes the routing token-major and reads an expert index of -1 as "no selection", so a + peer sends only its share of the assignments by masking the others, instead of building the + partitioned row list the collective path dispatches. The same ``partition_assignments`` rule + decides the share, so the two backends split the work identically. + """ + from deepspeed.moe.ep_tp_dispatch import tp_keep_mask + token_indices_sorted = torch.argsort(ro.selected_experts.view(-1), stable=True) + top_scores_sorted = ro.top_scores.view(-1)[token_indices_sorted] + expert_indices_sorted = ro.selected_experts.reshape(-1).index_select(0, token_indices_sorted) + _, restore_ctx = self._partition_assignments_over_tp(token_indices_sorted, + top_scores_sorted, + expert_indices_sorted, + num_tokens=num_tokens) + keep = tp_keep_mask(token_indices_sorted, restore_ctx, num_tokens, self.top_k) + selected_experts = ro.selected_experts.masked_fill(~keep, -1) + # torch.where passes the routing-weight gradient to the kept slots only, whatever DeepEP returns + # for the masked ones. + top_scores = torch.where(keep, ro.top_scores, torch.zeros_like(ro.top_scores)) + return RouterOutput(top_scores, selected_experts, ro.num_tokens_per_expert), restore_ctx + + def _restore_folded_deepep(self, partial: torch.Tensor, restore_ctx, *, record_only: bool) -> torch.Tensor: + """Sum the TP peers' partial outputs: DeepEP's combine already reduced each peer's kept assignments.""" + from deepspeed.moe.ep_tp_dispatch import dispatch_counters, sum_partial_rows_over_tp + tp_size = self.folding_group_handles.spec.tp_size + if self.validate_folding_routing and not record_only: + kept = torch.tensor([restore_ctx.counters["assignments_local"]], device=partial.device, dtype=torch.long) + dist.all_reduce(kept, group=self.tp_group) + if int(kept.item()) != restore_ctx.counters["assignments_total"]: + raise RuntimeError("AutoEP+AutoTP DeepEP coverage mismatch: the tensor-parallel peers dispatched " + f"{int(kept.item())} assignments for {restore_ctx.counters['assignments_total']}") + output = sum_partial_rows_over_tp(partial, self.tp_group, tp_size, record_only=record_only) + self._last_folding_dispatch_counters = dispatch_counters(restore_ctx) + return output + + def _deepep_route(self, tokens: torch.Tensor, ro: "RouterOutput", restore_ctx=None) -> torch.Tensor: """Dispatch, run the experts, and combine through DeepEP. ``tokens`` is [T, H] before top-k expansion. DeepEP replicates each @@ -1024,6 +1092,10 @@ def _deepep_route(self, tokens: torch.Tensor, ro: "RouterOutput") -> torch.Tenso sums them back. It therefore replaces the expansion and the reduction around the collectives, not just the collectives, and returns [T, H] ready for the shared tail of forward. + + Under AutoEP+AutoTP folding ``ro`` carries only this peer's share of the + assignments and ``restore_ctx`` describes the split; the peers' partial + outputs are then summed over the TP group. """ assert_dtype_supported(tokens.dtype) @@ -1116,8 +1188,12 @@ def _deepep_route(self, tokens: torch.Tensor, ro: "RouterOutput") -> torch.Tenso expert_output = apply_deepep_row_weights(expert_output, weights, self.row_weighting_impl) if record_only: - return deepep_record_combine(exchange, expert_output, handle) - return deepep_combine(exchange, expert_output, handle) + combined = deepep_record_combine(exchange, expert_output, handle) + else: + combined = deepep_combine(exchange, expert_output, handle) + if restore_ctx is None: + return combined + return self._restore_folded_deepep(combined, restore_ctx, record_only=record_only) def _finalize_output(self, output: torch.Tensor, x: torch.Tensor, hidden_states: torch.Tensor, hdim: int) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]: @@ -1216,8 +1292,12 @@ def _forward(self, hidden_states: torch.Tensor) -> torch.Tensor | tuple[torch.Te self.tokens_per_expert.add_(ro.num_tokens_per_expert) if self.ep_size > 1 and self.comm_backend == DEEPEP_BACKEND: - output = self._deepep_route(x, ro).reshape(bsz, seqlen, hdim) - return self._finalize_output(output, x, hidden_states, hdim) + if folded_tp: + ro, restore_ctx = self._partition_routing_over_tp(ro, num_tokens=bsz * seqlen) + output = self._deepep_route(x, ro, restore_ctx=restore_ctx) + else: + output = self._deepep_route(x, ro) + return self._finalize_output(output.reshape(bsz, seqlen, hdim), x, hidden_states, hdim) # Reorder tokens into expert-contiguous order. token_indices_sorted = torch.argsort(ro.selected_experts.view(-1), stable=True) @@ -1226,40 +1306,11 @@ def _forward(self, hidden_states: torch.Tensor) -> torch.Tensor | tuple[torch.Te restore_ctx = None if folded_tp: - from deepspeed.moe.ep_tp_dispatch import ( - RoutedAssignmentPayload, - assignment_ordinals_by_expert, - assert_tp_payload_consistent, - dispatch_counters, - partition_assignments, - restore_combined, - ) - payload = RoutedAssignmentPayload( - token_indices=(token_indices_sorted // self.top_k).to(torch.long), - expert_indices=expert_indices_sorted.to(torch.long), - assignment_indices=assignment_ordinals_by_expert(expert_indices_sorted.to(torch.long)), - capacity_slots=(token_indices_sorted % self.top_k).to(torch.long), - combine_weights=top_scores_sorted - if self.score_apply == "post" else torch.ones_like(top_scores_sorted), - drop_mask=torch.zeros_like(top_scores_sorted, dtype=torch.bool), - pad_mask=torch.zeros_like(top_scores_sorted, dtype=torch.bool), - input_splits=[0 for _ in range(self.ep_size)], - output_splits=[0 for _ in range(self.ep_size)], - extra={ - "destination_ranks": (expert_indices_sorted // self.num_local_experts).to(torch.long), - "top_scores": top_scores_sorted, - "num_tokens": torch.tensor(bsz * seqlen, device=hidden_states.device, dtype=torch.long), - }, - ) - if self.validate_folding_routing: - assert_tp_payload_consistent(payload, - tp_group=self.tp_group, - tp_size=self.folding_group_handles.spec.tp_size) - tp_rank = dist.get_rank(group=self.tp_group) - local_payload, restore_ctx = partition_assignments(payload, - tp_group=self.tp_group, - tp_rank=tp_rank, - tp_size=self.folding_group_handles.spec.tp_size) + from deepspeed.moe.ep_tp_dispatch import dispatch_counters, restore_combined + local_payload, restore_ctx = self._partition_assignments_over_tp(token_indices_sorted, + top_scores_sorted, + expert_indices_sorted, + num_tokens=bsz * seqlen) token_indices_for_compute = token_indices_sorted.index_select(0, restore_ctx.local_indices) top_scores_for_compute = top_scores_sorted.index_select(0, restore_ctx.local_indices) expert_indices_for_plan = local_payload.expert_indices diff --git a/deepspeed/moe/ep_tp_dispatch.py b/deepspeed/moe/ep_tp_dispatch.py index 6543ff93bff6..8db7e61956c7 100644 --- a/deepspeed/moe/ep_tp_dispatch.py +++ b/deepspeed/moe/ep_tp_dispatch.py @@ -428,6 +428,61 @@ def average_gradient_over_tp(tensor: torch.Tensor, tp_group, tp_size: int) -> to return _AverageGradientOverTP.apply(tensor, tp_group) +def tp_keep_mask(token_indices_sorted: torch.Tensor, ctx: RestoreContext, num_tokens: int, top_k: int) -> torch.Tensor: + """The assignments this TP peer keeps, as a ``[tokens, top_k]`` boolean mask. + + ``partition_assignments`` names the kept assignments by their position in the expert-sorted + list. ``token_indices_sorted`` maps each position back to ``token * top_k + slot``, the + token-major layout the router produced, which is the layout DeepEP's dispatch consumes. + """ + kept_positions = token_indices_sorted.index_select(0, ctx.local_indices) + keep = torch.zeros(num_tokens * top_k, dtype=torch.bool, device=token_indices_sorted.device) + keep[kept_positions] = True + return keep.view(num_tokens, top_k) + + +class _SumPartialRowsOverTP(torch.autograd.Function): + """Sum each TP peer's partial per-token output into the full output, replicated on every peer. + + For an exchange that has already reduced a peer's kept assignments to one row per token + (DeepEP's combine), there are no rows left to gather: the restore is a sum of + ``[tokens, hidden]`` partials over the folding group. + + Backward all-reduces the upstream gradient over the TP group, as ``_AllGatherVariableRows`` + does, so each peer's gradient carries the same ``tp_size`` factor as under + ``restore_combined``, and the folded AVERAGE and EXPERT_TP_CANCEL strategies cancel it + unchanged. The plain adjoint of a sum, the identity, would leave the router and expert + gradients ``tp_size`` times too small after those strategies. + """ + + @staticmethod + def forward(ctx, tensor, group, record_only): + ctx.group = group + if record_only: + # Nothing reads the recomputed output (skip_recompute_combine); only the backward matters. + return tensor.view_as(tensor) + summed = tensor.clone(memory_format=torch.contiguous_format) + dist.all_reduce(summed, group=group) + return summed + + @staticmethod + def backward(ctx, grad_output): + grad = grad_output.clone(memory_format=torch.contiguous_format) + dist.all_reduce(grad, group=ctx.group) + return grad, None, None + + +def sum_partial_rows_over_tp(tensor: torch.Tensor, + tp_group, + tp_size: int, + *, + record_only: bool = False) -> torch.Tensor: + """Return the sum of ``tensor`` over the TP folding group, with the folded gradient convention.""" + if tp_size <= 1 or not dist.is_initialized(): + return tensor + return _SumPartialRowsOverTP.apply(tensor, tp_group, record_only) + + def restore_combined(local_combined: torch.Tensor, ctx: RestoreContext, *, diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index ed5f42684c10..951d0f83224d 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -1027,7 +1027,7 @@ smoke coverage used for this AutoEP surface produced the following version gates | Description | Default | | -------------------------------------------------------------------------------------------------------------- | -------- | -| Experimental. In the DeepEP backward, send the experts' input gradient back while computing their weight gradients. The expert backward returns its input gradient first and defers its weight-gradient GEMMs to the DeepEP dispatch backward, which launches its combine asynchronously, runs those GEMMs with `comm_num_sm` SMs withheld so the combine can run beside them, and waits before returning, including when weight-gradient computation raises. Parameter-gradient semantics are unchanged; exact cross-backend equality is not guaranteed. First-order gradients only (`create_graph=True` raises). Requires `comm_backend="deepep"` with `autoep_size > 1`, the `torch._grouped_mm` expert path (`use_grouped_mm=true`, and `disable_triton_grouped_mm=true` on devices that prefer the Triton grouped GEMM), ZeRO stage 1 or 2 (not 0 or 3), and PyTorch's SM carveout getter/setter APIs; unsupported configurations fail rather than falling back. | `false` | +| Experimental. In the DeepEP backward, send the experts' input gradient back while computing their weight gradients. The expert backward returns its input gradient first and defers its weight-gradient GEMMs to the DeepEP dispatch backward, which launches its combine asynchronously, runs those GEMMs with `comm_num_sm` SMs withheld so the combine can run beside them, and waits before returning, including when weight-gradient computation raises. Parameter-gradient semantics are unchanged; exact cross-backend equality is not guaranteed. First-order gradients only (`create_graph=True` raises). Requires `comm_backend="deepep"` with `autoep_size > 1`, the `torch._grouped_mm` expert path (`use_grouped_mm=true`, and `disable_triton_grouped_mm=true` on devices that prefer the Triton grouped GEMM), ZeRO stage 1 or 2 (not 0 or 3), `tensor_parallel.autotp_size=1`, and PyTorch's SM carveout getter/setter APIs; unsupported configurations fail rather than falling back. | `false` | ***skip_recompute_combine***: [boolean] @@ -1168,7 +1168,7 @@ Use a built-in preset but override specific naming/weight fields for a fine-tune **Constraints:** - `autoep_size` must divide `num_experts` for all detected MoE layers -- AutoEP combines with AutoTP (`tensor_parallel.autotp_size > 1`) by folding them onto the same ranks, at ZeRO stages 0 to 3, with `expert_tensor_parallel_size` 1 and without ZeRO offload or DeepCompile +- AutoEP combines with AutoTP (`tensor_parallel.autotp_size > 1`) by folding them onto the same ranks, at ZeRO stages 0 to 3, with either `comm_backend`, with `expert_tensor_parallel_size` 1 and without ZeRO offload or DeepCompile - AutoEP with ZeRO Stage 3 is supported only without sequence parallelism, hpZeRO secondary tensor groups, non-1 `expert_tensor_parallel_size`, or quantized gradients - ZeRO Stage 3 saves AutoEP checkpoints partition-natively and supports same-topology save/load, module-only loads, optimizer-state-skipping loads, and universal checkpoint conversion (not yet with AutoTP folding). Universal loads can resume at a different data-parallel world size, a different `autoep_size`, or both (when the target `autoep_size` divides the expert count), including weights-only/module-only loads from the converted `fp32.pt` parameter files diff --git a/docs/code-docs/source/autoep.rst b/docs/code-docs/source/autoep.rst index aafd3f779be0..93bc15281dcb 100644 --- a/docs/code-docs/source/autoep.rst +++ b/docs/code-docs/source/autoep.rst @@ -199,6 +199,19 @@ constructed, including when the caller supplied a lazily initialized process group. This initialization does not run on subsequent forwards. The standard ``comm`` and ``autoep_size=1`` paths are unchanged. +With AutoEP+AutoTP folding (``tensor_parallel.autotp_size`` greater than 1), +the tensor-parallel peers of a group hold the same tokens and split the routed +assignments between them by the same rule as the collective path. On the DeepEP +path a peer marks the assignments it does not keep with an expert index of -1, +which DeepEP's dispatch reads as "no selection", and zeroes their routing +weights, so it sends only its share. DeepEP's combine returns the peer's partial +output, one row per token summed over the assignments it kept, and an +all-reduce over the tensor-parallel group adds the peers' partial outputs in the +activation dtype. The backward of that all-reduce all-reduces the gradient too, +so every gradient carries the same ``tp_size`` factor as on the collective path +and the folded gradient corrections apply unchanged. ``overlap_weight_grad`` is +rejected with folding until it has been validated there. + Received rows and routing weights are passed through without a prefix slice when their buffers already contain exactly the arrived rows. Overallocated buffers are still trimmed independently to the handle's row count. This avoids @@ -729,7 +742,8 @@ Requirements and limits: - AutoEP combines with AutoTP (``tensor_parallel.autotp_size > 1``) by folding: on the same ranks, AutoTP shards the layers its partition specification names and AutoEP distributes the routed experts. Folding - supports ZeRO stages 0 to 3 with ``expert_tensor_parallel_size=1``. With + supports ZeRO stages 0 to 3 with ``expert_tensor_parallel_size=1``, with + either ``comm_backend``. With ZeRO stage 3 the optimizer can be offloaded to the CPU (``offload_optimizer.device: "cpu"``); folding rejects optimizer offload with ZeRO stages 1 and 2 or to NVMe, Muon with optimizer offload, parameter diff --git a/tests/unit/module_inject/test_auto_ep_comm.py b/tests/unit/module_inject/test_auto_ep_comm.py index 5391c48d7ee5..2b0cd863c2fb 100644 --- a/tests/unit/module_inject/test_auto_ep_comm.py +++ b/tests/unit/module_inject/test_auto_ep_comm.py @@ -66,6 +66,18 @@ def test_deepep_accepts_a_configured_capacity(self): self.validate(config) + def test_deepep_accepts_folded_tensor_parallelism(self): + # AutoEP+AutoTP folding splits the routed assignments between the TP peers; the DeepEP route + # does that by masking, so the combination is no longer refused. + config = parse_autoep_config({ + "enabled": True, + "autoep_size": 2, + "comm_backend": "deepep", + "comm_max_tokens_per_rank": 4096, + }) + + validate_autoep_config(config, world_size=4, pp_size=1, tp_size=2, sp_size=1) + def test_sm_budget_and_qp_margin_are_configurable(self): config = parse_autoep_config({"enabled": True, "comm_num_sm": 24, "comm_qp_margin": 8}) diff --git a/tests/unit/v1/moe/test_autoep_autotp_dispatch.py b/tests/unit/v1/moe/test_autoep_autotp_dispatch.py index 31576ced4840..c859f4cb19cb 100644 --- a/tests/unit/v1/moe/test_autoep_autotp_dispatch.py +++ b/tests/unit/v1/moe/test_autoep_autotp_dispatch.py @@ -16,6 +16,8 @@ dispatch_counters, partition_assignments, restore_combined, + sum_partial_rows_over_tp, + tp_keep_mask, ) import deepspeed.moe.ep_tp_dispatch as dispatch from unit.v1.moe.autoep_test_utils import run_cpu_gloo_test @@ -253,3 +255,80 @@ def fake_all_reduce(tensor, op=None, group=None): with pytest.raises(RuntimeError, match="routing decisions differ"): assert_tp_payload_consistent(payload, tp_group=object(), tp_size=2) + + +def _payload_for_routing(selected_experts): + """The folded payload the AutoEP layer builds from a ``[tokens, top_k]`` routing.""" + num_tokens, top_k = selected_experts.shape + token_indices_sorted = torch.argsort(selected_experts.reshape(-1), stable=True) + expert_indices = selected_experts.reshape(-1).index_select(0, token_indices_sorted) + no_assignments = torch.zeros_like(expert_indices, dtype=torch.bool) + payload = RoutedAssignmentPayload( + token_indices=token_indices_sorted // top_k, + expert_indices=expert_indices, + assignment_indices=assignment_ordinals_by_expert(expert_indices), + capacity_slots=token_indices_sorted % top_k, + combine_weights=torch.ones(expert_indices.numel()), + drop_mask=no_assignments, + pad_mask=no_assignments.clone(), + input_splits=[expert_indices.numel()], + output_splits=[expert_indices.numel()], + extra={ + "destination_ranks": torch.zeros_like(expert_indices), + "num_tokens": torch.tensor(num_tokens, dtype=torch.long), + }, + ) + return payload, token_indices_sorted + + +@pytest.mark.parametrize("num_tokens, top_k, num_experts, tp_size", [(40, 3, 8, 3), (2, 1, 8, 4)]) +def test_tp_keep_mask_gives_every_assignment_to_exactly_one_peer(num_tokens, top_k, num_experts, tp_size): + generator = torch.Generator().manual_seed(num_tokens * 31 + tp_size) + selected_experts = torch.rand(num_tokens, num_experts, generator=generator).argsort(dim=1)[:, :top_k] + payload, token_indices_sorted = _payload_for_routing(selected_experts) + + masks = [] + for tp_rank in range(tp_size): + _, ctx = partition_assignments(payload, tp_group=None, tp_rank=tp_rank, tp_size=tp_size) + keep = tp_keep_mask(token_indices_sorted, ctx, num_tokens, top_k) + assert keep.shape == (num_tokens, top_k) + assert int(keep.sum()) == ctx.counters["assignments_local"] + # The mask names the same (token, slot) pairs as the row list the collective path dispatches. + kept_rows = set( + zip( + payload.token_indices.index_select(0, ctx.local_indices).tolist(), + payload.capacity_slots.index_select(0, ctx.local_indices).tolist())) + tokens, slots = keep.nonzero(as_tuple=True) + assert set(zip(tokens.tolist(), slots.tolist())) == kept_rows + masks.append(keep) + + # A second peer sending an assignment would double its contribution; a peer missing one would drop it. + assert torch.equal(torch.stack(masks).sum(dim=0), torch.ones(num_tokens, top_k, dtype=torch.long)) + + +def _sum_partial_rows_worker(rank, world_size, _shared_tmpdir): + tp_group = dist.get_world_group() + base = torch.arange(6, dtype=torch.float32).reshape(3, 2) + partial = (base * (rank + 1)).requires_grad_(True) + # Every peer holds the same upstream gradient, as it does in training: the layers after the + # MoE layer consume the replicated full output identically. + upstream = torch.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]) + + summed = sum_partial_rows_over_tp(partial, tp_group, world_size) + torch.testing.assert_close(summed, base * sum(peer + 1 for peer in range(world_size))) + summed.backward(upstream) + # The folded gradient convention: the restore leaves a tp_size factor on every gradient that + # passes through it, which AVERAGE and EXPERT_TP_CANCEL then divide out. A plain identity + # backward here would leave those gradients tp_size times too small. + assert torch.equal(partial.grad, upstream * world_size) + + # record_only: nothing reads the output, so no collective runs, but the backward is the same. + recorded = partial.detach().clone().requires_grad_(True) + out = sum_partial_rows_over_tp(recorded, tp_group, world_size, record_only=True) + assert torch.equal(out, recorded.detach()) + out.backward(upstream) + assert torch.equal(recorded.grad, upstream * world_size) + + +def test_sum_partial_rows_over_tp_sums_forward_and_keeps_the_tp_factor_backward(tmpdir): + run_cpu_gloo_test(_sum_partial_rows_worker, tmpdir, world_size=2) diff --git a/tests/unit/v1/moe/test_autoep_deepep_parity.py b/tests/unit/v1/moe/test_autoep_deepep_parity.py index 054f47d29f18..d2d3482067c2 100644 --- a/tests/unit/v1/moe/test_autoep_deepep_parity.py +++ b/tests/unit/v1/moe/test_autoep_deepep_parity.py @@ -18,6 +18,7 @@ import contextlib import functools +from types import SimpleNamespace from unittest import mock import pytest @@ -37,6 +38,7 @@ MockMoETransformer, engine_input_dtype, make_autoep_config, + run_cpu_gloo_test, seed_everything, skip_unless_h100_tests_enabled, ) @@ -200,8 +202,9 @@ def counted_forward(*args, _name=name, _forward=original_forward, **kwargs): def _snapshot_fp32_parameters(engine): optimizer = engine.optimizer master_parameters = {} - # Stage-0 low-precision wrappers do not expose the safe_get parameter mapping. - if hasattr(optimizer, "fp16_groups"): + # Stage-0 low-precision wrappers do not expose the safe_get parameter mapping. (ZeRO-3's optimizer also has + # fp16_groups, but keeps its fp32 partitions elsewhere; safe_get_full_fp32_param gathers them below.) + if hasattr(optimizer, "fp16_groups") and engine.zero_optimization_stage() == 0: state = optimizer.state_dict() for index, parameters in enumerate(optimizer.fp16_groups): if "fp32_groups_flat" in state: @@ -217,6 +220,9 @@ def _snapshot_fp32_parameters(engine): full_parameter = master_parameters.get(parameter) if full_parameter is None: full_parameter = safe_get_full_fp32_param(parameter) + if full_parameter is None and parameter.dtype == torch.float32: + # A parameter trained in fp32 is its own master copy. + full_parameter = parameter assert full_parameter is not None, f"Expected FP32 master parameter for {name}" assert full_parameter.dtype == torch.float32, f"Expected FP32 master parameter dtype for {name}" snapshot[name] = full_parameter.detach().cpu().clone() @@ -231,16 +237,32 @@ def _build_test_engine(backend, score_apply=None, skip_recompute_combine=False, zero_stage=1, + tp_size=1, + mixed_precision=True, **expert_parallel): seed_everything(seed) - config = make_autoep_config(ep_size=ep_size) - # Pinned, because make_autoep_config prefers fp16 wherever it is available - # and DeepEP dispatches bfloat16 only. Both backends have to run the same - # dtype anyway for the comparison to mean anything. - config.pop("fp16", None) - config["bf16"] = {"enabled": True} + config = make_autoep_config(ep_size=ep_size, mixed_precision=mixed_precision) + if mixed_precision: + # Pinned, because make_autoep_config prefers fp16 wherever it is available + # and DeepEP dispatches bfloat16 only. Both backends have to run the same + # dtype anyway for the comparison to mean anything. + config.pop("fp16", None) + config["bf16"] = {"enabled": True} config["zero_optimization"]["stage"] = zero_stage + if tp_size > 1: + # AutoEP+AutoTP folding with the dense weights kept whole, so that only the MoE dispatch and + # restore are folded. + config["tensor_parallel"] = { + "autotp_size": tp_size, + "partition_config": { + "use_default_specs": False, + "layer_specs": [{ + "patterns": [".*\\.weight$"], + "partition_type": "skip", + }], + }, + } config["expert_parallel"]["comm_backend"] = backend if row_weighting_impl != "auto": # The original cleanup/legacy comparisons keep the fixture's lr=1e-4. Only the new eager/fused @@ -288,6 +310,8 @@ def _run_one_step(backend, steps=1, seq_len=SEQ_LEN, zero_stage=1, + tp_size=1, + mixed_precision=True, **expert_parallel): """Build a model on ``backend``, run one step, return its output and grads.""" engine = _build_test_engine(backend, @@ -297,6 +321,8 @@ def _run_one_step(backend, score_apply=score_apply, skip_recompute_combine=skip_recompute_combine, zero_stage=zero_stage, + tp_size=tp_size, + mixed_precision=mixed_precision, **expert_parallel) if backend == "deepep" and not cleanup: _install_legacy_deepep_prep(engine) @@ -891,3 +917,186 @@ def test_cleanup_initializes_a_lazy_ep_communicator(self): rtol=5e-2, atol=5e-2, msg=f"cold-start gradient for {name}") + + +def _assert_folded_results_close(actual, expected, *, rtol, atol): + """The folded DeepEP route against the folded collective route: same tokens, same split, same sums.""" + torch.testing.assert_close(actual["output"], expected["output"], rtol=rtol, atol=atol) + torch.testing.assert_close(actual["input_gradient"], expected["input_gradient"], rtol=rtol, atol=atol) + assert set(actual["gradients"]) == set( + expected["gradients"]), "the two routes produced gradients for different parameters" + assert any(".router." in name for name in actual["gradients"]), "no router gradient was captured" + assert any(".experts." in name for name in actual["gradients"]), "no expert gradient was captured" + for name, reference in expected["gradients"].items(): + torch.testing.assert_close(actual["gradients"][name], + reference, + rtol=rtol, + atol=atol, + msg=f"gradient for {name}") + + +@pytest.mark.skipif(not _deepep_available(), reason="deep_ep is not installed") +class TestDeepEPFoldedMatchesCollective(DistributedTest): + """Under AutoEP+AutoTP folding (TP 2 x EP 2) the DeepEP route must agree with the folded collective route. + + Both split the assignments between the TP peers by the same rule, so a peer that sent an assignment + twice, dropped one, or restored the partial outputs with the wrong gradient factor would show up here. + """ + + world_size = 4 + reuse_dist_env = False + + @pytest.mark.parametrize("zero_stage", [1, 3]) + def test_forward_and_backward_match_the_folded_collective_path(self, zero_stage): + skip_unless_h100_tests_enabled("DeepEP parity needs H100s and a DeepEP build") + + collective = _run_one_step("comm", 2, seed=1234, tp_size=2, zero_stage=zero_stage) + deepep = _run_one_step("deepep", 2, seed=1234, tp_size=2, zero_stage=zero_stage, validate_folding_routing=True) + + # bfloat16 with a different reduction order, as in TestDeepEPMatchesCollective. + _assert_folded_results_close(deepep, collective, rtol=5e-2, atol=5e-2) + + def test_skip_recompute_combine_matches_the_folded_collective_path(self): + skip_unless_h100_tests_enabled("DeepEP parity needs H100s and a DeepEP build") + + collective = _run_one_step("comm", 2, seed=4321, tp_size=2, decoder_layer_checkpointing=True) + deepep = _run_one_step("deepep", + 2, + seed=4321, + tp_size=2, + decoder_layer_checkpointing=True, + skip_recompute_combine=True) + + _assert_folded_results_close(deepep, collective, rtol=5e-2, atol=5e-2) + + def test_fused_row_weighting_matches_the_folded_collective_path(self): + _skip_unless_fused_row_weighting_enabled("DeepEP parity needs H100s and a DeepEP build") + + collective = _run_one_step("comm", 2, seed=2468, tp_size=2) + deepep = _run_one_step("deepep", 2, seed=2468, tp_size=2, row_weighting_impl="fused") + + _assert_folded_results_close(deepep, collective, rtol=5e-2, atol=5e-2) + + +class _FakeDeepEPExchange: + """A stand-in for ``DeepEPExchange`` built from the collective primitives, so the DeepEP route runs on CPU. + + It keeps to the documented DeepEP contract the layer relies on: dispatch sends each token's row to the + rank that owns each selected expert, treats an expert index of -1 as no selection, and returns the + arrivals grouped by local expert with their routing weights and a handle holding the per-expert prefix + counts; combine sends the rows back and sums them per token without applying the weights. + """ + + def __init__(self, ep_group, num_experts, top_k, hidden_size, **_unused): + self.ep_group = ep_group + self.ep_size = dist.get_world_size(group=ep_group) + self.ep_rank = dist.get_rank(group=ep_group) + self.num_experts = num_experts + self.num_local_experts = num_experts // self.ep_size + self.top_k = top_k + self.num_max_tokens_per_rank = 1 << 20 + self.last_handle = None + self.last_pending = None + self.holders = 0 + + def release(self): + self.holders = max(self.holders - 1, 0) + + +def _fake_deepep_dispatch(exchange, + tokens, + topk_idx, + topk_weights, + replay=None, + *, + weight_grad_slot=None, + expert_weights=()): + from deepspeed.module_inject.auto_ep_layer import _AllToAllV, compute_split_plan_from_expert_indices + assert weight_grad_slot is None and not expert_weights, "the fake exchange has no weight-gradient overlap" + flat_experts = topk_idx.reshape(-1) + positions = torch.nonzero(flat_experts >= 0, as_tuple=False).flatten() + experts = flat_experts.index_select(0, positions) + # Experts are contiguous per rank, so expert order is destination-rank order, as the all-to-all needs. + order = torch.argsort(experts, stable=True) + positions = positions.index_select(0, order) + experts = experts.index_select(0, order) + rows = tokens.index_select(0, positions // exchange.top_k) + weights = topk_weights.reshape(-1).index_select(0, positions) + plan = compute_split_plan_from_expert_indices(expert_indices=experts, + num_experts=exchange.num_experts, + ep_size=exchange.ep_size, + num_local_experts=exchange.num_local_experts, + ep_group=exchange.ep_group) + received = _AllToAllV.apply(exchange.ep_group, rows, plan.input_splits, plan.output_splits) + recv_weights = _AllToAllV.apply(exchange.ep_group, weights.reshape(-1, 1), plan.input_splits, + plan.output_splits).reshape(-1) + arrived_experts = experts.new_empty(sum(plan.output_splits)) + dist.all_to_all_single(arrived_experts, + experts.contiguous(), + output_split_sizes=plan.output_splits, + input_split_sizes=plan.input_splits, + group=exchange.ep_group) + # Arrivals are source-major; DeepEP hands them over grouped by expert. + by_expert = torch.argsort(arrived_experts, stable=True) + received = received.index_select(0, by_expert) + recv_weights = recv_weights.index_select(0, by_expert) + local_experts = arrived_experts - exchange.ep_rank * exchange.num_local_experts + counts = torch.bincount(local_experts, minlength=exchange.num_local_experts) + handle = SimpleNamespace( + psum_num_recv_tokens_per_expert=counts.cumsum(0), + num_expanded_tokens=received.shape[0], + topk_idx=topk_idx, + do_expand=True, + plan=plan, + by_expert=by_expert, + positions=positions, + num_tokens=tokens.shape[0], + ) + exchange.last_handle = handle + return received, recv_weights, exchange + + +def _fake_deepep_combine(exchange, rows, handle): + from deepspeed.module_inject.auto_ep_layer import _AllToAllV + source_major = torch.empty_like(handle.by_expert) + source_major[handle.by_expert] = torch.arange(handle.by_expert.numel()) + rows = rows.index_select(0, source_major) + returned = _AllToAllV.apply(exchange.ep_group, rows, handle.plan.output_splits, handle.plan.input_splits) + tokens = handle.positions // exchange.top_k + return rows.new_zeros((handle.num_tokens, rows.shape[1])).index_add(0, tokens, returned) + + +@contextlib.contextmanager +def _fake_deepep_route(): + """Run the DeepEP route on the fake exchange: no deep_ep, no CUDA, any dtype.""" + real_barrier = auto_ep_layer.dist.barrier + + def barrier_without_device_ids(group=None, **_kwargs): + return real_barrier(group=group) + + with mock.patch.object(auto_ep_layer, "shared_exchange", lambda **kwargs: _FakeDeepEPExchange(**kwargs)), \ + mock.patch.object(auto_ep_layer, "deepep_dispatch", _fake_deepep_dispatch), \ + mock.patch.object(auto_ep_layer, "deepep_combine", _fake_deepep_combine), \ + mock.patch.object(auto_ep_layer, "assert_dtype_supported", lambda dtype: None), \ + mock.patch.object(auto_ep_layer.dist, "barrier", barrier_without_device_ids): + yield + + +def _cpu_folded_fake_deepep_worker(rank, world_size, _shared_tmpdir): + # TP 2 x EP 2 in fp32 on gloo: the two routes split the assignments the same way and sum the same + # products, so they agree to rounding of the summation order. + collective = _run_one_step("comm", 2, seed=1234, tp_size=2, mixed_precision=False, zero_stage=0) + with _fake_deepep_route(): + deepep = _run_one_step("deepep", + 2, + seed=1234, + tp_size=2, + mixed_precision=False, + zero_stage=0, + validate_folding_routing=True) + + _assert_folded_results_close(deepep, collective, rtol=1e-4, atol=1e-5) + + +def test_cpu_gloo_folded_deepep_route_matches_the_folded_collective_path(tmpdir): + run_cpu_gloo_test(_cpu_folded_fake_deepep_worker, tmpdir, world_size=4) diff --git a/tests/unit/v1/moe/test_autoep_expert_activation.py b/tests/unit/v1/moe/test_autoep_expert_activation.py index 30dff3aab603..bf6292965101 100644 --- a/tests/unit/v1/moe/test_autoep_expert_activation.py +++ b/tests/unit/v1/moe/test_autoep_expert_activation.py @@ -387,10 +387,10 @@ def validate(**settings): def test_overlap_weight_grad_settings_are_validated(self, monkeypatch): - def validate(zero_stage=1, **settings): + def validate(zero_stage=1, tp_size=1, **settings): base = {"enabled": True, "autoep_size": 2, "comm_backend": "deepep", "comm_max_tokens_per_rank": 64} config = parse_autoep_config({**base, **settings}) - validate_autoep_config(config, 2, 1, 1, 1, zero_stage=zero_stage) + validate_autoep_config(config, 2 * tp_size, 1, tp_size, 1, zero_stage=zero_stage) assert parse_autoep_config({"enabled": True}).overlap_weight_grad is False validate(overlap_weight_grad=True, zero_stage=1) @@ -405,6 +405,8 @@ def validate(zero_stage=1, **settings): for stage in (0, 3): with pytest.raises(ValueError, match=f"ZeRO stage {stage}"): validate(overlap_weight_grad=True, zero_stage=stage) + with pytest.raises(ValueError, match="AutoTP folding"): + validate(overlap_weight_grad=True, tp_size=2) for name in ("_get_sm_carveout_experimental", "_set_sm_carveout_experimental"): with monkeypatch.context() as missing_api: missing_api.delattr(torch._C, name, raising=False)