From e80c269ba4c68ef054d6b62ab94a938cec55351e Mon Sep 17 00:00:00 2001 From: yh0903 Date: Mon, 16 Nov 2026 20:26:27 -0800 Subject: [PATCH] AutoEP: opt-in routing weights inside the expert activation Apply the reviewed activation-weighting child delta on top of the merged overlap implementation, retaining current replay, skip-combine, frozen-parameter and clamped-activation contracts. Return routing-score gradients alongside input gradients while deferring only parameter gradients. Keep the disabled default unchanged and the weighted kernel arithmetic from the accepted implementation. Cover activation weighting together with skip-combine and the existing ZeRO-1/2 overlap matrix; retain the bounded numerical and historical performance claims. Signed-off-by: yh0903 --- deepspeed/module_inject/auto_ep_config.py | 9 +- deepspeed/module_inject/auto_ep_layer.py | 26 ++- .../module_inject/auto_ep_presets/base.py | 2 +- deepspeed/moe/ep_experts.py | 163 +++++++++++-- deepspeed/ops/triton_ops/swiglu_triton.py | 214 ++++++++++++++++++ docs/_pages/config-json.md | 2 +- docs/code-docs/source/autoep.rst | 34 +++ tests/unit/module_inject/test_auto_ep_comm.py | 67 +++++- .../unit/v1/moe/test_autoep_deepep_parity.py | 69 +++++- .../v1/moe/test_autoep_expert_activation.py | 136 ++++++++++- tests/unit/v1/moe/test_autoep_unit.py | 26 +++ .../v1/ops/triton_ops/test_swiglu_triton.py | 133 +++++++++++ 12 files changed, 838 insertions(+), 43 deletions(-) diff --git a/deepspeed/module_inject/auto_ep_config.py b/deepspeed/module_inject/auto_ep_config.py index 7289b92f0e7f..38e1358905b9 100644 --- a/deepspeed/module_inject/auto_ep_config.py +++ b/deepspeed/module_inject/auto_ep_config.py @@ -194,7 +194,7 @@ def validate_autoep_config( f"got '{config.combine_impl}'") # Validate row_weighting_impl - valid_row_weighting_impl = ("auto", "eager", "fused") + valid_row_weighting_impl = ("auto", "eager", "fused", "activation") if config.row_weighting_impl not in valid_row_weighting_impl: raise ValueError(f"row_weighting_impl must be one of {valid_row_weighting_impl}, " f"got '{config.row_weighting_impl}'") @@ -237,13 +237,14 @@ def validate_autoep_config( "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.row_weighting_impl in ("fused", "activation"): + impl = config.row_weighting_impl if config.comm_backend != "deepep": - raise ValueError('row_weighting_impl="fused" only runs inside the DeepEP route, but ' + raise ValueError(f'row_weighting_impl="{impl}" only runs inside the DeepEP route, but ' f'comm_backend="{config.comm_backend}" was selected. Set comm_backend to ' '"deepep", or leave row_weighting_impl unset.') if config.autoep_size == 1: - raise ValueError('row_weighting_impl="fused" only runs when DeepEP dispatch is active ' + raise ValueError(f'row_weighting_impl="{impl}" only runs when DeepEP dispatch is active ' '(autoep_size > 1), but autoep_size=1. Increase autoep_size, or leave ' "row_weighting_impl unset.") diff --git a/deepspeed/module_inject/auto_ep_layer.py b/deepspeed/module_inject/auto_ep_layer.py index 4c9550da5938..a21e97f8ee55 100644 --- a/deepspeed/module_inject/auto_ep_layer.py +++ b/deepspeed/module_inject/auto_ep_layer.py @@ -115,7 +115,8 @@ def resolve_combine_impl( return "weighted_sum" -def resolve_row_weighting_impl(config_override: Literal["auto", "eager", "fused"]) -> Literal["eager", "fused"]: +def resolve_row_weighting_impl( + config_override: Literal["auto", "eager", "fused", "activation"]) -> Literal["eager", "fused", "activation"]: """Resolve DeepEP row weighting implementation from config override.""" if config_override != "auto": return config_override @@ -586,6 +587,11 @@ def __init__( # The decoder layer holding this layer, set by attach_decoder_layer; held weakly, as the decoder layer # owns this module. self._decoder_layer = None + if self.row_weighting_impl == "activation" and self.score_apply != "post": + raise ValueError('row_weighting_impl="activation" applies the routing weights inside the expert ' + 'activation, after the experts\' first projections, so it requires score_apply to ' + f'resolve to "post"; preset \'{spec.model_family}\' resolves it to ' + f'"{self.score_apply}". Use "eager" or "fused" for this model.') self._fused_combine_checked = False self._fused_row_weighting_checked = False route_norm = spec.route_norm if config.route_norm is None else config.route_norm @@ -1105,15 +1111,23 @@ 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") - if weight_grad_slot is None: + if weights is not None and self.row_weighting_impl == "activation": + # The down projection is linear and has no bias, so scaling its input rows by the routing weights + # scales its output rows the same way, without a separate pass over the expert output. + expert_output = self.experts(received, + counts, + weight_grad_slot=weight_grad_slot, + row_weights=weights.reshape(-1)) + elif 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) - elif weights is not None: - expert_output = apply_deepep_row_weights(expert_output, weights, self.row_weighting_impl) + if weights is not None and self.row_weighting_impl != "activation": + if record_only: + expert_output = record_deepep_row_weights(expert_output, weights, self.row_weighting_impl) + else: + expert_output = apply_deepep_row_weights(expert_output, weights, self.row_weighting_impl) if record_only: return deepep_record_combine(exchange, expert_output, handle) diff --git a/deepspeed/module_inject/auto_ep_presets/base.py b/deepspeed/module_inject/auto_ep_presets/base.py index 1abe1ec665d4..366e9878344f 100644 --- a/deepspeed/module_inject/auto_ep_presets/base.py +++ b/deepspeed/module_inject/auto_ep_presets/base.py @@ -122,7 +122,7 @@ class AutoEPConfig: route_scale: float = 1.0 score_apply: Literal["auto", "pre", "post"] = "auto" combine_impl: Literal["auto", "weighted_sum", "fused_weighted_sum", "legacy_bmm"] = "auto" - row_weighting_impl: Literal["auto", "eager", "fused"] = "auto" + row_weighting_impl: Literal["auto", "eager", "fused", "activation"] = "auto" gate_up_impl: Literal["separate", "fused"] = "separate" overlap_weight_grad: bool = False comm_backend: Literal["comm", "deepep"] = "comm" diff --git a/deepspeed/moe/ep_experts.py b/deepspeed/moe/ep_experts.py index e579bc9227d2..303c5147cf28 100644 --- a/deepspeed/moe/ep_experts.py +++ b/deepspeed/moe/ep_experts.py @@ -49,7 +49,8 @@ class ExpertActivation: 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 - ``None`` for forms that are not such a product. + ``None`` for forms that are not such a product. ``weighted_fused_fn(gate, up, weights, alpha, limit)`` runs a + fused kernel that also scales each row by one FP32 weight, when the form has one. """ fn: Callable[[torch.Tensor, torch.Tensor, float, float], torch.Tensor] fused_fn: Callable[[torch.Tensor, torch.Tensor, float, float], torch.Tensor] | None = None @@ -59,6 +60,10 @@ class ExpertActivation: 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 + weighted_fused_fn: Callable[..., torch.Tensor] | None = None + weighted_fused_backward_fn: Callable[..., tuple[torch.Tensor, torch.Tensor, torch.Tensor]] | None = None + packed_weighted_fused_fn: Callable[..., torch.Tensor] | None = None + packed_weighted_fused_backward_fn: Callable[..., tuple[torch.Tensor, torch.Tensor]] | None = None #: The expert activations AutoEP can compute, by name. They are different functions: a model trained @@ -83,12 +88,18 @@ def register_expert_activation( 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, + weighted_fused_fn: Callable[..., torch.Tensor] | None = None, + weighted_fused_backward_fn: Callable[..., tuple[torch.Tensor, torch.Tensor, torch.Tensor]] | None = None, + packed_weighted_fused_fn: Callable[..., torch.Tensor] | None = None, + packed_weighted_fused_backward_fn: Callable[..., tuple[torch.Tensor, 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, - fused_backward_fn, packed_fused_backward_fn) + fused_backward_fn, packed_fused_backward_fn, weighted_fused_fn, + weighted_fused_backward_fn, packed_weighted_fused_fn, + packed_weighted_fused_backward_fn) def get_expert_activation(name: str) -> ExpertActivation: @@ -111,6 +122,12 @@ def _swiglu_fused(gate: torch.Tensor, up: torch.Tensor, alpha: float, limit: flo return swiglu(gate, up) +def _swiglu_weighted_fused(gate: torch.Tensor, up: torch.Tensor, weights: torch.Tensor, alpha: float, + limit: float) -> torch.Tensor: + from deepspeed.ops.triton_ops.swiglu_triton import swiglu_weighted + return swiglu_weighted(gate, up, weights) + + def _swiglu_packed_fused(gate_up: torch.Tensor, alpha: float, limit: float) -> torch.Tensor: from deepspeed.ops.triton_ops.swiglu_triton import swiglu_packed return swiglu_packed(gate_up) @@ -127,6 +144,21 @@ def _swiglu_packed_fused_backward(grad: torch.Tensor, gate_up: torch.Tensor, alp return swiglu_packed_backward(grad, gate_up) +def _swiglu_weighted_backward(grad, gate, up, weights, alpha, limit): + from deepspeed.ops.triton_ops.swiglu_triton import swiglu_weighted_backward + return swiglu_weighted_backward(grad, gate, up, weights) + + +def _swiglu_packed_weighted(gate_up, weights, alpha, limit): + from deepspeed.ops.triton_ops.swiglu_triton import swiglu_packed_weighted + return swiglu_packed_weighted(gate_up, weights) + + +def _swiglu_packed_weighted_backward(grad, gate_up, weights, alpha, limit): + from deepspeed.ops.triton_ops.swiglu_triton import swiglu_packed_weighted_backward + return swiglu_packed_weighted_backward(grad, gate_up, weights) + + def _geglu_tanh(gate: torch.Tensor, up: torch.Tensor, alpha: float, limit: float) -> torch.Tensor: return _gelu_tanh(gate) * up @@ -167,7 +199,11 @@ def _swiglu_oai_packed_fused(gate_up: torch.Tensor, alpha: float, limit: float) gate_fn=F.silu, packed_fused_fn=_swiglu_packed_fused, fused_backward_fn=_swiglu_fused_backward, - packed_fused_backward_fn=_swiglu_packed_fused_backward) + packed_fused_backward_fn=_swiglu_packed_fused_backward, + weighted_fused_fn=_swiglu_weighted_fused, + weighted_fused_backward_fn=_swiglu_weighted_backward, + packed_weighted_fused_fn=_swiglu_packed_weighted, + packed_weighted_fused_backward_fn=_swiglu_packed_weighted_backward) register_expert_activation("geglu_tanh", _geglu_tanh, gate_fn=_gelu_tanh) register_expert_activation("swiglu_clamped", _swiglu_clamped, @@ -188,13 +224,22 @@ def apply_expert_activation(gate: torch.Tensor, activation: str = "swiglu", alpha: float = 1.702, limit: float = 7.0, - fused: bool = True) -> torch.Tensor: + fused: bool = True, + row_weights: torch.Tensor | None = None) -> torch.Tensor: """Combine the gate and up projections of an expert MLP with the named activation. ``fused`` selects the form's fused kernel when it has one; ``fused=False`` keeps everything in plain PyTorch, which also runs on CPU tensors. + + ``row_weights``, one FP32 weight per row, scales each row of the result. It is computed in FP32 + and rounded once: in the form's weighted kernel when it has one, else in plain PyTorch. """ entry = get_expert_activation(activation) + if row_weights is not None: + _validate_row_weights(row_weights, gate) + if fused and entry.weighted_fused_fn is not None: + return entry.weighted_fused_fn(gate, up, row_weights, alpha, limit) + return (entry.fn(gate.float(), up.float(), alpha, limit) * row_weights.reshape(-1, 1)).to(gate.dtype) if fused and entry.fused_fn is not None: return entry.fused_fn(gate, up, alpha, limit) return entry.fn(gate, up, alpha, limit) @@ -204,19 +249,34 @@ def apply_packed_expert_activation(gate_up: torch.Tensor, activation: str = "swiglu", alpha: float = 1.702, limit: float = 7.0, - fused: bool = True) -> torch.Tensor: + fused: bool = True, + row_weights: torch.Tensor | None = None) -> torch.Tensor: """:func:`apply_expert_activation` for ``gate`` and ``up`` packed side by side in ``[..., 2 * I]``. Forms without a packed kernel run on views of the two halves, which their elementwise ops read in place. """ entry = get_expert_activation(activation) + if row_weights is not None: + _validate_row_weights(row_weights, gate_up) + if fused and entry.packed_weighted_fused_fn is not None: + return entry.packed_weighted_fused_fn(gate_up, row_weights, alpha, limit) + gate, up = gate_up.chunk(2, dim=-1) + return apply_expert_activation(gate, up, activation, alpha, limit, fused=False, row_weights=row_weights) if fused and entry.packed_fused_fn is not None: return entry.packed_fused_fn(gate_up, alpha, limit) gate, up = gate_up.chunk(2, dim=-1) return entry.fn(gate, up, alpha, limit) +def _validate_row_weights(weights: torch.Tensor, rows: torch.Tensor) -> None: + if weights.dtype != torch.float32 or weights.shape != (rows.shape[0], ): + raise ValueError( + f"row_weights must be FP32 with shape ({rows.shape[0]},), got {weights.dtype} {tuple(weights.shape)}") + if weights.device != rows.device: + raise ValueError(f"row_weights must be on {rows.device}, got {weights.device}") + + # --------------------------------------------------------------------------- # Expert computation: sequential for-loop (reference path) # --------------------------------------------------------------------------- @@ -231,6 +291,7 @@ def _run_experts_for_loop( activation: str = "swiglu", alpha: float = 1.702, limit: float = 7.0, + row_weights: torch.Tensor | None = None, ) -> torch.Tensor: """Compute SwiGLU expert MLP via a sequential for-loop over experts. @@ -245,6 +306,7 @@ def _run_experts_for_loop( activation: Expert activation name from ``EXPERT_ACTIVATIONS``. alpha: ``alpha`` for the forms that read it. limit: Clamp limit for the forms that read it. + row_weights: Optional FP32 weight per input row, shape ``(T,)``, applied inside the activation. Returns: Output tensor of shape ``(T, dim)``. @@ -260,6 +322,9 @@ def _run_experts_for_loop( split_size_or_sections=num_tokens_per_expert_list, dim=0, ) + weight_splits = [None] * len(x_splits) + if row_weights is not None: + weight_splits = torch.split(row_weights[:sum(num_tokens_per_expert_list)], num_tokens_per_expert_list) cast_dtype = x.dtype out_experts_splits = [] @@ -270,7 +335,13 @@ def _run_experts_for_loop( gate = torch.matmul(x_expert, w1_e) up = torch.matmul(x_expert, w3_e) # fused=False keeps the reference path in plain PyTorch, so it still runs on CPU tensors. - h = apply_expert_activation(gate, up, activation, alpha, limit, fused=False) + h = apply_expert_activation(gate, + up, + activation, + alpha, + limit, + fused=False, + row_weights=weight_splits[expert_idx]) h = torch.matmul(h, w2_e) out_experts_splits.append(h) @@ -327,6 +398,7 @@ def _run_experts_grouped_mm( activation: str = "swiglu", alpha: float = 1.702, limit: float = 7.0, + row_weights: torch.Tensor | None = None, ) -> torch.Tensor: """Compute SwiGLU expert MLP via torch._grouped_mm (grouped GEMM). @@ -338,7 +410,7 @@ def _run_experts_grouped_mm( w3: Up weight, shape ``(E, hidden_dim, dim)``. x: Input tokens, shape ``(T, dim)``. num_tokens_per_expert: Token counts per expert, shape ``(E,)``. - activation, alpha, limit: As in :func:`_run_experts_for_loop`. + activation, alpha, limit, row_weights: As in :func:`_run_experts_for_loop`. Returns: Output tensor of shape ``(T, dim)``. @@ -359,7 +431,7 @@ def _run_experts_grouped_mm( w3.to(cast_dtype).transpose(-2, -1), offs=offsets, ) - h = apply_expert_activation(gate, up, activation, alpha, limit) + h = apply_expert_activation(gate, up, activation, alpha, limit, row_weights=row_weights) out = torch._grouped_mm( h, w2.to(cast_dtype).transpose(-2, -1), @@ -378,6 +450,7 @@ def _run_experts_grouped_mm_fused_gate_up( activation: str = "swiglu", alpha: float = 1.702, limit: float = 7.0, + row_weights: torch.Tensor | None = None, ) -> torch.Tensor: """:func:`_run_experts_grouped_mm` with the gate and up projections in one grouped GEMM. @@ -401,7 +474,7 @@ def _run_experts_grouped_mm_fused_gate_up( w13.transpose(-2, -1), offs=offsets, ) - h = apply_packed_expert_activation(gate_up, activation, alpha, limit) + h = apply_packed_expert_activation(gate_up, activation, alpha, limit, row_weights=row_weights) out = torch._grouped_mm( h, w2.to(cast_dtype).transpose(-2, -1), @@ -435,6 +508,26 @@ def _packed_expert_activation_backward(grad: torch.Tensor, gate_up: torch.Tensor return torch.autograd.grad(apply_packed_expert_activation(gate_up, activation, alpha, limit), gate_up, grad)[0] +def _weighted_expert_activation_backward(grad, gate, up, weights, activation, alpha, limit): + entry = get_expert_activation(activation) + if entry.weighted_fused_fn is not None and entry.weighted_fused_backward_fn is not None: + return entry.weighted_fused_backward_fn(grad, gate, up, weights, alpha, limit) + with torch.enable_grad(): + gate, up, weights = (tensor.detach().requires_grad_(True) for tensor in (gate, up, weights)) + output = apply_expert_activation(gate, up, activation, alpha, limit, row_weights=weights) + return torch.autograd.grad(output, (gate, up, weights), grad) + + +def _packed_weighted_expert_activation_backward(grad, gate_up, weights, activation, alpha, limit): + entry = get_expert_activation(activation) + if entry.packed_weighted_fused_fn is not None and entry.packed_weighted_fused_backward_fn is not None: + return entry.packed_weighted_fused_backward_fn(grad, gate_up, weights, alpha, limit) + with torch.enable_grad(): + gate_up, weights = (tensor.detach().requires_grad_(True) for tensor in (gate_up, weights)) + output = apply_packed_expert_activation(gate_up, activation, alpha, limit, row_weights=weights) + return torch.autograd.grad(output, (gate_up, weights), grad) + + class ExpertWeightGradSlot: """Holds one expert forward's weight-gradient GEMMs until a later backward runs them. @@ -470,20 +563,22 @@ class _DeferredWeightGradExperts(torch.autograd.Function): """ @staticmethod - def forward(ctx, x, num_tokens_per_expert, w1, w2, w3, slot, activation, alpha, limit, fused_gate_up): + def forward(ctx, x, num_tokens_per_expert, w1, w2, w3, slot, activation, alpha, limit, fused_gate_up, row_weights): 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) + optional_weights = () if row_weights is None else (row_weights, ) + ctx.has_row_weights = row_weights is not None 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) + h = apply_packed_expert_activation(gate_up, activation, alpha, limit, row_weights=row_weights) + ctx.save_for_backward(x, offsets, w2c, h, w13, gate_up, *optional_weights) 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) + h = apply_expert_activation(gate, up, activation, alpha, limit, row_weights=row_weights) + ctx.save_for_backward(x, offsets, w2c, h, w1c, w3c, gate, up, *optional_weights) ctx.slot = slot ctx.activation = (activation, alpha, limit) ctx.fused_gate_up = fused_gate_up @@ -496,15 +591,25 @@ def backward(ctx, grad_out): 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 + row_weights = projection.pop() if ctx.has_row_weights else None + grad_row_weights = None 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) + if row_weights is None: + grad_gate_up = _packed_expert_activation_backward(grad_h, gate_up, *ctx.activation) + else: + grad_gate_up, grad_row_weights = _packed_weighted_expert_activation_backward( + grad_h, gate_up, row_weights, *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) + if row_weights is None: + grad_gate, grad_up = _expert_activation_backward(grad_h, gate, up, *ctx.activation) + else: + grad_gate, grad_up, grad_row_weights = _weighted_expert_activation_backward( + grad_h, gate, up, row_weights, *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] @@ -531,9 +636,9 @@ def weight_grads(): 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) + return (grad_x, None, *weight_grads(), None, None, None, None, None, grad_row_weights) ctx.slot.defer(weight_grads) - return (grad_x, ) + (None, ) * 9 + return (grad_x, ) + (None, ) * 9 + (grad_row_weights, ) # --------------------------------------------------------------------------- @@ -550,6 +655,7 @@ def _run_experts_triton_grouped_mm( activation: str = "swiglu", alpha: float = 1.702, limit: float = 7.0, + row_weights: torch.Tensor | None = None, ) -> torch.Tensor: """Compute SwiGLU expert MLP via the Triton grouped GEMM drop-in. @@ -571,7 +677,7 @@ def _run_experts_triton_grouped_mm( dtype = x.dtype gate = group_gemm_triton(x, w1.to(dtype), offsets, trans_b=True) up = group_gemm_triton(x, w3.to(dtype), offsets, trans_b=True) - h = apply_expert_activation(gate, up, activation, alpha, limit) + h = apply_expert_activation(gate, up, activation, alpha, limit, row_weights=row_weights) out = group_gemm_triton(h, w2.to(dtype), offsets, trans_b=True).type_as(x) return out @@ -677,11 +783,16 @@ def forward( x: torch.Tensor, num_tokens_per_expert: torch.Tensor, weight_grad_slot: ExpertWeightGradSlot | None = None, + *, + row_weights: torch.Tensor | None = None, ) -> torch.Tensor: """ Args: x: Input tokens, shape ``(T, dim)``. num_tokens_per_expert: Token counts per expert, shape ``(E,)``. + row_weights: Optional FP32 weight per row, shape ``(T,)``, that scales each row inside the + activation, before the down projection. The down projection is linear and has no bias, so + this scales each output row by its weight. 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. @@ -691,16 +802,20 @@ def forward( """ act = (self.activation, self.activation_alpha, self.activation_limit) + if row_weights is not None: + _validate_row_weights(row_weights, x) 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") + weight_grad_slot, *act, self.gate_up_impl == "fused", row_weights) if self.use_triton_grouped_mm: - return _run_experts_triton_grouped_mm(self.w1, self.w2, self.w3, x, num_tokens_per_expert, *act) + return _run_experts_triton_grouped_mm(self.w1, self.w2, self.w3, x, num_tokens_per_expert, *act, + row_weights) elif self.use_grouped_mm: if self.gate_up_impl == "fused": - return _run_experts_grouped_mm_fused_gate_up(self.w1, self.w2, self.w3, x, num_tokens_per_expert, *act) - return _run_experts_grouped_mm(self.w1, self.w2, self.w3, x, num_tokens_per_expert, *act) + return _run_experts_grouped_mm_fused_gate_up(self.w1, self.w2, self.w3, x, num_tokens_per_expert, *act, + row_weights) + return _run_experts_grouped_mm(self.w1, self.w2, self.w3, x, num_tokens_per_expert, *act, row_weights) else: - return _run_experts_for_loop(self.w1, self.w2, self.w3, x, num_tokens_per_expert, *act) + return _run_experts_for_loop(self.w1, self.w2, self.w3, x, num_tokens_per_expert, *act, row_weights) diff --git a/deepspeed/ops/triton_ops/swiglu_triton.py b/deepspeed/ops/triton_ops/swiglu_triton.py index ec554df7ba44..02ea4e146a9e 100644 --- a/deepspeed/ops/triton_ops/swiglu_triton.py +++ b/deepspeed/ops/triton_ops/swiglu_triton.py @@ -20,6 +20,11 @@ When Triton is unavailable the public :func:`swiglu` falls back to the eager PyTorch expression so callers on non-Triton builds keep working unchanged. +:func:`swiglu_weighted` also scales each row by one FP32 weight inside the same +kernel, ``h = silu(gate) * up * weight``, with one rounding to the input dtype. +An MoE layer can apply its routing weights there rather than to the expert +output, since the down projection that follows is linear. + :func:`swiglu_packed` takes ``gate`` and ``up`` packed side by side in one ``[..., 2 * I]`` tensor, the output of a single gate+up GEMM, and reads both halves in place with the same math, so the packed GEMM output needs no copy. @@ -30,6 +35,7 @@ import torch import torch.nn.functional as F +from deepspeed.accelerator import get_accelerator from deepspeed.ops.triton_ops._triton import _TRITON_AVAILABLE, triton, tl if _TRITON_AVAILABLE: @@ -206,6 +212,121 @@ def _swiglu_packed_backward_triton(grad_out: torch.Tensor, gate_up: torch.Tensor return grad_gate_up + @triton.jit + def _swiglu_weighted_fwd_kernel(gate_ptr, up_ptr, weight_ptr, out_ptr, n_elements, n_cols, + ROW_STRIDE: tl.constexpr, BLOCK_SIZE: tl.constexpr): + pid = tl.program_id(axis=0).to(tl.int64) + offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + mask = offsets < n_elements + + input_offsets = (offsets // n_cols) * ROW_STRIDE + offsets % n_cols + gate = tl.load(gate_ptr + input_offsets, mask=mask).to(tl.float32) + up = tl.load(up_ptr + input_offsets, mask=mask).to(tl.float32) + weight = tl.load(weight_ptr + offsets // n_cols, mask=mask) + + out = gate * tl.sigmoid(gate) * up * weight + tl.store(out_ptr + offsets, out.to(out_ptr.dtype.element_ty), mask=mask) + + @triton.jit + def _swiglu_weighted_bwd_kernel(grad_out_ptr, gate_ptr, up_ptr, weight_ptr, grad_gate_ptr, grad_up_ptr, + grad_weight_ptr, n_cols, ROW_STRIDE: tl.constexpr, GRAD_ROW_STRIDE: tl.constexpr, + BLOCK_SIZE: tl.constexpr): + # One program per row: the row's weight gradient is a sum over its columns. + row = tl.program_id(axis=0).to(tl.int64) + weight = tl.load(weight_ptr + row) + total = tl.zeros([BLOCK_SIZE], dtype=tl.float32) + for start in range(0, n_cols, BLOCK_SIZE): + cols = start + tl.arange(0, BLOCK_SIZE) + mask = cols < n_cols + offsets = row * n_cols + cols + grad_out = tl.load(grad_out_ptr + offsets, mask=mask, other=0.0).to(tl.float32) + input_offsets = row * ROW_STRIDE + cols + gate = tl.load(gate_ptr + input_offsets, mask=mask, other=0.0).to(tl.float32) + up = tl.load(up_ptr + input_offsets, mask=mask, other=0.0).to(tl.float32) + + sig = tl.sigmoid(gate) + silu = gate * sig + dsilu = sig * (1.0 + gate * (1.0 - sig)) + + grad_offsets = row * GRAD_ROW_STRIDE + cols + tl.store(grad_gate_ptr + grad_offsets, (grad_out * weight * up * dsilu).to(grad_gate_ptr.dtype.element_ty), + mask=mask) + tl.store(grad_up_ptr + grad_offsets, (grad_out * weight * silu).to(grad_up_ptr.dtype.element_ty), + mask=mask) + total += grad_out * silu * up + tl.store(grad_weight_ptr + row, tl.sum(total, axis=0)) + + def _swiglu_weighted_forward_triton(gate, up, weights): + out = torch.empty_like(gate, memory_format=torch.contiguous_format) + n_elements = gate.numel() + if n_elements > 0: + grid = (triton.cdiv(n_elements, _BLOCK_SIZE), ) + with torch.cuda.device(gate.device): #ignore-cuda + _swiglu_weighted_fwd_kernel[grid](gate, + up, + weights, + out, + n_elements, + gate.shape[1], + ROW_STRIDE=gate.stride(0), + BLOCK_SIZE=_BLOCK_SIZE, + num_warps=_NUM_WARPS) + + return out + + def _swiglu_weighted_backward_triton(grad_out, gate, up, weights, grad_gate, grad_up): + grad_out = grad_out.contiguous() + grad_weights = torch.zeros_like(weights) + n_rows, n_cols = gate.shape + if n_rows > 0 and n_cols > 0: + block = min(triton.next_power_of_2(n_cols), _BLOCK_SIZE) + with torch.cuda.device(gate.device): #ignore-cuda + _swiglu_weighted_bwd_kernel[(n_rows, )](grad_out, + gate, + up, + weights, + grad_gate, + grad_up, + grad_weights, + n_cols, + ROW_STRIDE=gate.stride(0), + GRAD_ROW_STRIDE=grad_gate.stride(0), + BLOCK_SIZE=block, + num_warps=4) + + return grad_weights + + class _SwiGLUWeightedFn(torch.autograd.Function): + + @staticmethod + def forward(ctx, gate, up, weights): + gate, up, weights = gate.contiguous(), up.contiguous(), weights.contiguous() + ctx.save_for_backward(gate, up, weights) + return _swiglu_weighted_forward_triton(gate, up, weights) + + @staticmethod + def backward(ctx, grad_out): + if torch.is_grad_enabled(): + raise RuntimeError("Weighted SwiGLU has no second derivative; create_graph=True is not supported") + gate, up, weights = ctx.saved_tensors + return swiglu_weighted_backward(grad_out, gate, up, weights) + + class _SwiGLUPackedWeightedFn(torch.autograd.Function): + + @staticmethod + def forward(ctx, gate_up, weights): + gate_up, weights = gate_up.contiguous(), weights.contiguous() + ctx.save_for_backward(gate_up, weights) + gate, up = gate_up.chunk(2, dim=-1) + return _swiglu_weighted_forward_triton(gate, up, weights) + + @staticmethod + def backward(ctx, grad_out): + if torch.is_grad_enabled(): + raise RuntimeError("Weighted SwiGLU has no second derivative; create_graph=True is not supported") + gate_up, weights = ctx.saved_tensors + return swiglu_packed_weighted_backward(grad_out, gate_up, weights) + def _swiglu_eager(gate: torch.Tensor, up: torch.Tensor) -> torch.Tensor: """Pure-PyTorch reference used as the non-Triton fallback.""" @@ -236,6 +357,99 @@ def swiglu(gate: torch.Tensor, up: torch.Tensor) -> torch.Tensor: return _SwiGLUFn.apply(gate, up) +def _swiglu_weighted_eager(gate: torch.Tensor, up: torch.Tensor, weights: torch.Tensor) -> torch.Tensor: + """Pure-PyTorch reference used as the fallback: the same FP32 expression, rounded once.""" + return (F.silu(gate.float()) * up.float() * weights.reshape(-1, 1)).to(gate.dtype) + + +def swiglu_weighted(gate: torch.Tensor, up: torch.Tensor, weights: torch.Tensor) -> torch.Tensor: + """SwiGLU scaled by one weight per row: ``silu(gate) * up * weights[:, None]``. + + Args: + gate: Gate projection output, shape ``[N, I]``, float16/bfloat16/float32. + up: Up projection output, same shape and dtype as ``gate``. + weights: One FP32 weight per row, shape ``[N]``. + + Returns: + Tensor of the same shape and dtype as ``gate``, computed in float32 and rounded once. Differentiable in + all three inputs; the weight gradient is FP32. + + Runs the fused kernel on CUDA when Triton is available and the eager expression otherwise. + """ + _validate_weighted_inputs(gate, up, weights) + if not (_TRITON_AVAILABLE and get_accelerator().on_accelerator(gate)): + return _swiglu_weighted_eager(gate, up, weights) + return _SwiGLUWeightedFn.apply(gate, up, weights) + + +def _validate_weighted_inputs(gate, up, weights): + if gate.dim() != 2 or gate.shape != up.shape: + raise ValueError(f"swiglu_weighted expects gate and up of one shape [N, I], got {tuple(gate.shape)} " + f"and {tuple(up.shape)}") + if gate.dtype != up.dtype: + raise ValueError(f"swiglu_weighted expects gate and up to have the same dtype, got {gate.dtype} and " + f"{up.dtype}") + if gate.dtype not in (torch.float32, torch.float16, torch.bfloat16): + raise ValueError(f"swiglu_weighted supports FP32/FP16/BF16 projections, got {gate.dtype}") + if weights.dtype != torch.float32 or weights.shape != (gate.shape[0], ): + raise ValueError(f"swiglu_weighted expects FP32 weights of shape ({gate.shape[0]},), got {weights.dtype} " + f"{tuple(weights.shape)}") + if gate.device != up.device or gate.device != weights.device: + raise ValueError("swiglu_weighted needs gate, up and FP32 weights on the same device") + + +def _validate_weighted_gradient(grad_out, gate): + if grad_out.shape != gate.shape or grad_out.device != gate.device: + raise ValueError("weighted SwiGLU gradient must match the output shape and device") + + +def swiglu_weighted_backward(grad_out, gate, up, weights): + """First-order gradient values of :func:`swiglu_weighted`, for custom autograd callers.""" + _validate_weighted_inputs(gate, up, weights) + _validate_weighted_gradient(grad_out, gate) + if not (_TRITON_AVAILABLE and get_accelerator().on_accelerator(gate)): + with torch.enable_grad(): + gate, up, weights = (tensor.detach().requires_grad_(True) for tensor in (gate, up, weights)) + return torch.autograd.grad(_swiglu_weighted_eager(gate, up, weights), (gate, up, weights), grad_out) + gate, up, weights = gate.contiguous(), up.contiguous(), weights.contiguous() + grad_gate, grad_up = torch.empty_like(gate), torch.empty_like(up) + grad_weights = _swiglu_weighted_backward_triton(grad_out, gate, up, weights, grad_gate, grad_up) + return grad_gate, grad_up, grad_weights + + +def _packed_weighted_views(gate_up, weights): + if gate_up.dim() != 2 or gate_up.shape[-1] % 2: + raise ValueError("swiglu_packed_weighted needs shape [N, 2 * I] with an even last dimension") + gate, up = gate_up.chunk(2, dim=-1) + _validate_weighted_inputs(gate, up, weights) + return gate, up + + +def swiglu_packed_weighted(gate_up, weights): + """Weighted SwiGLU reading a packed [N, 2 * I] projection without copying its halves.""" + gate, up = _packed_weighted_views(gate_up, weights) + if not (_TRITON_AVAILABLE and get_accelerator().on_accelerator(gate_up)): + return _swiglu_weighted_eager(gate, up, weights) + return _SwiGLUPackedWeightedFn.apply(gate_up, weights) + + +def swiglu_packed_weighted_backward(grad_out, gate_up, weights): + """First-order packed projection and FP32 row-weight gradients, computed in one kernel pass.""" + gate, up = _packed_weighted_views(gate_up, weights) + _validate_weighted_gradient(grad_out, gate) + if not (_TRITON_AVAILABLE and get_accelerator().on_accelerator(gate_up)): + with torch.enable_grad(): + gate_up, weights = (tensor.detach().requires_grad_(True) for tensor in (gate_up, weights)) + gate, up = gate_up.chunk(2, dim=-1) + return torch.autograd.grad(_swiglu_weighted_eager(gate, up, weights), (gate_up, weights), grad_out) + gate_up, weights = gate_up.contiguous(), weights.contiguous() + gate, up = gate_up.chunk(2, dim=-1) + grad_gate_up = torch.empty_like(gate_up) + grad_gate, grad_up = grad_gate_up.chunk(2, dim=-1) + grad_weights = _swiglu_weighted_backward_triton(grad_out, gate, up, weights, grad_gate, grad_up) + return grad_gate_up, grad_weights + + 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. diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index ed5f42684c10..50699254ce21 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -1015,7 +1015,7 @@ smoke coverage used for this AutoEP surface produced the following version gates | Description | Default | | -------------------------------------------------------------------------------------------------------------- | -------- | -| How the DeepEP route applies one FP32 routing weight to each received row at the existing `score_apply` boundary. `"auto"` resolves to `"eager"`, preserving `(rows.float() * weights).to(rows.dtype)`. `"fused"` is experimental and uses a separate Triton pointwise operator for that per-row product only; it does not perform the top-k reduction or move the BF16/FP16 rounding point. It requires `comm_backend="deepep"`, `autoep_size > 1`, CUDA, Triton, contiguous bfloat16/float16 rows shaped `[N, H]`, and contiguous FP32 weights shaped `[N, 1]` on the same device; DeepEP dispatch currently supports BF16 rows only. Fused weight gradients can differ from eager due to FP32 summation order. Unsupported configurations fail rather than falling back. | `"auto"` | +| How the DeepEP route applies one FP32 routing weight to each received row at the existing `score_apply` boundary. `"auto"` resolves to `"eager"`, preserving `(rows.float() * weights).to(rows.dtype)`. `"fused"` is experimental and uses a separate Triton pointwise operator for that per-row product only; it does not perform the top-k reduction or move the BF16/FP16 rounding point. It requires `comm_backend="deepep"`, `autoep_size > 1`, CUDA, Triton, contiguous bfloat16/float16 rows shaped `[N, H]`, and contiguous FP32 weights shaped `[N, 1]` on the same device; DeepEP dispatch currently supports BF16 rows only. Fused weight gradients can differ from eager due to FP32 summation order. `"activation"` is experimental and applies the weight in FP32 inside the expert activation before the bias-free linear down projection, rounding to the projection dtype once. This is the same mathematical function as post-expert weighting, but changes evaluation order and intermediate rounding; bitwise equality is not guaranteed. Separate/fused gate+up and backward overlap are composable; only parameter gradients are deferred, not the FP32 router-weight gradient. Weighted Triton kernels are first-order only (`create_graph=True` raises). Requires a resolved `score_apply="post"`, `comm_backend="deepep"` and `autoep_size > 1`; overlap's restrictions also apply when enabled. Unsupported configurations or weight metadata fail explicitly. | `"auto"` | ***gate_up_impl***: [string] diff --git a/docs/code-docs/source/autoep.rst b/docs/code-docs/source/autoep.rst index aafd3f779be0..7506f0bba8f7 100644 --- a/docs/code-docs/source/autoep.rst +++ b/docs/code-docs/source/autoep.rst @@ -408,6 +408,40 @@ gradient norm after backward and before optimizer clipping in ``engine.step()``. Adam's first update can differ on the scale of the learning rate when a near-zero gradient changes sign, even if the overall gradients agree closely. +``"activation"`` (experimental) applies the weight inside the expert +activation instead, between the experts' first projections and their down +projection: ``h = act(gate, up) * weight``. The down projection is linear and has +no bias, so this is the same mathematical function as ``"post"``, without a +separate pass over the expert output. For ``swiglu`` a +fused Triton kernel computes ``silu(gate) * up * weight`` in FP32 with one +rounding and returns the weight gradient from the same backward; other +activations compute the same product in FP32 in plain PyTorch before casting +to the projection dtype. This changes evaluation order and intermediate +rounding, including for FP32; BF16/FP16 results round at the weighted activation +instead of the weighted expert output. Bitwise equality to ``"eager"`` is not +claimed. It requires ``score_apply`` to resolve to +``"post"``, ``comm_backend="deepep"`` and ``autoep_size > 1``, and is rejected +otherwise. + +Both separate and fused gate+up projections are supported. The packed SwiGLU +path reads the two projection halves in place and writes a packed gradient, +using the same weighted kernel arithmetic without copying the halves. +With ``overlap_weight_grad``, the custom expert backward returns the FP32 +row-weight gradient alongside dX; only the parameter-gradient GEMMs are deferred. +This preserves the router gradient through DeepEP's async combine. The parent +option's ZeRO-stage/backend restrictions still apply. + +Weighted Triton activations support first-order gradients only: +``create_graph=True`` raises. Forward and backward select the input device's +current stream and restore the caller's device. Unsupported weight shape, +dtype or device placement is rejected before launching a kernel. + +On Qwen3-30B-A3B with 8 H100s (expert parallel size 8, micro-batch 4, 16 +accumulation steps, sequence length 4096, DeepEP with 36 SMs), an equivalent +benchmark prototype cut the step by 685 ms (3.5%) against the separate +weighting pass. The rest of the stack also had the fused gate+up projection, +the backward weight-gradient overlap and the recomputed-combine skip. + ``"fused"`` is rejected, rather than silently ignored, when AutoEP cannot honor it: diff --git a/tests/unit/module_inject/test_auto_ep_comm.py b/tests/unit/module_inject/test_auto_ep_comm.py index 5391c48d7ee5..8324d066af3a 100644 --- a/tests/unit/module_inject/test_auto_ep_comm.py +++ b/tests/unit/module_inject/test_auto_ep_comm.py @@ -487,6 +487,43 @@ def test_combine_receives_exactly_the_rows_that_arrived(self): self.assertEqual(seen["combine_rows"].shape[0], self.ARRIVED_ROWS) self.assertTrue(torch.equal(seen["counts"], torch.tensor([3, 3, 3, 3], dtype=torch.int32))) + def test_activation_row_weighting_hands_the_weights_to_the_experts(self): + # The experts apply them inside the activation; nothing scales the expert output afterwards. + seen = {} + + def experts(rows, counts, weight_grad_slot=None, *, row_weights=None): + seen["row_weights"] = row_weights + return rows * 2 + + prefix = torch.tensor([3, 6, 9, self.ARRIVED_ROWS], dtype=torch.int64) + handle = mock.Mock(psum_num_recv_tokens_per_expert=prefix, num_expanded_tokens=self.ARRIVED_ROWS) + exchange = mock.Mock(last_handle=handle, num_max_tokens_per_rank=1024) + received = torch.ones((self.BUFFER_ROWS, self.HIDDEN)) + recv_weights = torch.full((self.BUFFER_ROWS, ), self.WEIGHT) + layer = mock.Mock(_deepep_exchange=exchange, + num_local_experts=self.LOCAL_EXPERTS, + score_apply="post", + row_weighting_impl="activation", + overlap_weight_grad=False, + comm_num_sm=12, + comm_qp_margin=4, + experts=experts) + with mock.patch.object(auto_ep_layer, "deepep_dispatch", + lambda *_args, **_kwargs: (received, recv_weights, exchange)), \ + mock.patch.object(auto_ep_layer, "deepep_combine", lambda _exchange, rows, _handle: rows), \ + mock.patch.object(auto_ep_layer, "apply_deepep_row_weights", side_effect=AssertionError("applied")): + router_output = auto_ep_layer.RouterOutput( + top_scores=torch.ones((4, 2)), + selected_experts=torch.zeros((4, 2), dtype=torch.long), + num_tokens_per_expert=torch.zeros(self.LOCAL_EXPERTS, dtype=torch.long), + ) + tokens = torch.ones((4, self.HIDDEN), dtype=torch.bfloat16) + result = auto_ep_layer.AutoEPMoELayer._deepep_route(layer, tokens, router_output) + + self.assertEqual(seen["row_weights"].shape, (self.ARRIVED_ROWS, )) + self.assertTrue(torch.equal(seen["row_weights"], torch.full((self.ARRIVED_ROWS, ), self.WEIGHT))) + self.assertTrue(torch.equal(result, torch.full((self.ARRIVED_ROWS, self.HIDDEN), 2.0))) + def test_a_buffer_of_exactly_the_arrived_rows_is_used_without_slicing(self): # A slice would change nothing forward, but its backward zero-fills a # buffer-sized gradient and copies the real one into it. Pin that @@ -873,7 +910,7 @@ def setUp(self): ] self.target = torch.randn(self.TOKENS, self.HIDDEN) - def run_route(self, overlap, gate_up_impl="separate", checkpoint=None): + def run_route(self, overlap, gate_up_impl="separate", checkpoint=None, activation_weighting=False): from deepspeed.moe.ep_experts import ExpertWeightGradSlot, GroupedExperts log = [] @@ -910,7 +947,10 @@ def route(x, gate): 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) + if activation_weighting: + rows = experts(received, counts, slot, row_weights=recv_weights) + else: + rows = experts(received, counts, slot) * recv_weights.reshape(-1, 1) return auto_ep_comm.deepep_combine(exchange, rows, handle) carveouts = [] @@ -943,6 +983,16 @@ def test_overlap_matches_the_serial_backward_bitwise(self): self.assertEqual(log[-3:], ["combine_async", "weight_grads_with_12_sms_withheld", "wait"]) self.assertEqual(serial_log, ["combine", "combine"]) + def test_activation_row_gradients_compose_with_async_weight_gradients(self): + for gate_up_impl in ("separate", "fused"): + serial, _ = self.run_route(False, gate_up_impl, activation_weighting=True) + for checkpoint_mode in (None, "reentrant", "non_reentrant"): + with self.subTest(gate_up_impl=gate_up_impl, checkpoint=checkpoint_mode): + overlap, log = self.run_route(True, gate_up_impl, checkpoint_mode, activation_weighting=True) + for name, expected in serial.items(): + torch.testing.assert_close(overlap[name], expected, rtol=0, atol=0, msg=name) + self.assertEqual(log[-3:], ["combine_async", "weight_grads_with_12_sms_withheld", "wait"]) + def test_the_sm_carveout_is_restored(self): torch._C._set_sm_carveout_experimental(None) seen = [] @@ -1440,9 +1490,11 @@ def run_block(self, routing=None, steps=1, training=True, - outer_reentrant=False): + outer_reentrant=False, + row_weighting_impl="eager"): log = [] layer = self.make_layer(log, skip, score_apply) + layer.row_weighting_impl = row_weighting_impl decoder = self.DecoderLayer(layer, self.gate, self.routing if routing is None else routing, checkpoint_func, reads_output) decoder.train(training) @@ -1524,6 +1576,15 @@ def test_repeated_steps_do_not_replay_the_previous_steps_dispatch(self): ["dispatch", "combine", "dispatch", "combine", "cached_dispatch", "combine"] * 3) self.assertEqual(skipped_log, ["dispatch", "combine", "dispatch", "cached_dispatch", "combine"] * 3) + def test_activation_weighting_is_not_applied_twice_when_the_combine_is_skipped(self): + for routing in (self.routing, self.routing % (self.EXPERTS - 1)): + kwargs = dict(row_weighting_impl="activation", routing=routing, steps=2) + normal, normal_log = self.run_block(False, self.reentrant(), **kwargs) + skipped, skipped_log = self.run_block(True, self.reentrant(), **kwargs) + for name, expected in normal.items(): + torch.testing.assert_close(skipped[name], expected, rtol=0, atol=0, msg=name) + self.assertEqual(skipped_log.count("combine"), normal_log.count("combine") - 2) + def test_the_skipped_combine_returns_nan_so_a_reader_fails_loudly(self): normal, _ = self.run_block(False, self.reentrant(), reads_output=True) skipped, _ = self.run_block(True, self.reentrant(), reads_output=True) diff --git a/tests/unit/v1/moe/test_autoep_deepep_parity.py b/tests/unit/v1/moe/test_autoep_deepep_parity.py index 054f47d29f18..add730b621ad 100644 --- a/tests/unit/v1/moe/test_autoep_deepep_parity.py +++ b/tests/unit/v1/moe/test_autoep_deepep_parity.py @@ -682,6 +682,73 @@ 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("use_grouped_mm", [False, True]) + @pytest.mark.parametrize("activation_checkpointing, skewed_routing", [(False, False), (False, True), + (True, False)]) + def test_row_weighting_in_activation_matches_eager(self, activation_checkpointing, skewed_routing, use_grouped_mm): + # The grouped GEMM path runs the fused weighted SwiGLU kernel; the for-loop path, plain PyTorch. + skip_unless_h100_tests_enabled("row weighting in the activation needs H100s and a DeepEP build") + seed = 8642 + runs = {} + for impl in ("eager", "activation"): + runs[impl] = _run_one_step("deepep", + self.world_size, + seed, + activation_checkpointing=activation_checkpointing, + reentrant_checkpointing=True, + skewed_routing=skewed_routing, + row_weighting_impl=impl, + use_grouped_mm=use_grouped_mm) + eager, activation = runs["eager"], runs["activation"] + # The same function with the BF16 rounding moved into the activation: compared by relative error, not + # bitwise. Adam's first update can turn a near-zero gradient's rounding into a learning-rate-scale step, + # so the parameter deltas are not compared. + for (name, route), (_, expected_route) in zip(activation["routes"], eager["routes"]): + assert torch.equal(route, expected_route), name + for name in ("output", "input_gradient"): + _assert_native_fused_gradient_close(activation[name], eager[name], name=name) + assert activation["gradients"].keys() == eager["gradients"].keys() + for name, gradient in eager["gradients"].items(): + if gradient.norm() == 0: + # Skewed routing leaves an expert without tokens on the rank that owns it. + assert activation["gradients"][name].norm() == 0, f"{name} gradient should be zero" + continue + _assert_native_fused_gradient_close(activation["gradients"][name], gradient, name=name) + + @pytest.mark.parametrize("gate_up_impl", ["separate", "fused"]) + @pytest.mark.parametrize("skewed_routing", [False, True]) + @pytest.mark.parametrize("zero_stage", [1, 2]) + def test_activation_weighting_composes_with_backward_overlap(self, gate_up_impl, skewed_routing, zero_stage): + skip_unless_h100_tests_enabled("weighted activation/overlap composition needs H100s and DeepEP") + seed = 8748 + common = dict(gate_up_impl=gate_up_impl, + skewed_routing=skewed_routing, + zero_stage=zero_stage, + use_grouped_mm=True, + disable_triton_grouped_mm=True, + activation_checkpointing=True, + reentrant_checkpointing=True) + eager = _run_one_step("deepep", self.world_size, seed, row_weighting_impl="eager", **common) + serial = _run_one_step("deepep", self.world_size, seed, row_weighting_impl="activation", **common) + overlap = _run_one_step("deepep", + self.world_size, + seed, + row_weighting_impl="activation", + overlap_weight_grad=True, + **common) + for result in (serial, overlap): + assert result["gradients"].keys() == eager["gradients"].keys() + for (_, route), (_, expected_route) in zip(result["routes"], eager["routes"]): + assert torch.equal(route, expected_route) + for name in ("output", "input_gradient"): + _assert_native_fused_gradient_close(result[name], eager[name], name=name) + for name, expected in eager["gradients"].items(): + if expected.norm() == 0: + assert result["gradients"][name].norm() == 0, f"{name} must remain zero" + else: + _assert_native_fused_gradient_close(result["gradients"][name], expected, name=name) + assert torch._C._get_sm_carveout_experimental() is None, "SM carveout leaked from weighted overlap" + @pytest.mark.parametrize("gate_up_impl", ["separate", "fused"]) @pytest.mark.parametrize("skewed_routing", [False, True]) @pytest.mark.parametrize("zero_stage", [1, 2]) @@ -792,7 +859,7 @@ def test_retained_checkpoint_graph_interleaved_with_new_forward_is_rejected(self dist.barrier() @pytest.mark.parametrize("skewed_routing", [False, True]) - @pytest.mark.parametrize("row_weighting_impl", ["eager", "fused"]) + @pytest.mark.parametrize("row_weighting_impl", ["eager", "fused", "activation"]) def test_skipping_the_recomputed_combine_matches_the_normal_recompute(self, row_weighting_impl, skewed_routing): if row_weighting_impl == "fused": _skip_unless_fused_row_weighting_enabled("fused DeepEP row weighting needs H100s and a DeepEP build") diff --git a/tests/unit/v1/moe/test_autoep_expert_activation.py b/tests/unit/v1/moe/test_autoep_expert_activation.py index 30dff3aab603..e7ab99cefb8e 100644 --- a/tests/unit/v1/moe/test_autoep_expert_activation.py +++ b/tests/unit/v1/moe/test_autoep_expert_activation.py @@ -304,6 +304,110 @@ def test_fused_kernel_matches_plain_pytorch(self, activation): torch.testing.assert_close(gate.grad, gate32.grad.to(out.dtype), **close) torch.testing.assert_close(up.grad, up32.grad.to(out.dtype), **close) + @pytest.mark.parametrize("activation", tuple(EXPERT_ACTIVATIONS)) + def test_row_weights_are_the_fp32_product_rounded_once(self, activation): + torch.manual_seed(0) + gate = torch.randn(6, 8).bfloat16() + up = torch.randn(6, 8).bfloat16() + weights = torch.rand(6) + + got = apply_expert_activation(gate, up, activation, 1.5, 1.0, fused=False, row_weights=weights) + + fp32 = EXPERT_ACTIVATIONS[activation].fn(gate.float(), up.float(), 1.5, 1.0) * weights[:, None] + assert torch.equal(got, fp32.bfloat16()) + written = _written_out(gate.float(), up.float(), activation, 1.5, 1.0) * weights[:, None] + torch.testing.assert_close(got.float(), written, rtol=1e-2, atol=1e-2) + + @pytest.mark.parametrize("activation", tuple(EXPERT_ACTIVATIONS)) + def test_expert_row_weights_reject_incompatible_metadata(self, activation): + experts = GroupedExperts(dim=16, hidden_dim=32, num_experts=4, use_grouped_mm=False, activation=activation) + inputs = torch.ones((4, 16)) + counts = torch.ones(4, dtype=torch.int64) + bad_weights = (torch.ones(4, dtype=torch.bfloat16), torch.ones(3), torch.ones(4, + 1), torch.ones(4, device="meta")) + for weights in bad_weights: + with pytest.raises(ValueError, match="row_weights"): + experts(inputs, counts, row_weights=weights) + + @pytest.mark.parametrize("activation", tuple(EXPERT_ACTIVATIONS)) + def test_row_weights_scale_each_expert_output_row(self, activation): + # The down projection is linear and has no bias, so weighting its input row weights its output row. + torch.manual_seed(0) + experts = GroupedExperts(dim=16, + hidden_dim=32, + num_experts=4, + use_grouped_mm=False, + activation=activation, + activation_alpha=1.5, + activation_limit=1.0) + for weight in (experts.w1, experts.w2, experts.w3): + nn.init.normal_(weight, std=0.5) + counts = torch.tensor([1, 4, 0, 5]) # an empty expert, and two padding rows after the routed ones + x = torch.randn(12, 16, requires_grad=True) + weights = torch.rand(12, requires_grad=True) + x_post = x.detach().clone().requires_grad_(True) + weights_post = weights.detach().clone().requires_grad_(True) + + out = experts(x, counts, row_weights=weights) + post = experts(x_post, counts) * weights_post[:, None] + grad_out = torch.randn_like(out) + out.backward(grad_out) + post.backward(grad_out) + + torch.testing.assert_close(out, post, rtol=1e-5, atol=1e-5) + torch.testing.assert_close(x.grad, x_post.grad, rtol=1e-5, atol=1e-5) + torch.testing.assert_close(weights.grad[:10], weights_post.grad[:10], rtol=1e-4, atol=1e-5) + # Padding rows produce zeros whatever their weight. + assert not out[10:].any() + + @pytest.mark.parametrize("path", ["grouped_mm", "triton_grouped_mm", "fused_gate_up"]) + @pytest.mark.parametrize("activation", tuple(EXPERT_ACTIVATIONS)) + def test_grouped_gemm_paths_take_row_weights_like_the_for_loop(self, activation, path): + # For swiglu the grouped paths run the fused weighted kernel; the for-loop path, plain PyTorch. + from deepspeed.ops.triton_ops import is_triton_available + + if get_accelerator().device_name() == "cpu": + pytest.skip("needs an accelerator") + if path in ("grouped_mm", "fused_gate_up") and not hasattr(torch, "_grouped_mm"): + pytest.skip("this PyTorch build has no torch._grouped_mm") + if path == "triton_grouped_mm" and not is_triton_available(): + pytest.skip("the Triton grouped GEMM needs Triton") + device = get_accelerator().current_device_name() + torch.manual_seed(0) + shape = dict(dim=64, hidden_dim=128, num_experts=4) + act = dict(activation=activation, activation_alpha=1.5, activation_limit=1.0) + loop = GroupedExperts(use_grouped_mm=False, **shape, **act) + for weight in (loop.w1, loop.w2, loop.w3): + nn.init.normal_(weight, std=0.1) + grouped = GroupedExperts(use_grouped_mm=True, + disable_triton_grouped_mm=True, + gate_up_impl="fused" if path == "fused_gate_up" else "separate", + **shape, + **act) + grouped.load_state_dict(loop.state_dict()) + grouped.use_triton_grouped_mm = path == "triton_grouped_mm" + loop.to(device=device, dtype=torch.bfloat16) + grouped.to(device=device, dtype=torch.bfloat16) + + counts = torch.tensor([16, 32, 16, 64], device=device) + x = torch.randn(int(counts.sum()), 64, device=device, dtype=torch.bfloat16) + weights = torch.rand(int(counts.sum()), device=device) + inputs = {name: (x.clone().requires_grad_(True), weights.clone().requires_grad_(True)) for name in "lg"} + out_loop = loop(inputs["l"][0], counts, row_weights=inputs["l"][1]) + out_grouped = grouped(inputs["g"][0], counts, row_weights=inputs["g"][1]) + grad_out = torch.randn_like(out_loop) + out_loop.backward(grad_out) + out_grouped.backward(grad_out) + + def assert_same(got, want): + torch.testing.assert_close(got, want, rtol=2e-2, atol=2e-2 * want.abs().max().item()) + + assert_same(out_grouped, out_loop) + for index in range(2): + assert_same(inputs["g"][index].grad, inputs["l"][index].grad) + for name in ("w1", "w2", "w3"): + assert_same(getattr(grouped, name).grad, getattr(loop, name).grad) + def test_for_loop_path_does_not_need_the_triton_kernel(self, monkeypatch): # The for-loop path is the reference path and runs on CPU tensors. It must not reach the # Triton kernel, which exists whenever Triton is installed. @@ -611,7 +715,7 @@ def _grouped_mm_runs_on(device): 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): + def _compare(self, device, dtype, activation, gate_up_impl, deferred, weighted=False): torch.manual_seed(0) kwargs = dict(dim=16, hidden_dim=8, @@ -632,11 +736,14 @@ def _compare(self, device, dtype, activation, gate_up_impl, deferred): 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) + weights = torch.rand(24, device=device, dtype=torch.float32) if weighted else None + weights_plain = None if weights is None else weights.clone().requires_grad_(True) + weights_overlap = None if weights is None else weights.clone().requires_grad_(True) x_plain, x_overlapped = x.clone().requires_grad_(True), x.clone().requires_grad_(True) - out_plain = plain(x_plain, counts) + out_plain = plain(x_plain, counts, row_weights=weights_plain) out_plain.backward(grad_out) slot = ExpertWeightGradSlot() if deferred else None - out_overlapped = overlapped(x_overlapped, counts, slot) + out_overlapped = overlapped(x_overlapped, counts, slot, row_weights=weights_overlap) out_overlapped.backward(grad_out) if deferred: assert all(weight.grad is None for weight in overlapped.parameters()) @@ -647,6 +754,29 @@ def _compare(self, device, dtype, activation, gate_up_impl, deferred): 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) + if weighted: + torch.testing.assert_close(weights_overlap.grad, weights_plain.grad, rtol=1e-4, atol=1e-5) + assert weights_overlap.grad.dtype == torch.float32 + + @pytest.mark.parametrize("activation", tuple(EXPERT_ACTIVATIONS)) + @pytest.mark.parametrize("gate_up_impl", ["separate", "fused"]) + def test_weighted_gradients_compose_with_deferral_on_cpu(self, activation, gate_up_impl): + if not _grouped_mm_runs_on("cpu"): + pytest.skip("this PyTorch build has no CPU torch._grouped_mm") + for dtype in (torch.float32, torch.bfloat16): + self._compare("cpu", dtype, activation, gate_up_impl, True, weighted=True) + + @pytest.mark.parametrize("activation", tuple(EXPERT_ACTIVATIONS)) + @pytest.mark.parametrize("gate_up_impl", ["separate", "fused"]) + def test_weighted_gradients_compose_with_deferral_on_cuda(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, + weighted=True) @pytest.mark.parametrize("deferred", [False, True]) @pytest.mark.parametrize("gate_up_impl", ["separate", "fused"]) diff --git a/tests/unit/v1/moe/test_autoep_unit.py b/tests/unit/v1/moe/test_autoep_unit.py index fe77c10a1b97..7644b23364ea 100644 --- a/tests/unit/v1/moe/test_autoep_unit.py +++ b/tests/unit/v1/moe/test_autoep_unit.py @@ -396,6 +396,24 @@ def test_skip_recompute_combine_rejects_pattern_overrides_even_with_supported_pr config = parse_autoep_config({**settings, "skip_recompute_combine": True, "moe_layer_pattern": None}) validate_autoep_config(config, world_size=2, pp_size=1, tp_size=1, sp_size=1) + def test_row_weighting_in_activation_requires_the_deepep_route(self): + deepep = {"comm_backend": "deepep", "comm_max_tokens_per_rank": 4096} + rejected = ( + ({ + "autoep_size": 2 + }, 'row_weighting_impl="activation".*comm_backend="comm"'), + ({ + "autoep_size": 1, + **deepep + }, "autoep_size=1"), + ) + for overrides, match in rejected: + config = parse_autoep_config({"enabled": True, "row_weighting_impl": "activation", **overrides}) + with pytest.raises(ValueError, match=match): + validate_autoep_config(config, world_size=2, pp_size=1, tp_size=1, sp_size=1) + config = parse_autoep_config({"enabled": True, "autoep_size": 2, "row_weighting_impl": "activation", **deepep}) + validate_autoep_config(config, world_size=2, pp_size=1, tp_size=1, sp_size=1) + def test_fused_combine_rejects_folded_tensor_parallelism(self): config = parse_autoep_config({ "enabled": True, @@ -1568,6 +1586,14 @@ def test_skip_recompute_combine_is_limited_to_checked_presets(self): layer = AutoEPMoELayer(_make_spec(), source, ep_size=1, ep_rank=0, config=config) assert layer.skip_recompute_combine is True + def test_row_weighting_in_activation_requires_post_score_application(self): + source = MockMoEBlock(num_experts=4, ffn_hidden=128, hidden_size=64) + config = _runtime_config(enabled=True, autoep_size=1, row_weighting_impl="activation") + with pytest.raises(ValueError, match='row_weighting_impl="activation".*"pre"'): + AutoEPMoELayer(_make_spec(score_apply="pre"), source, ep_size=1, ep_rank=0, config=config) + layer = AutoEPMoELayer(_make_spec(score_apply="post"), source, ep_size=1, ep_rank=0, config=config) + assert layer.row_weighting_impl == "activation" + def test_router_cache_does_not_duplicate_model_level_gate_capture(self): source = MockMoEBlock(num_experts=4, ffn_hidden=128, hidden_size=64) layer = AutoEPMoELayer(_make_spec(router_logits_capture_target="router", router_logits_capture_mode="raw"), 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 e2ba91e71477..e0484076d8e0 100644 --- a/tests/unit/v1/ops/triton_ops/test_swiglu_triton.py +++ b/tests/unit/v1/ops/triton_ops/test_swiglu_triton.py @@ -30,11 +30,14 @@ def _load_swiglu_in_the_worker(): global get_accelerator, swiglu, swiglu_packed, swiglu_backward, swiglu_packed_backward global swiglu_clamped, swiglu_clamped_packed + global swiglu_weighted, swiglu_weighted_backward, swiglu_packed_weighted, swiglu_packed_weighted_backward # 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_backward, swiglu_packed_backward, swiglu_clamped, swiglu_clamped_packed) + from deepspeed.ops.triton_ops.swiglu_triton import (swiglu_weighted, swiglu_weighted_backward, + swiglu_packed_weighted, swiglu_packed_weighted_backward) if not is_triton_available(): pytest.skip("Triton is not available") @@ -87,6 +90,136 @@ def test_backward_matches_reference(dtype, shape): torch.testing.assert_close(up.grad, up_ref.grad, **_tol(dtype)) +def _ref_swiglu_weighted(gate, up, weights): + return F.silu(gate.float()) * up.float() * weights[:, None] + + +@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16]) +@pytest.mark.parametrize("shape", [(32, 16), (1, 1), (128, 768), (7, 13), (4, 2048), (2, 3000)]) +def test_weighted_forward_is_the_fp32_product_rounded_once(dtype, shape): + dev = get_accelerator().current_device_name() + gate = torch.randn(shape, device=dev, dtype=dtype) + up = torch.randn(shape, device=dev, dtype=dtype) + weights = torch.rand(shape[0], device=dev) + + out = swiglu_weighted(gate, up, weights) + + assert out.shape == gate.shape and out.dtype == dtype + torch.testing.assert_close(out, _ref_swiglu_weighted(gate, up, weights).to(dtype), **_tol(dtype)) + + +@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16]) +@pytest.mark.parametrize("shape", [(32, 16), (128, 768), (7, 13), (4, 2048), (2, 3000)]) +def test_weighted_backward_matches_reference(dtype, shape): + dev = get_accelerator().current_device_name() + gate = torch.randn(shape, device=dev, dtype=dtype, requires_grad=True) + up = torch.randn(shape, device=dev, dtype=dtype, requires_grad=True) + weights = torch.rand(shape[0], device=dev, requires_grad=True) + gate_ref = gate.detach().float().requires_grad_(True) + up_ref = up.detach().float().requires_grad_(True) + weights_ref = weights.detach().clone().requires_grad_(True) + grad_out = torch.randn(shape, device=dev, dtype=dtype) + + swiglu_weighted(gate, up, weights).backward(grad_out) + _ref_swiglu_weighted(gate_ref, up_ref, weights_ref).backward(grad_out.float()) + + torch.testing.assert_close(gate.grad, gate_ref.grad.to(dtype), **_tol(dtype)) + torch.testing.assert_close(up.grad, up_ref.grad.to(dtype), **_tol(dtype)) + # The weight gradient is an FP32 sum over the row; only summation order separates it from the reference. + assert weights.grad.dtype == torch.float32 + scale = weights_ref.grad.abs().max().item() + torch.testing.assert_close(weights.grad, weights_ref.grad, rtol=1e-4, atol=1e-5 * max(scale, 1.0)) + + +def test_weighted_empty_input(): + dev = get_accelerator().current_device_name() + gate = torch.empty(0, 16, device=dev, dtype=torch.bfloat16, requires_grad=True) + up = torch.empty(0, 16, device=dev, dtype=torch.bfloat16, requires_grad=True) + weights = torch.empty(0, device=dev, requires_grad=True) + out = swiglu_weighted(gate, up, weights) + out.sum().backward() + assert out.shape == (0, 16) and weights.grad.shape == (0, ) + + +def test_weighted_rejects_weights_that_are_not_one_fp32_value_per_row(): + dev = get_accelerator().current_device_name() + gate = torch.randn(4, 8, device=dev, dtype=torch.bfloat16) + up = torch.randn(4, 8, device=dev, dtype=torch.bfloat16) + for weights in (torch.rand(4, device=dev).half(), torch.rand(4, 1, device=dev), torch.rand(3, device=dev)): + with pytest.raises(ValueError, match="FP32 weights"): + swiglu_weighted(gate, up, weights) + with pytest.raises(ValueError, match="one shape"): + swiglu_weighted(gate, up[:, :4], torch.rand(4, device=dev)) + + +@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16]) +@pytest.mark.parametrize("shape", [(7, 13), (3, 768), (2, 3000), (0, 16)]) +def test_packed_weighted_matches_unpacked_and_standalone_backward(dtype, shape): + dev = get_accelerator().current_device_name() + generator = torch.Generator(device=dev).manual_seed(8748) + packed = torch.randn((shape[0], 2 * shape[1]), device=dev, dtype=dtype, generator=generator, requires_grad=True) + weights = torch.rand(shape[0], device=dev, generator=generator, requires_grad=True) + gate, up = packed.detach().chunk(2, dim=-1) + gate, up = gate.contiguous().requires_grad_(True), up.contiguous().requires_grad_(True) + reference_weights = weights.detach().clone().requires_grad_(True) + upstream = torch.randn((shape[1], shape[0]), device=dev, dtype=dtype, generator=generator).t() + actual = swiglu_packed_weighted(packed, weights) + expected = swiglu_weighted(gate, up, reference_weights) + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + torch.testing.assert_close(actual, _ref_swiglu_weighted(gate, up, reference_weights).to(dtype), **_tol(dtype)) + actual.backward(upstream) + expected.backward(upstream) + torch.testing.assert_close(packed.grad, torch.cat((gate.grad, up.grad), dim=-1), rtol=0, atol=0) + torch.testing.assert_close(weights.grad, reference_weights.grad, rtol=0, atol=0) + grad_packed, grad_weights = swiglu_packed_weighted_backward(upstream, packed.detach(), weights.detach()) + torch.testing.assert_close(grad_packed, packed.grad, rtol=0, atol=0) + torch.testing.assert_close(grad_weights, weights.grad, rtol=0, atol=0) + grad_gate, grad_up, grad_weights = swiglu_weighted_backward(upstream, gate.detach(), up.detach(), + reference_weights.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(grad_weights, reference_weights.grad, rtol=0, atol=0) + + +@pytest.mark.parametrize("packed", [False, True]) +def test_weighted_kernel_rejects_incomplete_higher_order_gradients(packed): + dev = get_accelerator().current_device_name() + projections = torch.ones((4, 26), device=dev, dtype=torch.bfloat16, requires_grad=True) + weights = torch.ones(4, device=dev, dtype=torch.float32, requires_grad=True) + if packed: + output = swiglu_packed_weighted(projections, weights) + else: + gate, up = projections.chunk(2, dim=-1) + output = swiglu_weighted(gate, up, weights) + with pytest.raises(RuntimeError, match="second derivative"): + torch.autograd.grad(output.float().sum(), (projections, weights), create_graph=True) + + +@pytest.mark.parametrize("packed", [False, True]) +def test_weighted_kernel_uses_its_input_device_and_preserves_the_caller(packed): + accelerator = get_accelerator() + if accelerator.device_count() < 2: + pytest.skip("weighted cross-device kernel needs two CUDA devices") + with torch.cuda.device(1): #ignore-cuda + projections = torch.ones((7, 26), + device=accelerator.current_device_name(), + dtype=torch.bfloat16, + requires_grad=True) + weights = torch.ones(7, device=accelerator.current_device_name(), dtype=torch.float32, requires_grad=True) + reference = projections.detach().float().requires_grad_(True) + reference_weights = weights.detach().clone().requires_grad_(True) + with torch.cuda.device(0): #ignore-cuda + gate, up = projections.chunk(2, dim=-1) + actual = swiglu_packed_weighted(projections, weights) if packed else swiglu_weighted(gate, up, weights) + expected = _ref_swiglu_weighted(*reference.chunk(2, dim=-1), reference_weights) + actual.float().sum().backward() + expected.sum().backward() + assert accelerator.current_device() == 0 + torch.testing.assert_close(actual, expected.to(actual.dtype), **_tol(actual.dtype)) + torch.testing.assert_close(projections.grad, reference.grad.to(projections.dtype), **_tol(projections.dtype)) + torch.testing.assert_close(weights.grad, reference_weights.grad, rtol=1e-4, atol=1e-5) + + def test_empty_input(): dev = get_accelerator().current_device_name() gate = torch.empty(0, 16, device=dev, dtype=torch.float32, requires_grad=True)