Skip to content
Merged
72 changes: 62 additions & 10 deletions deepspeed/module_inject/auto_ep_comm.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,18 @@ def combine_with_weight_grad(self, rows: torch.Tensor, handle, weight_grads=None
num_sms=self.num_sms)
return combined, combined_weights

def combine_with_weight_grad_async(self, rows: torch.Tensor, handle, weight_grads=None):
""":meth:`combine_with_weight_grad` on DeepEP's stream, returning the event to wait on before reading.

The current stream does not wait for it, so work queued next runs while the combine is in flight.
"""
combined, combined_weights, event = self.buffer.combine(rows,
handle=handle,
topk_weights=weight_grads,
num_sms=self.num_sms,
async_with_compute_stream=True)
return combined, combined_weights, event

def combine(self, rows: torch.Tensor, handle) -> torch.Tensor:
"""Reduce expert outputs back to the tokens they came from.

Expand Down Expand Up @@ -382,6 +394,20 @@ def destroy(self) -> None:
self.buffer.destroy()


def run_with_sm_carveout(num_sms: int, compute):
"""Run ``compute`` with ``num_sms`` SMs withheld from the GEMMs it launches.

torch._grouped_mm launches persistent kernels sized to every SM, which would leave a concurrent communication
kernel nowhere to run.
"""
previous = torch._C._get_sm_carveout_experimental()
torch._C._set_sm_carveout_experimental(num_sms)
try:
return compute()
finally:
torch._C._set_sm_carveout_experimental(previous)


def _in_backward() -> bool:
"""Whether this thread is running inside an autograd backward pass."""
return torch._C._current_graph_task_id() != -1
Expand Down Expand Up @@ -462,12 +488,22 @@ class _DeepEPDispatch(torch.autograd.Function):
"""Forward dispatch whose backward is the matching combine."""

@staticmethod
def forward(ctx, exchange: DeepEPExchange, tokens: torch.Tensor, topk_idx: torch.Tensor,
topk_weights: torch.Tensor, recorded_handle):
def forward(ctx,
exchange: DeepEPExchange,
tokens: torch.Tensor,
topk_idx: torch.Tensor,
topk_weights: torch.Tensor,
recorded_handle=None,
weight_grad_slot=None,
*expert_weights):
if recorded_handle is None:
received, recv_weights, handle = exchange.dispatch(tokens, topk_idx, topk_weights)
else:
received, recv_weights, handle = exchange.replay_dispatch(tokens, topk_idx, topk_weights, recorded_handle)
# With a slot, the experts leave their weight gradients there, and this backward returns them: the expert
# weights are inputs here, though the dispatch does not read them.
ctx.weight_grad_slot = weight_grad_slot
ctx.num_expert_weights = len(expert_weights)
ctx.exchange = exchange
ctx.handle = handle
ctx.tokens_shape = tokens.shape
Expand All @@ -480,15 +516,23 @@ def forward(ctx, exchange: DeepEPExchange, tokens: torch.Tensor, topk_idx: torch

@staticmethod
def backward(ctx, grad_received, grad_recv_weights):
grad_tokens, grad_weights = ctx.exchange.combine_with_weight_grad(
grad_received.contiguous(),
ctx.handle,
None if grad_recv_weights is None else grad_recv_weights.contiguous(),
)
rows = grad_received.contiguous()
row_weights = None if grad_recv_weights is None else grad_recv_weights.contiguous()
expert_grads = (None, ) * ctx.num_expert_weights
if ctx.weight_grad_slot is None:
grad_tokens, grad_weights = ctx.exchange.combine_with_weight_grad(rows, ctx.handle, row_weights)
else:
# Send the experts' input gradient first, and compute their weight gradients while it is in flight.
grad_tokens, grad_weights, event = ctx.exchange.combine_with_weight_grad_async(
rows, ctx.handle, row_weights)
try:
expert_grads = run_with_sm_carveout(ctx.exchange.num_sms, ctx.weight_grad_slot.run)
finally:
event.current_stream_wait()
conformed_weights = None
if grad_weights is not None and ctx.weights_shape is not None:
conformed_weights = _conform_rows(grad_weights, ctx.weights_shape).reshape(ctx.weights_shape)
return None, _conform_rows(grad_tokens, ctx.tokens_shape), None, conformed_weights, None
return (None, _conform_rows(grad_tokens, ctx.tokens_shape), None, conformed_weights, None, None, *expert_grads)


def _save_combine_context(ctx, exchange: DeepEPExchange, rows: torch.Tensor, handle) -> None:
Expand Down Expand Up @@ -536,15 +580,23 @@ def deepep_dispatch(exchange: DeepEPExchange,
tokens: torch.Tensor,
topk_idx: torch.Tensor,
topk_weights: torch.Tensor,
replay: DeepEPCheckpointReplay | None = None):
replay: DeepEPCheckpointReplay | None = None,
*,
weight_grad_slot=None,
expert_weights=()):
"""Dispatch tokens and their routing weights, keeping both differentiable.

