Skip to content
23 changes: 23 additions & 0 deletions tests/kernels/moe/test_moe_kernel_oracle.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,26 @@ def test_make_kernel_delegates(self) -> None:
None, # routing_tables default
)
assert out is sentinel_kernel


def test_fp8_round_up_intermediate_size_for_aiter() -> None:
"""Ensure fp8 MoE GEMM is rounded up to factor 128 when on AITER."""
from vllm.model_executor.layers.fused_moe.oracle.fp8 import (
Fp8MoeBackend,
fp8_round_up_hidden_size_and_intermediate_size,
)

# Should round
assert fp8_round_up_hidden_size_and_intermediate_size(
Fp8MoeBackend.AITER, 2048, 704
) == (2048, 768)

# no-op
assert fp8_round_up_hidden_size_and_intermediate_size(
Fp8MoeBackend.AITER, 2048, 1024
) == (2048, 1024)

# Non-AITER backends are untouched even when non-128-aligned.
assert fp8_round_up_hidden_size_and_intermediate_size(
Fp8MoeBackend.TRITON, 2048, 704
) == (2048, 704)
68 changes: 68 additions & 0 deletions tests/kernels/moe/test_rocm_aiter_moe.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,8 @@ def ref_moe_forward(
act = F.silu(gate) * up
elif activation == "gelu":
act = F.gelu(gate) * up
elif activation == "gelu_tanh":
act = F.gelu(gate, approximate="tanh") * up
else:
raise ValueError(f"Unknown activation: {activation}")
output[expert_mask] = act @ w2_f[expert_idx].T
Expand Down Expand Up @@ -600,6 +602,7 @@ def test_activation_method_enum_values():

assert ActivationMethod.SILU == 0
assert ActivationMethod.GELU == 1
assert ActivationMethod.GELU_TANH == 4


# MXFP4 kernel tests ------------------------------------------------------
Expand Down Expand Up @@ -850,6 +853,71 @@ def test_aiter_fused_moe_gelu_accuracy():
)


def test_aiter_fused_moe_gelu_tanh_accuracy():
Comment thread
simondanielsson marked this conversation as resolved.
Resolved
"""The tanh-approx GELU variant (Gemma-family MoE) should stay aligned with
the float32 tanh-approx reference."""
from vllm.model_executor.layers.fused_moe.experts.rocm_aiter_moe import (
ActivationMethod,
QuantMethod,
)

_assert_aiter_supported()
case = _make_moe_case(
num_tokens=32,
hidden_dim=512,
intermediate_dim=1024,
num_experts=4,
topk=2,
seed=42,
)
ref_out = ref_moe_forward(
case["hidden_states"],
case["w1"],
case["w2"],
case["topk_weights"],
case["topk_ids"],
activation="gelu_tanh",
)
out = _run_fused_moe(
case["hidden_states"],
case["w1"],
case["w2"],
case["topk_weights"],
case["topk_ids"],
activation_method=int(ActivationMethod.GELU_TANH),
quant_method=int(QuantMethod.NO),
)

assert out.shape == case["hidden_states"].shape
_assert_close_budget(
out.float(),
ref_out,
label="gelu_tanh_accuracy",
atol=0.05,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Same to AI

rtol=0.0,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
)
# The tolerance above cannot tell tanh-GELU from exact GELU on its own: make
# sure the kernel actually applied the tanh variant by checking it sits closer
# to the tanh reference than to the exact-GELU reference on inputs where the
# two references measurably differ.
ref_exact = ref_moe_forward(
case["hidden_states"],
case["w1"],
case["w2"],
case["topk_weights"],
case["topk_ids"],
activation="gelu",
)
ref_gap = (ref_out - ref_exact).abs().mean().item()
assert ref_gap > 1e-4, f"references indistinguishable (gap={ref_gap:.2e})"
err_tanh = (out.float() - ref_out).abs().mean().item()
err_exact = (out.float() - ref_exact).abs().mean().item()
assert err_tanh < err_exact, (
f"kernel closer to exact GELU ({err_exact:.3e}) "
f"than to tanh GELU ({err_tanh:.3e})"
)


def test_aiter_fused_moe_determinism():
"""The BF16 fused-MoE kernel should stay bitwise deterministic for the
same inputs."""
Expand Down
13 changes: 13 additions & 0 deletions vllm/_aiter_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from collections.abc import Callable
from typing import TYPE_CHECKING


import torch
from torch._ops import OpOverload

Expand Down Expand Up @@ -1908,6 +1909,18 @@ def is_fused_moe_situv2_a8w4_enabled(cls) -> bool:
# fused moe must be enabled as well.
return cls.is_fused_moe_enabled() and cls._MOE_SITUV2_A8W4

