Skip to content
Closed
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
6 changes: 6 additions & 0 deletions release_notes/fragments/20234.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
pr: 20234
entries:
- category: bugfix
text: Fixed conflicting MegaMoE communication contexts between the target and DSpark draft models when running DeepSeek V4.1 on Ascend A5.
model: deepseek-v4.1
hardware: [A5]
153 changes: 153 additions & 0 deletions tests/ut/ops/test_mega_moe_context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
# SPDX-License-Identifier: Apache-2.0
"""Regression coverage for target/draft sharing without native collectives."""

import sys
import unittest
from inspect import signature
from types import SimpleNamespace
from unittest.mock import Mock, patch

from vllm_ascend.ops.fused_moe.mega_moe_context import get_main_owned_buffer, is_draft_moe_config


def _buffer_factory(
group,
num_experts,
num_max_tokens_per_rank,
num_topk,
hidden,
intermediate_hidden,
*,
max_recv_token_num=0,
dispatch_quant_mode=0,
dispatch_quant_out_dtype=None,
combine_quant_mode=0,
comm_alg="",
topk_weights_type=0,
):
return SimpleNamespace(**locals(), context=object(), _ctx_manager=object(), ep_world_size=8, ccl_buffer_size=4096)


class TestMainOwnedMegaMoeBuffer(unittest.TestCase):
def setUp(self):
self.scope = SimpleNamespace()
self.group = object()
self.factory = Mock(wraps=_buffer_factory)
# Preserve the CANN factory's signature and module for ABI binding.
self.factory.__signature__ = signature(_buffer_factory)
self.factory.__module__ = __name__
self.size_query = Mock(return_value=4096)
self.size_patch = patch.object(
sys.modules[__name__], "_get_mega_moe_ccl_buffer_size", self.size_query, create=True
)
self.size_patch.start()
self.addCleanup(self.size_patch.stop)

def _get_buffer(self, is_draft=False, **overrides):
params = dict(
group=self.group,
num_experts=384,
num_max_tokens_per_rank=128,
num_topk=6,
hidden=16,
intermediate_hidden=64,
max_recv_token_num=1024,
dispatch_quant_mode=4,
dispatch_quant_out_dtype="float8",
)
params.update(overrides)
return get_main_owned_buffer(self.scope, self.factory, is_draft=is_draft, **params)

def test_main_draft_main_uses_one_context_with_independent_metadata(self):
main = self._get_buffer()
draft = self._get_buffer(is_draft=True, num_experts=128, num_topk=3, intermediate_hidden=32)
another_main = self._get_buffer()

self.factory.assert_called_once()
for view in (draft, another_main):
self.assertIs(view.context, main.context)
self.assertIs(view._ctx_manager, main._ctx_manager)
self.assertIs(view.group, main.group)
self.assertEqual(view.ccl_buffer_size, main.ccl_buffer_size)
self.assertEqual((main.num_experts, main.num_topk, main.intermediate_hidden), (384, 6, 64))
self.assertEqual((draft.num_experts, draft.num_topk, draft.intermediate_hidden), (128, 3, 32))
draft.dispatch_quant_mode = 0
self.assertEqual(main.dispatch_quant_mode, 4)
self.assertEqual(another_main.dispatch_quant_mode, 4)
self.assertEqual(self.size_query.call_args_list[0].args[:4], (8, 128, 128, 3))

def test_draft_first_fails_without_allocating_a_context(self):
with self.assertRaisesRegex(RuntimeError, "Main must initialize"):
self._get_buffer(is_draft=True)
self.factory.assert_not_called()
self.assertFalse(hasattr(self.scope, "_main_mega_moe_symm_buffer"))

def test_separate_mc2_groups_have_separate_owners(self):
main = self._get_buffer()
self.scope = SimpleNamespace()
self.group = object()
other = self._get_buffer()
self.assertIsNot(main.context, other.context)
self.assertEqual(self.factory.call_count, 2)