``weight_grad_slot`` and ``expert_weights`` overlap the backward: the experts leave the weight gradients of
``expert_weights`` in the slot, and this dispatch's backward computes them while it sends the experts' input
gradient back.

``replay`` is the calling layer's record of its forward dispatches, which
makes non-reentrant activation checkpointing recompute them faithfully.
"""
inside_backward = replay is not None and _in_backward()
recorded_handle = replay.forward_handle() if inside_backward else None
received, recv_weights = _DeepEPDispatch.apply(exchange, tokens, topk_idx, topk_weights, recorded_handle)
received, recv_weights = _DeepEPDispatch.apply(exchange, tokens, topk_idx, topk_weights, recorded_handle,
weight_grad_slot, *expert_weights)
# An outer reentrant checkpoint can build an inner graph during backward. A fresh grad-enabled dispatch
# still needs recording there; only a dispatch actually replaying a handle can reuse its existing entry.
if replay is not None and recorded_handle is None and torch.is_grad_enabled():
Expand Down
25 changes: 25 additions & 0 deletions deepspeed/module_inject/auto_ep_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ def parse_autoep_config(param_dict: dict) -> AutoEPConfig:
config.combine_impl = param_dict.get("combine_impl", "auto")
config.row_weighting_impl = param_dict.get("row_weighting_impl", "auto")
config.gate_up_impl = param_dict.get("gate_up_impl", "separate")
config.overlap_weight_grad = param_dict.get("overlap_weight_grad", False)
config.comm_backend = param_dict.get("comm_backend", "comm")
config.comm_num_sm = param_dict.get("comm_num_sm", 12)
config.comm_qp_margin = param_dict.get("comm_qp_margin", 4)
Expand Down Expand Up @@ -212,6 +213,30 @@ def validate_autoep_config(
raise ValueError(f"comm_backend must be one of {valid_comm_backend}, "
f"got '{config.comm_backend}'")

if not isinstance(config.overlap_weight_grad, bool):
raise ValueError(f"overlap_weight_grad must be true or false, got {config.overlap_weight_grad!r}")
if config.overlap_weight_grad:
if config.comm_backend != "deepep" or config.autoep_size == 1:
raise ValueError(
"overlap_weight_grad overlaps the experts' weight-gradient GEMMs with DeepEP's backward "
f'combine, but comm_backend="{config.comm_backend}" with autoep_size={config.autoep_size} '
'has none. Set comm_backend="deepep" with autoep_size > 1, or leave overlap_weight_grad '
"unset.")
if not config.use_grouped_mm:
raise ValueError("overlap_weight_grad defers the experts' torch._grouped_mm weight gradients, but "
"use_grouped_mm=false selects the sequential expert loop. Set use_grouped_mm=true, or "
"leave overlap_weight_grad unset.")
if zero_stage not in (1, 2):
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 not all(
hasattr(torch._C, name)
for name in ("_get_sm_carveout_experimental", "_set_sm_carveout_experimental")):
raise ValueError("overlap_weight_grad withholds DeepEP's SMs from the weight-gradient GEMMs through "
"torch._C._set_sm_carveout_experimental, which this PyTorch build lacks. Upgrade "
"PyTorch, or leave overlap_weight_grad unset.")

if config.row_weighting_impl == "fused":
if config.comm_backend != "deepep":
raise ValueError('row_weighting_impl="fused" only runs inside the DeepEP route, but '
Expand Down
21 changes: 18 additions & 3 deletions deepspeed/module_inject/auto_ep_layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
deepep_record_combine, new_exchange_scope, shared_exchange)
from deepspeed.moe.ep_router import TokenChoiceTopKRouter
from deepspeed.moe.ep_count import count_tokens_per_expert
from deepspeed.moe.ep_experts import GroupedExperts
from deepspeed.moe.ep_experts import ExpertWeightGradSlot, GroupedExperts
from deepspeed.moe.ep_repack import (_gather_source_zero_params, repack_expert_requires_grad_flags,
repack_expert_source_params, repack_expert_weights)

Expand Down Expand Up @@ -769,6 +769,11 @@ def __init__(
# Per layer, unlike the shared exchange: a checkpoint recompute must find this layer's forward handle.
self._deepep_replay = DeepEPCheckpointReplay()
self.comm_max_tokens_per_rank = config.comm_max_tokens_per_rank
self.overlap_weight_grad = config.overlap_weight_grad
if self.overlap_weight_grad and (self.experts.use_triton_grouped_mm or not self.experts.use_grouped_mm):
raise ValueError("overlap_weight_grad defers the experts' torch._grouped_mm weight gradients, but this "
"device selects the Triton grouped GEMM. Set disable_triton_grouped_mm=true, or leave "
"overlap_weight_grad unset.")

def _start_async_split_plan(self, num_tokens_per_expert: torch.Tensor) -> _PendingSplitPlan:
if self._async_split_plan_pending is not None:
Expand Down Expand Up @@ -1048,6 +1053,11 @@ def _deepep_route(self, tokens: torch.Tensor, ro: "RouterOutput") -> torch.Tenso
"job will produce, normally train_micro_batch_size_per_gpu * maximum padded sequence length, or "
'set comm_backend="comm".')

# With overlap, the experts' backward leaves their weight gradients in the slot, and the dispatch backward
# computes them while it sends the experts' input gradient back.
weight_grad_slot = ExpertWeightGradSlot() if self.overlap_weight_grad else None
expert_weights = (self.experts.w1, self.experts.w2, self.experts.w3) if self.overlap_weight_grad else ()

# In the decoder layer's reentrant recompute nothing reads this layer's output; the checkpoint only
# backpropagates through it. The post-expert row weighting and the combine then record their backward
# without running.
Expand All @@ -1059,7 +1069,9 @@ def _deepep_route(self, tokens: torch.Tensor, ro: "RouterOutput") -> torch.Tenso
tokens,
ro.selected_experts,
ro.top_scores,
replay=self._deepep_replay)
replay=self._deepep_replay,
weight_grad_slot=weight_grad_slot,
expert_weights=expert_weights)
handle = exchange.last_handle

# combine reads exactly the rows the handle says arrived, taken from
Expand Down Expand Up @@ -1093,7 +1105,10 @@ def _deepep_route(self, tokens: torch.Tensor, ro: "RouterOutput") -> torch.Tenso
raise RuntimeError(f"DeepEP returned {counts.numel()} expert counts, but this rank owns "
f"{self.num_local_experts} experts")

expert_output = self.experts(received, counts)
if weight_grad_slot is None:
expert_output = self.experts(received, counts)
else:
expert_output = self.experts(received, counts, weight_grad_slot=weight_grad_slot)

if weights is not None and record_only:
expert_output = record_deepep_row_weights(expert_output, weights, self.row_weighting_impl)
Expand Down
1 change: 1 addition & 0 deletions deepspeed/module_inject/auto_ep_presets/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ class AutoEPConfig:
combine_impl: Literal["auto", "weighted_sum", "fused_weighted_sum", "legacy_bmm"] = "auto"
row_weighting_impl: Literal["auto", "eager", "fused"] = "auto"
gate_up_impl: Literal["separate", "fused"] = "separate"
overlap_weight_grad: bool = False
comm_backend: Literal["comm", "deepep"] = "comm"
comm_num_sm: int = 12
comm_qp_margin: int = 4
Expand Down
Loading
Loading