Skip to content
Open
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
83 changes: 83 additions & 0 deletions tests/kernels/attention/test_moonmath_mla.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""ROCM_MOONMATH_MLA decode under decode context parallelism."""

import math
from types import SimpleNamespace

import pytest
import torch

from vllm.platforms import current_platform
from vllm.utils.import_utils import has_moonmath_amd

pytestmark = pytest.mark.skipif(
not (current_platform.is_rocm() and has_moonmath_amd()),
reason="ROCM_MOONMATH_MLA requires ROCm and moonmath_amd",
)

_LAT, _ROPE = 512, 64


@pytest.fixture(autouse=True)
def _cuda_default_device():
with torch.device("cuda"):
yield


def test_dcp_shards_merge_to_reference():
"""Each rank attends its round-robin KV shard; merging the outputs by the
returned LSE must reproduce unsharded causal attention over the whole KV."""
from vllm.v1.attention.backends.mla.moonmath_mla import MoonmathMLAImpl

world, num_reqs, seq_len, q_len, heads = 2, 2, 257, 4, 12
num_tokens = num_reqs * q_len
scale = 1.0 / math.sqrt(_LAT + _ROPE)
torch.manual_seed(0)
q = torch.randn(num_tokens, heads, _LAT + _ROPE, dtype=torch.bfloat16)
kv = (torch.randn(num_reqs, seq_len, _LAT + _ROPE) * 4).to(torch.float8_e4m3fnuz)

impl = MoonmathMLAImpl.__new__(MoonmathMLAImpl)
impl.scale = scale
impl._mm_kv_scale = 1.0
impl._max_model_len = seq_len
impl.dcp_world_size = world

outs, lses = [], []
for rank in range(world):
shard = kv[:, rank::world]
local_len = shard.shape[1]
decode = SimpleNamespace(
seq_lens=torch.full((num_reqs,), local_len, dtype=torch.int32),
paged_kv_indices=torch.arange(num_reqs * local_len, dtype=torch.int32),
paged_kv_indptr=torch.arange(
0, (num_reqs + 1) * local_len, local_len, dtype=torch.int32
),
dcp_tot_seq_lens=torch.full((num_reqs,), seq_len, dtype=torch.int32),
)
impl.dcp_rank = rank
out, lse = impl.forward_mqa(
q,
shard.reshape(-1, _LAT + _ROPE).contiguous(),
SimpleNamespace(decode=decode, causal=True),
layer=None,
)
outs.append(out.float())
lses.append(lse)
weights = torch.softmax(torch.stack(lses), dim=0).unsqueeze(-1)
merged = (weights * torch.stack(outs)).sum(dim=0)

latent, rope = kv[..., :_LAT].float(), kv[..., _LAT:].float()
q_lat, q_pe = q.float().split((_LAT, _ROPE), dim=-1)
ref = torch.empty_like(merged)
for req in range(num_reqs):
for pos in range(q_len):
row = req * q_len + pos
visible = seq_len - (q_len - 1 - pos)
scores = (
q_lat[row] @ latent[req, :visible].T + q_pe[row] @ rope[req, :visible].T
) * scale
ref[row] = torch.softmax(scores, dim=-1) @ latent[req, :visible]

rel_err = (merged - ref).abs().max() / ref.abs().max()
assert rel_err < 1e-2, f"relative error {rel_err:.3e}"
22 changes: 13 additions & 9 deletions tests/kernels/attention/test_rocm_aiter_fa.py
Original file line number Diff line number Diff line change
Expand Up @@ -689,12 +689,15 @@ def test_aiter_fa_sliding_window_matches_reference():

@pytest.mark.skipif(not on_mi3xx(), reason="MI300/MI350 ROCm only")
@pytest.mark.parametrize(
"shuffle,sliding_window", [(False, None), (False, 16), (True, None)]
"shuffle,sliding_window,block_size",
# 64-token pages are served whole only when a block cannot be split; their
# single-token decode goes to unified_attention.
[(False, None, 16), (False, 16, 16), (True, None, 16), (False, None, 64)],
)
@pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8"])
@pytest.mark.parametrize("batch", ["prefill", "extend", "mixed"])
def test_aiter_fa_shared_kv_matches_reference(
monkeypatch, shuffle, sliding_window, kv_cache_dtype, batch
monkeypatch, shuffle, sliding_window, block_size, kv_cache_dtype, batch
):
"""Shared layers read cached K/V for prefill and extend without modifying it."""
from tests.v1.attention.utils import (
Expand Down Expand Up @@ -725,6 +728,7 @@ def test_aiter_fa_shared_kv_matches_reference(
max_num_batched_tokens=1024,
)
config.cache_config.cache_dtype = kv_cache_dtype
config.cache_config.block_size = block_size
num_heads = config.model_config.get_num_attention_heads(config.parallel_config)
num_kv_heads = config.model_config.get_num_kv_heads(config.parallel_config)
head_size = config.model_config.get_head_size()
Expand Down Expand Up @@ -758,18 +762,18 @@ def test_aiter_fa_shared_kv_matches_reference(
torch.device("cuda"),
)
common = create_common_attn_metadata(
batch_spec, BLOCK_SIZE, torch.device("cuda"), max_block_idx=32
batch_spec, block_size, torch.device("cuda"), max_block_idx=32
)
cache_dtype = (
current_platform.fp8_dtype() if kv_cache_dtype == "fp8" else torch.bfloat16
)
kv_cache = (
torch.empty(
2, 32, BLOCK_SIZE, num_kv_heads * head_size, dtype=cache_dtype
2, 32, block_size, num_kv_heads * head_size, dtype=cache_dtype
).transpose(0, 1)
if shuffle
else torch.empty(
32, num_kv_heads, BLOCK_SIZE, 2 * head_size, dtype=cache_dtype
32, num_kv_heads, block_size, 2 * head_size, dtype=cache_dtype
)
)
target.kv_cache = kv_cache
Expand All @@ -780,22 +784,22 @@ def test_aiter_fa_shared_kv_matches_reference(
attn_layer._k_scale.fill_(k_scale)
attn_layer._v_scale.fill_(v_scale)
key = torch.randn(
32 * BLOCK_SIZE, num_kv_heads, head_size, dtype=torch.bfloat16
32 * block_size, num_kv_heads, head_size, dtype=torch.bfloat16
)
value = torch.randn_like(key)
target.impl.do_kv_cache_update(
target,
key,
value,
kv_cache,
torch.arange(32 * BLOCK_SIZE, dtype=torch.int64),
torch.arange(32 * block_size, dtype=torch.int64),
)
key_cache = ((key / k_scale).to(cache_dtype).to(key.dtype) * k_scale).reshape(
32, BLOCK_SIZE, num_kv_heads, head_size
32, block_size, num_kv_heads, head_size
)
value_cache = (
(value / v_scale).to(cache_dtype).to(value.dtype) * v_scale
).reshape(32, BLOCK_SIZE, num_kv_heads, head_size)
).reshape(32, block_size, num_kv_heads, head_size)
with torch.device("cpu"):
metadata = builder.build(0, common)
cache_before = kv_cache.view(torch.uint8).clone()
Expand Down
88 changes: 88 additions & 0 deletions tests/kernels/moe/test_ocp_mx_moe.py
Original file line number Diff line number Diff line change
Expand Up @@ -1821,6 +1821,94 @@ def test_mxfp4_emulation_rounds_up_to_block_size(
assert rounded_intermediate % OCP_MX_BLOCK_SIZE == 0


# Both AITER MXFP4 A16W4 backends serve K3's native intermediate size, so they
# must align it the same way; gfx942 can only take the Triton one. The generic
# ROCm 256 round-up inflates K3's 384/partition to 512 (+33% MoE weights), which
# OOMs before any KV cache is allocated. The exemption is scoped to the SiTU and
# SILU kernels, so every other activation must keep the 256 round-up.
@pytest.mark.skipif(not ROCM_AVAILABLE, reason="AITER MXFP4 backends target ROCm")
@pytest.mark.parametrize(
"backend_name,activation_name,expected",
[
("AITER_MXFP4_BF16", "SITU", (3584, 384)),
("AITER_MXFP4_BF16", "SILU", (3584, 384)),
("AITER_TRITON_MXFP4_BF16", "SITU", (3584, 384)),
("AITER_TRITON_MXFP4_BF16", "SILU", (3584, 384)),
("AITER_TRITON_MXFP4_BF16", "SWIGLUOAI", (3584, 512)),
],
)
def test_aiter_mxfp4_a16w4_alignment(
backend_name: str, activation_name: str, expected: tuple[int, int]
):
"""K3 at TP8: hidden 3584, intermediate 384/partition, both 128-aligned."""
from vllm.model_executor.layers.fused_moe.activation import MoEActivation
from vllm.model_executor.layers.fused_moe.oracle.mxfp4 import (
Mxfp4MoeBackend,
mxfp4_round_up_hidden_size_and_intermediate_size,
)

assert (
mxfp4_round_up_hidden_size_and_intermediate_size(
getattr(Mxfp4MoeBackend, backend_name),
3584,
384,
getattr(MoEActivation, activation_name),
)
== expected
)


# The moonmath kernels are an optional package. Without them there is no SiTU
# a16w4 kernel at all, so the class must DECLINE the activation and let the
# oracle fall through to AITER, rather than be selected and fail at weight load.
@pytest.mark.parametrize("installed", [True, False])
def test_aiter_w4a16_claims_situ_only_with_the_moonmath_kernels(
monkeypatch: pytest.MonkeyPatch, installed: bool
):
from vllm.model_executor.layers.fused_moe.activation import MoEActivation
from vllm.model_executor.layers.fused_moe.experts import (
moonmath_mxfp4_moe as experts,
)
from vllm.model_executor.layers.fused_moe.experts.aiter_mxfp4_w4a16_moe import (
AiterW4A16ExpertsMonolithic,
)

monkeypatch.setattr(experts, "has_moonmath_amd", lambda: installed)

assert (
experts.MoonmathW4A16SituExperts._supports_activation(MoEActivation.SITU)
is installed
)
# The AITER class is untouched: it never claims SiTU, and still serves the
# activations it always did, so a fall-through is unaffected either way.
aiter_cls = AiterW4A16ExpertsMonolithic
assert not aiter_cls._supports_activation(MoEActivation.SITU)
assert aiter_cls._supports_activation(MoEActivation.SILU)
assert aiter_cls._supports_activation(MoEActivation.SWIGLUOAI)


@pytest.mark.skipif(not current_platform.is_cuda_alike(), reason="needs a GPU")
@pytest.mark.parametrize("num_tokens,hidden", [(1, 7), (32, 7168)])
def test_moonmath_weighted_topk_sum_matches_fp32_reference(num_tokens, hidden):
from vllm.model_executor.layers.fused_moe.experts import (
moonmath_mxfp4_moe as experts,
)
from vllm.triton_utils import triton

topk = 16
down = torch.randn(num_tokens * topk, hidden, device="cuda", dtype=torch.bfloat16)
weights = torch.rand(num_tokens, topk, device="cuda", dtype=torch.float32)
out = torch.empty(num_tokens, hidden, device="cuda", dtype=torch.bfloat16)
experts._weighted_topk_sum_kernel[
(num_tokens, triton.cdiv(hidden, experts._REDUCE_BLOCK_H))
](down, weights, out, hidden, TOPK=topk, BLOCK_H=experts._REDUCE_BLOCK_H)

ref = torch.zeros(num_tokens, hidden, device="cuda", dtype=torch.float32)
for k in range(topk):
ref += down.view(num_tokens, topk, hidden)[:, k].float() * weights[:, k, None]
torch.testing.assert_close(out, ref.to(torch.bfloat16))


def test_select_mxfp4_moe_backend_raises_with_unsupported_reasons(
monkeypatch: pytest.MonkeyPatch,
):
Expand Down
3 changes: 1 addition & 2 deletions tests/v1/attention/test_attention_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -938,8 +938,6 @@ def test_flashinfer_xqa_single_token_decode_preserves_cudagraph_padding(monkeypa
impl.o_sf_scale = None
impl.window_left = -1
impl.sinks = None
impl.cache_config = unittest.mock.Mock()
impl.cache_config.get_resolved_kv_cache_layout.return_value = KVCacheLayout.LBHNC

layer = unittest.mock.Mock(
_q_scale=torch.tensor(1.0),
Expand All @@ -955,6 +953,7 @@ def test_flashinfer_xqa_single_token_decode_preserves_cudagraph_padding(monkeypa
q_len_per_req=1,
)
attn_metadata = flashinfer_backend.FlashInferMetadata(
kv_cache_layout=KVCacheLayout.LBHNC,
num_actual_tokens=2,
slot_mapping=torch.empty(0, dtype=torch.int64),
q_data_type_prefill=torch.bfloat16,
Expand Down
30 changes: 30 additions & 0 deletions tests/v1/attention/test_rocm_aiter_mla_mtp_split.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,9 @@ def _builder(
stub._fill_dcp_verify_page_table = (
AiterMLAMetadataBuilder._fill_dcp_verify_page_table.__get__(stub)
)
stub._decode_reads_aiter_schedule = (
AiterMLAMetadataBuilder._decode_reads_aiter_schedule.__get__(stub)
)
return stub


Expand Down Expand Up @@ -1044,3 +1047,30 @@ def test_a_two_token_bf16_block_is_allowed(monkeypatch):
monkeypatch, num_heads=12, kv_cache_dtype="auto", qlen=2, mtp_qlen=8
)
assert metadata.has_persistent_metadata


@pytest.mark.parametrize(
"num_reqs,qo_len,uniform,causal,heads,reads_schedule",
[
(8, 4, True, True, 12, False),
(8, 1, True, True, 96, False),
(8, 4, False, True, 12, True),
(8, 4, True, False, 12, True),
(8, 4, True, True, 160, True),
(400, 4, True, True, 12, True),
],
)
def test_moonmath_skips_aiter_schedule_only_for_batches_it_serves(
num_reqs, qo_len, uniform, causal, heads, reads_schedule
):
from vllm.v1.attention.backends.mla.moonmath_mla import (
MoonmathMLAMetadataBuilder,
)

builder = SimpleNamespace(_decode_num_heads=heads)
assert (
MoonmathMLAMetadataBuilder._decode_reads_aiter_schedule(
builder, num_reqs, qo_len, uniform, causal
)
is reads_schedule
)
Loading