def test_incompatible_group_or_communication_settings_do_not_allocate(self):
self._get_buffer()
for name, value in (
("group", object()),
("hidden", 32),
("dispatch_quant_mode", 0),
("dispatch_quant_out_dtype", None),
("combine_quant_mode", 4),
("comm_alg", "hierarchy"),
("topk_weights_type", 1),
):
with self.subTest(name=name), self.assertRaises(RuntimeError):
self._get_buffer(is_draft=True, **{name: value})
self.factory.assert_called_once()
self.size_query.assert_not_called()

def test_draft_token_capacity_cannot_exceed_main(self):
self._get_buffer()
with self.assertRaisesRegex(RuntimeError, "token capacity"):
self._get_buffer(is_draft=True, num_max_tokens_per_rank=129)
self.factory.assert_called_once()

def test_draft_ccl_capacity_cannot_exceed_main(self):
self._get_buffer()
self.size_query.return_value = 4097
with self.assertRaisesRegex(RuntimeError, "exceeds main"):
self._get_buffer(is_draft=True)
self.factory.assert_called_once()


class TestDraftMoEConfig(unittest.TestCase):
def _config(self, runner_type="generate", target_experts=384, draft_experts=128):
return SimpleNamespace(
model_config=SimpleNamespace(runner_type=runner_type, get_num_experts=lambda: target_experts),
speculative_config=SimpleNamespace(
draft_model_config=SimpleNamespace(get_num_experts=lambda: draft_experts)
),
)

def test_eager_mrv2_draft_is_identified_under_target_config(self):
config = self._config()
self.assertTrue(is_draft_moe_config(SimpleNamespace(num_experts=128), config))
self.assertFalse(is_draft_moe_config(SimpleNamespace(num_experts=384), config))

def test_redundant_experts_do_not_change_model_role(self):
config = self._config()
self.assertFalse(is_draft_moe_config(SimpleNamespace(num_experts=400, global_redundant_expert_num=16), config))
self.assertTrue(is_draft_moe_config(SimpleNamespace(num_experts=144, global_redundant_expert_num=16), config))

def test_explicit_draft_runner(self):
self.assertTrue(is_draft_moe_config(SimpleNamespace(num_experts=128), self._config(runner_type="draft")))

def test_no_speculation_or_same_expert_count(self):
moe = SimpleNamespace(num_experts=384)
config = self._config(draft_experts=384)
self.assertFalse(is_draft_moe_config(moe, config))
config.model_config.runner_type = "draft"
self.assertFalse(is_draft_moe_config(moe, config))
config.model_config.runner_type = "generate"
config.speculative_config = None
self.assertFalse(is_draft_moe_config(moe, config))
15 changes: 9 additions & 6 deletions tests/ut/ops/test_moe_comm_method.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from types import SimpleNamespace
from unittest.mock import MagicMock, patch

import torch
Expand Down Expand Up @@ -69,6 +70,7 @@ def _make_fused_mc2_comm_for_buffer_init(self):
comm_impl.token_dispatcher.ep_rank_id = 0
comm_impl.get_symm_buffer_for_mega_moe = MagicMock(return_value="symm_buffer")
comm_impl.mega_moe_symm_buffer = None
comm_impl._mega_moe_is_draft = False
return comm_impl

def tearDown(self):
Expand All @@ -80,8 +82,7 @@ def tearDown(self):
@patch("vllm_ascend.ops.fused_moe.moe_comm_method.logger.warning_once")
def test_mega_moe_symm_buffer_uses_mega_moe_max_tokens(self, mock_warning_once, mock_get_mc2_group):
self.mock_ascend_config.mega_moe_max_tokens = 512
mock_mc2_group = MagicMock()
mock_mc2_group.device_group = "mc2_group"
mock_mc2_group = SimpleNamespace(device_group="mc2_group")
mock_get_mc2_group.return_value = mock_mc2_group
comm_impl = self._make_fused_mc2_comm_for_buffer_init()

