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..68cbb52bc51a 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,45 @@ 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 expression and parameter-gradient semantics are unchanged; exact numerical equality + across GEMM shapes and implementations is not guaranteed. + + 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 +396,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 +411,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 +444,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 +477,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..83c289e54f79 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,90 @@ 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), ) + # Triton uses the current device and stream, which may differ from the input tensor's device. + with torch.cuda.device(gate_up.device): #ignore-cuda + _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): + # The Triton backward has no autograd graph, so create_graph would silently lose the second derivative. + if torch.is_grad_enabled(): + raise RuntimeError("The packed SwiGLU kernel has no second derivative; " + "backward with create_graph=True is not supported") + gate_up, = ctx.saved_tensors + grad_out = grad_out.contiguous() + grad_gate_up = torch.empty_like(gate_up) + + n_elements = grad_out.numel() + if n_elements > 0: + grid = (triton.cdiv(n_elements, _BLOCK_SIZE), ) + with torch.cuda.device(gate_up.device): #ignore-cuda + _swiglu_packed_bwd_kernel[grid](grad_out, + gate_up, + grad_gate_up, + n_elements, + INTER=gate_up.shape[-1] // 2, + BLOCK_SIZE=_BLOCK_SIZE, + num_warps=_NUM_WARPS) + + return grad_gate_up + def _swiglu_eager(gate: torch.Tensor, up: torch.Tensor) -> torch.Tensor: """Pure-PyTorch reference used as the non-Triton fallback.""" @@ -139,3 +227,26 @@ 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. + + The Triton path supports first-order gradients only and raises for ``create_graph=True``. + Forward and backward use the input device's current stream and restore the caller's current device. + 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 3ca6bf9064c1..698da5c25ff8 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 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 with first-order gradients only (`create_graph=True` raises). Parameters, checkpoints and optimizer state keep the separate `w1`/`w3` layout. The forward expression and parameter-gradient semantics are unchanged, but exact numerical equality is not guaranteed across GEMM shapes/backends; the input gradient accumulates both projections in one FP32 GEMM instead of adding two rounded results. Requires `use_grouped_mm=true` and the `torch._grouped_mm` path (set `disable_triton_grouped_mm=true` on devices that prefer the Triton grouped GEMM); unsupported configurations fail rather than falling back. | `"separate"` | + ***route_norm***: [boolean] | Description | Default | diff --git a/docs/code-docs/source/autoep.rst b/docs/code-docs/source/autoep.rst index 1859b02cf595..91cd96e71330 100644 --- a/docs/code-docs/source/autoep.rst +++ b/docs/code-docs/source/autoep.rst @@ -231,6 +231,66 @@ 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. + +The forward expression and parameter-gradient semantics are unchanged. Exact +output and weight-gradient equality was observed in the tested H100 cases, +not guaranteed for all GEMM backends, shapes or hardware. In the +backward pass, one input-gradient GEMM accumulates both projections in FP32, +where ``"separate"`` adds two results rounded to the input dtype, so the input gradient can differ in +the last bits. The numerical regression compares relative L2 errors with an +FP64 reference using the same represented BF16 parameters; it does not claim +universal bitwise equivalence or accuracy improvement. +Forward and parameter-gradient checks use the grouped-GEMM tests' existing +BF16 bound (2% relative plus 2% of the reference tensor's maximum magnitude). +The clamped activations' parameter gradients use an independent dense BF16 +reference because rounding a projection across the clamp boundary changes +its derivative discontinuously; smooth forms use the FP64 reference. +The input-gradient relative-L2 bound is unchanged. Cross-algorithm training +checks allow the same rounding scale, while reloading each parameter and +optimizer momentum tensor must still preserve its saved values exactly. + +The packed SwiGLU Triton path supports first-order gradients only: +``create_graph=True`` raises instead of silently dropping its second derivative. +Forward and backward launch on the input device's current stream, restoring +the caller's device. Other activations keep their existing eager expression. + +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 using an equivalent benchmark prototype in the +same allocation, 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..dbd4cb8fd32f 100644 --- a/tests/unit/v1/moe/test_autoep_expert_activation.py +++ b/tests/unit/v1/moe/test_autoep_expert_activation.py @@ -8,6 +8,7 @@ """ import copy +import io import math from types import SimpleNamespace @@ -15,6 +16,7 @@ import torch import torch.nn as nn import torch.nn.functional as F +from torch.utils.checkpoint import checkpoint from deepspeed.accelerator import get_accelerator from deepspeed.module_inject.auto_ep import AutoEP @@ -30,6 +32,7 @@ EXPERT_ACTIVATIONS, GroupedExperts, apply_expert_activation, + apply_packed_expert_activation, register_expert_activation, ) from unit.v1.moe.autoep_test_utils import MockMoETransformer @@ -68,6 +71,12 @@ def _written_out(gate, up, activation, alpha, limit): raise AssertionError(f"{activation}: add it here when adding a built-in form") +def _assert_bf16_gemm_close(actual, expected): + # Rounding error through several GEMMs/activation operations scales with the tensor magnitude, + # not each near-zero element. Reuse the grouped-GEMM suite's existing 2% magnitude-scaled bound. + torch.testing.assert_close(actual.double(), expected.double(), rtol=2e-2, atol=2e-2 * expected.abs().max().item()) + + class TestApplyExpertActivation: def test_swiglu_oai_known_values(self): @@ -204,7 +213,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 +221,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 +230,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) @@ -237,16 +250,10 @@ def test_grouped_gemm_paths_match_the_for_loop(self, activation, path): out_loop.backward(grad_out) out_grouped.backward(grad_out) - # The paths differ only in bf16 rounding: the fused kernel rounds once after fp32 math, the - # eager ops once per op. A matmul then sums the rounded values, so the absolute error of an - # output or gradient scales with the largest magnitude in that tensor, not with each element. - def assert_same(got, want): - torch.testing.assert_close(got, want, rtol=2e-2, atol=2e-2 * want.abs().max().item()) - - assert_same(out_grouped, out_loop) - assert_same(x_grouped.grad, x_loop.grad) + _assert_bf16_gemm_close(out_grouped, out_loop) + _assert_bf16_gemm_close(x_grouped.grad, x_loop.grad) for name in ("w1", "w2", "w3"): - assert_same(getattr(grouped, name).grad, getattr(loop, name).grad) + _assert_bf16_gemm_close(getattr(grouped, name).grad, getattr(loop, name).grad) def test_for_loop_path_does_not_need_the_triton_kernel(self, monkeypatch): # The for-loop path is the reference path and runs on CPU tensors. It must not reach the @@ -263,6 +270,212 @@ 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.""" + + def test_gemm_error_bound_accepts_rounding_but_rejects_incorrect_values(self): + expected = torch.tensor([1.0, -0.25, 0.0, 2.0], dtype=torch.float64) + rounded = expected.to(torch.bfloat16) + rounded[0] = torch.nextafter(rounded[0], torch.full_like(rounded[0], float("inf"))) + _assert_bf16_gemm_close(rounded, expected) + incorrect = rounded.clone() + incorrect[0] += 0.25 + with pytest.raises(AssertionError): + _assert_bf16_gemm_close(incorrect, expected) + + @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): + # Different valid GEMM algorithms need not round identically. Check both paths against FP64 with + # the same represented weights, retaining the existing magnitude-scaled and input-gradient L2 bounds. + 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()) + separate.to(device=device, dtype=torch.bfloat16) + fused.to(device=device, dtype=torch.bfloat16) + reference = copy.deepcopy(separate).to(dtype=torch.float64) + reference.use_grouped_mm = False + + 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) + out_reference = reference(x_reference, counts) + out_reference.backward(grad_out.double()) + + for output in (out_fused, out_separate): + _assert_bf16_gemm_close(output, out_reference) + weight_reference = reference + if EXPERT_ACTIVATIONS[activation].uses_limit: + # BF16 projection rounding can cross a clamp's derivative discontinuity. Use independent + # dense BF16 matmuls for the parameter-gradient reference instead of changing the bound. + weight_reference = copy.deepcopy(separate) + weight_reference.use_grouped_mm = False + weight_reference.zero_grad() + weight_reference(x.clone().requires_grad_(True), counts).backward(grad_out) + for experts in (fused, separate): + for name in ("w1", "w2", "w3"): + _assert_bf16_gemm_close(getattr(experts, name).grad, getattr(weight_reference, name).grad) + assert not getattr(experts, name).grad[1].any() + + 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 + + @pytest.mark.parametrize("activation", tuple(EXPERT_ACTIVATIONS)) + @pytest.mark.parametrize("recompute", [False, True]) + def test_accumulated_updates_and_checkpoint_keep_the_separate_parameters(self, activation, recompute): + if get_accelerator().device_name() != "cuda" or not hasattr(torch, "_grouped_mm"): + pytest.skip("needs CUDA with torch._grouped_mm") + device = get_accelerator().current_device_name() + generator = torch.Generator(device=device).manual_seed(8733) + shape = dict(dim=256, hidden_dim=384, num_experts=4) + settings = dict(use_grouped_mm=True, + disable_triton_grouped_mm=True, + activation=activation, + activation_alpha=1.5, + activation_limit=1.0) + separate = GroupedExperts(**shape, **settings).to(device=device, dtype=torch.bfloat16) + for weight in separate.parameters(): + nn.init.normal_(weight, std=0.06, generator=generator) + fused = GroupedExperts(**shape, **settings, gate_up_impl="fused").to(device=device, dtype=torch.bfloat16) + fused.load_state_dict(separate.state_dict()) + separate_optimizer = torch.optim.SGD(separate.parameters(), lr=0.01, momentum=0.9) + fused_optimizer = torch.optim.SGD(fused.parameters(), lr=0.01, momentum=0.9) + counts = torch.tensor([16, 0, 32, 16], device=device) + + for step in range(2): + for _ in range(2): + hidden = torch.randn((64, 256), device=device, dtype=torch.bfloat16, generator=generator) + upstream = torch.randn(hidden.shape, device=device, dtype=hidden.dtype, generator=generator) + expected = separate(hidden.clone().requires_grad_(True), counts) + fused_hidden = hidden.clone().requires_grad_(True) + actual = checkpoint(fused, fused_hidden, counts, use_reentrant=True) if recompute else fused( + fused_hidden, counts) + _assert_bf16_gemm_close(actual, expected) + actual.backward(upstream) + expected.backward(upstream) + for name in ("w1", "w2", "w3"): + _assert_bf16_gemm_close(getattr(fused, name).grad, getattr(separate, name).grad) + assert not getattr(fused, name).grad[1].any() + separate_optimizer.step() + fused_optimizer.step() + for name in ("w1", "w2", "w3"): + fused_weight, reference_weight = getattr(fused, name), getattr(separate, name) + _assert_bf16_gemm_close(fused_weight, reference_weight) + _assert_bf16_gemm_close(fused_optimizer.state[fused_weight]["momentum_buffer"], + separate_optimizer.state[reference_weight]["momentum_buffer"]) + assert tuple(fused.state_dict()) == ("w1", "w2", "w3") + separate_optimizer.zero_grad() + fused_optimizer.zero_grad() + + if step == 0: + # The next update must use reloaded separate parameters, not a cached concatenation or optimizer layout. + serialized = io.BytesIO() + torch.save({"experts": fused.state_dict(), "optimizer": fused_optimizer.state_dict()}, serialized) + serialized.seek(0) + state = torch.load(serialized, weights_only=True) + fused = GroupedExperts(**shape, **settings, gate_up_impl="fused").to(device=device, + dtype=torch.bfloat16) + fused.load_state_dict(state["experts"]) + for name in ("w1", "w2", "w3"): + torch.testing.assert_close(getattr(fused, name), state["experts"][name], rtol=0, atol=0) + fused_optimizer = torch.optim.SGD(fused.parameters(), lr=0.01, momentum=0.9) + fused_optimizer.load_state_dict(state["optimizer"]) + assert fused_optimizer.state_dict()["param_groups"] == state["optimizer"]["param_groups"] + saved_parameter_ids = state["optimizer"]["param_groups"][0]["params"] + for parameter, saved_id in zip(fused.parameters(), saved_parameter_ids): + torch.testing.assert_close(fused_optimizer.state[parameter]["momentum_buffer"], + state["optimizer"]["state"][saved_id]["momentum_buffer"], + rtol=0, + atol=0) + + 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..61c1b16fe346 100644 --- a/tests/unit/v1/ops/triton_ops/test_swiglu_triton.py +++ b/tests/unit/v1/ops/triton_ops/test_swiglu_triton.py @@ -13,15 +13,19 @@ import torch import torch.nn.functional as F -from deepspeed.accelerator import get_accelerator -from deepspeed.ops.triton_ops import is_triton_available -from deepspeed.ops.triton_ops.swiglu_triton import swiglu -if not is_triton_available(): - pytest.skip("Triton is not available", allow_module_level=True) +@pytest.fixture(autouse=True) +def _load_swiglu_in_the_worker(): + global get_accelerator, swiglu, swiglu_packed + # The shared Triton availability probe initializes its driver, so it must run after pytest forks its worker. + from deepspeed.accelerator import get_accelerator + from deepspeed.ops.triton_ops import is_triton_available + from deepspeed.ops.triton_ops.swiglu_triton import swiglu, swiglu_packed -if not (get_accelerator().is_available() and get_accelerator().device_name() == "cuda"): - pytest.skip("Fused Triton SwiGLU requires a CUDA device", allow_module_level=True) + if not is_triton_available(): + pytest.skip("Triton is not available") + if not (get_accelerator().is_available() and get_accelerator().device_name() == "cuda"): + pytest.skip("Fused Triton SwiGLU requires a CUDA device") def _tol(dtype): @@ -98,6 +102,88 @@ 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_exactly(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's values exactly, forward and backward. + generator = torch.Generator(device=get_accelerator().current_device_name()).manual_seed(8733) + dev = get_accelerator().current_device_name() + gate = torch.randn(shape, device=dev, dtype=dtype, generator=generator, requires_grad=True) + up = torch.randn(shape, device=dev, dtype=dtype, generator=generator, requires_grad=True) + gate_up = torch.cat([gate, up], dim=-1).detach().requires_grad_(True) + grad_out = torch.randn(shape, device=dev, dtype=dtype, generator=generator) + + 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) + + +@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16]) +def test_packed_non_contiguous_input_and_gradient(dtype): + dev = get_accelerator().current_device_name() + generator = torch.Generator(device=dev).manual_seed(8733) + gate_up = torch.randn(32, 64, device=dev, dtype=dtype, generator=generator).t().requires_grad_(True) + reference = gate_up.detach().clone().requires_grad_(True) + gate, up = reference.chunk(2, dim=-1) + upstream = torch.randn(16, 64, device=dev, dtype=dtype, generator=generator).t() + assert not gate_up.is_contiguous() and not upstream.is_contiguous() + + actual = swiglu_packed(gate_up) + expected = swiglu(gate, up) + torch.testing.assert_close(actual, _ref_swiglu(gate, up), **_tol(dtype)) + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + actual.backward(upstream) + expected.backward(upstream) + torch.testing.assert_close(gate_up.grad, reference.grad, rtol=0, atol=0) + + +@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16]) +def test_packed_create_graph_is_rejected(dtype): + dev = get_accelerator().current_device_name() + gate_up = torch.ones((4, 32), device=dev, dtype=dtype, requires_grad=True) + loss = swiglu_packed(gate_up).float().sum() + with pytest.raises(RuntimeError, match="second derivative"): + torch.autograd.grad(loss, gate_up, create_graph=True) + + +@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16]) +def test_packed_uses_the_input_device_and_stream(dtype): + accelerator = get_accelerator() + if accelerator.device_count() < 2: + pytest.skip("cross-device launch regression needs two CUDA devices") + with torch.cuda.device(0): #ignore-cuda + caller_stream = accelerator.current_stream() + input_device = accelerator.device_name(1) + stream = accelerator.Stream(device=1) + with accelerator.stream(stream): + gate_up = torch.ones((7, 26), device=input_device, dtype=dtype, requires_grad=True) + reference = gate_up.detach().clone().requires_grad_(True) + with accelerator.stream(stream), torch.cuda.device(0): #ignore-cuda + actual = swiglu_packed(gate_up) + assert accelerator.current_device() == 0 + gate, up = reference.chunk(2, dim=-1) + expected = _ref_swiglu(gate, up) + actual.float().sum().backward() + expected.float().sum().backward() + assert accelerator.current_device() == 0 + stream.synchronize() + assert accelerator.current_stream() == caller_stream + torch.testing.assert_close(actual, expected, **_tol(dtype)) + torch.testing.assert_close(gate_up.grad, reference.grad, **_tol(dtype)) + + +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)