@staticmethod
@functools.lru_cache(maxsize=1)
def fused_moe_supports_gelu_tanh() -> bool:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggestion: I think we can drop this given we ship v0.1.21 now. Instead we can just check whether aiter is available. (similarly with the error in rocm_aiter_fused_experts)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done in 891ebe7: removed fused_moe_supports_gelu_tanh() and the error in rocm_aiter_fused_experts; GELU_TANH is now just listed in _supports_activation.

"""aiter >= v0.1.21 (ROCm/aiter#4620) exposes ActivationType.GeluTanh for the
CK 2-stage fused MoE; older releases have no such enum member and the FP8
tkw1 path would reject the wire value."""
try:
from aiter import ActivationType
except ImportError:
return False
return hasattr(ActivationType, "GeluTanh")

@classmethod
@if_aiter_supported
def topk_softmax_supports_fused_sigmoid(cls) -> bool:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ class ActivationMethod(IntEnum):
# without importing the ActivationType enum from AITER globally.
SILU = 0
GELU = 1
GELU_TANH = 4


aiter_topK_meta_data: tuple[torch.Tensor, torch.Tensor] | None = None
Expand Down Expand Up @@ -262,6 +263,10 @@ def rocm_aiter_fused_experts(
activation_method = ActivationMethod.SILU
elif activation == MoEActivation.GELU:
activation_method = ActivationMethod.GELU
elif activation == MoEActivation.GELU_TANH:
if not rocm_aiter_ops.fused_moe_supports_gelu_tanh():
raise ValueError("AITER GELU_TANH fused MoE needs aiter >= v0.1.21")
activation_method = ActivationMethod.GELU_TANH
elif activation == MoEActivation.SWIGLUOAI:
activation_method = rocm_aiter_ops.get_aiter_activation_type("swiglu")
elif activation == MoEActivation.SWIGLUOAI_UNINTERLEAVE:
Expand Down Expand Up @@ -488,6 +493,10 @@ def _supports_quant_scheme(

@staticmethod
def _supports_activation(activation: MoEActivation) -> bool:
if activation == MoEActivation.GELU_TANH:
# Needs aiter >= v0.1.21 (ActivationType.GeluTanh); otherwise fall back
# to the non-AITER experts instead of failing at dispatch time.
return rocm_aiter_ops.fused_moe_supports_gelu_tanh()
return activation in [
MoEActivation.SILU,
MoEActivation.GELU,
Expand Down
19 changes: 19 additions & 0 deletions vllm/model_executor/layers/fused_moe/oracle/fp8.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
kFp8Static128BlockSym,
)
from vllm.platforms import current_platform
from vllm.utils.math_utils import round_up

logger = init_logger(__name__)

Expand Down Expand Up @@ -67,6 +68,24 @@ class Fp8MoeBackend(Enum):
AITER_MXFP8 = "AITER_MXFP8"


def fp8_round_up_hidden_size_and_intermediate_size(
backend: Fp8MoeBackend,
hidden_size: int,
intermediate_size: int,
) -> tuple[int, int]:
"""Round up hidden_size and intermediate_size based on backend requirements."""
if backend == Fp8MoeBackend.AITER:
# AITER's 2-stage CK fp8 MoE GEMM is numerically broken for intermediate
# sizes that aren't 128-aligned (e.g. Gemma4-26B-A4B's 704;
# activation-independent). Align to 128. NOTE: the loader only
# narrow-copies the checkpoint's real rows/columns into the padded
# parameters, so the expert weights must be allocated zeroed (see the
# fp8 MoE methods' create_weights); an uninitialized tail is live
# garbage weight for the kernel.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: don't think this comment is needed here

Suggested change
# activation-independent). Align to 128. NOTE: the loader only
# narrow-copies the checkpoint's real rows/columns into the padded
# parameters, so the expert weights must be allocated zeroed (see the
# fp8 MoE methods' create_weights); an uninitialized tail is live
# garbage weight for the kernel.
# activation-independent). Align to 128.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done.

intermediate_size = round_up(intermediate_size, 128)
return hidden_size, intermediate_size


def _get_priority_backends(
moe_config: FusedMoEConfig,
weight_key: QuantKey | None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from vllm.distributed import get_tensor_model_parallel_world_size
from vllm.logger import init_logger
from vllm.model_executor.layers.fused_moe import (
FusedMoEParallelConfig,
FusedMoeWeightScaleSupported,
RoutedExperts,
SharedExperts,
Expand All @@ -21,6 +22,7 @@
)
from vllm.model_executor.layers.fused_moe.oracle.fp8 import (
convert_to_fp8_moe_kernel_format,
fp8_round_up_hidden_size_and_intermediate_size,
make_fp8_moe_kernel,
make_fp8_moe_quant_config,
select_fp8_moe_backend,
Expand Down Expand Up @@ -110,6 +112,29 @@ def __init__(
allow_vllm_cutlass=True,
)

def maybe_roundup_sizes(
self,
hidden_size: int,
intermediate_size_per_partition: int,
act_dtype: torch.dtype,
moe_parallel_config: FusedMoEParallelConfig,
) -> tuple[int, int]:
original = (hidden_size, intermediate_size_per_partition)
hidden_size, intermediate_size_per_partition = super().maybe_roundup_sizes(
hidden_size=hidden_size,
intermediate_size_per_partition=intermediate_size_per_partition,
act_dtype=act_dtype,
moe_parallel_config=moe_parallel_config,
)
rounded = fp8_round_up_hidden_size_and_intermediate_size(
self.fp8_backend, hidden_size, intermediate_size_per_partition
)
# The loader only narrow-copies the checkpoint into padded parameters, so
# padded expert weights (either dimension rounded up, by this method or by
# the base class) must be allocated zeroed; see create_weights.
self._pad_expert_weights = rounded != original
return rounded

def create_weights(
self,
layer: torch.nn.Module,
Expand Down Expand Up @@ -153,8 +178,13 @@ def create_weights(
)

# WEIGHTS
# Padded (rounded-up) expert weights must start zeroed: the loader only writes
# the checkpoint's real rows/columns and an uninitialized tail is live weight.
alloc = (
torch.zeros if getattr(self, "_pad_expert_weights", False) else torch.empty
)
w13_weight = torch.nn.Parameter(
torch.empty(
alloc(
num_experts,
w13_num_shards * intermediate_size_per_partition,
hidden_size,
Expand All @@ -166,7 +196,7 @@ def create_weights(
set_weight_attrs(w13_weight, extra_weight_attrs)

w2_weight = torch.nn.Parameter(
torch.empty(
alloc(
num_experts,
hidden_size,
intermediate_size_per_partition,
Expand Down
34 changes: 32 additions & 2 deletions vllm/model_executor/layers/quantization/fp8.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from vllm.model_executor.layers.attention import Attention
from vllm.model_executor.layers.fused_moe import (
FusedMoEMethodBase,
FusedMoEParallelConfig,
FusedMoeWeightScaleSupported,
RoutedExperts,
SharedExperts,
Expand All @@ -29,6 +30,7 @@
)
from vllm.model_executor.layers.fused_moe.oracle.fp8 import (
convert_to_fp8_moe_kernel_format,
fp8_round_up_hidden_size_and_intermediate_size,
make_fp8_moe_kernel,
make_fp8_moe_quant_config,
refine_fp8_moe_block_shape,
Expand Down Expand Up @@ -533,6 +535,29 @@ def __init__(self, quant_config: Fp8Config, layer: RoutedExperts):
allow_vllm_cutlass=False,
)

def maybe_roundup_sizes(
self,
hidden_size: int,
intermediate_size_per_partition: int,
act_dtype: torch.dtype,
moe_parallel_config: FusedMoEParallelConfig,
) -> tuple[int, int]:
original = (hidden_size, intermediate_size_per_partition)
hidden_size, intermediate_size_per_partition = super().maybe_roundup_sizes(
hidden_size=hidden_size,
intermediate_size_per_partition=intermediate_size_per_partition,
act_dtype=act_dtype,
moe_parallel_config=moe_parallel_config,
)
rounded = fp8_round_up_hidden_size_and_intermediate_size(
self.fp8_backend, hidden_size, intermediate_size_per_partition
)
# The loader only narrow-copies the checkpoint into padded parameters, so
# padded expert weights (either dimension rounded up, by this method or by
# the base class) must be allocated zeroed; see create_weights.
self._pad_expert_weights = rounded != original
return rounded

def create_weights(
self,
layer: RoutedExperts,
Expand Down Expand Up @@ -584,8 +609,13 @@ def create_weights(
block_n, block_k = moe_block_shape

# WEIGHTS
# Padded (rounded-up) expert weights must start zeroed: the loader only writes
# the checkpoint's real rows/columns and an uninitialized tail is live weight.
alloc = (
torch.zeros if getattr(self, "_pad_expert_weights", False) else torch.empty

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggestion: can we check hidden_size != self.moe.hidden_dim_unpadded and intermediate_size_per_partition != self.moe.intermediate_size_per_partition_unpadded instead to avoid having this new mutable state?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done. create_weights now compares hidden_size / intermediate_size_per_partition with self.moe.hidden_dim_unpadded / intermediate_size_per_partition_unpadded (RoutedExperts writes the rounded sizes into moe_config and the *_unpadded fields keep the originals), same in the compressed-tensors method. maybe_roundup_sizes is back to just returning the rounded sizes, no state on the method.

)
w13_weight = torch.nn.Parameter(
torch.empty(
alloc(
num_experts,
self.moe.w13_num_shards * intermediate_size_per_partition,
hidden_size,
Expand All @@ -597,7 +627,7 @@ def create_weights(
set_weight_attrs(w13_weight, extra_weight_attrs)

w2_weight = torch.nn.Parameter(
torch.empty(
alloc(
num_experts,
hidden_size,
intermediate_size_per_partition,
Expand Down
Loading