From 52edfc62d530e4a77b3ac0890f096f2f98063c83 Mon Sep 17 00:00:00 2001 From: yh0903 Date: Sat, 3 Oct 2026 01:11:58 -0700 Subject: [PATCH 1/5] Add an opt-in fused gate+up grouped GEMM for AutoEP experts AutoEP's grouped experts run the gate and up projections of the same input as two grouped GEMMs, and in the backward pass add the two input-gradient GEMM results. expert_parallel.gate_up_impl="fused" concatenates w1 and w3 on each call and runs one torch._grouped_mm with twice the output columns. A single input-gradient GEMM then accumulates both projections in FP32. The activation reads the two halves of the packed output in place: swiglu through a new Triton kernel, swiglu_packed, with the same FP32 math as the existing swiglu kernel; the other registered forms through their eager expression on views. Parameters keep the separate w1/w3 layout, so checkpoints, expert tensor parallelism and optimizer state are unchanged. The default, "separate", keeps the existing path. "fused" is rejected when the experts would not run torch._grouped_mm. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: yh0903 --- deepspeed/module_inject/auto_ep_config.py | 9 ++ deepspeed/module_inject/auto_ep_layer.py | 1 + .../module_inject/auto_ep_presets/base.py | 1 + deepspeed/moe/ep_experts.py | 89 +++++++++++- deepspeed/ops/triton_ops/swiglu_triton.py | 102 ++++++++++++++ docs/_pages/config-json.md | 6 + docs/code-docs/source/autoep.rst | 42 ++++++ .../v1/moe/test_autoep_expert_activation.py | 127 +++++++++++++++++- .../v1/ops/triton_ops/test_swiglu_triton.py | 37 ++++- 9 files changed, 407 insertions(+), 7 deletions(-) diff --git a/deepspeed/module_inject/auto_ep_config.py b/deepspeed/module_inject/auto_ep_config.py index 29ebe8b931d8..007b9b9595ae 100644 --- a/deepspeed/module_inject/auto_ep_config.py +++ b/deepspeed/module_inject/auto_ep_config.py @@ -61,6 +61,7 @@ def parse_autoep_config(param_dict: dict) -> AutoEPConfig: config.score_apply = param_dict.get("score_apply", "auto") 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.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) @@ -194,6 +195,14 @@ def validate_autoep_config( raise ValueError(f"row_weighting_impl must be one of {valid_row_weighting_impl}, " f"got '{config.row_weighting_impl}'") + valid_gate_up_impl = ("separate", "fused") + if config.gate_up_impl not in valid_gate_up_impl: + raise ValueError(f"gate_up_impl must be one of {valid_gate_up_impl}, got '{config.gate_up_impl}'") + if config.gate_up_impl == "fused" and not config.use_grouped_mm: + raise ValueError('gate_up_impl="fused" runs the gate and up projections as one torch._grouped_mm, but ' + "use_grouped_mm=false selects the sequential expert loop. Set use_grouped_mm=true, or " + "leave gate_up_impl unset.") + # Validate comm_backend valid_comm_backend = ("comm", "deepep") if config.comm_backend not in valid_comm_backend: diff --git a/deepspeed/module_inject/auto_ep_layer.py b/deepspeed/module_inject/auto_ep_layer.py index 013dd21a38b5..d46a4f405829 100644 --- a/deepspeed/module_inject/auto_ep_layer.py +++ b/deepspeed/module_inject/auto_ep_layer.py @@ -637,6 +637,7 @@ def __init__( activation=spec.expert_activation, activation_alpha=spec.expert_activation_alpha, activation_limit=spec.expert_activation_limit, + gate_up_impl=config.gate_up_impl, ) _copy_parameter_data(self.experts.w1, w1) _copy_parameter_data(self.experts.w2, w2) diff --git a/deepspeed/module_inject/auto_ep_presets/base.py b/deepspeed/module_inject/auto_ep_presets/base.py index 8315ef9c80bc..d5904ad38bf9 100644 --- a/deepspeed/module_inject/auto_ep_presets/base.py +++ b/deepspeed/module_inject/auto_ep_presets/base.py @@ -123,6 +123,7 @@ class AutoEPConfig: 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" + gate_up_impl: Literal["separate", "fused"] = "separate" 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 3bb3db5dd435..e868e208eb52 100644 --- a/deepspeed/moe/ep_experts.py +++ b/deepspeed/moe/ep_experts.py @@ -40,7 +40,9 @@ class ExpertActivation: """One way an expert MLP turns its gate and up projections into the input of the down projection. ``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. ``uses_alpha`` and ``uses_limit`` say + 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 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 @@ -51,6 +53,7 @@ class ExpertActivation: uses_alpha: bool = False 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 #: The expert activations AutoEP can compute, by name. They are different functions: a model trained @@ -72,11 +75,12 @@ def register_expert_activation( uses_alpha: bool = False, 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, ) -> 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) + EXPERT_ACTIVATIONS[name] = ExpertActivation(fn, fused_fn, uses_alpha, uses_limit, gate_fn, packed_fused_fn) def get_expert_activation(name: str) -> ExpertActivation: @@ -99,6 +103,11 @@ def _swiglu_fused(gate: torch.Tensor, up: torch.Tensor, alpha: float, limit: flo return swiglu(gate, up) +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) + + def _geglu_tanh(gate: torch.Tensor, up: torch.Tensor, alpha: float, limit: float) -> torch.Tensor: return _gelu_tanh(gate) * up @@ -113,7 +122,11 @@ def _swiglu_oai(gate: torch.Tensor, up: torch.Tensor, alpha: float, limit: float return (up + 1.0) * (gate * torch.sigmoid(gate * alpha)) -register_expert_activation("swiglu", _swiglu, fused_fn=_swiglu_fused, gate_fn=F.silu) +register_expert_activation("swiglu", + _swiglu, + fused_fn=_swiglu_fused, + gate_fn=F.silu, + packed_fused_fn=_swiglu_packed_fused) register_expert_activation("geglu_tanh", _geglu_tanh, gate_fn=_gelu_tanh) register_expert_activation("swiglu_clamped", _swiglu_clamped, uses_limit=True, gate_fn=F.silu) register_expert_activation("swiglu_oai", _swiglu_oai, uses_alpha=True, uses_limit=True) @@ -136,6 +149,23 @@ def apply_expert_activation(gate: torch.Tensor, return entry.fn(gate, up, alpha, limit) +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: + """: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 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) + + # --------------------------------------------------------------------------- # Expert computation: sequential for-loop (reference path) # --------------------------------------------------------------------------- @@ -254,6 +284,44 @@ def _run_experts_grouped_mm( return out +def _run_experts_grouped_mm_fused_gate_up( + w1: torch.Tensor, + w2: torch.Tensor, + w3: torch.Tensor, + x: torch.Tensor, + num_tokens_per_expert: torch.Tensor, + activation: str = "swiglu", + alpha: float = 1.702, + limit: float = 7.0, +) -> torch.Tensor: + """:func:`_run_experts_grouped_mm` with the gate and up projections in one grouped GEMM. + + The parameters keep their separate ``w1``/``w3`` layout; their concatenation is rebuilt on each call. + One GEMM over ``2 * hidden_dim`` output columns replaces two in the forward pass, and in the backward + pass a single input-gradient GEMM accumulates both projections in FP32 instead of adding two rounded + results. The forward values and weight gradients are those of the separate path. + + Args mirror :func:`_run_experts_grouped_mm`. + """ + offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32) + + cast_dtype = x.dtype + w13 = torch.cat([w1.to(cast_dtype), w3.to(cast_dtype)], dim=1) + gate_up = torch._grouped_mm( + x.to(cast_dtype), + w13.transpose(-2, -1), + offs=offsets, + ) + h = apply_packed_expert_activation(gate_up, activation, alpha, limit) + out = torch._grouped_mm( + h, + w2.to(cast_dtype).transpose(-2, -1), + offs=offsets, + ).type_as(x) + + return out + + # --------------------------------------------------------------------------- # Expert computation: Triton grouped GEMM (sm80 / sm86 fast path) # --------------------------------------------------------------------------- @@ -327,6 +395,9 @@ class GroupedExperts(nn.Module): the default is plain SwiGLU. activation_alpha (float): ``alpha`` for the forms that read it (``swiglu_oai``). activation_limit (float): Clamp limit for the forms that read it. + gate_up_impl (str): ``"separate"`` runs the gate and up projections as two grouped GEMMs; + ``"fused"`` runs them as one over the concatenated weights. ``"fused"`` needs the + ``torch._grouped_mm`` path. """ def __init__( @@ -339,6 +410,7 @@ def __init__( activation: str = "swiglu", activation_alpha: float = 1.702, activation_limit: float = 7.0, + gate_up_impl: str = "separate", ): super().__init__() # An unknown name is refused here, at construction, rather than at the first forward step. @@ -371,6 +443,15 @@ def __init__( "Triton to enable the Triton grouped-GEMM path, or set " "use_grouped_mm=False to use the sequential expert loop.") + if gate_up_impl not in ("separate", "fused"): + raise ValueError(f'gate_up_impl must be "separate" or "fused", got {gate_up_impl!r}') + self.gate_up_impl = gate_up_impl + if gate_up_impl == "fused" and (not use_grouped_mm or self.use_triton_grouped_mm): + selected = "the Triton grouped GEMM" if use_grouped_mm else "the sequential expert loop" + raise ValueError('gate_up_impl="fused" runs the gate and up projections as one torch._grouped_mm, ' + f"but {selected} was selected. Set use_grouped_mm=true and, on devices that prefer " + 'the Triton kernel, disable_triton_grouped_mm=true, or leave gate_up_impl unset.') + if use_grouped_mm and self.use_triton_grouped_mm: warning_once("Triton grouped-GEMM path is selected for grouped_gemm. " "The Triton path is preferred on compute capability smaller than sm90, " @@ -395,6 +476,8 @@ def forward( 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: + 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) else: return _run_experts_for_loop(self.w1, self.w2, self.w3, x, num_tokens_per_expert, *act) diff --git a/deepspeed/ops/triton_ops/swiglu_triton.py b/deepspeed/ops/triton_ops/swiglu_triton.py index 89038417ccc0..0b1005f6e4d5 100644 --- a/deepspeed/ops/triton_ops/swiglu_triton.py +++ b/deepspeed/ops/triton_ops/swiglu_triton.py @@ -19,6 +19,10 @@ 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_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. """ from __future__ import annotations @@ -111,6 +115,83 @@ def backward(ctx, grad_out: torch.Tensor): 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): + pid = tl.program_id(axis=0).to(tl.int64) + offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + mask = offsets < n_elements + # Output element (row, col) reads gate at (row, col) and up at (row, INTER + col) of the packed row. + gate_offsets = (offsets // INTER) * (2 * INTER) + offsets % INTER + + gate = tl.load(gate_up_ptr + gate_offsets, mask=mask).to(tl.float32) + up = tl.load(gate_up_ptr + gate_offsets + INTER, mask=mask).to(tl.float32) + + out = gate * tl.sigmoid(gate) * up + + tl.store(out_ptr + offsets, out.to(out_ptr.dtype.element_ty), mask=mask) + + @triton.jit + def _swiglu_packed_bwd_kernel(grad_out_ptr, gate_up_ptr, grad_gate_up_ptr, n_elements, INTER: 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 + gate_offsets = (offsets // INTER) * (2 * INTER) + offsets % INTER + + grad_out = tl.load(grad_out_ptr + offsets, mask=mask).to(tl.float32) + gate = tl.load(gate_up_ptr + gate_offsets, mask=mask).to(tl.float32) + up = tl.load(gate_up_ptr + gate_offsets + INTER, mask=mask).to(tl.float32) + + sig = tl.sigmoid(gate) + silu = gate * sig + dsilu = sig * (1.0 + gate * (1.0 - sig)) + + grad_gate = grad_out * up * dsilu + grad_up = grad_out * silu + + tl.store(grad_gate_up_ptr + gate_offsets, grad_gate.to(grad_gate_up_ptr.dtype.element_ty), mask=mask) + tl.store(grad_gate_up_ptr + gate_offsets + INTER, grad_up.to(grad_gate_up_ptr.dtype.element_ty), mask=mask) + + class _SwiGLUPackedFn(torch.autograd.Function): + + @staticmethod + def forward(ctx, gate_up: torch.Tensor) -> torch.Tensor: + gate_up = gate_up.contiguous() + inter = gate_up.shape[-1] // 2 + out = gate_up.new_empty(gate_up.shape[:-1] + (inter, )) + + n_elements = out.numel() + if n_elements > 0: + grid = (triton.cdiv(n_elements, _BLOCK_SIZE), ) + _swiglu_packed_fwd_kernel[grid](gate_up, + out, + n_elements, + INTER=inter, + BLOCK_SIZE=_BLOCK_SIZE, + num_warps=_NUM_WARPS) + + ctx.save_for_backward(gate_up) + return out + + @staticmethod + def backward(ctx, grad_out: torch.Tensor): + gate_up, = ctx.saved_tensors + grad_out = grad_out.contiguous() + grad_gate_up = torch.empty_like(gate_up) + + n_elements = grad_out.numel() + if n_elements > 0: + grid = (triton.cdiv(n_elements, _BLOCK_SIZE), ) + _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: """Pure-PyTorch reference used as the non-Triton fallback.""" @@ -139,3 +220,24 @@ def swiglu(gate: torch.Tensor, up: torch.Tensor) -> torch.Tensor: return _swiglu_eager(gate, up) return _SwiGLUFn.apply(gate, up) + + +def swiglu_packed(gate_up: torch.Tensor) -> torch.Tensor: + """Fused SwiGLU of a packed gate+up tensor: ``silu(gate_up[..., :I]) * gate_up[..., I:]``. + + Args: + gate_up: The gate and up projections side by side, shape ``[..., 2 * I]``, float16/bfloat16/float32. + + Returns: + Tensor of shape ``[..., I]`` and the dtype of ``gate_up``, matching :func:`swiglu` on the two halves. + + Falls back to the eager PyTorch expression when Triton is unavailable. + """ + if gate_up.dim() == 0 or gate_up.shape[-1] % 2: + raise ValueError(f"swiglu_packed expects an even last dimension, got shape {tuple(gate_up.shape)}") + + if not _TRITON_AVAILABLE: + gate, up = gate_up.chunk(2, dim=-1) + return _swiglu_eager(gate, up) + + return _SwiGLUPackedFn.apply(gate_up) diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index e010e555b3db..dca2b495f1f8 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -997,6 +997,12 @@ smoke coverage used for this AutoEP surface produced the following version gates | -------------------------------------------------------------------------------------------------------------- | -------- | | 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"` | +***gate_up_impl***: [string] + +| Description | Default | +| -------------------------------------------------------------------------------------------------------------- | -------- | +| 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. Parameters, checkpoints and optimizer state keep the separate `w1`/`w3` layout. Forward values and weight gradients are those of `"separate"`; the input gradient accumulates both projections in one FP32 GEMM accumulation 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"` | + ***route_norm***: [boolean] | Description | Default | diff --git a/docs/code-docs/source/autoep.rst b/docs/code-docs/source/autoep.rst index 766fbd14973a..3891b550cba5 100644 --- a/docs/code-docs/source/autoep.rst +++ b/docs/code-docs/source/autoep.rst @@ -231,6 +231,48 @@ SMs. The default of 12 was chosen by measuring whole steps: 8 SMs gave a median it is alone on the fabric, which exhausts the queue pairs ZeRO and the data-parallel groups have already claimed in a training step. +**Fused gate and up projections (experimental):** + +The grouped experts compute two projections of the same input, ``gate`` with +``w1`` and ``up`` with ``w3``, before the expert activation. ``gate_up_impl`` +selects whether they run as two grouped GEMMs or as one: + +.. code-block:: json + + { + "expert_parallel": { + "enabled": true, + "autoep_size": 8, + "gate_up_impl": "fused" + } + } + +``"separate"`` (default) keeps the existing two GEMMs. ``"fused"`` concatenates +``w1`` and ``w3`` on each call and runs one ``torch._grouped_mm`` with twice the +output columns. The activation then reads the two halves of that output in +place: ``swiglu`` uses a Triton kernel, and the other forms run their usual +expression on views of the halves. The parameters are not changed, so +checkpoints, universal checkpoints, expert tensor parallelism and optimizer +state, including Muon's per-expert treatment of ``w1`` and ``w3``, see the same +layout as before. + +Forward values and weight gradients are those of ``"separate"``. In the +backward pass, one input-gradient GEMM accumulates both projections in FP32, +where ``"separate"`` adds two BF16 results, so the input gradient can differ in +the last bits; it is at least as close to an FP64 reference. + +Most of the saving is in the backward pass: one input-gradient GEMM instead of +two, and no separate addition. On Qwen3-30B-A3B with 8 H100s (expert parallel +size 8, micro-batch 4, 16 accumulation steps, sequence length 4096, DeepEP and +reentrant activation checkpointing), a full optimizer step went from 22.02 s to +21.60 s (-1.9%) in two pairs measured in the same job, with unchanged peak +allocated memory and about 0.4 GB more reserved memory. + +``"fused"`` is rejected, rather than silently ignored, when the experts would +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``. + **DeepEP row weighting implementation (experimental):** DeepEP dispatch returns one received row per routed assignment and one FP32 diff --git a/tests/unit/v1/moe/test_autoep_expert_activation.py b/tests/unit/v1/moe/test_autoep_expert_activation.py index 91ffebb0d85a..841cbc09a88e 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 @@ EXPERT_ACTIVATIONS, GroupedExperts, apply_expert_activation, + apply_packed_expert_activation, register_expert_activation, ) from unit.v1.moe.autoep_test_utils import MockMoETransformer @@ -204,7 +205,7 @@ def test_for_loop_matches_dense_reference(self, activation): ref.sum().backward() torch.testing.assert_close(x.grad, x_ref.grad) - @pytest.mark.parametrize("path", ["grouped_mm", "triton_grouped_mm"]) + @pytest.mark.parametrize("path", ["grouped_mm", "triton_grouped_mm", "fused_gate_up"]) @pytest.mark.parametrize("activation", tuple(EXPERT_ACTIVATIONS)) def test_grouped_gemm_paths_match_the_for_loop(self, activation, path): # The grouped-GEMM paths hand the activation the packed [rows, ffn] tensors and, for swiglu, @@ -212,7 +213,7 @@ def test_grouped_gemm_paths_match_the_for_loop(self, activation, path): # three paths must compute the same function, forward and backward. Runs on the accelerator. if get_accelerator().device_name() == "cpu": pytest.skip("needs an accelerator") - if path == "grouped_mm" and not hasattr(torch, "_grouped_mm"): + if path in ("grouped_mm", "fused_gate_up") and not hasattr(torch, "_grouped_mm"): pytest.skip("this PyTorch build has no torch._grouped_mm") device = get_accelerator().current_device_name() torch.manual_seed(0) @@ -221,7 +222,11 @@ def test_grouped_gemm_paths_match_the_for_loop(self, activation, path): loop = GroupedExperts(use_grouped_mm=False, **shape, **act) for weight in (loop.w1, loop.w2, loop.w3): nn.init.normal_(weight, std=0.1) # pre-activations of order one: the clamps engage on ~1/5 of them - grouped = GroupedExperts(use_grouped_mm=True, disable_triton_grouped_mm=True, **shape, **act) + 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) @@ -263,6 +268,122 @@ def _fail(*args, **kwargs): assert experts(torch.randn(4, 8), torch.tensor([2, 2])).shape == (4, 8) +class TestFusedGateUp: + """gate_up_impl="fused": one grouped GEMM over the concatenated gate and up weights.""" + + @pytest.mark.parametrize("activation", tuple(EXPERT_ACTIVATIONS)) + def test_packed_activation_matches_the_separate_halves(self, activation): + # Same elementwise math on views of the two halves. On CPU, a strided view can take a different + # vectorization path than a contiguous tensor, so agreement is to rounding rather than bitwise. + torch.manual_seed(0) + gate = torch.randn(6, 5, requires_grad=True) + up = torch.randn(6, 5, requires_grad=True) + gate_up = torch.cat([gate, up], dim=-1).detach().requires_grad_(True) + expected = apply_expert_activation(gate, up, activation, 1.5, 1.0, fused=False) + packed = apply_packed_expert_activation(gate_up, activation, 1.5, 1.0, fused=False) + + torch.testing.assert_close(packed, expected) + grad = torch.randn_like(expected) + expected.backward(grad) + packed.backward(grad) + torch.testing.assert_close(gate_up.grad, torch.cat([gate.grad, up.grad], dim=-1)) + + def test_only_swiglu_has_a_packed_kernel(self): + # The other forms run their plain expression on views of the two halves, so none of them needs one. + assert [name for name, entry in EXPERT_ACTIVATIONS.items() if entry.packed_fused_fn] == ["swiglu"] + + def test_default_keeps_the_separate_projections(self): + assert parse_autoep_config({"enabled": True}).gate_up_impl == "separate" + assert GroupedExperts(dim=8, hidden_dim=16, num_experts=2, use_grouped_mm=False).gate_up_impl == "separate" + fused = parse_autoep_config({"enabled": True, "gate_up_impl": "fused"}) + assert fused.gate_up_impl == "fused" + + def test_unsupported_settings_are_rejected(self, monkeypatch): + + def validate(**settings): + validate_autoep_config(parse_autoep_config({"enabled": True, **settings}), 1, 1, 1, 1) + + validate(gate_up_impl="fused") + with pytest.raises(ValueError, match="gate_up_impl must be one of"): + validate(gate_up_impl="concat") + with pytest.raises(ValueError, match="sequential expert loop"): + validate(gate_up_impl="fused", use_grouped_mm=False) + with pytest.raises(ValueError, match="gate_up_impl must be"): + GroupedExperts(dim=8, hidden_dim=16, num_experts=2, use_grouped_mm=False, gate_up_impl="concat") + with pytest.raises(ValueError, match="sequential expert loop"): + GroupedExperts(dim=8, hidden_dim=16, num_experts=2, use_grouped_mm=False, gate_up_impl="fused") + # Devices below sm90 auto-select the Triton grouped GEMM, which has no fused form. + monkeypatch.setattr(type(get_accelerator()), "prefer_triton_grouped_mm", lambda self: True) + with pytest.raises(ValueError, match="disable_triton_grouped_mm"): + GroupedExperts(dim=8, hidden_dim=16, num_experts=2, use_grouped_mm=True, gate_up_impl="fused") + assert GroupedExperts(dim=8, + hidden_dim=16, + num_experts=2, + use_grouped_mm=True, + disable_triton_grouped_mm=True, + gate_up_impl="fused").gate_up_impl == "fused" + + def test_config_reaches_the_replaced_experts(self): + if not hasattr(torch, "_grouped_mm"): + pytest.skip("this PyTorch build has no torch._grouped_mm") + model = _custom_pattern_model() + config = _runtime_config(moe_layer_pattern=MOE_PATTERN, + use_grouped_mm=True, + disable_triton_grouped_mm=True, + gate_up_impl="fused") + auto_ep = AutoEP(model, config) + [spec] = auto_ep.ep_parser() + auto_ep.replace_moe_layer(spec, ep_size=1, ep_rank=0) + experts = model.model.layers[0].mlp.experts + assert experts.gate_up_impl == "fused" + # Parameters, and so checkpoints and optimizer state, keep the separate layout. + assert [name for name, _ in experts.named_parameters()] == ["w1", "w2", "w3"] + + @pytest.mark.parametrize("activation", tuple(EXPERT_ACTIVATIONS)) + def test_matches_separate_with_skewed_and_empty_experts(self, activation): + # Forward values and weight gradients are the separate path's; the input gradient sums both projections + # inside one FP32 GEMM accumulation, so it is held to FP64 instead and must be no less accurate. + if get_accelerator().device_name() != "cuda" or not hasattr(torch, "_grouped_mm"): + pytest.skip("needs CUDA with torch._grouped_mm and FP64") + device = get_accelerator().current_device_name() + torch.manual_seed(0) + shape = dict(dim=256, hidden_dim=384, num_experts=4) + act = dict(activation=activation, activation_alpha=1.5, activation_limit=1.0) + separate = GroupedExperts(use_grouped_mm=True, disable_triton_grouped_mm=True, **shape, **act) + for weight in (separate.w1, separate.w2, separate.w3): + nn.init.normal_(weight, std=0.06) + fused = GroupedExperts(use_grouped_mm=True, + disable_triton_grouped_mm=True, + gate_up_impl="fused", + **shape, + **act) + fused.load_state_dict(separate.state_dict()) + reference = copy.deepcopy(separate).to(device=device, dtype=torch.float64) + reference.use_grouped_mm = False + separate.to(device=device, dtype=torch.bfloat16) + fused.to(device=device, dtype=torch.bfloat16) + + counts = torch.tensor([37, 0, 291, 72], device=device) + x = torch.randn(int(counts.sum()), 256, device=device, dtype=torch.bfloat16) + grad_out = torch.randn(x.shape, device=device, dtype=torch.bfloat16) + inputs = {name: x.clone().requires_grad_(True) for name in ("separate", "fused")} + out_separate = separate(inputs["separate"], counts) + out_fused = fused(inputs["fused"], counts) + out_separate.backward(grad_out) + out_fused.backward(grad_out) + x_reference = x.double().requires_grad_(True) + reference(x_reference, counts).backward(grad_out.double()) + + torch.testing.assert_close(out_fused, out_separate, rtol=0, atol=0) + for name in ("w1", "w2", "w3"): + torch.testing.assert_close(getattr(fused, name).grad, getattr(separate, name).grad, rtol=0, atol=0) + + def relative_error(got): + return ((got.double() - x_reference.grad).norm() / x_reference.grad.norm()).item() + + assert relative_error(inputs["fused"].grad) <= relative_error(inputs["separate"].grad) * 1.05 + + class TestPresetAndConfig: def test_builtin_presets_name_their_form(self): 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 8c74d9453eae..d4b1dcdcb2b4 100644 --- a/tests/unit/v1/ops/triton_ops/test_swiglu_triton.py +++ b/tests/unit/v1/ops/triton_ops/test_swiglu_triton.py @@ -15,7 +15,7 @@ from deepspeed.accelerator import get_accelerator from deepspeed.ops.triton_ops import is_triton_available -from deepspeed.ops.triton_ops.swiglu_triton import swiglu +from deepspeed.ops.triton_ops.swiglu_triton import swiglu, swiglu_packed if not is_triton_available(): pytest.skip("Triton is not available", allow_module_level=True) @@ -98,6 +98,41 @@ def test_shape_mismatch_raises(): swiglu(gate, up) +@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16]) +@pytest.mark.parametrize("shape", [(32, 16), (1, 1), (7, 13), (4, 768), (3, 5, 384), (0, 16)]) +def test_packed_matches_the_separate_kernel_bitwise(dtype, shape): + # The packed kernel reads gate and up in place from one [..., 2 * I] tensor with the same FP32 math, so + # it must reproduce the separate kernel exactly, forward and backward. + 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) + gate_up = torch.cat([gate, up], dim=-1).detach().requires_grad_(True) + grad_out = torch.randn(shape, device=dev, dtype=dtype) + + out = swiglu_packed(gate_up) + expected = swiglu(gate, up) + assert out.shape == expected.shape and out.dtype == dtype + torch.testing.assert_close(out, expected, rtol=0, atol=0) + torch.testing.assert_close(out, _ref_swiglu(gate, up), **_tol(dtype)) + + out.backward(grad_out) + expected.backward(grad_out) + torch.testing.assert_close(gate_up.grad, torch.cat([gate.grad, up.grad], dim=-1), rtol=0, atol=0) + + +def test_packed_non_contiguous_input(): + dev = get_accelerator().current_device_name() + gate_up = torch.randn(32, 64, device=dev, dtype=torch.float32).t() + gate, up = gate_up.chunk(2, dim=-1) + + torch.testing.assert_close(swiglu_packed(gate_up), _ref_swiglu(gate, up), **_tol(torch.float32)) + + +def test_packed_odd_width_raises(): + with pytest.raises(ValueError, match="even last dimension"): + swiglu_packed(torch.randn(4, 7, device=get_accelerator().current_device_name())) + + def test_dtype_mismatch_raises(): dev = get_accelerator().current_device_name() gate = torch.randn(8, 16, device=dev, dtype=torch.float16) From a4b4067d45e53105b297d8104c641885ffdf679e Mon Sep 17 00:00:00 2001 From: yh0903 Date: Sat, 3 Oct 2026 20:00:12 -0700 Subject: [PATCH 2/5] Overlap AutoEP's expert weight gradients with the DeepEP backward combine In the DeepEP backward, the experts' input gradient is combined back to the token ranks while their weight gradients are independent of it, yet a grouped GEMM's backward computes both before the combine starts. With expert_parallel.overlap_weight_grad, the experts' backward returns the input gradient first and leaves its weight-gradient GEMMs in an ExpertWeightGradSlot. The DeepEP dispatch, which takes the expert weights as extra inputs, launches its backward combine asynchronously, runs those GEMMs on the compute stream with comm_num_sm SMs withheld through PyTorch's SM carveout so the combine has room to run, waits on the combine and returns the weight gradients through autograd. The GEMMs are the products autograd forms for torch._grouped_mm, so gradients are those of the serial backward. The activation registry gains optional standalone backward functions for the fused kernels, provided for swiglu; forms without one are recomputed and differentiated. The option is rejected unless comm_backend is deepep with autoep_size > 1, the experts run torch._grouped_mm, ZeRO stage is 1 or 2, and the SM carveout API exists. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: yh0903 --- deepspeed/module_inject/auto_ep_comm.py | 75 +++++++-- deepspeed/module_inject/auto_ep_config.py | 25 +++ deepspeed/module_inject/auto_ep_layer.py | 15 +- .../module_inject/auto_ep_presets/base.py | 1 + deepspeed/moe/ep_experts.py | 144 +++++++++++++++++- deepspeed/ops/triton_ops/swiglu_triton.py | 85 +++++++---- docs/_pages/config-json.md | 6 + docs/code-docs/source/autoep.rst | 48 ++++++ tests/unit/module_inject/test_auto_ep_comm.py | 140 ++++++++++++++++- .../unit/v1/moe/test_autoep_deepep_parity.py | 32 +++- .../v1/moe/test_autoep_expert_activation.py | 115 ++++++++++++++ .../v1/ops/triton_ops/test_swiglu_triton.py | 19 ++- 12 files changed, 654 insertions(+), 51 deletions(-) diff --git a/deepspeed/module_inject/auto_ep_comm.py b/deepspeed/module_inject/auto_ep_comm.py index d08b43975344..76f0745527c2 100644 --- a/deepspeed/module_inject/auto_ep_comm.py +++ b/deepspeed/module_inject/auto_ep_comm.py @@ -319,6 +319,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. @@ -354,6 +366,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 _conform_rows(tensor: torch.Tensor, shape) -> torch.Tensor: """Trim or zero-extend ``tensor`` to ``shape``'s row count. @@ -376,9 +402,18 @@ 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): + def forward(ctx, + exchange: DeepEPExchange, + tokens: torch.Tensor, + topk_idx: torch.Tensor, + topk_weights: torch.Tensor, + weight_grad_slot=None, + *expert_weights): received, recv_weights, handle = exchange.dispatch(tokens, topk_idx, topk_weights) + # 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 @@ -391,15 +426,21 @@ 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) + expert_grads = run_with_sm_carveout(ctx.exchange.num_sms, ctx.weight_grad_slot.run) + 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 + return (None, _conform_rows(grad_tokens, ctx.tokens_shape), None, conformed_weights, None, *expert_grads) class _DeepEPCombine(torch.autograd.Function): @@ -420,10 +461,20 @@ def backward(ctx, grad_combined): return None, _conform_rows(grad_rows, ctx.rows_shape), None -def deepep_dispatch(exchange: DeepEPExchange, tokens: torch.Tensor, topk_idx: torch.Tensor, - topk_weights: torch.Tensor): - """Dispatch tokens and their routing weights, keeping both differentiable.""" - received, recv_weights = _DeepEPDispatch.apply(exchange, tokens, topk_idx, topk_weights) +def deepep_dispatch(exchange: DeepEPExchange, + tokens: torch.Tensor, + topk_idx: torch.Tensor, + topk_weights: torch.Tensor, + 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. + """ + received, recv_weights = _DeepEPDispatch.apply(exchange, tokens, topk_idx, topk_weights, weight_grad_slot, + *expert_weights) return received, recv_weights, exchange diff --git a/deepspeed/module_inject/auto_ep_config.py b/deepspeed/module_inject/auto_ep_config.py index 007b9b9595ae..7377b2ba1d95 100644 --- a/deepspeed/module_inject/auto_ep_config.py +++ b/deepspeed/module_inject/auto_ep_config.py @@ -6,6 +6,8 @@ from __future__ import annotations +import torch + from deepspeed.module_inject.auto_ep_presets.base import ( _UNSET, _raise_unsupported_load_balance_coeff, @@ -62,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) @@ -209,6 +212,28 @@ 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 == 3: + raise ValueError("overlap_weight_grad returns expert weight gradients from the DeepEP dispatch, which " + "has not been validated with ZeRO stage 3 partitioned expert parameters. Use ZeRO " + "stage 1 or 2, or leave overlap_weight_grad unset.") + if not hasattr(torch._C, "_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 d46a4f405829..52dee2dcfae3 100644 --- a/deepspeed/module_inject/auto_ep_layer.py +++ b/deepspeed/module_inject/auto_ep_layer.py @@ -33,7 +33,7 @@ deepep_dispatch, 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) @@ -716,6 +716,11 @@ def __init__( self.comm_qp_margin = config.comm_qp_margin self._deepep_exchange = None 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: @@ -837,8 +842,12 @@ 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 () received, recv_weights, exchange = deepep_dispatch(self._deepep_exchange, tokens, ro.selected_experts, - ro.top_scores) + ro.top_scores, weight_grad_slot, expert_weights) handle = exchange.last_handle # combine reads exactly the rows the handle says arrived, taken from @@ -865,7 +874,7 @@ 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) + expert_output = self.experts(received, counts, weight_grad_slot) if weights is not None: expert_output = apply_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 d5904ad38bf9..9db681e2ca66 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 e868e208eb52..e9ffb9a3854a 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 @@ -126,7 +145,9 @@ def _swiglu_oai(gate: torch.Tensor, 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, uses_limit=True, gate_fn=F.silu) register_expert_activation("swiglu_oai", _swiglu_oai, uses_alpha=True, uses_limit=True) @@ -322,6 +343,114 @@ 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, torch.Tensor, torch.Tensor]]) -> 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, torch.Tensor, torch.Tensor]: + 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): + x, offsets, w2c, h, *projection = ctx.saved_tensors + 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) + + def weight_grads(): + grad_w2 = torch._grouped_mm(grad_out.transpose(-2, -1), h, offs=offsets) + if ctx.fused_gate_up: + grad_w13 = torch._grouped_mm(grad_gate_up.transpose(-2, -1), x, offs=offsets) + inter = grad_w13.shape[1] // 2 + grad_w1, grad_w3 = grad_w13.narrow(1, 0, inter), grad_w13.narrow(1, inter, inter) + else: + grad_w1 = torch._grouped_mm(grad_gate.transpose(-2, -1), x, offs=offsets) + grad_w3 = torch._grouped_mm(grad_up.transpose(-2, -1), x, offs=offsets) + return tuple(grad.to(dtype) 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) # --------------------------------------------------------------------------- @@ -462,17 +591,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 0b1005f6e4d5..43991ddcbf0a 100644 --- a/deepspeed/ops/triton_ops/swiglu_triton.py +++ b/deepspeed/ops/triton_ops/swiglu_triton.py @@ -96,24 +96,27 @@ 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), ) - _swiglu_bwd_kernel[grid](grad_out, - gate, - up, - grad_gate, - grad_up, - n_elements, - BLOCK_SIZE=_BLOCK_SIZE, - num_warps=_NUM_WARPS) + grad_gate = torch.empty_like(gate) + grad_up = torch.empty_like(up) - return grad_gate, grad_up + n_elements = gate.numel() + if n_elements > 0: + grid = (triton.cdiv(n_elements, _BLOCK_SIZE), ) + _swiglu_bwd_kernel[grid](grad_out, + gate, + up, + grad_gate, + grad_up, + n_elements, + BLOCK_SIZE=_BLOCK_SIZE, + num_warps=_NUM_WARPS) + + 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): @@ -176,21 +179,24 @@ def forward(ctx, gate_up: torch.Tensor) -> torch.Tensor: @staticmethod def backward(ctx, grad_out: torch.Tensor): 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), ) - _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), ) + _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: @@ -222,6 +228,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/docs/_pages/config-json.md b/docs/_pages/config-json.md index dca2b495f1f8..8510270708bc 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -1003,6 +1003,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. Parameters, checkpoints and optimizer state keep the separate `w1`/`w3` layout. Forward values and weight gradients are those of `"separate"`; the input gradient accumulates both projections in one FP32 GEMM accumulation 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. Gradients are those of the serial backward. 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, and a PyTorch build with `torch._C._set_sm_carveout_experimental`; unsupported configurations fail rather than falling back. | `false` | + ***route_norm***: [boolean] | Description | Default | diff --git a/docs/code-docs/source/autoep.rst b/docs/code-docs/source/autoep.rst index 3891b550cba5..0721bab56552 100644 --- a/docs/code-docs/source/autoep.rst +++ b/docs/code-docs/source/autoep.rst @@ -273,6 +273,54 @@ 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 gradients are those of the serial backward: the same GEMMs, in the same +products autograd forms for ``torch._grouped_mm``, run in a different order. + +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, and PyTorch provides +``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 fc1dbc9ea7d9..7ce6122b57de 100644 --- a/tests/unit/module_inject/test_auto_ep_comm.py +++ b/tests/unit/module_inject/test_auto_ep_comm.py @@ -362,7 +362,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 @@ -372,6 +372,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, @@ -448,9 +449,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), \ @@ -512,6 +514,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 @@ -720,6 +723,136 @@ 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, + 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 + experts = GroupedExperts(dim=self.HIDDEN, + hidden_dim=self.INTER, + num_experts=self.EXPERTS, + use_grouped_mm=True, + disable_triton_grouped_mm=True, + 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) + + 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, slot, + 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 in (None, "reentrant", "non_reentrant"): + with self.subTest(gate_up_impl=gate_up_impl, checkpoint=checkpoint): + overlapped, log = self.run_route(True, gate_up_impl, checkpoint) + 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()) + + class TestAutogradSignatures(unittest.TestCase): """Both directions must return a gradient for every differentiable input. @@ -745,7 +878,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, 4) + # The expert weights arrive as varargs when the backward overlaps, and return through *expert_grads. + self.assertEqual(inputs, 6) 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 3acdf55e01f7..1edad5ed1448 100644 --- a/tests/unit/v1/moe/test_autoep_deepep_parity.py +++ b/tests/unit/v1/moe/test_autoep_deepep_parity.py @@ -190,7 +190,8 @@ def _run_one_step(backend, reentrant_checkpointing=False, skewed_routing=False, row_weighting_impl="auto", - score_apply=None): + score_apply=None, + **expert_parallel): """Build a model on ``backend``, run one step, return its output and grads.""" seed_everything(seed) @@ -208,6 +209,7 @@ def _run_one_step(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 backend == "deepep": # Sized explicitly rather than from the first batch, so both backends # see identical shapes whatever that batch turns out to be. @@ -567,6 +569,34 @@ 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]) + def test_overlapped_weight_gradients_match_the_serial_backward(self, gate_up_impl, skewed_routing): + """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, + activation_checkpointing=True, + reentrant_checkpointing=True, + gate_up_impl=gate_up_impl, + 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) + + _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( "activation_checkpointing, skewed_routing", [ diff --git a/tests/unit/v1/moe/test_autoep_expert_activation.py b/tests/unit/v1/moe/test_autoep_expert_activation.py index 841cbc09a88e..ed8df4367483 100644 --- a/tests/unit/v1/moe/test_autoep_expert_activation.py +++ b/tests/unit/v1/moe/test_autoep_expert_activation.py @@ -28,6 +28,7 @@ from deepspeed.module_inject.auto_ep_presets.registry import resolve_preset_candidates from deepspeed.moe.ep_experts import ( EXPERT_ACTIVATIONS, + ExpertWeightGradSlot, GroupedExperts, apply_expert_activation, apply_packed_expert_activation, @@ -323,6 +324,36 @@ 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=0, **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) + 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) + with pytest.raises(ValueError, match="ZeRO stage 3"): + validate(overlap_weight_grad=True, zero_stage=3) + monkeypatch.delattr(torch._C, "_set_sm_carveout_experimental") + 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) + def test_config_reaches_the_replaced_experts(self): if not hasattr(torch, "_grouped_mm"): pytest.skip("this PyTorch build has no torch._grouped_mm") @@ -384,6 +415,90 @@ def relative_error(got): assert relative_error(inputs["fused"].grad) <= relative_error(inputs["separate"].grad) * 1.05 +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: + """Weight gradients left in a slot are the plain path's, bitwise; only when they are computed 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_bitwise_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") + 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_bitwise_with_the_fused_kernels(self, activation, gate_up_impl): + # On CUDA the swiglu forms run the Triton kernels, whose backward the deferred path calls directly. + 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) + + 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/ops/triton_ops/test_swiglu_triton.py b/tests/unit/v1/ops/triton_ops/test_swiglu_triton.py index d4b1dcdcb2b4..11551ede302a 100644 --- a/tests/unit/v1/ops/triton_ops/test_swiglu_triton.py +++ b/tests/unit/v1/ops/triton_ops/test_swiglu_triton.py @@ -15,7 +15,7 @@ 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 +from deepspeed.ops.triton_ops.swiglu_triton import swiglu, swiglu_backward, swiglu_packed, swiglu_packed_backward if not is_triton_available(): pytest.skip("Triton is not available", allow_module_level=True) @@ -120,6 +120,23 @@ def test_packed_matches_the_separate_kernel_bitwise(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_bitwise(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) + + def test_packed_non_contiguous_input(): dev = get_accelerator().current_device_name() gate_up = torch.randn(32, 64, device=dev, dtype=torch.float32).t() From 56dac2a02383204db9cd4bf969c4534ccc17d0fa Mon Sep 17 00:00:00 2001 From: yh0903 Date: Sat, 3 Oct 2026 20:16:54 -0700 Subject: [PATCH 3/5] Run the overlap tests' CPU cases where Triton is installed, and enable grouped GEMM in the DeepEP case Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: yh0903 --- tests/unit/module_inject/test_auto_ep_comm.py | 2 ++ tests/unit/v1/moe/test_autoep_deepep_parity.py | 1 + tests/unit/v1/moe/test_autoep_expert_activation.py | 4 ++++ 3 files changed, 7 insertions(+) diff --git a/tests/unit/module_inject/test_auto_ep_comm.py b/tests/unit/module_inject/test_auto_ep_comm.py index 7ce6122b57de..415a3c2bbd36 100644 --- a/tests/unit/module_inject/test_auto_ep_comm.py +++ b/tests/unit/module_inject/test_auto_ep_comm.py @@ -787,11 +787,13 @@ def run_route(self, overlap, gate_up_impl="separate", checkpoint=None): 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): diff --git a/tests/unit/v1/moe/test_autoep_deepep_parity.py b/tests/unit/v1/moe/test_autoep_deepep_parity.py index 1edad5ed1448..78a45a67ab02 100644 --- a/tests/unit/v1/moe/test_autoep_deepep_parity.py +++ b/tests/unit/v1/moe/test_autoep_deepep_parity.py @@ -583,6 +583,7 @@ def test_overlapped_weight_gradients_match_the_serial_backward(self, gate_up_imp 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) diff --git a/tests/unit/v1/moe/test_autoep_expert_activation.py b/tests/unit/v1/moe/test_autoep_expert_activation.py index ed8df4367483..5bf2c64818f7 100644 --- a/tests/unit/v1/moe/test_autoep_expert_activation.py +++ b/tests/unit/v1/moe/test_autoep_expert_activation.py @@ -25,6 +25,7 @@ validate_autoep_config, ) from deepspeed.module_inject.auto_ep_layer import AutoEPMoELayer +from deepspeed.ops.triton_ops import is_triton_available from deepspeed.module_inject.auto_ep_presets.registry import resolve_preset_candidates from deepspeed.moe.ep_experts import ( EXPERT_ACTIVATIONS, @@ -471,6 +472,9 @@ def _compare(self, device, dtype, activation, gate_up_impl, deferred): def test_matches_the_plain_path_bitwise_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(): + # The grouped path's fused kernel is Triton, which reads CUDA tensors only; the CUDA test covers it. + 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) From 0ba538a99e8e5902e7bdbffa0a6734628d01be11 Mon Sep 17 00:00:00 2001 From: yh0903 Date: Tue, 10 Nov 2026 16:45:06 -0800 Subject: [PATCH 4/5] Skip frozen expert weight-gradient GEMMs in AutoEP overlap Use autograd input-gradient requirements to omit dW work for frozen expert weights and return None, while retaining dX and active parameter gradients. Keep the fused gate/up dW GEMM whenever either projection is trainable. Compare frozen-weight GEMM counts with the serial path and explicitly verify native DeepEP ElasticBuffer in model parity. Existing optimizer support, numerical bounds, scheduling and defaults are unchanged. The human author reviewed the exact four-file diff before signoff. Focused H100 validation passed 40 cases on the public parent and 16 on this repair source tree, with source seals and JUnit counts verified. CPU regressions and changed-files pre-commit passed; no new throughput or convergence sweep was run. Signed-off-by: yh0903 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- deepspeed/moe/ep_experts.py | 31 +++++++---- docs/code-docs/source/autoep.rst | 2 + .../unit/v1/moe/test_autoep_deepep_parity.py | 5 ++ .../v1/moe/test_autoep_expert_activation.py | 53 +++++++++++++++++++ 4 files changed, 82 insertions(+), 9 deletions(-) diff --git a/deepspeed/moe/ep_experts.py b/deepspeed/moe/ep_experts.py index 1c56f3c66454..3b1af6391974 100644 --- a/deepspeed/moe/ep_experts.py +++ b/deepspeed/moe/ep_experts.py @@ -409,12 +409,13 @@ class ExpertWeightGradSlot: def __init__(self): self._compute = None - def defer(self, compute: Callable[[], tuple[torch.Tensor, torch.Tensor, torch.Tensor]]) -> 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, torch.Tensor, torch.Tensor]: + 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") @@ -469,16 +470,28 @@ def backward(ctx, grad_out): 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_w2 = torch._grouped_mm(grad_out.transpose(-2, -1), h, offs=offsets) + 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: - grad_w13 = torch._grouped_mm(grad_gate_up.transpose(-2, -1), x, offs=offsets) - inter = grad_w13.shape[1] // 2 - grad_w1, grad_w3 = grad_w13.narrow(1, 0, inter), grad_w13.narrow(1, inter, inter) + 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: - grad_w1 = torch._grouped_mm(grad_gate.transpose(-2, -1), x, offs=offsets) - grad_w3 = torch._grouped_mm(grad_up.transpose(-2, -1), x, offs=offsets) - return tuple(grad.to(dtype) for grad, dtype in zip((grad_w1, grad_w2, grad_w3), ctx.weight_dtypes)) + 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) diff --git a/docs/code-docs/source/autoep.rst b/docs/code-docs/source/autoep.rst index 8acbe1701575..6ecc52c53bae 100644 --- a/docs/code-docs/source/autoep.rst +++ b/docs/code-docs/source/autoep.rst @@ -351,6 +351,8 @@ 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 diff --git a/tests/unit/v1/moe/test_autoep_deepep_parity.py b/tests/unit/v1/moe/test_autoep_deepep_parity.py index b7ab2a237316..f4ecd316c643 100644 --- a/tests/unit/v1/moe/test_autoep_deepep_parity.py +++ b/tests/unit/v1/moe/test_autoep_deepep_parity.py @@ -666,6 +666,11 @@ def test_overlapped_weight_gradients_match_the_serial_backward(self, gate_up_imp 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()] diff --git a/tests/unit/v1/moe/test_autoep_expert_activation.py b/tests/unit/v1/moe/test_autoep_expert_activation.py index 4a2087ca3f5b..61a06cdc82a0 100644 --- a/tests/unit/v1/moe/test_autoep_expert_activation.py +++ b/tests/unit/v1/moe/test_autoep_expert_activation.py @@ -645,6 +645,59 @@ def test_matches_the_plain_path_exactly_with_the_fused_kernels(self, activation, 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"): From 285f6e90fd884c2c0cab96561fea71bb890eab50 Mon Sep 17 00:00:00 2001 From: Masahiro Tanaka Date: Sat, 14 Nov 2026 13:33:06 -0800 Subject: [PATCH 5/5] Fix duplicate AutoEP Triton availability import Signed-off-by: Masahiro Tanaka --- tests/unit/v1/moe/test_autoep_expert_activation.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/unit/v1/moe/test_autoep_expert_activation.py b/tests/unit/v1/moe/test_autoep_expert_activation.py index 8bc93a2c3ae4..30dff3aab603 100644 --- a/tests/unit/v1/moe/test_autoep_expert_activation.py +++ b/tests/unit/v1/moe/test_autoep_expert_activation.py @@ -27,7 +27,6 @@ validate_autoep_config, ) from deepspeed.module_inject.auto_ep_layer import AutoEPMoELayer -from deepspeed.ops.triton_ops import is_triton_available from deepspeed.module_inject.auto_ep_presets.registry import resolve_preset_candidates from deepspeed.moe.ep_experts import ( EXPERT_ACTIVATIONS,