Expand All @@ -100,8 +101,7 @@ def test_mega_moe_symm_buffer_clamps_to_safe_capacity_for_p_node(self, mock_get_
# mega_moe_max_tokens (32768) exceeds the absolute safe upper bound
# (1024), so the P-node buffer must be clamped to that bound.
self.mock_ascend_config.mega_moe_max_tokens = 32768
mock_mc2_group = MagicMock()
mock_mc2_group.device_group = "mc2_group"
mock_mc2_group = SimpleNamespace(device_group="mc2_group")
mock_get_mc2_group.return_value = mock_mc2_group
comm_impl = self._make_fused_mc2_comm_for_buffer_init()

Expand All @@ -117,8 +117,7 @@ def test_mega_moe_symm_buffer_clamps_to_safe_capacity_for_p_node(self, mock_get_
@patch("vllm_ascend.ops.fused_moe.moe_comm_method.get_mc2_group")
def test_mega_moe_symm_buffer_uses_safe_capacity_for_d_node(self, mock_get_mc2_group, mock_warning_once):
self.mock_ascend_config.mega_moe_max_tokens = 32768
mock_mc2_group = MagicMock()
mock_mc2_group.device_group = "mc2_group"
mock_mc2_group = SimpleNamespace(device_group="mc2_group")
mock_get_mc2_group.return_value = mock_mc2_group
comm_impl = self._make_fused_mc2_comm_for_buffer_init()

Expand Down Expand Up @@ -221,6 +220,10 @@ def op(*args, activation="swiglu", activation_params=None, **kwargs):
patch.object(FusedMC2CommImpl, "_get_token_dispatcher"),
patch.object(FusedMC2CommImpl, "_get_prepare_finalize"),
patch("vllm_ascend.ops.fused_moe.moe_comm_method.is_mega_moe_supported", return_value=True),
patch(
"vllm_ascend.ops.fused_moe.moe_comm_method.get_current_vllm_config",
return_value=SimpleNamespace(model_config=SimpleNamespace(runner_type="generate")),
),
patch("vllm_ascend.ops.fused_moe.moe_utils.load_cann_mega_moe_ops", return_value=(MagicMock(), op)),
patch("vllm_ascend.ops.fused_moe.moe_comm_method.torch.zeros"),
):
Expand Down
96 changes: 96 additions & 0 deletions vllm_ascend/ops/fused_moe/mega_moe_context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# SPDX-License-Identifier: Apache-2.0
"""Main-owned MegaMoe communication storage for serialized target/draft calls."""

from collections.abc import Callable
from importlib import import_module
from inspect import signature
from types import SimpleNamespace
from typing import Any


def is_draft_moe_config(moe_config: Any, vllm_config: Any) -> bool:
"""Identify a draft communicator even when MRv2 constructs it under target config.

MRv2 eager DSpark forwards retain the target's context flag. The loaded
target/draft model descriptors still distinguish their logical expert
counts; redundant target slots must not turn a target into a draft.
"""
is_draft_runner = getattr(vllm_config.model_config, "runner_type", None) == "draft"

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.

high

If vllm_config is None (which can happen when called outside of an active engine/worker context, such as during offline testing or initialization), accessing vllm_config.model_config will raise an AttributeError. A defensive None check should be added at the beginning of the function.

Suggested change
is_draft_runner = getattr(vllm_config.model_config, "runner_type", None) == "draft"
if vllm_config is None:
return False
is_draft_runner = getattr(vllm_config.model_config, "runner_type", None) == "draft"

speculative = getattr(vllm_config, "speculative_config", None)
draft_config = getattr(speculative, "draft_model_config", None)
if draft_config is None:
return is_draft_runner
target_experts = int(vllm_config.model_config.get_num_experts())
draft_experts = int(draft_config.get_num_experts())
Comment on lines +23 to +24

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.

high

The code calls vllm_config.model_config.get_num_experts() and draft_config.get_num_experts(). However, in standard vLLM, ModelConfig does not have a get_num_experts() method. This will raise an AttributeError at runtime during E2E execution. To ensure compatibility and robustness, we should safely retrieve the number of experts from hf_config or check if the method exists before calling it.

    def _get_experts(cfg: Any) -> int:
        if hasattr(cfg, "get_num_experts"):
            return int(cfg.get_num_experts())
        hf_cfg = getattr(cfg, "hf_config", None)
        if hf_cfg is not None:
            for attr in ("num_experts", "n_routed_experts", "num_local_experts"):
                if hasattr(hf_cfg, attr):
                    return int(getattr(hf_cfg, attr))
        return 0

    target_experts = _get_experts(vllm_config.model_config)
    draft_experts = _get_experts(draft_config)

# Equal expert layouts already share a cached MoECommMethod, including
# its lazy initialization when it was last constructed by the draft.
if target_experts == draft_experts:
return False
logical_experts = int(moe_config.num_experts) - int(getattr(moe_config, "global_redundant_expert_num", 0))
return is_draft_runner or logical_experts == draft_experts


def get_main_owned_buffer(
scope: Any,
factory: Callable,
*,
is_draft: bool,
group: Any,
num_experts: int,
num_max_tokens_per_rank: int,
num_topk: int,
**kwargs,
):
"""Allocate once for main; give draft its own metadata over that storage.

The MC2 group coordinator owns the allocation for its lifetime. Target
and draft must execute serially. A draft-first request or insufficient
capacity fails before a second native communication context is created.
"""
bound = signature(factory).bind(group, num_experts, num_max_tokens_per_rank, num_topk, **kwargs)
bound.apply_defaults()
params = bound.arguments
owner = getattr(scope, "_main_mega_moe_symm_buffer", None)
if owner is None:
if is_draft:
raise RuntimeError("Main must initialize MegaMoe before the draft")
owner = factory(*bound.args, **bound.kwargs)
scope._main_mega_moe_symm_buffer = owner
return owner
Comment on lines +53 to +59

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.

high

Monkey-patching the scope object (which is the MC2 process group or its wrapper) with _main_mega_moe_symm_buffer is risky. If scope is a C++ extension object (such as PyTorch's native ProcessGroup or a class without a dynamic __dict__ or using __slots__), setting arbitrary attributes on it will raise an AttributeError. To safely associate the buffer with the group's lifetime without monkey-patching, we can use a module-level weakref.WeakKeyDictionary.

    if not hasattr(get_main_owned_buffer, "_group_buffers"):
        import weakref
        get_main_owned_buffer._group_buffers = weakref.WeakKeyDictionary()
    group_buffers = get_main_owned_buffer._group_buffers

    owner = group_buffers.get(scope)
    if owner is None:
        if is_draft:
            raise RuntimeError("Main must initialize MegaMoe before the draft")
        owner = factory(*bound.args, **bound.kwargs)
        group_buffers[scope] = owner
        return owner


if group is not owner.group:
raise RuntimeError("Main and draft MegaMoe process groups differ")
for name in (
"hidden",
"dispatch_quant_mode",
"dispatch_quant_out_dtype",
"combine_quant_mode",
"comm_alg",
"topk_weights_type",
):
if params[name] != getattr(owner, name):
raise RuntimeError(f"Incompatible shared MegaMoe setting: {name}")
if num_max_tokens_per_rank > owner.num_max_tokens_per_rank:
raise RuntimeError("Draft token capacity exceeds the main allocation")
module = import_module(factory.__module__)
required = module._get_mega_moe_ccl_buffer_size(
owner.ep_world_size,
num_experts,
num_max_tokens_per_rank,
num_topk,
params["hidden"],
params["max_recv_token_num"],
params["dispatch_quant_mode"],
params["dispatch_quant_out_dtype"],
params["combine_quant_mode"],
params["comm_alg"],
params["topk_weights_type"],
)
if required > owner.ccl_buffer_size:
raise RuntimeError(f"Requested MegaMoe capacity {required} exceeds main's {owner.ccl_buffer_size} bytes")
view = SimpleNamespace(**vars(owner))
for name, value in params.items():
setattr(view, name, value)
assert view.context is owner.context
assert view._ctx_manager is owner._ctx_manager
return view
Comment on lines +91 to +96

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.

high

Using SimpleNamespace(**vars(owner)) to create a view of owner is fragile. If owner is a C++ extension object or uses __slots__, vars(owner) will raise a TypeError. Furthermore, vars(owner) only copies instance attributes from __dict__, meaning any class-level attributes, properties, or methods defined on owner's class will be completely missing from the SimpleNamespace view. To ensure robustness and preserve all methods and properties, we should use a delegating wrapper class instead.

Suggested change
view = SimpleNamespace(**vars(owner))
for name, value in params.items():
setattr(view, name, value)
assert view.context is owner.context
assert view._ctx_manager is owner._ctx_manager
return view
class SymmBufferView:
def __init__(self, owner, params):
self.__dict__["_owner"] = owner
self.__dict__["_params"] = params
def __getattr__(self, name):
if name in self._params:
return self._params[name]
return getattr(self._owner, name)
def __setattr__(self, name, value):
self._params[name] = value
view = SymmBufferView(owner, params)
assert view.context is owner.context
assert view._ctx_manager is owner._ctx_manager
return view

16 changes: 11 additions & 5 deletions vllm_ascend/ops/fused_moe/moe_comm_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from typing import cast

import torch
from vllm.config import get_current_vllm_config
from vllm.logger import logger
from vllm.model_executor.layers.fused_moe import FusedMoEConfig

Expand All @@ -32,6 +33,7 @@
from vllm_ascend.ops.fused_moe.dataclass.moe_mlp import MoEMlpComputeInput, build_mlp_compute_input
from vllm_ascend.ops.fused_moe.dataclass.prepare_finalize import MoEPrepareOutput
from vllm_ascend.ops.fused_moe.dataclass.token_dispatcher import build_token_dispatch_input
from vllm_ascend.ops.fused_moe.mega_moe_context import get_main_owned_buffer, is_draft_moe_config
from vllm_ascend.ops.fused_moe.moe_mlp import apply_moe_mlp, maybe_record_event
from vllm_ascend.ops.fused_moe.prepare_finalize import (
PrepareAndFinalize,
Expand Down Expand Up @@ -301,6 +303,7 @@ def __init__(self, moe_config):
self._mega_moe_hccl_state_stale = False
self.enable_fused_mc2 = get_ascend_config().enable_fused_mc2
if self.enable_fused_mc2 == 1 and is_mega_moe_supported():
self._mega_moe_is_draft = is_draft_moe_config(moe_config, get_current_vllm_config())
self.mega_moe_symm_buffer = None
self.get_symm_buffer_for_mega_moe, self.mega_moe = moe_utils.load_cann_mega_moe_ops()
# Resolve the Python ABI once, before the first collective/capture.
Expand Down Expand Up @@ -454,11 +457,14 @@ def _init_mega_moe_symm_buffer(
self.token_dispatcher.global_bs,
)

return self.get_symm_buffer_for_mega_moe(
group,
num_experts,
num_max_tokens_per_rank,
num_topk,
return get_main_owned_buffer(
get_mc2_group(),
self.get_symm_buffer_for_mega_moe,
is_draft=self._mega_moe_is_draft,
group=group,
num_experts=num_experts,
num_max_tokens_per_rank=num_max_tokens_per_rank,
num_topk=num_topk,
hidden=self.moe_config.hidden_dim,
intermediate_hidden=2 * self.moe_config.intermediate_size_per_partition,
max_recv_token_num=max_recv_token_num,
Expand Down
Loading