Skip to content

Commit c683d0f

Browse files
2luckydogwestbook1006zmc1997mengguangxinliuwj-research
committed
perf(moe): use a plain tensor add for the MoE tail combine
MoE layers with both shared and routed experts merge the two outputs once per layer at the end of the block. The Ascend runner mirrors upstream's ``MoERunner.forward`` and performs that combine with ``torch._foreach_add([shared_output], [fused_output])[0]``. Both operands are ordinary activation tensors, so this is a plain elementwise add. ``_foreach_add`` exists to amortise dispatch across a tensor list; with a one-element list there is nothing to amortise, and on NPU the multi-tensor path still launches a dedicated ``ForeachAddList`` kernel. That launch costs ~13-17us regardless of tensor size, once per MoE layer, on every decode step: for a 45-layer MoE model this is ~0.75ms of pure launch overhead sitting on the token-to-token critical path. The multi-tensor form is still required in the graph modes: the superkernel generation path only accepts this combine through ``torch._foreach_add``, and a plain ``aclnnAdd`` disconnects the graph. So the combine uses whichever form the mode requires: * ``ascend_compilation_config.enable_super_kernel`` or ``enable_static_kernel`` set -> keep ``torch._foreach_add``, unchanged behaviour; * otherwise -> ``shared_output + fused_output``, which is bit-identical (same dtype, same operand order, elementwise add) and saves one op launch per MoE layer. No new configuration key or environment variable: the mode is read from the existing compilation config once in ``__init__`` and cached on the instance, so the hot path never re-reads it and no graph recompilation happens mid-run. A runner built without an initialized Ascend config (unit tests) keeps the graph-safe foreach path. The combine is extracted into ``_combine_shared_and_routed_output`` so both branches are directly unit-tested. Co-authored-by: westbook1006 <1210973614@qq.com> Co-authored-by: zmc1997 <742133686@qq.com> Co-authored-by: mengguangxin <mgx0018@163.com> Co-authored-by: liuwj-research <liuwj.2008@tsinghua.org.cn> Co-authored-by: dailiang16 <dailiang0110@yeah.net> Signed-off-by: 2luckydog <2981945956@qq.com>
1 parent 695e939 commit c683d0f

2 files changed

Lines changed: 171 additions & 9 deletions

