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
9 changes: 9 additions & 0 deletions deepspeed/module_inject/auto_ep_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

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 Add the required Signed-off-by trailer

This is a one-parent non-merge commit, but git log -1 --format='%B' 8213255561f7700869cafa528429eec5546669e3 contains no Signed-off-by: trailer. Add the trailer using the configured author identity; otherwise the commit cannot satisfy the repository's DCO/CI requirement.

AGENTS.md reference: AGENTS.md:L8-L9

Useful? React with 👍 / 👎.

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)
Expand Down Expand Up @@ -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:
Expand Down
1 change: 1 addition & 0 deletions deepspeed/module_inject/auto_ep_layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions deepspeed/module_inject/auto_ep_presets/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
90 changes: 87 additions & 3 deletions deepspeed/moe/ep_experts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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:
Expand All @@ -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

Expand All @@ -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)
Expand All @@ -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)
# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -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)
# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -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__(
Expand All @@ -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.
Expand Down Expand Up @@ -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, "
Expand All @@ -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)
111 changes: 111 additions & 0 deletions deepspeed/ops/triton_ops/swiglu_triton.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -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)
6 changes: 6 additions & 0 deletions docs/_pages/config-json.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
Loading
Loading