Skip to content
Draft
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
32 changes: 24 additions & 8 deletions tests/kernels/mhc/test_mhc_kernels.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from functools import partial
from types import SimpleNamespace
from typing import Any

import pytest
import torch
Expand Down Expand Up @@ -1829,21 +1830,29 @@ def check(actual):


@requires_rocm_mhc_overlap
@pytest.mark.parametrize("fused_ep_moe", [False, True])
@pytest.mark.parametrize("seam_kernel", ["triton", "mega"])
@pytest.mark.parametrize("over_limit", [False, True], ids=["at_limit", "over_limit"])
@pytest.mark.parametrize(
"entry,num_splits",
[("broadcast", 1), ("pipeline", 1), ("residual", 2), ("engram", 1)],
)
def test_deepseek_v41_rocm_decoder_overlap_matches_serial(
entry, num_splits, over_limit, seam_kernel, monkeypatch, default_vllm_config
entry,
num_splits,
over_limit,
seam_kernel,
fused_ep_moe,
monkeypatch,
default_vllm_config,
):
"""The decoder layer splits its seams only inside a FULL graph capture of at
most `MHC_OVERLAP_MAX_TOKENS` tokens, and the replayed layer matches the
serial one. `num_splits` counts the seams that carry a post block: layer
0, a pipeline entry and Engram fold none into the attention seam, and the
FFN seam always has one. With packed weights every fused seam, the
side-stream gates included, runs as Mega-MHC."""
FFN seam always has one, which stays serial when the MoE runs AITER
FusedEPMoE (nothing may run beside it). With packed weights every fused
seam, the side-stream gates included, runs as Mega-MHC."""
from vllm._aiter_ops import rocm_aiter_ops
from vllm.config import CUDAGraphMode
from vllm.forward_context import set_forward_context
Expand Down Expand Up @@ -1879,11 +1888,18 @@ def test_deepseek_v41_rocm_decoder_overlap_matches_serial(
decoder.attn_norm = decoder.ffn_norm = RMSNorm(hidden_size, 1e-6).to(
device=DEVICE, dtype=torch.bfloat16
)
_stub_sublayers(
decoder,
lambda positions, x, _: x * 0.5,
lambda x, input_ids: x * 0.25,
)
ffn: Any = lambda x, input_ids: x * 0.25 # noqa: E731
_stub_sublayers(decoder, lambda positions, x, _: x * 0.5, ffn)
if fused_ep_moe:

class FusedEPMoEExperts:
max_tokens_across_dp = staticmethod(lambda num_tokens: num_tokens)

def uses_fused_ep_moe(self, max_tokens_across_dp):
return True

ffn.use_mega_moe, ffn.experts = True, FusedEPMoEExperts()
num_splits -= 1
with torch.device(DEVICE):
decoder.hc_attn_fn = torch.randn(24, 4 * hidden_size) * 0.02
decoder.hc_ffn_fn = torch.randn(24, 4 * hidden_size) * 0.02
Expand Down
151 changes: 144 additions & 7 deletions tests/models/test_deepseek_v4_aiter_mega_moe.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project

import os
from types import SimpleNamespace

import pytest
import torch

from vllm.config import ParallelConfig, SchedulerConfig, VllmConfig
from vllm.config.quantization import QuantizationConfigArgs
from vllm.forward_context import set_forward_context
from vllm.model_executor.layers.fused_moe import (
fused_moe_make_expert_params_mapping,
)
Expand All @@ -23,6 +26,11 @@
from vllm.platforms import current_platform
from vllm.utils.torch_utils import aux_stream

from ..kernels.moe.modular_kernel_tools.parallel_utils import (
parallel_launch_with_config,
)
from ..utils import multi_gpu_test

HIDDEN = 64
INTER = 64

Expand Down Expand Up @@ -194,9 +202,11 @@ def test_shared_expert_route_appended(monkeypatch):
@pytest.mark.skipif(not current_platform.is_rocm(), reason="Requires ROCm")
@pytest.mark.parametrize("hash_routing", [False, True])
@pytest.mark.parametrize("num_tokens", [1, 37])
@pytest.mark.parametrize("shared_stream", [False, True])
@pytest.mark.parametrize(
"shared_stream, fused_ep_moe", [(False, False), (True, False), (True, True)]
)
def test_mega_moe_routing_matches_reference(
monkeypatch, hash_routing, num_tokens, shared_stream
monkeypatch, hash_routing, num_tokens, shared_stream, fused_ep_moe
):
num_experts, top_k, vocab = 16, 4, 64
scaling = 2.5
Expand Down Expand Up @@ -227,15 +237,27 @@ def forward(self, x):

captured = {}

def experts(x, topk_weights, topk_ids):
captured["weights"], captured["ids"] = topk_weights, topk_ids
return 2 * x
class Experts:
max_tokens_across_dp = staticmethod(
DeepseekV4AiterMegaMoEExperts.max_tokens_across_dp
)

def __call__(self, x, topk_weights, topk_ids, max_tokens_across_dp=None):
captured["weights"], captured["ids"] = topk_weights, topk_ids
return 2 * x

def uses_fused_ep_moe(self, max_tokens_across_dp):
return fused_ep_moe

def shared_experts(x):
captured["shared_stream"] = torch.cuda.current_stream()
return 3 * x

moe = DeepseekV4MoE.__new__(DeepseekV4MoE)
torch.nn.Module.__init__(moe)
moe.gate = Gate()
moe.experts = experts
moe.shared_experts = lambda x: 3 * x
moe.experts = Experts()
moe.shared_experts = shared_experts
moe.shared_experts_stream = aux_stream() if shared_stream else None
moe.shared_experts_events = (
(torch.cuda.Event(), torch.cuda.Event()) if shared_stream else None
Expand Down Expand Up @@ -274,3 +296,118 @@ def experts(x, topk_weights, topk_ids):
atol=1e-4,
)
torch.testing.assert_close(out, 5 * x)
# FusedEPMoE must not share the GPU, so the shared expert then runs serially.
on_aux_stream = captured["shared_stream"] == moe.shared_experts_stream
assert on_aux_stream is (shared_stream and not fused_ep_moe)


def _fused_ep_moe_vs_mega_moe_worker(pgi, vllm_config, cpu_group):
rank, world_size = pgi.rank, pgi.world_size
num_experts, hidden, inter, top_k = 48 * world_size, 5120, 2304, 6
generator = torch.Generator(device=pgi.device).manual_seed(rank)
layers: dict[bool, DeepseekV4AiterMegaMoEExperts] = {}
for fused in (False, True):
# finalize_weights() reads the flag.
os.environ["VLLM_ROCM_USE_AITER_FUSED_EP_MOE"] = str(int(fused))
experts = DeepseekV4AiterMegaMoEExperts(
vllm_config,
num_experts=num_experts,
top_k=top_k,
hidden_size=hidden,
intermediate_size=inter,
swiglu_limit=10.0,
)
if not layers:
for name, param in experts.named_parameters():
if name.endswith("scale"):
# E8M0 exponents 2^-7 .. 2^-4.
param.data.random_(120, 124, generator=generator)
else:
param.data.random_(0, 256, generator=generator)
raw = {k: v.clone() for k, v in experts.state_dict().items()}
experts.load_state_dict(raw)
experts.finalize_weights()
layers[fused] = experts

def inputs(num_tokens):
x = torch.randn(num_tokens, hidden, generator=generator).bfloat16()
topk_ids = (
torch.rand(num_tokens, num_experts, generator=generator)
.topk(top_k)
.indices.int()
)
topk_weights = torch.rand(num_tokens, top_k, generator=generator)
return x, topk_weights, topk_ids

def step(tokens_across_dp):
return set_forward_context(
None,
vllm_config,
num_tokens=tokens_across_dp[rank],
num_tokens_across_dp=torch.tensor(
tokens_across_dp, dtype=torch.int32, device="cpu"
),
)

assert not layers[False].uses_fused_ep_moe(1)
assert layers[True].uses_fused_ep_moe(768)
assert not layers[True].uses_fused_ep_moe(769)
# Tokens per DP rank. Every rank follows the DP max, including one with no
# tokens: FusedEPMoE up to 768, MegaMoEV2 from 769.
for tokens_across_dp in ([1, 1], [37, 300], [0, 37], [768, 1], [769, 1]):
x, topk_weights, topk_ids = inputs(tokens_across_dp[rank])
with step(tokens_across_dp):
expected = layers[False](x, topk_weights, topk_ids)
out = layers[True](x, topk_weights, topk_ids)
assert out.shape == expected.shape == x.shape
if max(tokens_across_dp) > 768:
# Both layers ran the same MegaMoEV2 runtime.
torch.testing.assert_close(out, expected, rtol=0, atol=0)
elif x.shape[0]:
cosine = torch.nn.functional.cosine_similarity(
out.float().flatten(), expected.float().flatten(), dim=0
)
# Both quantize to MXFP8 and requantize the activation; on random
# inputs like these FusedEPMoE is within 1e-5 (cosine) of an fp32
# reference and MegaMoEV2 within 4e-4.
assert cosine > 0.999, (tokens_across_dp, cosine)

# CUDA graphs: DP ranks are padded to the same size.
for num_tokens in (1, 37, 300):
x, topk_weights, topk_ids = inputs(num_tokens)
static = [t.clone() for t in (x, topk_weights, topk_ids)]
with step([num_tokens] * world_size):
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
graph_out = layers[True](*static)
new_inputs = (x.flip(0), topk_weights.flip(0), topk_ids.flip(0))
for buffer, value in zip(static, new_inputs):
buffer.copy_(value)
graph.replay()
torch.testing.assert_close(
graph_out, layers[True](*new_inputs), rtol=0, atol=0
)


@multi_gpu_test(num_gpus=2)
@pytest.mark.skipif(not current_platform.is_rocm(), reason="Requires ROCm")
def test_fused_ep_moe_matches_mega_moe():
"""With 2 DP / EP ranks, the FusedEPMoE layer gives the MegaMoEV2 layer's
output on the same weights, every rank follows the DP-max cutoff, and graph
replays match eager calls bitwise."""
fused_ep_moe = mega_moe_module._fused_ep_moe_module()
if fused_ep_moe is None or not fused_ep_moe.fused_ep_moe_supported(
world_size=2, model_dim=5120, inter_dim=2304, experts=96, topk=6
):
pytest.skip("AITER FusedEPMoE is unavailable on this AITER or GPU")
vllm_config = VllmConfig(
parallel_config=ParallelConfig(
data_parallel_size=2,
enable_expert_parallel=True,
all2all_backend="mori",
),
scheduler_config=SchedulerConfig.default_factory(max_num_batched_tokens=1024),
)
# MegaMoEV2 needs more than MoRI's default 2 GB symmetric heap.
env = {"VLLM_ROCM_USE_AITER": "1", "MORI_SHMEM_HEAP_SIZE": "8G"}
parallel_launch_with_config(2, _fused_ep_moe_vs_mega_moe_worker, vllm_config, env)
10 changes: 10 additions & 0 deletions vllm/envs.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@
VLLM_ROCM_USE_AITER_TRITON_SPARSE_MLA: bool = False
VLLM_ROCM_USE_AITER_FLYDSL_SPARSE_MLA: bool = False
VLLM_ROCM_AITER_FLYDSL_SPARSE_MLA_MIN_TOKENS: int = 160
VLLM_ROCM_USE_AITER_FUSED_EP_MOE: bool = False
VLLM_ROCM_USE_AITER_TRITON_ROPE: bool = False
VLLM_ROCM_USE_AITER_FP8BMM: bool = False
VLLM_ROCM_USE_AITER_FP4BMM: bool = False
Expand Down Expand Up @@ -1455,6 +1456,15 @@ def _resolve_rust_cli_path() -> str | None:
"VLLM_ROCM_AITER_FLYDSL_SPARSE_MLA_MIN_TOKENS": lambda: int(
os.getenv("VLLM_ROCM_AITER_FLYDSL_SPARSE_MLA_MIN_TOKENS", "160")
),
# With --moe-backend aiter_mega_moe, run each MoE layer that AITER's
# FusedEPMoE supports (hidden 5120, intermediate 2304, top 6, at most 63
# experts per rank, no fused shared expert; gfx950 with 256 CUs, i.e.
# DeepSeek-V4.1-Flash on EP8) as one persistent launch when every DP rank
# has at most 768 tokens, and on MegaMoEV2 otherwise. Needs an AITER with
# aiter.ops.flydsl.fused_ep_moe. Disabled by default.
"VLLM_ROCM_USE_AITER_FUSED_EP_MOE": lambda: (
os.getenv("VLLM_ROCM_USE_AITER_FUSED_EP_MOE", "False").lower() in ("true", "1")
),
# Whether to use aiter rope.
# By default is disabled.
"VLLM_ROCM_USE_AITER_TRITON_ROPE": lambda: (
Expand Down
Loading