Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 32 additions & 2 deletions deepspeed/moe/ep_experts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
232 changes: 232 additions & 0 deletions deepspeed/ops/triton_ops/swiglu_triton.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Comment on lines +282 to +283

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve NaNs through the clamp

When a preceding grouped GEMM yields a NaN in gate or up, Triton's elementwise minimum/maximum use their default non-NaN-propagating mode, unlike the eager torch.clamp reference, so these lines replace the NaN with a finite clamp bound. The backward kernel repeats that clamp and its comparisons then zero the corresponding gradient, allowing a diverged AutoEP step to produce finite outputs and gradients; request NaN propagation (or use comparisons that preserve NaNs) in both kernels.

Useful? React with 👍 / 👎.


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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Guard separate launches with the input device

When gate and up reside on a CUDA device that is not the process's current device (for example, tensors on cuda:1 while the caller remains on cuda:0), this launch and the analogous backward launch run on Triton's current device/stream rather than the tensor device, so the kernel sees inaccessible pointers or launches on the wrong stream. The packed implementation already enters an input-device context around both launches; the separate implementation needs the same protection.

AGENTS.md reference: AGENTS.md:L40-L40

Useful? React with 👍 / 👎.

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):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject higher-order gradients in the separate path

When a caller requests create_graph=True from the separate swiglu_clamped path, this backward writes gradients into fresh empty_like buffers via Triton, so the returned first derivatives are detached and a subsequent derivative fails. The packed class explicitly detects and rejects this unsupported mode, but this new separate class neither rejects it nor provides a differentiable fallback; add the same guard or a differentiable backward here.

Useful? React with 👍 / 👎.

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)
2 changes: 1 addition & 1 deletion docs/_pages/config-json.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
33 changes: 30 additions & 3 deletions tests/unit/v1/moe/test_autoep_expert_activation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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"
Expand Down
Loading
Loading