File tree

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# SPDX-License-Identifier: Apache-2.0
2+
from types import SimpleNamespace
3+
from unittest.mock import patch
4+
5+
import pytest
6+
import torch
7+
8+
from vllm_ascend.ops.fused_moe import fused_moe as fused_moe_module
9+
10+
11+
def _make_runner(plain_tail_add: bool):
12+
"""Build a runner shell that only carries the resolved combine mode."""
13+
runner = fused_moe_module.AscendMoERunner.__new__(fused_moe_module.AscendMoERunner)
14+
runner._plain_tail_add = plain_tail_add
15+
return runner
16+
17+
18+
def _config(enable_super_kernel: bool, enable_static_kernel: bool):
19+
return SimpleNamespace(
20+
ascend_compilation_config=SimpleNamespace(
21+
enable_super_kernel=enable_super_kernel,
22+
enable_static_kernel=enable_static_kernel,
23+
)
24+
)
25+
26+
27+
@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16, torch.float32])
28+
def test_tail_combine_branches_are_bit_identical(dtype):
29+
torch.manual_seed(0)
30+
shared = torch.randn(5, 8, dtype=dtype)
31+
routed = torch.randn(5, 8, dtype=dtype)
32+
33+
combined_plain = _make_runner(True)._combine_shared_and_routed_output(shared, routed)
34+
combined_foreach = _make_runner(False)._combine_shared_and_routed_output(shared, routed)
35+
36+
assert combined_plain.dtype == dtype
37+
torch.testing.assert_close(combined_plain, combined_foreach, rtol=0, atol=0)
38+
39+
40+
def test_tail_combine_preserves_empty_input_shape():
41+
shared = torch.empty(0, 8, dtype=torch.bfloat16)
42+
routed = torch.empty(0, 8, dtype=torch.bfloat16)
43+
44+
for plain in (True, False):
45+
out = _make_runner(plain)._combine_shared_and_routed_output(shared, routed)
46+
assert out.shape == (0, 8)
47+
assert out.dtype == torch.bfloat16
48+
49+
50+
def test_default_branch_uses_single_element_foreach_add():
51+
shared = torch.randn(3, 8, dtype=torch.bfloat16)
52+
routed = torch.randn(3, 8, dtype=torch.bfloat16)
53+
original = torch._foreach_add
54+
list_lengths = []
55+
56+
def spy(tensors_a, tensors_b, *args, **kwargs):
57+
list_lengths.append((len(tensors_a), len(tensors_b)))
58+
return original(tensors_a, tensors_b, *args, **kwargs)
59+
60+
with patch.object(torch, "_foreach_add", side_effect=spy) as mocked:
61+
out = _make_runner(False)._combine_shared_and_routed_output(shared, routed)
62+
63+
assert mocked.call_count == 1
64+
assert list_lengths == [(1, 1)]
65+
torch.testing.assert_close(out, shared + routed, rtol=0, atol=0)
66+
67+
68+
def test_plain_branch_never_dispatches_foreach_add():
69+
shared = torch.randn(3, 8, dtype=torch.bfloat16)
70+
routed = torch.randn(3, 8, dtype=torch.bfloat16)
71+
72+
def fail(*args, **kwargs):
73+
raise AssertionError("torch._foreach_add must not be dispatched when the plain add is used")
74+
75+
with patch.object(torch, "_foreach_add", side_effect=fail):
76+
out = _make_runner(True)._combine_shared_and_routed_output(shared, routed)
77+
78+
torch.testing.assert_close(out, shared + routed, rtol=0, atol=0)
79+
80+
81+
@pytest.mark.parametrize(
82+
"enable_super_kernel,enable_static_kernel,expected",
83+
[
84+
(False, False, True),
85+
(True, False, False),
86+
(False, True, False),
87+
(True, True, False),
88+
],
89+
)
90+
def test_plain_tail_add_follows_graph_mode(monkeypatch, enable_super_kernel, enable_static_kernel, expected):
91+
monkeypatch.setattr(
92+
fused_moe_module,
93+
"get_ascend_config",
94+
lambda: _config(enable_super_kernel, enable_static_kernel),
95+
)
96+
97+
assert fused_moe_module._plain_tail_add_enabled() is expected
98+
99+
100+
def test_plain_tail_add_requires_initialized_ascend_config(monkeypatch):
101+
def raise_runtime_error():
102+
raise RuntimeError("Ascend config is not initialized")
103+
104+
monkeypatch.setattr(fused_moe_module, "get_ascend_config", raise_runtime_error)
105+
106+
assert fused_moe_module._plain_tail_add_enabled() is False
107+
108+
109+
def test_runner_built_without_init_keeps_foreach_path():
110+
"""Runners assembled via ``__new__`` (as existing tests do) must not crash."""
111+
runner = fused_moe_module.AscendMoERunner.__new__(fused_moe_module.AscendMoERunner)
112+
shared = torch.randn(3, 8, dtype=torch.bfloat16)
113+
routed = torch.randn(3, 8, dtype=torch.bfloat16)
114+
115+
with patch.object(torch, "_foreach_add", wraps=torch._foreach_add) as mocked:
116+
out = runner._combine_shared_and_routed_output(shared, routed)
117+
118+
assert mocked.call_count == 1
119+
torch.testing.assert_close(out, shared + routed, rtol=0, atol=0)

‎vllm_ascend/ops/fused_moe/fused_moe.py‎

Lines changed: 52 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
from vllm.model_executor.layers.fused_moe.runner.moe_runner import _moe_forward_shared, _unpack
3030
from vllm.utils.torch_utils import direct_register_custom_op
3131

32+
from vllm_ascend.ascend_config import get_ascend_config
3233
from vllm_ascend.ascend_forward_context import _EXTRA_CTX, MoECommType
3334
from vllm_ascend.distributed.parallel_state import get_mc2_group
3435
from vllm_ascend.ops.fused_moe.dataclass.shared_experts import PreparedSharedExpertInput, RoutedMoEMilestones
@@ -83,7 +84,30 @@ def _ascend_moe_forward_shared_sp_fake(
8384
)
8485

8586

