From b5febe562af7ba948cc1b3546bf449fe66bec2fc Mon Sep 17 00:00:00 2001 From: pengdurice Date: Thu, 15 Oct 2026 19:30:21 +0000 Subject: [PATCH] AutoEP: fused Triton kernel for the clamped expert activations Signed-off-by: pengdurice --- deepspeed/moe/ep_experts.py | 34 ++- deepspeed/ops/triton_ops/swiglu_triton.py | 232 ++++++++++++++++++ docs/_pages/config-json.md | 2 +- .../v1/moe/test_autoep_expert_activation.py | 33 ++- .../v1/ops/triton_ops/test_swiglu_triton.py | 185 +++++++++++++- 5 files changed, 477 insertions(+), 9 deletions(-) diff --git a/deepspeed/moe/ep_experts.py b/deepspeed/moe/ep_experts.py index 68cbb52bc51a..832adcc5a7d0 100644 --- a/deepspeed/moe/ep_experts.py +++ b/deepspeed/moe/ep_experts.py @@ -122,14 +122,44 @@ def _swiglu_oai(gate: torch.Tensor, up: torch.Tensor, alpha: float, limit: float return (up + 1.0) * (gate * torch.sigmoid(gate * alpha)) +def _swiglu_clamped_fused(gate: torch.Tensor, up: torch.Tensor, alpha: float, limit: float) -> torch.Tensor: + from deepspeed.ops.triton_ops.swiglu_triton import swiglu_clamped + return swiglu_clamped(gate, up, alpha=alpha, limit=limit, oai=False) + + +def _swiglu_oai_fused(gate: torch.Tensor, up: torch.Tensor, alpha: float, limit: float) -> torch.Tensor: + from deepspeed.ops.triton_ops.swiglu_triton import swiglu_clamped + return swiglu_clamped(gate, up, alpha=alpha, limit=limit, oai=True) + + +def _swiglu_clamped_packed_fused(gate_up: torch.Tensor, alpha: float, limit: float) -> torch.Tensor: + from deepspeed.ops.triton_ops.swiglu_triton import swiglu_clamped_packed + return swiglu_clamped_packed(gate_up, alpha=alpha, limit=limit, oai=False) + + +def _swiglu_oai_packed_fused(gate_up: torch.Tensor, alpha: float, limit: float) -> torch.Tensor: + from deepspeed.ops.triton_ops.swiglu_triton import swiglu_clamped_packed + return swiglu_clamped_packed(gate_up, alpha=alpha, limit=limit, oai=True) + + 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) +register_expert_activation("swiglu_clamped", + _swiglu_clamped, + fused_fn=_swiglu_clamped_fused, + uses_limit=True, + gate_fn=F.silu, + packed_fused_fn=_swiglu_clamped_packed_fused) +register_expert_activation("swiglu_oai", + _swiglu_oai, + fused_fn=_swiglu_oai_fused, + uses_alpha=True, + uses_limit=True, + packed_fused_fn=_swiglu_oai_packed_fused) def apply_expert_activation(gate: torch.Tensor, diff --git a/deepspeed/ops/triton_ops/swiglu_triton.py b/deepspeed/ops/triton_ops/swiglu_triton.py index 83c289e54f79..4035f3e1cccb 100644 --- a/deepspeed/ops/triton_ops/swiglu_triton.py +++ b/deepspeed/ops/triton_ops/swiglu_triton.py @@ -250,3 +250,235 @@ def swiglu_packed(gate_up: torch.Tensor) -> torch.Tensor: return _swiglu_eager(gate, up) return _SwiGLUPackedFn.apply(gate_up) + + +# --------------------------------------------------------------------------- +# Clamped forms: silu(clamp(gate)) * clamp(up) ("swiglu_clamped", DeepSeek-V4) +# (clamp(up) + 1) * g * sigmoid(alpha * g) ("swiglu_oai", GPT-OSS / MiniMax-M3), g = clamp(gate) +# gate is clamped from above only, up on both sides. Same fusion as above: one kernel each way, float32 +# math, only gate and up saved for backward. The eager expression saves about five [rows, ffn] temporaries +# (the two clamps, the sigmoid, the products); on an expert-parallel rank that receives several times the +# average rows this is where the memory goes (MiniMax-M3, 65,536 tokens: an 11.96 GiB temporary here). +# --------------------------------------------------------------------------- + +if _TRITON_AVAILABLE: + + @triton.jit + def _swiglu_clamped_fwd_kernel(gate_ptr, up_ptr, out_ptr, n_elements, alpha, limit, OAI: tl.constexpr, + PACKED: tl.constexpr, 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 + if PACKED: + # gate_ptr and up_ptr are the same [rows, 2 * INTER] tensor, as in _swiglu_packed_fwd_kernel. + gate_offsets = (offsets // INTER) * (2 * INTER) + offsets % INTER + up_offsets = gate_offsets + INTER + else: + gate_offsets = offsets + up_offsets = offsets + + gate = tl.load(gate_ptr + gate_offsets, mask=mask).to(tl.float32) + up = tl.load(up_ptr + up_offsets, mask=mask).to(tl.float32) + g = tl.minimum(gate, limit) + u = tl.minimum(tl.maximum(up, -limit), limit) + + if OAI: + out = (u + 1.0) * (g * tl.sigmoid(g * alpha)) + else: + out = (g * tl.sigmoid(g)) * u + + tl.store(out_ptr + offsets, out.to(out_ptr.dtype.element_ty), mask=mask) + + @triton.jit + def _swiglu_clamped_bwd_kernel(grad_out_ptr, gate_ptr, up_ptr, grad_gate_ptr, grad_up_ptr, n_elements, alpha, + limit, OAI: tl.constexpr, PACKED: tl.constexpr, 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 + if PACKED: + gate_offsets = (offsets // INTER) * (2 * INTER) + offsets % INTER + up_offsets = gate_offsets + INTER + else: + gate_offsets = offsets + up_offsets = offsets + + grad_out = tl.load(grad_out_ptr + offsets, mask=mask).to(tl.float32) + gate = tl.load(gate_ptr + gate_offsets, mask=mask).to(tl.float32) + up = tl.load(up_ptr + up_offsets, mask=mask).to(tl.float32) + g = tl.minimum(gate, limit) + u = tl.minimum(tl.maximum(up, -limit), limit) + # torch.clamp passes the gradient through where the input is inside the limits, inclusive. + pass_gate = gate <= limit + pass_up = (up >= -limit) & (up <= limit) + + if OAI: + sig = tl.sigmoid(g * alpha) + f = g * sig + df = sig * (1.0 + alpha * g * (1.0 - sig)) + grad_gate = grad_out * (u + 1.0) * df + grad_up = grad_out * f + else: + sig = tl.sigmoid(g) + f = g * sig + df = sig * (1.0 + g * (1.0 - sig)) + grad_gate = grad_out * u * df + grad_up = grad_out * f + grad_gate = tl.where(pass_gate, grad_gate, 0.0) + grad_up = tl.where(pass_up, grad_up, 0.0) + + tl.store(grad_gate_ptr + gate_offsets, grad_gate.to(grad_gate_ptr.dtype.element_ty), mask=mask) + tl.store(grad_up_ptr + up_offsets, grad_up.to(grad_up_ptr.dtype.element_ty), mask=mask) + + class _SwiGLUClampedFn(torch.autograd.Function): + + @staticmethod + def forward(ctx, gate: torch.Tensor, up: torch.Tensor, alpha: float, limit: float, oai: bool) -> torch.Tensor: + gate = gate.contiguous() + up = up.contiguous() + out = torch.empty_like(gate) + n_elements = gate.numel() + if n_elements > 0: + grid = (triton.cdiv(n_elements, _BLOCK_SIZE), ) + _swiglu_clamped_fwd_kernel[grid](gate, + up, + out, + n_elements, + float(alpha), + float(limit), + OAI=oai, + PACKED=False, + INTER=1, + BLOCK_SIZE=_BLOCK_SIZE, + num_warps=_NUM_WARPS) + ctx.save_for_backward(gate, up) + ctx.alpha, ctx.limit, ctx.oai = float(alpha), float(limit), bool(oai) + return out + + @staticmethod + def backward(ctx, grad_out: torch.Tensor): + gate, up = ctx.saved_tensors + grad_out = grad_out.contiguous() + grad_gate = torch.empty_like(gate) + grad_up = torch.empty_like(up) + n_elements = gate.numel() + if n_elements > 0: + grid = (triton.cdiv(n_elements, _BLOCK_SIZE), ) + _swiglu_clamped_bwd_kernel[grid](grad_out, + gate, + up, + grad_gate, + grad_up, + n_elements, + ctx.alpha, + ctx.limit, + OAI=ctx.oai, + PACKED=False, + INTER=1, + BLOCK_SIZE=_BLOCK_SIZE, + num_warps=_NUM_WARPS) + return grad_gate, grad_up, None, None, None + + class _SwiGLUClampedPackedFn(torch.autograd.Function): + + @staticmethod + def forward(ctx, gate_up: torch.Tensor, alpha: float, limit: float, oai: bool) -> 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_clamped_fwd_kernel[grid](gate_up, + gate_up, + out, + n_elements, + float(alpha), + float(limit), + OAI=oai, + PACKED=True, + INTER=inter, + BLOCK_SIZE=_BLOCK_SIZE, + num_warps=_NUM_WARPS) + ctx.save_for_backward(gate_up) + ctx.alpha, ctx.limit, ctx.oai = float(alpha), float(limit), bool(oai) + 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 clamped 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_clamped_bwd_kernel[grid](grad_out, + gate_up, + gate_up, + grad_gate_up, + grad_gate_up, + n_elements, + ctx.alpha, + ctx.limit, + OAI=ctx.oai, + PACKED=True, + INTER=gate_up.shape[-1] // 2, + BLOCK_SIZE=_BLOCK_SIZE, + num_warps=_NUM_WARPS) + return grad_gate_up, None, None, None + + +def _swiglu_clamped_eager(gate: torch.Tensor, up: torch.Tensor, alpha: float, limit: float, oai: bool) -> torch.Tensor: + """Pure-PyTorch reference used as the non-Triton fallback.""" + gate = gate.clamp(max=limit) + up = up.clamp(min=-limit, max=limit) + if oai: + return (up + 1.0) * (gate * torch.sigmoid(gate * alpha)) + return F.silu(gate) * up + + +def swiglu_clamped(gate: torch.Tensor, + up: torch.Tensor, + alpha: float = 1.702, + limit: float = 7.0, + oai: bool = True) -> torch.Tensor: + """Fused clamped SwiGLU. + + ``oai=True``: ``(clamp(up) + 1) * g * sigmoid(alpha * g)`` with ``g = clamp(gate, max=limit)`` and + ``up`` clamped to ``[-limit, limit]`` (GPT-OSS, MiniMax-M3). ``oai=False``: ``silu(g) * clamp(up)`` + (DeepSeek-V4). Falls back to the eager expression when Triton is unavailable or the tensors are on + the CPU. + """ + if gate.shape != up.shape: + raise ValueError(f"swiglu_clamped expects gate and up to have the same shape, got {tuple(gate.shape)} " + f"and {tuple(up.shape)}") + if gate.dtype != up.dtype: + raise ValueError(f"swiglu_clamped expects gate and up to have the same dtype, got {gate.dtype} and {up.dtype}") + if not _TRITON_AVAILABLE or gate.device.type == "cpu": + return _swiglu_clamped_eager(gate, up, alpha, limit, oai) + return _SwiGLUClampedFn.apply(gate, up, alpha, limit, oai) + + +def swiglu_clamped_packed(gate_up: torch.Tensor, + alpha: float = 1.702, + limit: float = 7.0, + oai: bool = True) -> torch.Tensor: + """:func:`swiglu_clamped` of ``gate`` and ``up`` packed side by side in one ``[..., 2 * I]`` tensor, the output + of one gate+up GEMM, read in place as :func:`swiglu_packed` does. + + The Triton path supports first-order gradients only and raises for ``create_graph=True``. Falls back to the + eager expression on the two halves when Triton is unavailable or the tensor is on the CPU. + """ + if gate_up.dim() == 0 or gate_up.shape[-1] % 2: + raise ValueError(f"swiglu_clamped_packed expects an even last dimension, got shape {tuple(gate_up.shape)}") + if not _TRITON_AVAILABLE or gate_up.device.type == "cpu": + gate, up = gate_up.chunk(2, dim=-1) + return _swiglu_clamped_eager(gate, up, alpha, limit, oai) + return _SwiGLUClampedPackedFn.apply(gate_up, alpha, limit, oai) diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index a658724ee577..b519842d083e 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -1097,7 +1097,7 @@ smoke coverage used for this AutoEP surface produced the following version gates | Description | Default | | -------------------------------------------------------------------------------------------------------- | ------- | -| How the expert MLP combines its gate and up projections, by a name registered in `deepspeed.moe.ep_experts.EXPERT_ACTIVATIONS`: `"swiglu"` (`silu(gate) * up`), `"geglu_tanh"` (`gelu_tanh(gate) * up`, Gemma-4), `"swiglu_clamped"` (`silu(clamp(gate)) * clamp(up)`, DeepSeek-V4) or `"swiglu_oai"` (`(clamp(up) + 1) * clamp(gate) * sigmoid(alpha * clamp(gate))`, GPT-OSS and MiniMax-M3). `null` = use preset default, which is `"swiglu"` for every built-in preset. AutoEP checks the name against the model: a clamp limit on the experts module or the model config, or an experts `act_fn` that is not the named form's gate function, is an error unless this key is set. The clamp limit and alpha are taken from the model when it states them. `deepspeed.moe.ep_experts.register_expert_activation` adds a form. | `null` | +| How the expert MLP combines its gate and up projections, by a name registered in `deepspeed.moe.ep_experts.EXPERT_ACTIVATIONS`: `"swiglu"` (`silu(gate) * up`), `"geglu_tanh"` (`gelu_tanh(gate) * up`, Gemma-4), `"swiglu_clamped"` (`silu(clamp(gate)) * clamp(up)`, DeepSeek-V4) or `"swiglu_oai"` (`(clamp(up) + 1) * clamp(gate) * sigmoid(alpha * clamp(gate))`, GPT-OSS and MiniMax-M3). `null` = use preset default, which is `"swiglu"` for every built-in preset. AutoEP checks the name against the model: a clamp limit on the experts module or the model config, or an experts `act_fn` that is not the named form's gate function, is an error unless this key is set. The clamp limit and alpha are taken from the model when it states them. With Triton on an accelerator, `"swiglu"` and the two clamped forms run a fused Triton kernel (one kernel forward, one backward, only the gate and up projections kept for backward); `"geglu_tanh"`, and every form on the CPU, runs in plain PyTorch. `deepspeed.moe.ep_experts.register_expert_activation` adds a form. | `null` | #### Custom Model Example diff --git a/tests/unit/v1/moe/test_autoep_expert_activation.py b/tests/unit/v1/moe/test_autoep_expert_activation.py index dbd4cb8fd32f..8baac2f8c125 100644 --- a/tests/unit/v1/moe/test_autoep_expert_activation.py +++ b/tests/unit/v1/moe/test_autoep_expert_activation.py @@ -255,6 +255,32 @@ def test_grouped_gemm_paths_match_the_for_loop(self, activation, path): for name in ("w1", "w2", "w3"): _assert_bf16_gemm_close(getattr(grouped, name).grad, getattr(loop, name).grad) + @pytest.mark.parametrize("activation", [name for name, entry in EXPERT_ACTIVATIONS.items() if entry.fused_fn]) + def test_fused_kernel_matches_plain_pytorch(self, activation): + # What the grouped-GEMM expert paths get on the accelerator (fused=True) must be the same + # function as the plain-PyTorch form, to within one rounding of the low-precision dtype: the + # reference is the plain form evaluated in float32 on the same inputs and rounded once. + if get_accelerator().device_name() == "cpu": + pytest.skip("needs an accelerator") + device = get_accelerator().current_device_name() + torch.manual_seed(0) + # scale 4 with limit 7 puts about 8 % of the values past a clamp + gate = (4 * torch.randn(256, 3072, device=device)).to(torch.bfloat16).requires_grad_(True) + up = (4 * torch.randn(256, 3072, device=device)).to(torch.bfloat16).requires_grad_(True) + grad_out = torch.randn_like(gate) + out = apply_expert_activation(gate, up, activation, 1.702, 7.0, fused=True) + out.backward(grad_out) + + gate32 = gate.detach().float().requires_grad_(True) + up32 = up.detach().float().requires_grad_(True) + out32 = apply_expert_activation(gate32, up32, activation, 1.702, 7.0, fused=False) + out32.backward(grad_out.float()) + + close = dict(rtol=1.2e-2, atol=1e-3) # about one bf16 ulp at the output magnitude + torch.testing.assert_close(out, out32.to(out.dtype), **close) + torch.testing.assert_close(gate.grad, gate32.grad.to(out.dtype), **close) + torch.testing.assert_close(up.grad, up32.grad.to(out.dtype), **close) + def test_for_loop_path_does_not_need_the_triton_kernel(self, monkeypatch): # The for-loop path is the reference path and runs on CPU tensors. It must not reach the # Triton kernel, which exists whenever Triton is installed. @@ -300,9 +326,10 @@ def test_packed_activation_matches_the_separate_halves(self, activation): 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_packed_kernels_are_registered(self): + # geglu_tanh runs its plain expression on views of the two halves; the SwiGLU forms read them in place. + assert [name for name, entry in EXPERT_ACTIVATIONS.items() + if entry.packed_fused_fn] == ["swiglu", "swiglu_clamped", "swiglu_oai"] def test_default_keeps_the_separate_projections(self): assert parse_autoep_config({"enabled": True}).gate_up_impl == "separate" 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 61c1b16fe346..621bf83739d0 100644 --- a/tests/unit/v1/ops/triton_ops/test_swiglu_triton.py +++ b/tests/unit/v1/ops/triton_ops/test_swiglu_triton.py @@ -2,11 +2,23 @@ # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team -"""Unit tests for the fused Triton SwiGLU (``deepspeed.ops.triton_ops.swiglu_triton``). +"""Unit tests for the fused Triton SwiGLU kernels (``deepspeed.ops.triton_ops.swiglu_triton``). Correctness of ``swiglu(gate, up) == silu(gate) * up`` is checked for the forward output and both input gradients against an eager PyTorch reference, across dtypes and even / uneven / empty shapes. + +``swiglu_clamped`` covers the two clamped forms, both with ``gate`` clamped from above at +``limit`` and ``up`` clamped to ``[-limit, limit]``: +``oai=True`` -> ``(up + 1) * g * sigmoid(alpha * g)`` (GPT-OSS, MiniMax-M3) +``oai=False`` -> ``silu(g) * up`` (DeepSeek-V4) +Its forward output and both input gradients are checked against the expression evaluated +in float32 on the same inputs and rounded once to the test dtype, with inputs scaled so +that a good share of them lie past the clamp limits. Comparing against the expression +evaluated IN the low-precision dtype would not work: it rounds after each of its seven +operations and lands two to three ulps away from the kernel, which computes in float32 +and rounds once. A second assertion checks that the kernel is never farther from the +float32 result than that low-precision evaluation is. """ import pytest @@ -16,11 +28,11 @@ @pytest.fixture(autouse=True) def _load_swiglu_in_the_worker(): - global get_accelerator, swiglu, swiglu_packed + global get_accelerator, swiglu, swiglu_packed, swiglu_clamped, swiglu_clamped_packed # The shared Triton availability probe initializes its driver, so it must run after pytest forks its worker. from deepspeed.accelerator import get_accelerator from deepspeed.ops.triton_ops import is_triton_available - from deepspeed.ops.triton_ops.swiglu_triton import swiglu, swiglu_packed + from deepspeed.ops.triton_ops.swiglu_triton import swiglu, swiglu_packed, swiglu_clamped, swiglu_clamped_packed if not is_triton_available(): pytest.skip("Triton is not available") @@ -190,3 +202,170 @@ def test_dtype_mismatch_raises(): up = torch.randn(8, 16, device=dev, dtype=torch.float32) with pytest.raises(ValueError): swiglu(gate, up) + + +# --------------------------------------------------------------------------- +# Clamped forms +# --------------------------------------------------------------------------- + + +def _clamped_tol(dtype): + # about one ulp of the dtype at the output magnitude, plus a small absolute floor + if dtype == torch.float32: + return dict(atol=1e-5, rtol=1e-5) + if dtype == torch.float16: + return dict(atol=1e-4, rtol=1.5e-3) + return dict(atol=1e-3, rtol=1.2e-2) # bfloat16 + + +def _clamped_eager(gate, up, alpha, limit, oai): + """The two forms as the model code writes them (GptOssExperts / DeepseekV4Experts._apply_gate).""" + gate = gate.clamp(max=limit) + up = up.clamp(min=-limit, max=limit) + if oai: + return (up + 1.0) * (gate * torch.sigmoid(gate * alpha)) + return F.silu(gate) * up + + +def _clamped_reference(gate, up, alpha, limit, oai, grad_out=None): + """Eager expression in float32 on the same inputs, rounded once to the input dtype; optionally its + gradients (with grad_out also upcast), rounded the same way.""" + g = gate.detach().float().requires_grad_(grad_out is not None) + u = up.detach().float().requires_grad_(grad_out is not None) + out = _clamped_eager(g, u, alpha, limit, oai) + if grad_out is None: + return out.to(gate.dtype) + out.backward(grad_out.float()) + return out.detach().to(gate.dtype), g.grad.to(gate.dtype), u.grad.to(gate.dtype) + + +def _max_err(a, b): + return (a.float() - b.float()).abs().max().item() + + +def _assert_no_less_accurate(kernel_out, eager_out, ref, dtype): + # The kernel must not be farther from the float32 result than the eager evaluation in the test + # dtype is, within the same tolerance as assert_close. In float32 that eager evaluation IS the + # reference, so without the slack the check would demand more than the tolerance allows. + tol = _clamped_tol(dtype) + slack = tol["atol"] + tol["rtol"] * ref.float().abs().max().item() + assert _max_err(kernel_out, ref) <= _max_err(eager_out, ref) + slack + + +def _clamped_inputs(shape, dtype, scale=4.0, requires_grad=False): + # scale 4 with limit 7 puts about 8 % of gate values and 8 % of up values past a clamp + dev = get_accelerator().current_device_name() + gate = (scale * torch.randn(shape, device=dev)).to(dtype).requires_grad_(requires_grad) + up = (scale * torch.randn(shape, device=dev)).to(dtype).requires_grad_(requires_grad) + return gate, up + + +@pytest.mark.parametrize("oai", [True, False]) +@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16]) +@pytest.mark.parametrize("shape", [(32, 16), (1, 1), (128, 512), (7, 13), (4, 2048), (2, 3000)]) +def test_clamped_forward_matches_reference(oai, dtype, shape): + gate, up = _clamped_inputs(shape, dtype) + out = swiglu_clamped(gate, up, alpha=1.702, limit=7.0, oai=oai) + ref = _clamped_reference(gate, up, 1.702, 7.0, oai) + assert out.shape == ref.shape + assert out.dtype == dtype + torch.testing.assert_close(out, ref, **_clamped_tol(dtype)) + _assert_no_less_accurate(out, _clamped_eager(gate, up, 1.702, 7.0, oai), ref, dtype) + + +@pytest.mark.parametrize("oai", [True, False]) +@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16]) +@pytest.mark.parametrize("shape", [(32, 16), (128, 512), (7, 13), (4, 2048), (2, 3000)]) +def test_clamped_backward_matches_reference(oai, dtype, shape): + gate, up = _clamped_inputs(shape, dtype, requires_grad=True) + gate_eager = gate.detach().clone().requires_grad_(True) + up_eager = up.detach().clone().requires_grad_(True) + grad_out = torch.randn(shape, device=gate.device, dtype=dtype) + + swiglu_clamped(gate, up, alpha=1.702, limit=7.0, oai=oai).backward(grad_out) + _clamped_eager(gate_eager, up_eager, 1.702, 7.0, oai).backward(grad_out) + _, ref_gate, ref_up = _clamped_reference(gate, up, 1.702, 7.0, oai, grad_out=grad_out) + + torch.testing.assert_close(gate.grad, ref_gate, **_clamped_tol(dtype)) + torch.testing.assert_close(up.grad, ref_up, **_clamped_tol(dtype)) + _assert_no_less_accurate(gate.grad, gate_eager.grad, ref_gate, dtype) + _assert_no_less_accurate(up.grad, up_eager.grad, ref_up, dtype) + + +@pytest.mark.parametrize("oai", [True, False]) +def test_clamped_alpha_and_limit_are_honoured(oai): + # limit 2 with scale 4 clamps about 60 % of the values; alpha 1 changes the oai form + gate, up = _clamped_inputs((64, 256), torch.float32, requires_grad=True) + gate_ref = gate.detach().clone().requires_grad_(True) + up_ref = up.detach().clone().requires_grad_(True) + out = swiglu_clamped(gate, up, alpha=1.0, limit=2.0, oai=oai) + ref = _clamped_eager(gate_ref, up_ref, 1.0, 2.0, oai) + torch.testing.assert_close(out, ref, **_clamped_tol(torch.float32)) + out.sum().backward() + ref.sum().backward() + torch.testing.assert_close(gate.grad, gate_ref.grad, **_clamped_tol(torch.float32)) + torch.testing.assert_close(up.grad, up_ref.grad, **_clamped_tol(torch.float32)) + # the gradient must be exactly zero where the input was clamped + assert torch.all(up.grad[up.detach().abs() > 2.0] == 0) + assert torch.all(gate.grad[gate.detach() > 2.0] == 0) + + +def test_clamped_gradient_at_the_limit_is_inclusive(): + # torch.clamp passes the gradient where input == limit; the kernel must agree + dev = get_accelerator().current_device_name() + gate = torch.full((8, 8), 7.0, device=dev, requires_grad=True) + up = torch.full((8, 8), -7.0, device=dev, requires_grad=True) + gate_ref = gate.detach().clone().requires_grad_(True) + up_ref = up.detach().clone().requires_grad_(True) + swiglu_clamped(gate, up, 1.702, 7.0, True).sum().backward() + _clamped_eager(gate_ref, up_ref, 1.702, 7.0, True).sum().backward() + torch.testing.assert_close(gate.grad, gate_ref.grad) + torch.testing.assert_close(up.grad, up_ref.grad) + assert torch.all(gate.grad != 0) and torch.all(up.grad != 0) + + +def test_clamped_empty_input(): + dev = get_accelerator().current_device_name() + gate = torch.empty(0, 16, device=dev, dtype=torch.float32, requires_grad=True) + up = torch.empty(0, 16, device=dev, dtype=torch.float32, requires_grad=True) + out = swiglu_clamped(gate, up, 1.702, 7.0, True) + assert out.shape == (0, 16) + out.sum().backward() + assert gate.grad.shape == gate.shape + + +def test_clamped_non_contiguous_input(): + dev = get_accelerator().current_device_name() + gate = (4 * torch.randn(64, 32, device=dev, dtype=torch.float32)).t() + up = (4 * torch.randn(64, 32, device=dev, dtype=torch.float32)).t() + torch.testing.assert_close(swiglu_clamped(gate, up, 1.702, 7.0, True), _clamped_eager(gate, up, 1.702, 7.0, True), + **_clamped_tol(torch.float32)) + + +def test_clamped_shape_and_dtype_mismatch_rejected(): + dev = get_accelerator().current_device_name() + with pytest.raises(ValueError, match="same shape"): + swiglu_clamped(torch.randn(4, 8, device=dev), torch.randn(4, 9, device=dev)) + with pytest.raises(ValueError, match="same dtype"): + swiglu_clamped(torch.randn(4, 8, device=dev), torch.randn(4, 8, device=dev, dtype=torch.float16)) + + +@pytest.mark.parametrize("oai", [True, False]) +@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16]) +@pytest.mark.parametrize("shape", [(32, 16), (7, 13), (3, 5, 384), (0, 16)]) +def test_clamped_packed_matches_the_separate_kernel_exactly(oai, dtype, shape): + # The packed path (one gate+up GEMM output) must give the separate clamped kernel's values exactly, forward + # and backward; inputs at scale 4 put a good share of them past the clamp limits. + dev = get_accelerator().current_device_name() + generator = torch.Generator(device=dev).manual_seed(8652) + gate = (4 * torch.randn(shape, device=dev, generator=generator)).to(dtype).requires_grad_(True) + up = (4 * torch.randn(shape, device=dev, generator=generator)).to(dtype).requires_grad_(True) + gate_up = torch.cat([gate, up], dim=-1).detach().requires_grad_(True) + grad_out = torch.randn(shape, device=dev, generator=generator).to(dtype) + + out = swiglu_clamped_packed(gate_up, alpha=1.702, limit=7.0, oai=oai) + expected = swiglu_clamped(gate, up, alpha=1.702, limit=7.0, oai=oai) + torch.testing.assert_close(out, expected, rtol=0, atol=0) + 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)