Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions deepspeed/module_inject/auto_ep_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")):
Expand Down
143 changes: 97 additions & 46 deletions deepspeed/module_inject/auto_ep_layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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)

Expand Down Expand Up @@ -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]:
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down
55 changes: 55 additions & 0 deletions deepspeed/moe/ep_tp_dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
*,
Expand Down
4 changes: 2 additions & 2 deletions docs/_pages/config-json.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand Down Expand Up @@ -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

Expand Down
Loading
Loading