87+
def _plain_tail_add_enabled() -> bool:
88+
"""Whether the MoE tail combine may use a plain tensor add.
89+
90+
``torch._foreach_add`` is required while the superkernel / static-kernel
91+
graph is in use: the superkernel generation path only accepts the combine
92+
through the multi-tensor op, and a plain ``aclnnAdd`` disconnects the
93+
graph. Outside those modes both forms are bit-identical elementwise adds,
94+
and the plain one avoids one op launch per MoE layer.
95+
"""
96+
try:
97+
compilation_config = get_ascend_config().ascend_compilation_config
98+
except RuntimeError:
99+
# Runners built outside ``init_ascend_config`` (unit tests) keep the
100+
# graph-safe default.
101+
return False
102+
return not (compilation_config.enable_super_kernel or compilation_config.enable_static_kernel)
103+
104+
86105
class AscendMoERunner(MoERunner): # type: ignore[no-redef]
106+
# Keeps the graph-safe path for instances built without ``__init__`` (tests
107+
# construct runners via ``__new__`` to exercise single helpers); ``__init__``
108+
# overrides it with the mode resolved from the compilation config.
109+
_plain_tail_add: bool = False
110+
87111
def __init__(
88112
self,
89113
layer_name,
@@ -126,6 +150,10 @@ def __init__(
126150
self._gate = gate
127151
self.hidden_size = moe_config.hidden_dim
128152

153+
# Resolved once so the hot path never reads the config. See
154+
# ``_plain_tail_add_enabled`` for why the graph modes keep foreach.
155+
self._plain_tail_add = _plain_tail_add_enabled()
156+
129157
self.quant_type = routed_experts.quant_type
130158
self.routed_experts.router = router
131159

@@ -180,16 +208,15 @@ def forward(
180208
through the OOT PluggableLayer dispatch of ``MoERunner``).
181209
182210
Upstream inlines the shared+routed output combine, which is not
183-
exposed as an overridable hook. On NPU the combine goes through the
184-
fused multi-tensor add kernel (``torch._foreach_add``), whose kernel
185-
launch count is independent of the tensor-list length and which is
186-
the NPU-validated fast path for the MoE combine. Every other step,
187-
including the runtime-aware reduction hooks (#16550), is inherited
188-
unchanged.
211+
exposed as an overridable hook, so the combine is routed through
212+
``_combine_shared_and_routed_output``. It uses a plain tensor add
213+
unless the superkernel / static-kernel graph requires the multi-tensor
214+
form; see that method for the details. Every other step, including the
215+
runtime-aware reduction hooks (#16550), is inherited unchanged.
189216
190217
Future plan: once the aclnnAdd_AddAiCore_Add kernel is available via
191-
the superkernel integration, upstream's plain add becomes the fast
192-
path and this override can be dropped.
218+
the superkernel integration, the graph modes can use the plain add too
219+
and this override can be dropped entirely.
193220
"""
194221
# Apply transform for routed experts (e.g., latent projection for
195222
# latent MoE). When the caller pre-applies the routed input transform
@@ -279,14 +306,30 @@ def forward(
279306
fused_output = self.apply_routed_output_transform(fused_output)
280307

281308
if shared_output is not None:
282-
result = torch._foreach_add([shared_output], [fused_output])[0]
309+
result = self._combine_shared_and_routed_output(shared_output, fused_output)
283310
else:
284311
result = fused_output
285312

286313
result = self._maybe_reduce_final_output(result, og_hidden_dim_post_xform, fused_output_is_reduced)
287314

288315
return self._maybe_add_zero_expert_output(result)
289316

317+
def _combine_shared_and_routed_output(
318+
self,
319+
shared_output: torch.Tensor,
320+
fused_output: torch.Tensor,
321+
) -> torch.Tensor:
322+
"""Sum the shared and routed MoE outputs.
323+
324+
Both branches are the same bf16 elementwise add and produce identical
325+
results; they only differ in the kernel that performs it. The plain
326+
add is used unless a graph mode requires the multi-tensor form, which
327+
is decided once in ``__init__``.
328+
"""
329+
if self._plain_tail_add:
330+
return shared_output + fused_output
331+
return torch._foreach_add([shared_output], [fused_output])[0]
332+
290333
@property
291334
def is_internal_router(self) -> bool:
292335
# main (cdc4824a21): vllm#51838 removed the gate branch in

0 commit comments

Comments
 (0)