[MoE] Generalize masked activation for padded layouts (#51217)
Signed-off-by: mgoin <mgoin64@gmail.com> Co-authored-by: OpenAI Codex <codex@openai.com>
This commit is contained in:
co-authored by
OpenAI Codex
parent
a232e29e9d
commit
82b7d49a6e
@@ -9,6 +9,8 @@ from typing import TYPE_CHECKING
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.model_executor.layers.fused_moe.config import (
|
||||
FusedMoEConfig,
|
||||
@@ -134,11 +136,31 @@ _APPLY_MOE_ACTIVATIONS = frozenset(
|
||||
)
|
||||
|
||||
|
||||
_MASKED_MOE_ACTIVATION_NAMES: dict[MoEActivation, str] = {
|
||||
MoEActivation.SILU: "silu",
|
||||
MoEActivation.GELU: "gelu",
|
||||
MoEActivation.GELU_TANH: "gelu_tanh",
|
||||
MoEActivation.SITU: "situ",
|
||||
MoEActivation.SWIGLUOAI: "swigluoai",
|
||||
MoEActivation.SWIGLUOAI_UNINTERLEAVE: "swigluoai_uninterleave",
|
||||
MoEActivation.SWIGLUSTEP: "swiglustep",
|
||||
MoEActivation.SILU_NO_MUL: "silu_no_mul",
|
||||
MoEActivation.GELU_NO_MUL: "gelu_no_mul",
|
||||
MoEActivation.GELU_TANH_NO_MUL: "gelu_tanh_no_mul",
|
||||
MoEActivation.RELU2_NO_MUL: "relu2_no_mul",
|
||||
}
|
||||
|
||||
|
||||
def apply_moe_activation_supported(activation: MoEActivation) -> bool:
|
||||
"""Whether ``apply_moe_activation`` supports an activation."""
|
||||
return activation in _APPLY_MOE_ACTIVATIONS
|
||||
|
||||
|
||||
def apply_moe_activation_masked_supported(activation: MoEActivation) -> bool:
|
||||
"""Whether the masked ``apply_moe_activation`` path supports an activation."""
|
||||
return activation in _MASKED_MOE_ACTIVATION_NAMES
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ApplyMoEActivationConfig:
|
||||
"""Configuration forwarded to ``apply_moe_activation``."""
|
||||
@@ -177,6 +199,96 @@ class ApplyMoEActivationConfig:
|
||||
_DEFAULT_APPLY_MOE_ACTIVATION_CONFIG = ApplyMoEActivationConfig()
|
||||
|
||||
|
||||
def _validate_moe_activation_shapes(
|
||||
activation: MoEActivation,
|
||||
output: torch.Tensor,
|
||||
input: torch.Tensor,
|
||||
expected_dim: int,
|
||||
) -> None:
|
||||
assert input.dim() == expected_dim, f"Input must be {expected_dim}D"
|
||||
assert output.dim() == expected_dim, f"Output must be {expected_dim}D"
|
||||
assert input.shape[:-1] == output.shape[:-1], (
|
||||
f"Input/output leading shapes must match: {input.shape} vs {output.shape}"
|
||||
)
|
||||
if activation.is_gated:
|
||||
assert output.size(-1) * 2 == input.size(-1), (
|
||||
f"{activation.value} expects 2x ratio: "
|
||||
f"{output.size(-1) * 2} vs {input.size(-1)}"
|
||||
)
|
||||
else:
|
||||
assert output.size(-1) == input.size(-1), (
|
||||
f"{activation.value} expects equal sizes: "
|
||||
f"{output.size(-1)} vs {input.size(-1)}"
|
||||
)
|
||||
|
||||
|
||||
def _apply_moe_activation_masked(
|
||||
activation: MoEActivation,
|
||||
output: torch.Tensor,
|
||||
input: torch.Tensor,
|
||||
valid_token_counts: torch.Tensor,
|
||||
config: ApplyMoEActivationConfig,
|
||||
) -> torch.Tensor:
|
||||
masked_activation = _MASKED_MOE_ACTIVATION_NAMES.get(activation)
|
||||
if masked_activation is None:
|
||||
raise NotImplementedError(
|
||||
f"Masked MoE activation is not implemented for {activation.value}"
|
||||
)
|
||||
|
||||
assert input.dim() in (2, 3), "Masked input must be 2D or 3D"
|
||||
_validate_moe_activation_shapes(activation, output, input, expected_dim=input.dim())
|
||||
assert input.dtype == output.dtype, "Input and output dtypes must match"
|
||||
assert input.device == output.device, "Input and output devices must match"
|
||||
assert input.is_contiguous(), "Input must be contiguous"
|
||||
assert output.is_contiguous(), "Output must be contiguous"
|
||||
assert valid_token_counts.dtype == torch.int32, (
|
||||
"valid_token_counts must use torch.int32"
|
||||
)
|
||||
assert valid_token_counts.dim() == 1, "valid_token_counts must be 1D"
|
||||
assert valid_token_counts.device == input.device, (
|
||||
"valid_token_counts must be on the input device"
|
||||
)
|
||||
assert valid_token_counts.is_contiguous(), "valid_token_counts must be contiguous"
|
||||
expected_counts = input.size(0) if input.dim() == 3 else 1
|
||||
assert valid_token_counts.size(0) == expected_counts, (
|
||||
f"valid_token_counts must have {expected_counts} element(s) for "
|
||||
f"{input.dim()}D input"
|
||||
)
|
||||
|
||||
masked_clamp_limit = 0.0 if config.clamp_limit is None else config.clamp_limit
|
||||
masked_alpha = config.alpha
|
||||
if activation == MoEActivation.SILU and config.clamp_limit is not None:
|
||||
masked_activation = "silu_with_clamp"
|
||||
elif activation == MoEActivation.SITU:
|
||||
assert config.activation_situ_beta is not None, (
|
||||
"SITU requires activation_situ_beta from FusedMoEConfig"
|
||||
)
|
||||
elif activation == MoEActivation.SWIGLUOAI:
|
||||
masked_clamp_limit = 7.0
|
||||
masked_alpha = 1.702
|
||||
elif activation == MoEActivation.SWIGLUOAI_UNINTERLEAVE:
|
||||
assert config.clamp_limit is not None, (
|
||||
"SWIGLUOAI_UNINTERLEAVE requires clamp_limit"
|
||||
)
|
||||
elif activation == MoEActivation.SWIGLUSTEP:
|
||||
masked_clamp_limit = 7.0
|
||||
|
||||
torch.ops._C.masked_moe_activation(
|
||||
output,
|
||||
input,
|
||||
valid_token_counts,
|
||||
masked_activation,
|
||||
masked_clamp_limit,
|
||||
masked_alpha,
|
||||
config.beta,
|
||||
1.0 if config.activation_situ_beta is None else config.activation_situ_beta,
|
||||
-1.0
|
||||
if config.activation_situ_linear_beta is None
|
||||
else config.activation_situ_linear_beta,
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
def silu_and_mul_with_clamp(
|
||||
output: torch.Tensor,
|
||||
input: torch.Tensor,
|
||||
@@ -184,7 +296,12 @@ def silu_and_mul_with_clamp(
|
||||
topk_ids: torch.Tensor | None = None,
|
||||
expert_map: torch.Tensor | None = None,
|
||||
) -> None:
|
||||
if topk_ids is not None and expert_map is not None:
|
||||
if current_platform.is_xpu():
|
||||
d = input.shape[-1] // 2
|
||||
gate = torch.clamp(input[..., :d], max=clamp_limit)
|
||||
up = torch.clamp(input[..., d:], min=-clamp_limit, max=clamp_limit)
|
||||
output.copy_(gate * torch.sigmoid(gate) * up)
|
||||
elif topk_ids is not None and expert_map is not None:
|
||||
from vllm.model_executor.layers.fused_moe.utils import swiglu_limit_func
|
||||
|
||||
swiglu_limit_func(output, input, clamp_limit, topk_ids, expert_map)
|
||||
@@ -201,12 +318,15 @@ def apply_moe_activation(
|
||||
activation_config: ApplyMoEActivationConfig | None = None,
|
||||
topk_ids: torch.Tensor | None = None,
|
||||
expert_map: torch.Tensor | None = None,
|
||||
valid_rows: torch.Tensor | None = None,
|
||||
valid_token_counts: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Apply MoE activation function.
|
||||
|
||||
The configuration drives specialized activation behavior. Routing tensors
|
||||
remain per-call inputs because they depend on the current token assignment.
|
||||
and valid token counts remain per-call inputs because they depend on the
|
||||
current token assignment. A single token count masks a flat ``[T, D]``
|
||||
buffer; one count per expert masks each prefix in a padded ``[E, T, D]``
|
||||
buffer.
|
||||
"""
|
||||
config = (
|
||||
_DEFAULT_APPLY_MOE_ACTIVATION_CONFIG
|
||||
@@ -214,19 +334,17 @@ def apply_moe_activation(
|
||||
else activation_config
|
||||
)
|
||||
|
||||
assert input.dim() == 2, "Input must be 2D"
|
||||
assert output.dim() == 2, "Output must be 2D"
|
||||
if activation.is_gated:
|
||||
assert output.size(-1) * 2 == input.size(-1), (
|
||||
f"{activation.value} expects 2x ratio: "
|
||||
f"{output.size(-1) * 2} vs {input.size(-1)}"
|
||||
)
|
||||
else:
|
||||
assert output.size(-1) == input.size(-1), (
|
||||
f"{activation.value} expects equal sizes: "
|
||||
f"{output.size(-1)} vs {input.size(-1)}"
|
||||
if valid_token_counts is not None:
|
||||
return _apply_moe_activation_masked(
|
||||
activation,
|
||||
output,
|
||||
input,
|
||||
valid_token_counts,
|
||||
config,
|
||||
)
|
||||
|
||||
_validate_moe_activation_shapes(activation, output, input, expected_dim=2)
|
||||
|
||||
# Activations with gated multiplication (gate × activation(up))
|
||||
if activation == MoEActivation.SILU:
|
||||
if config.clamp_limit is not None:
|
||||
@@ -257,7 +375,6 @@ def apply_moe_activation(
|
||||
-1.0
|
||||
if config.activation_situ_linear_beta is None
|
||||
else config.activation_situ_linear_beta,
|
||||
valid_rows,
|
||||
)
|
||||
elif activation == MoEActivation.SWIGLUOAI:
|
||||
torch.ops._C.swigluoai_and_mul(output, input)
|
||||
@@ -298,7 +415,7 @@ def situ_and_mul_quant(
|
||||
beta: float,
|
||||
linear_beta: float | None,
|
||||
group_size: int = 0,
|
||||
valid_rows: torch.Tensor | None = None,
|
||||
num_valid_tokens: torch.Tensor | None = None,
|
||||
topk: int = 1,
|
||||
) -> None:
|
||||
"""Fused Kimi SITU activation + dynamic FP8 quantization.
|
||||
@@ -314,11 +431,11 @@ def situ_and_mul_quant(
|
||||
[M, d // 128], matching humming ``quant_input(group_size=128, float32)``.
|
||||
|
||||
``linear_beta`` <= 0 (or None) means "unset" (up passed through), matching
|
||||
``SituAndMul(linear_beta=None)``. ``valid_rows`` (int32 scalar tensor) is the
|
||||
DeepEP v2 contiguous-layout valid *token* count (e.g. ``psum[-1:]``); the
|
||||
kernel multiplies it by ``topk`` to bound rows, so no host-side cast/multiply
|
||||
is needed. Padding rows are skipped and receive a benign scale of 1.0. Kept
|
||||
in this module so that every ``torch.ops._C.situ*`` call lives in one file.
|
||||
``SituAndMul(linear_beta=None)``. ``num_valid_tokens`` (int32 scalar tensor)
|
||||
is the DeepEP v2 contiguous-layout token count (e.g. ``psum[-1:]``); the
|
||||
kernel multiplies it by ``topk`` to bound rows. Padding rows are skipped and
|
||||
receive a benign scale of 1.0. Kept in this module so that every
|
||||
``torch.ops._C.situ*`` call lives in one file.
|
||||
"""
|
||||
torch.ops._C.situ_and_mul_quant(
|
||||
output,
|
||||
@@ -327,6 +444,6 @@ def situ_and_mul_quant(
|
||||
beta,
|
||||
-1.0 if linear_beta is None else linear_beta,
|
||||
group_size,
|
||||
valid_rows,
|
||||
num_valid_tokens,
|
||||
topk,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user