diff --git a/deepspeed/module_inject/auto_ep_comm.py b/deepspeed/module_inject/auto_ep_comm.py index 0df8ce5761ff..c74898a52b8e 100644 --- a/deepspeed/module_inject/auto_ep_comm.py +++ b/deepspeed/module_inject/auto_ep_comm.py @@ -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. @@ -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 @@ -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 @@ -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: @@ -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(): diff --git a/deepspeed/module_inject/auto_ep_config.py b/deepspeed/module_inject/auto_ep_config.py index dbe8d7dd9ba6..7289b92f0e7f 100644 --- a/deepspeed/module_inject/auto_ep_config.py +++ b/deepspeed/module_inject/auto_ep_config.py @@ -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) @@ -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 ' diff --git a/deepspeed/module_inject/auto_ep_layer.py b/deepspeed/module_inject/auto_ep_layer.py index c54c4ab60cec..4c9550da5938 100644 --- a/deepspeed/module_inject/auto_ep_layer.py +++ b/deepspeed/module_inject/auto_ep_layer.py @@ -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) @@ -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: @@ -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. @@ -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 @@ -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) diff --git a/deepspeed/module_inject/auto_ep_presets/base.py b/deepspeed/module_inject/auto_ep_presets/base.py index 6cefb9068870..1abe1ec665d4 100644 --- a/deepspeed/module_inject/auto_ep_presets/base.py +++ b/deepspeed/module_inject/auto_ep_presets/base.py @@ -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 diff --git a/deepspeed/moe/ep_experts.py b/deepspeed/moe/ep_experts.py index 1771e44fc6fb..e579bc9227d2 100644 --- a/deepspeed/moe/ep_experts.py +++ b/deepspeed/moe/ep_experts.py @@ -42,7 +42,10 @@ class ExpertActivation: ``fn(gate, up, alpha, limit)`` computes the form in plain PyTorch; ``fused_fn`` has the same signature and runs a fused kernel, when the form has one. ``packed_fused_fn(gate_up, alpha, limit)`` is a fused kernel that reads ``gate`` and ``up`` packed side by side in one ``[..., 2 * I]`` tensor; - forms without one run ``fn`` on views of the two halves. ``uses_alpha`` and ``uses_limit`` say + forms without one run ``fn`` on views of the two halves. ``fused_backward_fn(grad, gate, up, alpha, limit)`` + and ``packed_fused_backward_fn(grad, gate_up, alpha, limit)`` return the gradients the fused kernels' own + backward computes, for callers that run the forward inside their own autograd function; without them such + callers recompute the forward to differentiate it. ``uses_alpha`` and ``uses_limit`` say which of the two scalars the form reads. ``gate_fn`` is the elementwise function the form applies to ``gate`` when it is ``gate_fn(gate) * up`` inside the clamp region; AutoEP compares it with the ``act_fn`` of the model's experts module to catch a preset that names the wrong form. It is @@ -54,6 +57,8 @@ class ExpertActivation: uses_limit: bool = False gate_fn: Callable[[torch.Tensor], torch.Tensor] | None = None packed_fused_fn: Callable[[torch.Tensor, float, float], torch.Tensor] | None = None + fused_backward_fn: Callable[..., tuple[torch.Tensor, torch.Tensor]] | None = None + packed_fused_backward_fn: Callable[..., torch.Tensor] | None = None #: The expert activations AutoEP can compute, by name. They are different functions: a model trained @@ -76,11 +81,14 @@ def register_expert_activation( uses_limit: bool = False, gate_fn: Callable[[torch.Tensor], torch.Tensor] | None = None, packed_fused_fn: Callable[[torch.Tensor, float, float], torch.Tensor] | None = None, + fused_backward_fn: Callable[..., tuple[torch.Tensor, torch.Tensor]] | None = None, + packed_fused_backward_fn: Callable[..., torch.Tensor] | None = None, ) -> None: """Make ``name`` selectable as a preset's or the config's ``expert_activation``.""" if name in EXPERT_ACTIVATIONS: raise ValueError(f"expert activation {name!r} is already registered") - EXPERT_ACTIVATIONS[name] = ExpertActivation(fn, fused_fn, uses_alpha, uses_limit, gate_fn, packed_fused_fn) + EXPERT_ACTIVATIONS[name] = ExpertActivation(fn, fused_fn, uses_alpha, uses_limit, gate_fn, packed_fused_fn, + fused_backward_fn, packed_fused_backward_fn) def get_expert_activation(name: str) -> ExpertActivation: @@ -108,6 +116,17 @@ def _swiglu_packed_fused(gate_up: torch.Tensor, alpha: float, limit: float) -> t return swiglu_packed(gate_up) +def _swiglu_fused_backward(grad: torch.Tensor, gate: torch.Tensor, up: torch.Tensor, alpha: float, limit: float): + from deepspeed.ops.triton_ops.swiglu_triton import swiglu_backward + return swiglu_backward(grad, gate, up) + + +def _swiglu_packed_fused_backward(grad: torch.Tensor, gate_up: torch.Tensor, alpha: float, + limit: float) -> torch.Tensor: + from deepspeed.ops.triton_ops.swiglu_triton import swiglu_packed_backward + return swiglu_packed_backward(grad, gate_up) + + def _geglu_tanh(gate: torch.Tensor, up: torch.Tensor, alpha: float, limit: float) -> torch.Tensor: return _gelu_tanh(gate) * up @@ -146,7 +165,9 @@ def _swiglu_oai_packed_fused(gate_up: torch.Tensor, alpha: float, limit: float) _swiglu, fused_fn=_swiglu_fused, gate_fn=F.silu, - packed_fused_fn=_swiglu_packed_fused) + packed_fused_fn=_swiglu_packed_fused, + fused_backward_fn=_swiglu_fused_backward, + packed_fused_backward_fn=_swiglu_packed_fused_backward) register_expert_activation("geglu_tanh", _geglu_tanh, gate_fn=_gelu_tanh) register_expert_activation("swiglu_clamped", _swiglu_clamped, @@ -390,6 +411,131 @@ def _run_experts_grouped_mm_fused_gate_up( return out +def _expert_activation_backward(grad: torch.Tensor, gate: torch.Tensor, up: torch.Tensor, activation: str, + alpha: float, limit: float) -> tuple[torch.Tensor, torch.Tensor]: + """Gradients of :func:`apply_expert_activation` with respect to ``gate`` and ``up``.""" + entry = get_expert_activation(activation) + if entry.fused_fn is not None and entry.fused_backward_fn is not None: + return entry.fused_backward_fn(grad, gate, up, alpha, limit) + forward = entry.fused_fn or entry.fn + with torch.enable_grad(): + gate = gate.detach().requires_grad_(True) + up = up.detach().requires_grad_(True) + return torch.autograd.grad(forward(gate, up, alpha, limit), (gate, up), grad) + + +def _packed_expert_activation_backward(grad: torch.Tensor, gate_up: torch.Tensor, activation: str, alpha: float, + limit: float) -> torch.Tensor: + """Gradient of :func:`apply_packed_expert_activation` with respect to ``gate_up``.""" + entry = get_expert_activation(activation) + if entry.packed_fused_fn is not None and entry.packed_fused_backward_fn is not None: + return entry.packed_fused_backward_fn(grad, gate_up, alpha, limit) + with torch.enable_grad(): + gate_up = gate_up.detach().requires_grad_(True) + return torch.autograd.grad(apply_packed_expert_activation(gate_up, activation, alpha, limit), gate_up, grad)[0] + + +class ExpertWeightGradSlot: + """Holds one expert forward's weight-gradient GEMMs until a later backward runs them. + + The expert backward returns its input gradient at once and leaves its weight gradients here, so the backward + that sends that input gradient onward can start the send first and compute the weight gradients while it is in + flight. + """ + + def __init__(self): + self._compute = None + + def defer(self, compute: Callable[[], tuple[torch.Tensor | None, torch.Tensor | None, + torch.Tensor | None]]) -> None: + if self._compute is not None: + raise RuntimeError("an expert weight gradient was deferred twice into one slot") + self._compute = compute + + def run(self) -> tuple[torch.Tensor | None, torch.Tensor | None, torch.Tensor | None]: + if self._compute is None: + raise RuntimeError("the expert backward did not run before the backward that computes its weight " + "gradients") + compute, self._compute = self._compute, None + return compute() + + +class _DeferredWeightGradExperts(torch.autograd.Function): + """The grouped-GEMM expert MLP, with its weight gradients optionally deferred to an :class:`ExpertWeightGradSlot`. + + Forward runs exactly what :func:`_run_experts_grouped_mm` (or its fused gate+up variant) runs. Backward forms the + products autograd forms for ``torch._grouped_mm`` (``_grouped_mm_mat1_backward`` and + ``_grouped_mm_mat2_backward``), so every gradient matches the plain path; only when the weight gradients are + computed changes. + """ + + @staticmethod + def forward(ctx, x, num_tokens_per_expert, w1, w2, w3, slot, activation, alpha, limit, fused_gate_up): + offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32) + dtype = x.dtype + w1c, w2c, w3c = w1.to(dtype), w2.to(dtype), w3.to(dtype) + if fused_gate_up: + w13 = torch.cat([w1c, w3c], dim=1) + gate_up = torch._grouped_mm(x, w13.transpose(-2, -1), offs=offsets) + h = apply_packed_expert_activation(gate_up, activation, alpha, limit) + ctx.save_for_backward(x, offsets, w2c, h, w13, gate_up) + else: + gate = torch._grouped_mm(x, w1c.transpose(-2, -1), offs=offsets) + up = torch._grouped_mm(x, w3c.transpose(-2, -1), offs=offsets) + h = apply_expert_activation(gate, up, activation, alpha, limit) + ctx.save_for_backward(x, offsets, w2c, h, w1c, w3c, gate, up) + ctx.slot = slot + ctx.activation = (activation, alpha, limit) + ctx.fused_gate_up = fused_gate_up + ctx.weight_dtypes = (w1.dtype, w2.dtype, w3.dtype) + return torch._grouped_mm(h, w2c.transpose(-2, -1), offs=offsets).type_as(x) + + @staticmethod + def backward(ctx, grad_out): + if torch.is_grad_enabled(): + raise RuntimeError("Deferred expert gradients have no second derivative; " + "backward with create_graph=True is not supported") + x, offsets, w2c, h, *projection = ctx.saved_tensors + grad_out = grad_out.contiguous() + grad_h = torch._grouped_mm(grad_out, w2c, offs=offsets) + if ctx.fused_gate_up: + w13, gate_up = projection + grad_gate_up = _packed_expert_activation_backward(grad_h, gate_up, *ctx.activation) + grad_x = torch._grouped_mm(grad_gate_up, w13, offs=offsets) + else: + w1c, w3c, gate, up = projection + grad_gate, grad_up = _expert_activation_backward(grad_h, gate, up, *ctx.activation) + grad_x = torch._grouped_mm(grad_gate, w1c, offs=offsets) + torch._grouped_mm(grad_up, w3c, offs=offsets) + + needs_w1, needs_w2, needs_w3 = ctx.needs_input_grad[2:5] + + def weight_grads(): + grad_w1 = grad_w2 = grad_w3 = None + if needs_w2: + grad_w2 = torch._grouped_mm(grad_out.transpose(-2, -1), h, offs=offsets) + if ctx.fused_gate_up: + if needs_w1 or needs_w3: + grad_w13 = torch._grouped_mm(grad_gate_up.transpose(-2, -1), x, offs=offsets) + inter = grad_w13.shape[1] // 2 + if needs_w1: + grad_w1 = grad_w13.narrow(1, 0, inter) + if needs_w3: + grad_w3 = grad_w13.narrow(1, inter, inter) + else: + if needs_w1: + grad_w1 = torch._grouped_mm(grad_gate.transpose(-2, -1), x, offs=offsets) + if needs_w3: + grad_w3 = torch._grouped_mm(grad_up.transpose(-2, -1), x, offs=offsets) + return tuple( + grad.to(dtype) if grad is not None else None + for grad, dtype in zip((grad_w1, grad_w2, grad_w3), ctx.weight_dtypes)) + + if ctx.slot is None: + return (grad_x, None, *weight_grads(), None, None, None, None, None) + ctx.slot.defer(weight_grads) + return (grad_x, ) + (None, ) * 9 + + # --------------------------------------------------------------------------- # Expert computation: Triton grouped GEMM (sm80 / sm86 fast path) # --------------------------------------------------------------------------- @@ -530,17 +676,26 @@ def forward( self, x: torch.Tensor, num_tokens_per_expert: torch.Tensor, + weight_grad_slot: ExpertWeightGradSlot | None = None, ) -> torch.Tensor: """ Args: x: Input tokens, shape ``(T, dim)``. num_tokens_per_expert: Token counts per expert, shape ``(E,)``. + weight_grad_slot: Where the backward leaves the weight-gradient GEMMs for a later backward to run; + the expert weights' gradients then reach them through that later backward. Needs the + ``torch._grouped_mm`` path. Returns: Output tensor of shape ``(T, dim)``. """ act = (self.activation, self.activation_alpha, self.activation_limit) + if weight_grad_slot is not None: + if self.use_triton_grouped_mm or not self.use_grouped_mm: + raise RuntimeError("deferring expert weight gradients needs the torch._grouped_mm path") + return _DeferredWeightGradExperts.apply(x, num_tokens_per_expert, self.w1, self.w2, self.w3, + weight_grad_slot, *act, self.gate_up_impl == "fused") if self.use_triton_grouped_mm: return _run_experts_triton_grouped_mm(self.w1, self.w2, self.w3, x, num_tokens_per_expert, *act) elif self.use_grouped_mm: diff --git a/deepspeed/ops/triton_ops/swiglu_triton.py b/deepspeed/ops/triton_ops/swiglu_triton.py index 8cc5a17c1b84..ec554df7ba44 100644 --- a/deepspeed/ops/triton_ops/swiglu_triton.py +++ b/deepspeed/ops/triton_ops/swiglu_triton.py @@ -96,14 +96,18 @@ def forward(ctx, gate: torch.Tensor, up: torch.Tensor) -> torch.Tensor: @staticmethod def backward(ctx, grad_out: torch.Tensor): gate, up = ctx.saved_tensors - grad_out = grad_out.contiguous() + return _swiglu_backward_triton(grad_out, gate, up) - grad_gate = torch.empty_like(gate) - grad_up = torch.empty_like(up) + def _swiglu_backward_triton(grad_out: torch.Tensor, gate: torch.Tensor, up: torch.Tensor): + grad_out = grad_out.contiguous() - n_elements = gate.numel() - if n_elements > 0: - grid = (triton.cdiv(n_elements, _BLOCK_SIZE), ) + grad_gate = torch.empty_like(gate) + grad_up = torch.empty_like(up) + + n_elements = gate.numel() + if n_elements > 0: + grid = (triton.cdiv(n_elements, _BLOCK_SIZE), ) + with torch.cuda.device(gate.device): #ignore-cuda _swiglu_bwd_kernel[grid](grad_out, gate, up, @@ -113,7 +117,7 @@ def backward(ctx, grad_out: torch.Tensor): BLOCK_SIZE=_BLOCK_SIZE, num_warps=_NUM_WARPS) - return grad_gate, grad_up + return grad_gate, grad_up @triton.jit def _swiglu_packed_fwd_kernel(gate_up_ptr, out_ptr, n_elements, INTER: tl.constexpr, BLOCK_SIZE: tl.constexpr): @@ -182,22 +186,25 @@ def backward(ctx, grad_out: torch.Tensor): raise RuntimeError("The packed SwiGLU kernel has no second derivative; " "backward with create_graph=True is not supported") gate_up, = ctx.saved_tensors - grad_out = grad_out.contiguous() - grad_gate_up = torch.empty_like(gate_up) + return _swiglu_packed_backward_triton(grad_out, gate_up) - n_elements = grad_out.numel() - if n_elements > 0: - grid = (triton.cdiv(n_elements, _BLOCK_SIZE), ) - with torch.cuda.device(gate_up.device): #ignore-cuda - _swiglu_packed_bwd_kernel[grid](grad_out, - gate_up, - grad_gate_up, - n_elements, - INTER=gate_up.shape[-1] // 2, - BLOCK_SIZE=_BLOCK_SIZE, - num_warps=_NUM_WARPS) + def _swiglu_packed_backward_triton(grad_out: torch.Tensor, gate_up: torch.Tensor) -> torch.Tensor: + grad_out = grad_out.contiguous() + grad_gate_up = torch.empty_like(gate_up) - return grad_gate_up + n_elements = grad_out.numel() + if n_elements > 0: + grid = (triton.cdiv(n_elements, _BLOCK_SIZE), ) + with torch.cuda.device(gate_up.device): #ignore-cuda + _swiglu_packed_bwd_kernel[grid](grad_out, + gate_up, + grad_gate_up, + n_elements, + INTER=gate_up.shape[-1] // 2, + BLOCK_SIZE=_BLOCK_SIZE, + num_warps=_NUM_WARPS) + + return grad_gate_up def _swiglu_eager(gate: torch.Tensor, up: torch.Tensor) -> torch.Tensor: @@ -229,6 +236,29 @@ def swiglu(gate: torch.Tensor, up: torch.Tensor) -> torch.Tensor: return _SwiGLUFn.apply(gate, up) +def swiglu_backward(grad_out: torch.Tensor, gate: torch.Tensor, up: torch.Tensor): + """The gradients of :func:`swiglu` with respect to ``gate`` and ``up``, as its own backward computes them. + + For callers that run the forward inside their own autograd function and keep ``gate`` and ``up``. + """ + if not _TRITON_AVAILABLE: + with torch.enable_grad(): + gate = gate.detach().requires_grad_(True) + up = up.detach().requires_grad_(True) + return torch.autograd.grad(_swiglu_eager(gate, up), (gate, up), grad_out) + return _swiglu_backward_triton(grad_out, gate.contiguous(), up.contiguous()) + + +def swiglu_packed_backward(grad_out: torch.Tensor, gate_up: torch.Tensor) -> torch.Tensor: + """The gradient of :func:`swiglu_packed` with respect to ``gate_up``, as its own backward computes it.""" + if not _TRITON_AVAILABLE: + with torch.enable_grad(): + gate_up = gate_up.detach().requires_grad_(True) + gate, up = gate_up.chunk(2, dim=-1) + return torch.autograd.grad(_swiglu_eager(gate, up), gate_up, grad_out)[0] + return _swiglu_packed_backward_triton(grad_out, gate_up.contiguous()) + + def swiglu_packed(gate_up: torch.Tensor) -> torch.Tensor: """Fused SwiGLU of a packed gate+up tensor: ``silu(gate_up[..., :I]) * gate_up[..., I:]``. diff --git a/deepspeed/runtime/engine.py b/deepspeed/runtime/engine.py index 54a645ac77bf..d4e00cf3a91d 100644 --- a/deepspeed/runtime/engine.py +++ b/deepspeed/runtime/engine.py @@ -848,7 +848,12 @@ def _configure_expert_parallel(self, model, collect_sources=None): pp_size = bwc_pipeline_parallel_world_size(self.mpu) world_size = dist.get_world_size() - validate_autoep_config(autoep_config, world_size, pp_size, tp_size, sp_size) + validate_autoep_config(autoep_config, + world_size, + pp_size, + tp_size, + sp_size, + zero_stage=self.zero_optimization_stage()) folding_spec = build_folding_spec( world_size=world_size, pp_size=pp_size, diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index 580ef14c80bc..ed5f42684c10 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -1023,6 +1023,12 @@ smoke coverage used for this AutoEP surface produced the following version gates | -------------------------------------------------------------------------------------------------------------- | -------- | | How the grouped experts compute their gate and up projections. `"separate"` runs two grouped GEMMs. `"fused"` is experimental and runs one `torch._grouped_mm` over the gate and up weights concatenated on each call, followed by an activation that reads the two halves of its output in place; for `swiglu` this is a Triton kernel with first-order gradients only (`create_graph=True` raises). Parameters, checkpoints and optimizer state keep the separate `w1`/`w3` layout. The forward expression and parameter-gradient semantics are unchanged, but exact numerical equality is not guaranteed across GEMM shapes/backends; the input gradient accumulates both projections in one FP32 GEMM instead of adding two rounded results. Requires `use_grouped_mm=true` and the `torch._grouped_mm` path (set `disable_triton_grouped_mm=true` on devices that prefer the Triton grouped GEMM); unsupported configurations fail rather than falling back. | `"separate"` | +***overlap_weight_grad***: [boolean] + +| 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` | + ***skip_recompute_combine***: [boolean] | Description | Default | diff --git a/docs/code-docs/source/autoep.rst b/docs/code-docs/source/autoep.rst index 845d4c41f97b..657c76000442 100644 --- a/docs/code-docs/source/autoep.rst +++ b/docs/code-docs/source/autoep.rst @@ -321,6 +321,60 @@ not run ``torch._grouped_mm``: with ``use_grouped_mm=false``, or on devices that select the Triton grouped GEMM (compute capability below 9.0) unless ``disable_triton_grouped_mm=true``. +**Overlapping expert weight gradients with the DeepEP backward (experimental):** + +In the backward pass, the experts compute their input gradient (dX), which +DeepEP then combines back to the ranks the tokens came from, and their weight +gradients (dW). The two are independent, but normally run one after the other: +a grouped GEMM's backward computes dX and dW together, before the combine +starts. ``overlap_weight_grad`` runs them side by side: + +.. code-block:: json + + { + "expert_parallel": { + "enabled": true, + "autoep_size": 8, + "comm_backend": "deepep", + "comm_max_tokens_per_rank": 16384, + "gate_up_impl": "fused", + "overlap_weight_grad": true + } + } + +The expert backward returns dX at once and leaves its dW GEMMs in a slot. The +DeepEP dispatch, which takes the expert weights as extra inputs, launches its +backward combine of dX on DeepEP's stream, runs the dW GEMMs on the compute +stream, waits for the combine, and returns dW through autograd, so ZeRO's +gradient handling is unchanged. ``torch._grouped_mm`` launches persistent +kernels sized to every SM, which would leave the combine nowhere to run, so the +dW GEMMs are launched with ``comm_num_sm`` SMs withheld through PyTorch's +experimental SM carveout, restored immediately afterwards. +The asynchronous combine is waited on even if a weight-gradient GEMM raises. +Frozen expert weights omit their dW GEMMs and return no gradient. With fused +gate+up, the shared dW GEMM is omitted only when both projections are frozen. + +The same gradient products autograd forms for ``torch._grouped_mm`` run in a +different schedule; exact numerical equality across algorithms or hardware +is not guaranteed. This path supports first-order gradients only and rejects +``create_graph=True`` rather than constructing an incomplete derivative. + +On Qwen3-30B-A3B with 8 H100s (expert parallel size 8, micro-batch 4, 16 +accumulation steps, sequence length 4096, reentrant activation checkpointing, +``gate_up_impl="fused"``), a full optimizer step went from 21.57 s to 21.10 s +(-2.2%) in two pairs measured in the same job; overlapping without the SM +carveout recovered only -0.7%. A kernel profile showed DeepEP running alongside +the grouped GEMMs for 1.3 s of the step, against none before. Peak allocated +memory was unchanged and reserved memory about 0.7 GB higher. + +``overlap_weight_grad`` is rejected, rather than silently ignored, unless +``comm_backend="deepep"`` with ``autoep_size > 1``, the experts run +``torch._grouped_mm`` (``use_grouped_mm=true``, and +``disable_triton_grouped_mm=true`` on devices that select the Triton grouped +GEMM), ZeRO stage is 1 or 2 (not 0 or 3), and PyTorch provides both +``torch._C._get_sm_carveout_experimental`` and +``torch._C._set_sm_carveout_experimental``. + **DeepEP row weighting implementation (experimental):** DeepEP dispatch returns one received row per routed assignment and one FP32 diff --git a/tests/unit/module_inject/test_auto_ep_comm.py b/tests/unit/module_inject/test_auto_ep_comm.py index e7a5046d5ed5..5391c48d7ee5 100644 --- a/tests/unit/module_inject/test_auto_ep_comm.py +++ b/tests/unit/module_inject/test_auto_ep_comm.py @@ -370,7 +370,7 @@ def fake_combine(_exchange, rows, _handle, **kwargs): seen["combine_kwargs"] = kwargs return rows - def fake_experts(rows, counts): + def fake_experts(rows, counts, _weight_grad_slot=None): seen["expert_input"] = rows seen["counts"] = counts return rows @@ -380,6 +380,7 @@ def fake_experts(rows, counts): num_local_experts=self.LOCAL_EXPERTS, score_apply=score_apply, row_weighting_impl=row_weighting_impl, + overlap_weight_grad=False, comm_num_sm=12, comm_qp_margin=4, experts=fake_experts, @@ -456,9 +457,10 @@ def fake_fused(rows, weights): num_local_experts=2, score_apply="post", row_weighting_impl="fused", + overlap_weight_grad=False, comm_num_sm=12, comm_qp_margin=4, - experts=lambda rows, _counts: rows, + experts=lambda rows, _counts, _slot=None: rows, ) with mock.patch.object(auto_ep_layer, "deepep_dispatch", fake_dispatch), \ @@ -538,6 +540,7 @@ def experts(rows, counts): num_local_experts=self.LOCAL_EXPERTS, score_apply=score_apply, row_weighting_impl="eager", + overlap_weight_grad=False, comm_num_sm=12, comm_qp_margin=4, experts=experts) @@ -602,6 +605,7 @@ def layer(ep_size=2, comm_backend=DEEPEP_BACKEND, *, return_router_logits=False) layer.combine_impl = "weighted_sum" layer._fused_combine_checked = False layer.row_weighting_impl = "eager" + layer.overlap_weight_grad = False layer._fused_row_weighting_checked = False layer.ep_size = ep_size layer.comm_backend = comm_backend @@ -812,6 +816,174 @@ def test_the_forward_dispatch_records_an_expanded_layout(self): self.assertIs(exchange.buffer.dispatch.call_args.kwargs["do_expand"], True) +class TestWeightGradOverlap(unittest.TestCase): + """The dispatch backward sends the experts' input gradient while computing their weight gradients. + + It must produce exactly the serial backward's gradients, start the combine before the weight-gradient GEMMs, + withhold DeepEP's SMs from those GEMMs only while launching them, and wait before reading the combine. + """ + + TOKENS, TOP_K, EXPERTS, HIDDEN, INTER = 24, 2, 4, 16, 8 + + class Buffer: + """DeepEP's expanded dispatch/combine contract on one rank, with the asynchronous combine.""" + + def __init__(self, test, log): + self.test = test + self.log = log + + def dispatch(self, tokens, *, topk_idx=None, topk_weights=None, handle=None, do_expand=False, **kwargs): + test = self.test + if handle is None: + slots = [(token, slot) for expert in range(test.EXPERTS) + for token, slot in (topk_idx == expert).nonzero().tolist()] + counts = torch.bincount(topk_idx.flatten(), minlength=test.EXPERTS) + handle = SimpleNamespace(do_expand=True, + topk_idx=topk_idx.clone(), + token_of_row=torch.tensor([token for token, _ in slots]), + slot_of_row=torch.tensor([slot for _, slot in slots]), + num_expanded_tokens=len(slots), + psum_num_recv_tokens_per_expert=torch.cumsum(counts, 0)) + weights = None if topk_weights is None else topk_weights[handle.token_of_row, handle.slot_of_row] + return tokens[handle.token_of_row], None, weights, handle, None + + def combine(self, rows, *, handle, topk_weights=None, async_with_compute_stream=False, **kwargs): + test, log = self.test, self.log + log.append("combine_async" if async_with_compute_stream else "combine") + combined = rows.new_zeros(test.TOKENS, rows.shape[1]).index_add(0, handle.token_of_row, rows) + combined_weights = None + if topk_weights is not None: + combined_weights = topk_weights.new_zeros(test.TOKENS, test.TOP_K) + combined_weights[handle.token_of_row, handle.slot_of_row] = topk_weights + return combined, combined_weights, SimpleNamespace(current_stream_wait=lambda: log.append("wait")) + + def setUp(self): + try: + torch._grouped_mm(torch.zeros(4, 16), torch.zeros(1, 16, 8), offs=torch.tensor([4], dtype=torch.int32)) + except (AttributeError, RuntimeError, NotImplementedError): + self.skipTest("this PyTorch build has no CPU torch._grouped_mm") + torch.manual_seed(0) + self.routing = torch.randint(0, self.EXPERTS - 1, (self.TOKENS, self.TOP_K)) # one expert stays empty + self.inputs = torch.randn(self.TOKENS, self.HIDDEN) + self.gate = torch.randn(self.HIDDEN, self.TOP_K) + self.weights = [ + torch.randn(self.EXPERTS, self.INTER, self.HIDDEN) * 0.3, + torch.randn(self.EXPERTS, self.HIDDEN, self.INTER) * 0.3, + torch.randn(self.EXPERTS, self.INTER, self.HIDDEN) * 0.3 + ] + self.target = torch.randn(self.TOKENS, self.HIDDEN) + + def run_route(self, overlap, gate_up_impl="separate", checkpoint=None): + from deepspeed.moe.ep_experts import ExpertWeightGradSlot, GroupedExperts + + log = [] + exchange = auto_ep_comm.DeepEPExchange.__new__(auto_ep_comm.DeepEPExchange) + exchange.buffer = self.Buffer(self, log) + exchange.deep_ep = SimpleNamespace(topk_idx_t=torch.int64) + exchange.num_experts, exchange.num_sms, exchange.last_handle = self.EXPERTS, 12, None + # A form without a Triton kernel, so the CPU route runs wherever Triton is installed. + experts = GroupedExperts(dim=self.HIDDEN, + hidden_dim=self.INTER, + num_experts=self.EXPERTS, + use_grouped_mm=True, + disable_triton_grouped_mm=True, + activation="geglu_tanh", + gate_up_impl=gate_up_impl) + with torch.no_grad(): + for name, value in zip(("w1", "w2", "w3"), self.weights): + getattr(experts, name).copy_(value) + x = self.inputs.clone().requires_grad_(True) + gate = self.gate.clone().requires_grad_(True) + replay = auto_ep_comm.DeepEPCheckpointReplay() + + def route(x, gate): + scores = torch.softmax(x @ gate, dim=-1) + slot = ExpertWeightGradSlot() if overlap else None + expert_weights = (experts.w1, experts.w2, experts.w3) if overlap else () + received, recv_weights, _ = auto_ep_comm.deepep_dispatch(exchange, + x, + self.routing, + scores, + replay=replay, + weight_grad_slot=slot, + expert_weights=expert_weights) + handle = exchange.last_handle + prefix = handle.psum_num_recv_tokens_per_expert + counts = torch.diff(prefix, prepend=prefix.new_zeros(1)).to(torch.int32) + rows = experts(received, counts, slot) * recv_weights.reshape(-1, 1) + return auto_ep_comm.deepep_combine(exchange, rows, handle) + + carveouts = [] + original_run = auto_ep_comm.run_with_sm_carveout + + def recorded_run(num_sms, compute): + log.append(f"weight_grads_with_{num_sms}_sms_withheld") + carveouts.append(num_sms) + return original_run(num_sms, compute) + + with mock.patch.object(auto_ep_comm, "run_with_sm_carveout", recorded_run): + if checkpoint is None: + combined = route(x, gate) + else: + combined = torch.utils.checkpoint.checkpoint(route, x, gate, use_reentrant=checkpoint == "reentrant") + (combined * self.target).sum().backward() + grads = {"output": combined.detach(), "x": x.grad, "gate": gate.grad} + grads.update({name: getattr(experts, name).grad for name in ("w1", "w2", "w3")}) + return grads, log + + def test_overlap_matches_the_serial_backward_bitwise(self): + for gate_up_impl in ("separate", "fused"): + serial, serial_log = self.run_route(False, gate_up_impl) + for checkpoint_mode in (None, "reentrant", "non_reentrant"): + with self.subTest(gate_up_impl=gate_up_impl, checkpoint=checkpoint_mode): + overlapped, log = self.run_route(True, gate_up_impl, checkpoint_mode) + for name, expected in serial.items(): + torch.testing.assert_close(overlapped[name], expected, rtol=0, atol=0, msg=name) + # The backward combine is launched before the weight gradients and read only after them. + self.assertEqual(log[-3:], ["combine_async", "weight_grads_with_12_sms_withheld", "wait"]) + self.assertEqual(serial_log, ["combine", "combine"]) + + def test_the_sm_carveout_is_restored(self): + torch._C._set_sm_carveout_experimental(None) + seen = [] + result = auto_ep_comm.run_with_sm_carveout(12, lambda: seen.append(torch._C._get_sm_carveout_experimental())) + self.assertIsNone(result) + self.assertEqual(seen, [12]) + self.assertIsNone(torch._C._get_sm_carveout_experimental()) + with self.assertRaises(RuntimeError): + auto_ep_comm.run_with_sm_carveout(12, lambda: (_ for _ in ()).throw(RuntimeError("compute failed"))) + self.assertIsNone(torch._C._get_sm_carveout_experimental()) + + def test_failed_weight_gradients_still_wait_for_the_async_combine(self): + from deepspeed.moe.ep_experts import ExpertWeightGradSlot + + log = [] + exchange = auto_ep_comm.DeepEPExchange.__new__(auto_ep_comm.DeepEPExchange) + exchange.buffer = self.Buffer(self, log) + exchange.deep_ep = SimpleNamespace(topk_idx_t=torch.int64) + exchange.num_experts, exchange.num_sms, exchange.last_handle = self.EXPERTS, 12, None + slot = ExpertWeightGradSlot() + + def fail_weight_gradients(): + log.append("weight_grads_failed") + raise RuntimeError("weight gradients failed") + + slot.defer(fail_weight_gradients) + inputs = self.inputs.clone().requires_grad_(True) + weights = [weight.clone().requires_grad_(True) for weight in self.weights] + received, _, _ = auto_ep_comm.deepep_dispatch(exchange, + inputs, + self.routing, + torch.ones(self.TOKENS, self.TOP_K), + weight_grad_slot=slot, + expert_weights=weights) + previous = torch._C._get_sm_carveout_experimental() + with self.assertRaisesRegex(RuntimeError, "weight gradients failed"): + received.sum().backward() + self.assertEqual(log[-3:], ["combine_async", "weight_grads_failed", "wait"]) + self.assertEqual(torch._C._get_sm_carveout_experimental(), previous) + + class TestCheckpointRecomputeLayout(unittest.TestCase): """Activation-checkpoint recompute must reproduce the forward's dispatch layout. @@ -1124,7 +1296,8 @@ def test_dispatch_backward_returns_a_gradient_per_input(self): # ctx is not an input autograd returns a gradient for. inputs = len(inspect.signature(_DeepEPDispatch.forward).parameters) - 1 - self.assertEqual(inputs, 5) + # The expert weights arrive as varargs when the backward overlaps, and return through *expert_grads. + self.assertEqual(inputs, 7) self.assertEqual(self.gradient_count(_DeepEPDispatch.backward), inputs) def test_combine_backward_returns_a_gradient_per_input(self): diff --git a/tests/unit/v1/moe/test_autoep_deepep_parity.py b/tests/unit/v1/moe/test_autoep_deepep_parity.py index 0a537bc4b70d..054f47d29f18 100644 --- a/tests/unit/v1/moe/test_autoep_deepep_parity.py +++ b/tests/unit/v1/moe/test_autoep_deepep_parity.py @@ -30,7 +30,7 @@ from deepspeed.module_inject.auto_ep_comm import DeepEPExchange, destroy_exchanges from deepspeed.module_inject.auto_ep_layer import AutoEPMoELayer from deepspeed.ops.triton_ops import autoep_fused_token_ops as fused_ops -from deepspeed.utils import safe_get_full_fp32_param +from deepspeed.utils import safe_get_full_fp32_param, safe_get_full_grad from unit.common import DistributedTest from unit.v1.moe.autoep_test_utils import ( @@ -229,7 +229,9 @@ def _build_test_engine(backend, *, row_weighting_impl="auto", score_apply=None, - skip_recompute_combine=False): + skip_recompute_combine=False, + zero_stage=1, + **expert_parallel): seed_everything(seed) config = make_autoep_config(ep_size=ep_size) @@ -238,6 +240,7 @@ def _build_test_engine(backend, # dtype anyway for the comparison to mean anything. config.pop("fp16", None) config["bf16"] = {"enabled": True} + config["zero_optimization"]["stage"] = zero_stage 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 @@ -246,6 +249,7 @@ def _build_test_engine(backend, config["expert_parallel"]["row_weighting_impl"] = row_weighting_impl if score_apply is not None: config["expert_parallel"]["score_apply"] = score_apply + config["expert_parallel"].update(expert_parallel) if skip_recompute_combine: config["expert_parallel"]["skip_recompute_combine"] = True if backend == "deepep": @@ -282,14 +286,18 @@ def _run_one_step(backend, decoder_layer_checkpointing=False, skip_recompute_combine=False, steps=1, - seq_len=SEQ_LEN): + seq_len=SEQ_LEN, + zero_stage=1, + **expert_parallel): """Build a model on ``backend``, run one step, return its output and grads.""" engine = _build_test_engine(backend, ep_size, seed, row_weighting_impl=row_weighting_impl, score_apply=score_apply, - skip_recompute_combine=skip_recompute_combine) + skip_recompute_combine=skip_recompute_combine, + zero_stage=zero_stage, + **expert_parallel) if backend == "deepep" and not cleanup: _install_legacy_deepep_prep(engine) if skewed_routing: @@ -331,10 +339,13 @@ def capture_route(_module, _inputs, output, *, _name=name): loss = output.float().pow(2).mean() engine.backward(loss) - gradients = { - name: parameter.grad.detach().float().clone() - for name, parameter in engine.module.named_parameters() if parameter.grad is not None - } + gradients = {} + for name, parameter in engine.module.named_parameters(): + if not parameter.requires_grad: + continue + gradient = safe_get_full_grad(parameter) + assert gradient is not None, f"Expected accumulated gradient for {name} before clipping" + gradients[name] = gradient.detach().float().clone() score_gradient_parts = {} for name, scores in score_tensors: if scores.grad is not None: @@ -671,6 +682,42 @@ def test_fused_row_weighting_handles_empty_experts_and_skewed_routing(self, scor assert torch.count_nonzero(all_routes == 3) == 0 assert torch.count_nonzero(all_routes == 1) > torch.count_nonzero(all_routes == 2) + @pytest.mark.parametrize("gate_up_impl", ["separate", "fused"]) + @pytest.mark.parametrize("skewed_routing", [False, True]) + @pytest.mark.parametrize("zero_stage", [1, 2]) + def test_overlapped_weight_gradients_match_the_serial_backward(self, gate_up_impl, skewed_routing, zero_stage): + """overlap_weight_grad changes when the experts' weight gradients are computed, not their values. + + The two runs dispatch separately, so DeepEP's arrival order can differ between them and change summation + order; gradients a backward mismatched by the overlap would be off by order one rather than by rounding. + """ + skip_unless_h100_tests_enabled("DeepEP backward overlap needs H100s and a DeepEP build") + seed = 4321 + common = dict(skewed_routing=skewed_routing, + zero_stage=zero_stage, + activation_checkpointing=True, + reentrant_checkpointing=True, + gate_up_impl=gate_up_impl, + use_grouped_mm=True, + disable_triton_grouped_mm=True) + + serial = _run_one_step("deepep", self.world_size, seed, **common) + overlapped = _run_one_step("deepep", self.world_size, seed, overlap_weight_grad=True, **common) + + for result in (serial, overlapped): + assert result["exchanges"], "the test did not exercise DeepEP" + for exchange in result["exchanges"]: + assert isinstance(exchange.buffer, exchange.deep_ep.ElasticBuffer) + + _assert_cleanup_results_close(overlapped, serial, compare_score_gradients=False) + pairs = [("input_gradient", overlapped["input_gradient"], serial["input_gradient"])] + pairs += [(name, overlapped["gradients"][name], grad) for name, grad in serial["gradients"].items()] + for name, actual, expected in pairs: + if expected.norm() > 0: + error = ((actual - expected).norm() / expected.norm()).item() + assert error < 1e-2, f"{name} relative L2 error {error:.3e}" + assert torch._C._get_sm_carveout_experimental() is None, "the SM carveout leaked out of the backward" + @pytest.mark.parametrize("skewed_routing", [False, True]) @pytest.mark.parametrize("nested", [False, True], ids=["non-reentrant", "nested-in-reentrant"]) def test_non_reentrant_checkpointing_replays_the_forward_dispatch_layout(self, skewed_routing, nested): diff --git a/tests/unit/v1/moe/test_autoep_expert_activation.py b/tests/unit/v1/moe/test_autoep_expert_activation.py index 6824db26da93..30dff3aab603 100644 --- a/tests/unit/v1/moe/test_autoep_expert_activation.py +++ b/tests/unit/v1/moe/test_autoep_expert_activation.py @@ -30,6 +30,7 @@ from deepspeed.module_inject.auto_ep_presets.registry import resolve_preset_candidates from deepspeed.moe.ep_experts import ( EXPERT_ACTIVATIONS, + ExpertWeightGradSlot, GroupedExperts, _zero_empty_expert_grad, apply_expert_activation, @@ -384,6 +385,78 @@ def validate(**settings): disable_triton_grouped_mm=True, gate_up_impl="fused").gate_up_impl == "fused" + def test_overlap_weight_grad_settings_are_validated(self, monkeypatch): + + def validate(zero_stage=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) + + assert parse_autoep_config({"enabled": True}).overlap_weight_grad is False + validate(overlap_weight_grad=True, zero_stage=1) + validate(overlap_weight_grad=True, zero_stage=2) + validate(overlap_weight_grad=False, zero_stage=0) + with pytest.raises(ValueError, match="must be true or false"): + validate(overlap_weight_grad="yes") + with pytest.raises(ValueError, match='Set comm_backend="deepep"'): + validate(overlap_weight_grad=True, comm_backend="comm") + with pytest.raises(ValueError, match="sequential expert loop"): + validate(overlap_weight_grad=True, use_grouped_mm=False) + for stage in (0, 3): + with pytest.raises(ValueError, match=f"ZeRO stage {stage}"): + validate(overlap_weight_grad=True, zero_stage=stage) + 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) + with pytest.raises(ValueError, match="lacks"): + validate(overlap_weight_grad=True) + + def test_overlap_weight_grad_rejects_the_triton_grouped_gemm(self, monkeypatch): + monkeypatch.setattr(type(get_accelerator()), "prefer_triton_grouped_mm", lambda self: True) + model = _custom_pattern_model() + auto_ep = AutoEP(model, + _runtime_config(moe_layer_pattern=MOE_PATTERN, use_grouped_mm=True, overlap_weight_grad=True)) + [spec] = auto_ep.ep_parser() + with pytest.raises(ValueError, match="disable_triton_grouped_mm=true"): + auto_ep.replace_moe_layer(spec, ep_size=1, ep_rank=0) + + @pytest.mark.parametrize("zero_stage", [0, 1, 2, 3]) + def test_engine_passes_the_actual_zero_stage_to_overlap_validation(self, monkeypatch, zero_stage): + from deepspeed.runtime import engine as engine_module + from deepspeed.module_inject import auto_ep_config + + class ValidationReached(Exception): + pass + + config = parse_autoep_config({ + "enabled": True, + "autoep_size": 2, + "comm_backend": "deepep", + "comm_max_tokens_per_rank": 64, + "overlap_weight_grad": True + }) + shell = SimpleNamespace(_config=SimpleNamespace(expert_parallel_config=config), + mpu=None, + autotp_size=lambda: 1, + _autoep_sequence_parallel_world_size=lambda: 1, + zero_optimization_stage=lambda: zero_stage) + validate = auto_ep_config.validate_autoep_config + + def validate_then_stop(*args, **kwargs): + validate(*args, **kwargs) + raise ValidationReached + + # Exercise the engine wiring before building collectives: its previous omitted keyword treated every + # actual optimizer stage as stage 0, even when the direct configuration validation was correct. + monkeypatch.setattr(auto_ep_config, "validate_autoep_config", validate_then_stop) + monkeypatch.setattr(engine_module.dist, "get_world_size", lambda: 2) + if zero_stage in (1, 2): + with pytest.raises(ValidationReached): + engine_module.DeepSpeedEngine._configure_expert_parallel(shell, nn.Identity()) + else: + with pytest.raises(ValueError, match=f"ZeRO stage {zero_stage}"): + engine_module.DeepSpeedEngine._configure_expert_parallel(shell, nn.Identity()) + def test_config_reaches_the_replaced_experts(self): if not hasattr(torch, "_grouped_mm"): pytest.skip("this PyTorch build has no torch._grouped_mm") @@ -525,6 +598,161 @@ def test_accumulated_updates_and_checkpoint_keep_the_separate_parameters(self, a atol=0) +def _grouped_mm_runs_on(device): + try: + torch._grouped_mm(torch.zeros(4, 16, device=device), + torch.zeros(1, 16, 8, device=device), + offs=torch.tensor([4], dtype=torch.int32, device=device)) + except (AttributeError, RuntimeError, NotImplementedError): + return False + return True + + +class TestDeferredExpertWeightGrad: + """Deferred gradients obey the plain path's contract; only their computation schedule changes.""" + + def _compare(self, device, dtype, activation, gate_up_impl, deferred): + torch.manual_seed(0) + kwargs = dict(dim=16, + hidden_dim=8, + num_experts=4, + use_grouped_mm=True, + disable_triton_grouped_mm=True, + activation=activation, + activation_alpha=1.5, + activation_limit=1.0, + gate_up_impl=gate_up_impl) + plain = GroupedExperts(**kwargs) + for weight in plain.parameters(): + nn.init.normal_(weight, std=0.4) + overlapped = GroupedExperts(**kwargs) + overlapped.load_state_dict(plain.state_dict()) + plain.to(device=device, dtype=dtype) + overlapped.to(device=device, dtype=dtype) + counts = torch.tensor([5, 0, 7, 12], device=device) + x = torch.randn(24, 16, device=device, dtype=dtype) + grad_out = torch.randn(24, 16, device=device, dtype=dtype) + x_plain, x_overlapped = x.clone().requires_grad_(True), x.clone().requires_grad_(True) + out_plain = plain(x_plain, counts) + out_plain.backward(grad_out) + slot = ExpertWeightGradSlot() if deferred else None + out_overlapped = overlapped(x_overlapped, counts, slot) + out_overlapped.backward(grad_out) + if deferred: + assert all(weight.grad is None for weight in overlapped.parameters()) + for weight, grad in zip((overlapped.w1, overlapped.w2, overlapped.w3), slot.run()): + weight.grad = grad + + torch.testing.assert_close(out_overlapped, out_plain, rtol=0, atol=0) + torch.testing.assert_close(x_overlapped.grad, x_plain.grad, rtol=0, atol=0) + for name in ("w1", "w2", "w3"): + torch.testing.assert_close(getattr(overlapped, name).grad, getattr(plain, name).grad, rtol=0, atol=0) + + @pytest.mark.parametrize("deferred", [False, True]) + @pytest.mark.parametrize("gate_up_impl", ["separate", "fused"]) + @pytest.mark.parametrize("activation", tuple(EXPERT_ACTIVATIONS)) + def test_matches_the_plain_path_exactly_on_cpu(self, activation, gate_up_impl, deferred): + if not _grouped_mm_runs_on("cpu"): + pytest.skip("this PyTorch build has no CPU torch._grouped_mm") + if EXPERT_ACTIVATIONS[activation].fused_fn is not None and is_triton_available(): + pytest.skip("with Triton installed, this form's grouped path needs CUDA tensors") + for dtype in (torch.float32, torch.bfloat16): + self._compare("cpu", dtype, activation, gate_up_impl, deferred) + + @pytest.mark.parametrize("gate_up_impl", ["separate", "fused"]) + @pytest.mark.parametrize("activation", tuple(EXPERT_ACTIVATIONS)) + def test_matches_the_plain_path_exactly_with_the_fused_kernels(self, activation, gate_up_impl): + if get_accelerator().device_name() != "cuda" or not hasattr(torch, "_grouped_mm"): + pytest.skip("needs CUDA with torch._grouped_mm") + self._compare(get_accelerator().current_device_name(), torch.bfloat16, activation, gate_up_impl, True) + + @pytest.mark.parametrize("gate_up_impl", ["separate", "fused"]) + @pytest.mark.parametrize("trainable", [(False, False, False), (False, True, False), (True, False, False), + (False, False, True)]) + def test_frozen_weight_gradients_are_not_computed(self, gate_up_impl, trainable, record_property): + if get_accelerator().device_name() == "cuda": + device, dtype = get_accelerator().current_device_name(), torch.bfloat16 + else: + if not _grouped_mm_runs_on("cpu"): + pytest.skip("this PyTorch build has no CPU torch._grouped_mm") + device, dtype = "cpu", torch.float32 + torch.manual_seed(0) + kwargs = dict(dim=16, + hidden_dim=8, + num_experts=3, + disable_triton_grouped_mm=True, + activation="geglu_tanh", + gate_up_impl=gate_up_impl) + plain, overlapped = GroupedExperts(**kwargs), GroupedExperts(**kwargs) + for weight in plain.parameters(): + nn.init.normal_(weight, std=0.4) + overlapped.load_state_dict(plain.state_dict()) + for experts in (plain, overlapped): + experts.to(device=device, dtype=dtype) + for name, requires_grad in zip(("w1", "w2", "w3"), trainable): + getattr(experts, name).requires_grad_(requires_grad) + counts = torch.tensor([3, 0, 5], device=device) + hidden = torch.randn(8, 16, device=device, dtype=dtype) + grad_output = torch.randn_like(hidden) + results, gemm_counts = [], [] + for experts in (plain, overlapped): + inputs = hidden.clone().requires_grad_(True) + slot = ExpertWeightGradSlot() if experts is overlapped else None + with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU]) as profile: + output = experts(inputs, counts, weight_grad_slot=slot) + output.backward(grad_output) + if slot is not None: + for name, grad in zip(("w1", "w2", "w3"), slot.run()): + weight = getattr(experts, name) + assert (grad is None) == (not weight.requires_grad) + weight.grad = grad + # Frozen gradients already match numerically; the regression is redundant GEMM work. + gemm_counts.append(sum(event.count for event in profile.key_averages() + if event.key == "aten::_grouped_mm")) + results.append((output, inputs.grad)) + for actual, expected in zip(results[1], results[0]): + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + for name in ("w1", "w2", "w3"): + torch.testing.assert_close(getattr(overlapped, name).grad, getattr(plain, name).grad, rtol=0, atol=0) + assert gemm_counts[0] > 0 + assert gemm_counts[1] == gemm_counts[0] + record_property("serial_grouped_mm_count", gemm_counts[0]) + record_property("overlapped_grouped_mm_count", gemm_counts[1]) + + @pytest.mark.parametrize("gate_up_impl", ["separate", "fused"]) + def test_create_graph_is_rejected(self, gate_up_impl): + if not _grouped_mm_runs_on("cpu"): + pytest.skip("this PyTorch build has no CPU torch._grouped_mm") + experts = GroupedExperts(dim=16, + hidden_dim=8, + num_experts=1, + disable_triton_grouped_mm=True, + activation="geglu_tanh", + gate_up_impl=gate_up_impl) + for weight in experts.parameters(): + nn.init.normal_(weight, std=0.1) + hidden = torch.ones((4, 16), requires_grad=True) + output = experts(hidden, torch.tensor([4]), weight_grad_slot=ExpertWeightGradSlot()) + with pytest.raises(RuntimeError, match="second derivative"): + torch.autograd.grad(output.sum(), hidden, create_graph=True) + + def test_slot_runs_once_after_the_expert_backward(self): + slot = ExpertWeightGradSlot() + with pytest.raises(RuntimeError, match="did not run before"): + slot.run() + slot.defer(lambda: (1, 2, 3)) + with pytest.raises(RuntimeError, match="deferred twice"): + slot.defer(lambda: (1, 2, 3)) + assert slot.run() == (1, 2, 3) + with pytest.raises(RuntimeError, match="did not run before"): + slot.run() + + def test_deferring_needs_the_grouped_mm_path(self): + experts = GroupedExperts(dim=8, hidden_dim=16, num_experts=2, use_grouped_mm=False) + with pytest.raises(RuntimeError, match="torch._grouped_mm path"): + experts(torch.randn(4, 8), torch.tensor([2, 2]), ExpertWeightGradSlot()) + + class TestPresetAndConfig: def test_builtin_presets_name_their_form(self): diff --git a/tests/unit/v1/moe/test_autoep_unit.py b/tests/unit/v1/moe/test_autoep_unit.py index 24d773ad3c7f..fe77c10a1b97 100644 --- a/tests/unit/v1/moe/test_autoep_unit.py +++ b/tests/unit/v1/moe/test_autoep_unit.py @@ -503,12 +503,13 @@ def ep_parser(self): observed = {} - def record_validate(config, world_size, pp_size, tp_size, sp_size): + def record_validate(config, world_size, pp_size, tp_size, sp_size, zero_stage=None): observed["validate"] = { "world_size": world_size, "pp_size": pp_size, "tp_size": tp_size, "sp_size": sp_size, + "zero_stage": zero_stage, } def record_create(**kwargs): @@ -537,6 +538,7 @@ def record_create(**kwargs): assert groups.mpu is None assert observed["validate"]["sp_size"] == 2 + assert observed["validate"]["zero_stage"] == 0 assert observed["create"]["mp_size"] == 2 assert observed["create"]["mp_mode"] == "sp" diff --git a/tests/unit/v1/ops/triton_ops/test_swiglu_triton.py b/tests/unit/v1/ops/triton_ops/test_swiglu_triton.py index 621bf83739d0..e2ba91e71477 100644 --- a/tests/unit/v1/ops/triton_ops/test_swiglu_triton.py +++ b/tests/unit/v1/ops/triton_ops/test_swiglu_triton.py @@ -28,11 +28,13 @@ @pytest.fixture(autouse=True) def _load_swiglu_in_the_worker(): - global get_accelerator, swiglu, swiglu_packed, swiglu_clamped, swiglu_clamped_packed + global get_accelerator, swiglu, swiglu_packed, swiglu_backward, swiglu_packed_backward + global swiglu_clamped, swiglu_clamped_packed # The shared Triton availability probe initializes its driver, so it must run after pytest forks its worker. from deepspeed.accelerator import get_accelerator from deepspeed.ops.triton_ops import is_triton_available - from deepspeed.ops.triton_ops.swiglu_triton import swiglu, swiglu_packed, swiglu_clamped, swiglu_clamped_packed + from deepspeed.ops.triton_ops.swiglu_triton import (swiglu, swiglu_packed, swiglu_backward, swiglu_packed_backward, + swiglu_clamped, swiglu_clamped_packed) if not is_triton_available(): pytest.skip("Triton is not available") @@ -137,6 +139,44 @@ def test_packed_matches_the_separate_kernel_exactly(dtype, shape): torch.testing.assert_close(gate_up.grad, torch.cat([gate.grad, up.grad], dim=-1), rtol=0, atol=0) +@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16]) +def test_standalone_backward_matches_autograd_exactly(dtype): + # Callers that run the forward inside their own autograd function differentiate it with these. + dev = get_accelerator().current_device_name() + gate = torch.randn(7, 384, device=dev, dtype=dtype, requires_grad=True) + up = torch.randn(7, 384, device=dev, dtype=dtype, requires_grad=True) + gate_up = torch.cat([gate, up], dim=-1).detach().requires_grad_(True) + grad_out = torch.randn(7, 384, device=dev, dtype=dtype) + swiglu(gate, up).backward(grad_out) + swiglu_packed(gate_up).backward(grad_out) + + grad_gate, grad_up = swiglu_backward(grad_out, gate.detach(), up.detach()) + torch.testing.assert_close(grad_gate, gate.grad, rtol=0, atol=0) + torch.testing.assert_close(grad_up, up.grad, rtol=0, atol=0) + torch.testing.assert_close(swiglu_packed_backward(grad_out, gate_up.detach()), gate_up.grad, rtol=0, atol=0) + + +@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16]) +def test_standalone_backwards_select_the_input_device(dtype): + accelerator = get_accelerator() + if accelerator.device_count() < 2: + pytest.skip("standalone cross-device backward needs two CUDA devices") + with torch.cuda.device(1): #ignore-cuda + gate = torch.ones((7, 13), device=accelerator.current_device_name(), dtype=dtype, requires_grad=True) + up = torch.full_like(gate, 0.5, requires_grad=True) + packed = torch.cat((gate, up), dim=-1).detach().requires_grad_(True) + upstream = torch.ones_like(gate) + swiglu(gate, up).backward(upstream) + swiglu_packed(packed).backward(upstream) + with torch.cuda.device(0): #ignore-cuda + grad_gate, grad_up = swiglu_backward(upstream, gate.detach(), up.detach()) + grad_packed = swiglu_packed_backward(upstream, packed.detach()) + assert accelerator.current_device() == 0 + torch.testing.assert_close(grad_gate, gate.grad, rtol=0, atol=0) + torch.testing.assert_close(grad_up, up.grad, rtol=0, atol=0) + torch.testing.assert_close(grad_packed, packed.grad, rtol=0, atol=0) + + @pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16]) def test_packed_non_contiguous_input_and_gradient(dtype): dev = get_accelerator().current_device_name()