Merged
[feat] integrate A5 SwigluGroup expert fusion #468
[feat] integrate A5 SwigluGroup expert fusion #468
Merged
张伟Add on Jul 27
Total: 16 files changed+1022-71
@@ -29,6 +29,7 @@ model_converters = ModelConvertersContainer.Config(
29 - [MHCPre](#mhcpre)29 - [MHCPre](#mhcpre)
30 - [MHCPost](#mhcpost)30 - [MHCPost](#mhcpost)
31 - [GMM(Grouped MatMul)](#gmmgrouped-matmul)31 - [GMM(Grouped MatMul)](#gmmgrouped-matmul)
32+ - [SwigluGroup](#swiglugroup)
32 - [NPU MoE Dispatch](#npu-moe-dispatch)33 - [NPU MoE Dispatch](#npu-moe-dispatch)
33 - [RMSNorm](#rmsnorm)34 - [RMSNorm](#rmsnorm)
34 - [RoPE](#rope)35 - [RoPE](#rope)
@@ -142,10 +143,40 @@ get_model_converter_config("npu_gmm")
142 143 
143-----------144-----------
144 145 
146+## SwigluGroup
147+ 
148+在 MoE 专家 FFN 中,`w1` 和 `w3` 投影结果会组成 gate/up 激活输入。
149+常规实现需要依次完成限幅(模型配置 `swiglu_limit` 时)和 SwiGLU 激活;
150+调用方传入 routed-score 时,还需对激活结果进行缩放,之后再送入 `w2` 投影。
151+`SwigluGroup` 将这些连续的逐元素计算(包括可选的 routed-score 缩放)
152+合并为一次算子调用,减少中间张量和算子下发开销。
153+ 
154+`npu_swiglu_group` ModelConverter 将共享专家和路由专家的上述激活阶段
155+替换为 `cann_ops_nn.swiglu_group`。共享专家仍使用普通线性层,可独立启用;
156+路由专家会自动启用 `npu_gmm` 的分组矩阵乘路径,并将两次 GMM 之间的激活
157+替换为 `SwigluGroup`。已有的 `npu_gmm` 配置可以保留,两者的先后顺序不影响
158+最终转换结果。
159+ 
160+启用方式:
161+ 
162+```python
163+get_model_converter_config("npu_swiglu_group"),
164+```
165+ 
166+对于包含路由专家的模型,不需要再单独配置 `npu_gmm`。
167+ 
168+**ModelConverter 源码路径:** `torchtitan_npu/converters/kernels/swiglu_group.py`
169+ 
170+**通用共享专家适配:** `torchtitan_npu/models/common/moe.py`
171+ 
172+**相关 NPU 融合算子开发者文档:** [`SwigluGroup`](https://gitcode.com/cann/ops-nn/blob/master/torch_extension/cann_ops_nn/ops/activation/swiglu_group/swiglu_group.md)、[`SwigluGroupBackward`](https://gitcode.com/cann/ops-nn/blob/master/torch_extension/cann_ops_nn/ops/activation/swiglu_group_backward/swiglu_group_backward.md)
173+ 
174+-----------
175+ 
145 176 
146## NPU MoE Dispatch177## NPU MoE Dispatch
147 178 
148-`npu_moe_dispatch` 面向 DS 系列和 Qwen3 MoE 的标准 `ExpertParallel` 路径。该 ModelConverter 负责接入 NPU MoE dispatch 流程:router 后仍使用 `npu_moe_token_permute` 做第一组 token/expert 聚合,expert 计算后仍使用 unpermute 还原;同时通过并行策略更新器将标准 `ExpertParallel` 替换为 `NpuExpertParallel`。179+`npu_moe_dispatch` 面向 DS 系列和 Qwen3 MoE 的标准 `ExpertParallel` 路径。该 ModelConverter 负责接入 NPU MoE dispatch 流程:router 后仍使用 `npu_moe_token_permute` 做第一组 token/expert 聚合,expert 计算后仍使用 unpermute 还原;同时通过并行策略更新器将标准 `ExpertParallel` 替换为 `NpuExpertParallel`。共享专家的通用 FeedForward 适配也由该层完成,默认使用原生小算子 activation,具体融合算子由后续 converter 注入。
149 180 
150在 EP all-to-all 之后,标准 dispatch 流程需要把 rank-major token layout 重新整理为 local expert-major layout。这里的 `torch_npu.npu_moe_re_routing` 只优化这一段 local reroute:它替换旧路径中的 `repeat_interleave + npu_moe_token_permute`,减少局部重排热点上的冗余算子。181在 EP all-to-all 之后,标准 dispatch 流程需要把 rank-major token layout 重新整理为 local expert-major layout。这里的 `torch_npu.npu_moe_re_routing` 只优化这一段 local reroute:它替换旧路径中的 `repeat_interleave + npu_moe_token_permute`,减少局部重排热点上的冗余算子。
151 182 
@@ -3,6 +3,7 @@
3# This source code is licensed under the BSD-style license found in the3# This source code is licensed under the BSD-style license found in the
4# LICENSE file in the root directory of this source tree.4# LICENSE file in the root directory of this source tree.
5 5 
6+from types import SimpleNamespace
6from unittest.mock import MagicMock7from unittest.mock import MagicMock
7 8 
8import pytest9import pytest
@@ -42,3 +43,23 @@ def simple_model():
42 self.linear = nn.Linear(64, 64)43 self.linear = nn.Linear(64, 64)
43 44 
44 return SimpleMethod()45 return SimpleMethod()
46+ 
47+ 
48+@pytest.fixture
49+def prepare_shared_expert_for_conversion():
50+ def _prepare(model, shared):
51+ linears = (shared.w1, shared.w2, shared.w3)
52+ shared.swiglu_limit = 2.0
53+ marker = torch.tensor(1.0)
54+ shared.register_buffer("conversion_marker", marker)
55+ shared.eval()
56+ hook_calls = []
57+ shared.register_forward_hook(lambda *args: hook_calls.append(True))
58+ return SimpleNamespace(
59+ linears=linears,
60+ marker=marker,
61+ hook_calls=hook_calls,
62+ state_dict_keys=tuple(model.state_dict()),
63+ )
64+ 
65+ return _prepare
@@ -23,7 +23,9 @@ from torchtitan_npu.converters.framework.parallelize_plan_update_wrapper import
23)23)
24from torchtitan_npu.converters.framework.state_dict_update_wrapper import (24from torchtitan_npu.converters.framework.state_dict_update_wrapper import (
25 apply_state_dict_update,25 apply_state_dict_update,
26+ get_state_dict_adapter_wrapper,
26)27)
28+from torchtitan_npu.converters.model_custom_interface import ModelCustomConverter
27 29 
28 30 
29@contextmanager31@contextmanager
@@ -80,6 +82,19 @@ class TestApplyParallelizePlanUpdater:
80 82 
81 83 
82class TestApplyStateDictUpdateIntegration:84class TestApplyStateDictUpdateIntegration:
85+ @classmethod
86+ def test_wrapper_owns_updater_registration(cls):
87+ class MockOriginalAdapter:
88+ pass
89+ 
90+ class CustomStateDictUpdater(StateDictUpdater):
91+ pass
92+ 
93+ adapter_wrapper = get_state_dict_adapter_wrapper(MockOriginalAdapter)
94+ 
95+ assert adapter_wrapper.add_state_dict_updater(CustomStateDictUpdater) is True
96+ assert adapter_wrapper.add_state_dict_updater(CustomStateDictUpdater) is False
97+ 
83 @classmethod98 @classmethod
84 def test_apply_state_dict_updater(cls):99 def test_apply_state_dict_updater(cls):
85 call_order = []100 call_order = []
@@ -145,6 +160,93 @@ class TestApplyStateDictUpdateIntegration:
145 assert result_from_hf.get("updater_from_hf_applied") is True160 assert result_from_hf.get("updater_from_hf_applied") is True
146 assert result_from_hf.get("original_from_hf_applied") is True161 assert result_from_hf.get("original_from_hf_applied") is True
147 162 
163+ @classmethod
164+ def test_duplicate_updater_type_is_applied_once(cls):
165+ call_order = []
166+ 
167+ class CustomStateDictUpdater(StateDictUpdater):
168+ @classmethod
169+ def to_hf(cls, state_dict):
170+ call_order.append("updater_to_hf")
171+ return state_dict
172+ 
173+ @classmethod
174+ def from_hf(cls, state_dict):
175+ call_order.append("updater_from_hf")
176+ return state_dict
177+ 
178+ class MockOriginalAdapter:
179+ @classmethod
180+ def to_hf(cls, state_dict):
181+ call_order.append("original_to_hf")
182+ return state_dict
183+ 
184+ @classmethod
185+ def from_hf(cls, state_dict):
186+ call_order.append("original_from_hf")
187+ return state_dict
188+ 
189+ train_spec = Mock()
190+ train_spec.state_dict_adapter = MockOriginalAdapter
191+ 
192+ apply_state_dict_update(CustomStateDictUpdater, train_spec)
193+ apply_state_dict_update(CustomStateDictUpdater, train_spec)
194+ 
195+ adapter = train_spec.state_dict_adapter()
196+ adapter.to_hf({})
197+ assert call_order == ["updater_to_hf", "original_to_hf"]
198+ 
199+ call_order.clear()
200+ adapter.from_hf({})
201+ assert call_order == ["original_from_hf", "updater_from_hf"]
202+ 
203+ 
204+class TestModelCustomConfigConverter:
205+ @classmethod
206+ def test_state_dict_updater_predicate_uses_converted_model(cls):
207+ class CapabilityConverter(ModelCustomConverter):
208+ def convert(self, model):
209+ model.has_state_dict_update_capability = model.enable_capability
210+ 
211+ class ConditionalStateDictUpdater(StateDictUpdater):
212+ @classmethod
213+ def to_hf(cls, state_dict):
214+ return state_dict
215+ 
216+ @classmethod
217+ def from_hf(cls, state_dict):
218+ return state_dict
219+ 
220+ class ConditionalConfig(ModelCustomConfig):
221+ name = "conditional_state_dict_update"
222+ model_converter = CapabilityConverter
223+ state_dict_updater = ConditionalStateDictUpdater
224+ state_dict_updater_predicate = staticmethod(
225+ lambda model: model.has_state_dict_update_capability
226+ )
227+ 
228+ class ConditionalConfigConverter(ModelCustomConfigConverter):
229+ _model_config = ConditionalConfig
230+ 
231+ converter = ConditionalConfigConverter.__new__(ConditionalConfigConverter)
232+ converter.model_spec = Mock()
233+ 
234+ with patch(
235+ "torchtitan_npu.converters.framework.model_custom_config_converter.apply_state_dict_update"
236+ ) as mock_apply_state_dict_update:
237+ disabled_model = nn.Module()
238+ disabled_model.enable_capability = False
239+ converter.convert(disabled_model)
240+ mock_apply_state_dict_update.assert_not_called()
241+ 
242+ enabled_model = nn.Module()
243+ enabled_model.enable_capability = True
244+ converter.convert(enabled_model)
245+ mock_apply_state_dict_update.assert_called_once_with(
246+ ConditionalStateDictUpdater,
247+ converter.model_spec,
248+ )
249+ 
148 250 
149class TestRegisterModelConverter:251class TestRegisterModelConverter:
150 @classmethod252 @classmethod
@@ -8,9 +8,15 @@ from types import SimpleNamespace
8from typing import Any, cast8from typing import Any, cast
9 9 
10import torch10import torch
11+import torch.nn as nn
12+import torch.nn.functional as F
13+from torchtitan.models.common.feed_forward import FeedForward
14+from torchtitan.models.common.linear import Linear
15+from torchtitan.models.common.moe import MoE
11 16 
12from torchtitan_npu.converters.kernels import moe_dispatch, permutation17from torchtitan_npu.converters.kernels import moe_dispatch, permutation
13from torchtitan_npu.converters.kernels.permutation import NPUMoeReRouting18from torchtitan_npu.converters.kernels.permutation import NPUMoeReRouting
19+from torchtitan_npu.models.common import moe as common_moe
14 20 
15 21 
16def _expert_parallel_module():22def _expert_parallel_module():
@@ -34,6 +40,28 @@ def _call_token_dispatch(parallel_style, inputs, device_mesh):
34 return token_dispatch(torch.nn.Module(), inputs, device_mesh)40 return token_dispatch(torch.nn.Module(), inputs, device_mesh)
35 41 
36 42 
43+def _feed_forward(dim: int = 2, hidden_dim: int = 2) -> FeedForward:
44+ return FeedForward.Config(
45+ w1=Linear.Config(in_features=dim, out_features=hidden_dim, bias=False),
46+ w2=Linear.Config(in_features=hidden_dim, out_features=dim, bias=False),
47+ w3=Linear.Config(in_features=dim, out_features=hidden_dim, bias=False),
48+ ).build()
49+ 
50+ 
51+def _moe_with_shared_experts() -> MoE:
52+ module = MoE.__new__(MoE)
53+ nn.Module.__init__(module)
54+ module.shared_experts = _feed_forward()
55+ return module
56+ 
57+ 
58+class _MoeContainer(nn.Module):
59+ def __init__(self):
60+ super().__init__()
61+ self.feed_forward = _feed_forward()
62+ self.moe = _moe_with_shared_experts()
63+ 
64+ 
37def _call_token_combine(parallel_style, routed_output, device_mesh):65def _call_token_combine(parallel_style, routed_output, device_mesh):
38 token_combine = attrgetter("_token_combine")(parallel_style)66 token_combine = attrgetter("_token_combine")(parallel_style)
39 return token_combine(torch.nn.Module(), routed_output, device_mesh)67 return token_combine(torch.nn.Module(), routed_output, device_mesh)
@@ -53,6 +81,37 @@ def test_moe_dispatch_config_wires_converter_and_plan_updater():
53 assert isinstance(standard, moe_dispatch.NpuExpertParallel)81 assert isinstance(standard, moe_dispatch.NpuExpertParallel)
54 82 
55 83 
84+def test_moe_dispatch_installs_native_shared_expert_adapter(
85+ prepare_shared_expert_for_conversion,
86+):
87+ model = _MoeContainer()
88+ dense = model.feed_forward
89+ shared = model.moe.shared_experts
90+ state = prepare_shared_expert_for_conversion(model, shared)
91+ 
92+ for linear in state.linears:
93+ with torch.no_grad():
94+ linear.weight.copy_(torch.eye(2))
95+ 
96+ moe_dispatch.NpuMoeDispatchConverter(SimpleNamespace(name="deepseek_v4")).convert(model)
97+ converted_shared = model.moe.shared_experts
98+ x = torch.tensor([[-3.0, 4.0]])
99+ output = converted_shared(x)
100+ expected = F.silu(torch.clamp(x, max=2.0)) * torch.clamp(x, min=-2.0, max=2.0)
101+ 
102+ assert isinstance(model.moe, moe_dispatch.NpuMoE)
103+ assert model.feed_forward is dense
104+ assert converted_shared is shared
105+ assert isinstance(converted_shared, common_moe.NpuSharedExperts)
106+ assert getattr(converted_shared, "_expert_activation_fn") is common_moe.native_shared_expert_activation
107+ assert (converted_shared.w1, converted_shared.w2, converted_shared.w3) == state.linears
108+ assert converted_shared.conversion_marker is state.marker
109+ assert not converted_shared.training
110+ assert state.hook_calls == [True]
111+ assert tuple(model.state_dict()) == state.state_dict_keys
112+ assert torch.allclose(output, expected)
113+ 
114+ 
56def test_tilelang_moe_reduce_config_is_independent_opt_in():115def test_tilelang_moe_reduce_config_is_independent_opt_in():
57 assert moe_dispatch.TileLangMoeReduceModelConfig.model_converter is moe_dispatch.TileLangMoeReduceConverter116 assert moe_dispatch.TileLangMoeReduceModelConfig.model_converter is moe_dispatch.TileLangMoeReduceConverter
58 assert issubclass(117 assert issubclass(
@@ -5,7 +5,10 @@
5 5 
6from contextlib import contextmanager6from contextlib import contextmanager
7 7 
8+import torch.nn as nn
9+ 
8from torchtitan_npu.converters import registry10from torchtitan_npu.converters import registry
11+from torchtitan_npu.converters.kernels import gmm as gmm_module
9 12 
10 13 
11@contextmanager14@contextmanager
@@ -69,6 +72,8 @@ def test_core_converter_registrations_exist():
69 72 
70 for module_name in (73 for module_name in (
71 "torchtitan_npu.converters.kernels.dsa",74 "torchtitan_npu.converters.kernels.dsa",
75+ "torchtitan_npu.converters.kernels.gmm",
76+ "torchtitan_npu.converters.kernels.swiglu_group",
72 "torchtitan_npu.converters.kernels.rms_norm",77 "torchtitan_npu.converters.kernels.rms_norm",
73 "torchtitan_npu.converters.kernels.rope",78 "torchtitan_npu.converters.kernels.rope",
74 "torchtitan_npu.converters.kernels.inplace_partial_rope",79 "torchtitan_npu.converters.kernels.inplace_partial_rope",
@@ -80,6 +85,8 @@ def test_core_converter_registrations_exist():
80 85 
81 expected_model_converter_names = [86 expected_model_converter_names = [
82 "npu_dsa",87 "npu_dsa",
88+ "npu_gmm",
89+ "npu_swiglu_group",
83 "npu_rms_norm",90 "npu_rms_norm",
84 "npu_rope",91 "npu_rope",
85 "npu_rope_inplace_partial",92 "npu_rope_inplace_partial",
@@ -91,3 +98,19 @@ def test_core_converter_registrations_exist():
91 config = registry().get(name)98 config = registry().get(name)
92 assert config is not None, f"{name} should be registered"99 assert config is not None, f"{name} should be registered"
93 assert config.name == name100 assert config.name == name
101+ 
102+ swiglu_config = registry().get("npu_swiglu_group")
103+ assert swiglu_config is not None
104+ assert swiglu_config.state_dict_updater is gmm_module.GMMStateDictUpdater
105+ state_dict_updater_predicate = swiglu_config.state_dict_updater_predicate
106+ assert callable(state_dict_updater_predicate)
107+ assert state_dict_updater_predicate(nn.Module()) is False
108+ 
109+ model_with_npu_grouped_experts = nn.Module()
110+ npu_grouped_experts = gmm_module.NpuGroupedExperts.__new__(
111+ gmm_module.NpuGroupedExperts
112+ )
113+ nn.Module.__init__(npu_grouped_experts)
114+ model_with_npu_grouped_experts.add_module("experts", npu_grouped_experts)
115+ assert state_dict_updater_predicate(model_with_npu_grouped_experts) is True
116+ assert registry().get("npu_gmm_swiglu") is None
@@ -0,0 +1,411 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2+#
3+# This source code is licensed under the BSD-style license found in the
4+# LICENSE file in the root directory of this source tree.
5+ 
6+from types import SimpleNamespace
7+ 
8+import pytest
9+import torch
10+import torch.nn as nn
11+from torchtitan.models.common.feed_forward import FeedForward
12+from torchtitan.models.common.linear import Linear
13+from torchtitan.models.common.moe import GroupedExperts, MoE
14+ 
15+from torchtitan_npu.converters.kernels import gmm as gmm_module
16+from torchtitan_npu.converters.kernels import moe_dispatch as moe_module
17+from torchtitan_npu.converters.kernels import swiglu_group as swiglu_module
18+from torchtitan_npu.converters.framework.model_custom_config_converter import (
19+ ModelCustomConfigConverter,
20+)
21+from torchtitan_npu.models.common import moe as common_moe
22+ 
23+_EXPERT_ACTIVATION_ATTR = "_expert_activation"
24+_EXPERT_ACTIVATION_FN_ATTR = "_expert_activation_fn"
25+ 
26+ 
27+def _install_fake_ops(monkeypatch, forward, backward=None):
28+ namespace = SimpleNamespace(
29+ swiglu_group=SimpleNamespace(default=forward),
30+ swiglu_group_backward=SimpleNamespace(default=backward),
31+ )
32+ monkeypatch.setattr(torch.ops, "cann_ops_nn", namespace)
33+ 
34+ 
35+def _slice_swiglu_output(x, *, weight, group_index, clamp_limit):
36+ return x[..., : x.shape[-1] // 2].clone()
37+ 
38+ 
39+def _allow_cann_ops_import(monkeypatch):
40+ monkeypatch.setattr(swiglu_module.importlib, "import_module", lambda _name: None)
41+ 
42+ 
43+def _grouped_experts() -> GroupedExperts:
44+ return GroupedExperts.Config(
45+ dim=2,
46+ hidden_dim=2,
47+ num_experts=1,
48+ use_grouped_mm=False,
49+ ).build()
50+ 
51+ 
52+def _feed_forward(dim: int = 2, hidden_dim: int = 2) -> FeedForward:
53+ return FeedForward.Config(
54+ w1=Linear.Config(in_features=dim, out_features=hidden_dim, bias=False),
55+ w2=Linear.Config(in_features=hidden_dim, out_features=dim, bias=False),
56+ w3=Linear.Config(in_features=dim, out_features=hidden_dim, bias=False),
57+ ).build()
58+ 
59+ 
60+def _swiglu_group_converter():
61+ return swiglu_module.NpuSwigluGroupConverter(SimpleNamespace(name="deepseek_v4"))
62+ 
63+ 
64+def _moe_dispatch_converter():
65+ return moe_module.NpuMoeDispatchConverter(SimpleNamespace(name="deepseek_v4"))
66+ 
67+ 
68+class _IdentityStateDictAdapter:
69+ @classmethod
70+ def to_hf(cls, state_dict):
71+ return state_dict
72+ 
73+ @classmethod
74+ def from_hf(cls, state_dict):
75+ return state_dict
76+ 
77+ 
78+def _apply_model_config(model, model_spec, model_config):
79+ class TestModelConfigConverter(ModelCustomConfigConverter):
80+ _model_config = model_config
81+ 
82+ converter = TestModelConfigConverter.__new__(TestModelConfigConverter)
83+ converter.model_spec = model_spec
84+ converter.convert(model)
85+ 
86+ 
87+def _moe_with_shared_experts() -> MoE:
88+ module = MoE.__new__(MoE)
89+ nn.Module.__init__(module)
90+ module.shared_experts = _feed_forward()
91+ return module
92+ 
93+ 
94+class _SharedExpertContainer(nn.Module):
95+ def __init__(self):
96+ super().__init__()
97+ self.feed_forward = _feed_forward()
98+ self.moe = _moe_with_shared_experts()
99+ 
100+ 
101+class _FeedForwardContainer(_SharedExpertContainer):
102+ def __init__(self):
103+ super().__init__()
104+ self.experts = _grouped_experts()
105+ 
106+ 
107+def test_activation_calls_documented_op_with_gmm_inputs(monkeypatch):
108+ calls = []
109+ 
110+ def forward(x, *, weight, group_index, clamp_limit):
111+ calls.append((x, weight, group_index, clamp_limit))
112+ return x[..., : x.shape[-1] // 2]
113+ 
114+ _install_fake_ops(monkeypatch, forward)
115+ h = torch.randn(4, 16)
116+ routed_scores = torch.randn(4, 2, dtype=torch.float64)[:, :1]
117+ 
118+ output = swiglu_module.swiglu_group_activation(h, 3.0, routed_scores)
119+ 
120+ assert output.shape == (4, 8)
121+ op_x, op_weight, group_index, clamp_limit = calls[0]
122+ assert op_x is h
123+ assert op_weight.dtype == torch.float32
124+ assert op_weight.is_contiguous()
125+ assert group_index is None
126+ assert clamp_limit == 3.0
127+ 
128+ 
129+def test_activation_uses_documented_optional_defaults(monkeypatch):
130+ calls = []
131+ 
132+ def forward(x, *, weight, group_index, clamp_limit):
133+ calls.append((weight, group_index, clamp_limit))
134+ return x[..., : x.shape[-1] // 2]
135+ 
136+ _install_fake_ops(monkeypatch, forward)
137+ 
138+ swiglu_module.swiglu_group_activation(torch.randn(4, 16))
139+ 
140+ assert calls == [(None, None, -1.0)]
141+ 
142+ 
143+def test_activation_delegates_autograd_to_documented_op(monkeypatch):
144+ def forward(x, *, weight, group_index, clamp_limit):
145+ assert group_index is None
146+ assert clamp_limit == -1.0
147+ return x[..., : x.shape[-1] // 2] * weight
148+ 
149+ def fail_backward(*args, **kwargs):
150+ raise AssertionError("local Autograd bridge must not call the backward op")
151+ 
152+ _install_fake_ops(monkeypatch, forward, fail_backward)
153+ x = torch.arange(8, dtype=torch.float32).reshape(2, 4).requires_grad_()
154+ routed_scores = torch.tensor([[2.0], [3.0]], requires_grad=True)
155+ 
156+ swiglu_module.swiglu_group_activation(x, routed_scores=routed_scores).sum().backward()
157+ 
158+ assert torch.equal(
159+ x.grad,
160+ torch.tensor([[2.0, 2.0, 0.0, 0.0], [3.0, 3.0, 0.0, 0.0]]),
161+ )
162+ assert torch.equal(routed_scores.grad, torch.tensor([[1.0], [9.0]]))
163+ 
164+ 
165+def test_converter_imports_cann_ops_without_executing_a_runtime_probe(monkeypatch):
166+ model = _SharedExpertContainer()
167+ imports = []
168+ 
169+ monkeypatch.setattr(swiglu_module.importlib, "import_module", imports.append)
170+ assert not hasattr(swiglu_module, "_probe_swiglu_group_execution")
171+ 
172+ _swiglu_group_converter().convert(model)
173+ 
174+ assert imports == ["cann_ops_nn.ops"]
175+ 
176+ 
177+def test_converter_propagates_cann_ops_import_error(monkeypatch):
178+ model = _FeedForwardContainer()
179+ routed_experts = model.experts
180+ routed_weights = (routed_experts.w1, routed_experts.w2, routed_experts.w3)
181+ shared_experts = model.moe.shared_experts
182+ shared_linears = (shared_experts.w1, shared_experts.w2, shared_experts.w3)
183+ state_dict_keys = tuple(model.state_dict())
184+ 
185+ def raise_import_error(_name):
186+ raise ModuleNotFoundError("No module named 'cann_ops_nn'")
187+ 
188+ monkeypatch.setattr(swiglu_module.importlib, "import_module", raise_import_error)
189+ 
190+ with pytest.raises(ModuleNotFoundError, match="cann_ops_nn"):
191+ _swiglu_group_converter().convert(model)
192+ 
193+ assert model.experts is routed_experts
194+ assert isinstance(model.experts, GroupedExperts)
195+ assert not isinstance(model.experts, gmm_module.NpuGroupedExperts)
196+ assert not hasattr(model.experts, _EXPERT_ACTIVATION_FN_ATTR)
197+ assert model.experts.w1 is routed_weights[0]
198+ assert model.experts.w2 is routed_weights[1]
199+ assert model.experts.w3 is routed_weights[2]
200+ assert model.moe.shared_experts is shared_experts
201+ assert isinstance(model.moe.shared_experts, FeedForward)
202+ assert not isinstance(model.moe.shared_experts, common_moe.NpuSharedExperts)
203+ assert model.moe.shared_experts.w1 is shared_linears[0]
204+ assert model.moe.shared_experts.w2 is shared_linears[1]
205+ assert model.moe.shared_experts.w3 is shared_linears[2]
206+ assert tuple(model.state_dict()) == state_dict_keys
207+ 
208+ 
209+def test_converter_does_not_import_cann_ops_without_compatible_targets(monkeypatch):
210+ model = nn.Sequential(nn.Linear(2, 2))
211+ 
212+ def fail_if_imported(_name):
213+ raise AssertionError("models without compatible targets must not import cann_ops_nn")
214+ 
215+ monkeypatch.setattr(swiglu_module.importlib, "import_module", fail_if_imported)
216+ 
217+ _swiglu_group_converter().convert(model)
218+ 
219+ 
220+@pytest.mark.parametrize(
221+ "converter_order",
222+ [
223+ ("npu_gmm", "npu_swiglu_group"),
224+ ("npu_swiglu_group", "npu_gmm"),
225+ ],
226+ ids=("gmm-then-swiglu-group", "swiglu-group-then-gmm"),
227+)
228+def test_npu_gmm_and_swiglu_group_are_order_independent(monkeypatch, converter_order):
229+ _allow_cann_ops_import(monkeypatch)
230+ model = _FeedForwardContainer()
231+ shared_experts = model.moe.shared_experts
232+ model_spec = SimpleNamespace(
233+ name="deepseek_v4",
234+ state_dict_adapter=_IdentityStateDictAdapter,
235+ )
236+ 
237+ def fused_activation(h, swiglu_limit=None, routed_scores=None):
238+ return h
239+ 
240+ monkeypatch.setattr(swiglu_module, "swiglu_group_activation", fused_activation)
241+ # Resolve after test_registry reloads converter modules during the same test session.
242+ converter_configs = {
243+ "npu_gmm": gmm_module.GMMModelConfig,
244+ "npu_swiglu_group": swiglu_module.SwigluGroupModelConfig,
245+ }
246+ first_config = converter_configs.get(converter_order[0])
247+ second_config = converter_configs.get(converter_order[1])
248+ assert first_config is not None
249+ assert second_config is not None
250+ 
251+ _apply_model_config(model, model_spec, first_config)
252+ converted_experts = model.experts
253+ _apply_model_config(model, model_spec, second_config)
254+ 
255+ assert model.experts is converted_experts
256+ assert isinstance(model.experts, gmm_module.NpuGroupedExperts)
257+ assert getattr(model.experts, _EXPERT_ACTIVATION_FN_ATTR) is fused_activation
258+ assert model.moe.shared_experts is shared_experts
259+ assert isinstance(shared_experts, common_moe.NpuSharedExperts)
260+ assert getattr(shared_experts, _EXPERT_ACTIVATION_FN_ATTR) is fused_activation
261+ assert (
262+ model_spec.state_dict_adapter.add_state_dict_updater(
263+ gmm_module.GMMStateDictUpdater
264+ )
265+ is False
266+ )
267+ 
268+ 
269+def test_npu_swiglu_group_converts_shared_expert_without_npu_gmm(
270+ monkeypatch,
271+ prepare_shared_expert_for_conversion,
272+):
273+ _allow_cann_ops_import(monkeypatch)
274+ model = _SharedExpertContainer()
275+ dense = model.feed_forward
276+ shared = model.moe.shared_experts
277+ state = prepare_shared_expert_for_conversion(model, shared)
278+ model_spec = SimpleNamespace(
279+ name="deepseek_v4",
280+ state_dict_adapter=_IdentityStateDictAdapter,
281+ )
282+ operator_calls = []
283+ 
284+ def fused_activation(x, swiglu_limit=None, routed_scores=None):
285+ operator_calls.append((x, swiglu_limit, routed_scores))
286+ return x[..., : x.shape[-1] // 2]
287+ 
288+ monkeypatch.setattr(swiglu_module, "swiglu_group_activation", fused_activation)
289+ 
290+ _apply_model_config(model, model_spec, swiglu_module.SwigluGroupModelConfig)
291+ converted_shared = model.moe.shared_experts
292+ x = torch.ones(1, 2)
293+ expected_packed = torch.cat((state.linears[0](x), state.linears[2](x)), dim=-1)
294+ converted_shared(x)
295+ 
296+ assert model.feed_forward is dense
297+ assert converted_shared is shared
298+ assert isinstance(converted_shared, common_moe.NpuSharedExperts)
299+ assert getattr(converted_shared, _EXPERT_ACTIVATION_FN_ATTR) is swiglu_module.swiglu_group_activation
300+ assert (converted_shared.w1, converted_shared.w2, converted_shared.w3) == state.linears
301+ assert converted_shared.conversion_marker is state.marker
302+ assert not converted_shared.training
303+ assert state.hook_calls == [True]
304+ assert tuple(model.state_dict()) == state.state_dict_keys
305+ assert torch.equal(operator_calls[0][0], expected_packed)
306+ assert operator_calls[0][0].is_contiguous()
307+ assert operator_calls[0][1:] == (2.0, None)
308+ assert model_spec.state_dict_adapter is _IdentityStateDictAdapter
309+ 
310+ 
311+def test_swiglu_group_does_not_own_routed_expert_execution():
312+ assert not hasattr(swiglu_module, "SwigluGroupExperts")
313+ assert not hasattr(swiglu_module, "_run_experts_for_loop")
314+ assert not hasattr(swiglu_module, "_run_experts_grouped_mm")
315+ 
316+ 
317+def test_swiglu_group_converts_raw_routed_and_shared_experts(monkeypatch):
318+ _allow_cann_ops_import(monkeypatch)
319+ model = _FeedForwardContainer()
320+ shared_experts = model.moe.shared_experts
321+ 
322+ _swiglu_group_converter().convert(model)
323+ 
324+ assert isinstance(model.experts, gmm_module.NpuGroupedExperts)
325+ assert getattr(model.experts, _EXPERT_ACTIVATION_FN_ATTR) is swiglu_module.swiglu_group_activation
326+ assert model.moe.shared_experts is shared_experts
327+ assert isinstance(shared_experts, common_moe.NpuSharedExperts)
328+ assert getattr(shared_experts, _EXPERT_ACTIVATION_FN_ATTR) is swiglu_module.swiglu_group_activation
329+ 
330+ 
331+def test_swiglu_group_converts_raw_routed_experts_without_shared_experts(monkeypatch):
332+ _allow_cann_ops_import(monkeypatch)
333+ model = nn.Module()
334+ model.experts = _grouped_experts()
335+ 
336+ _swiglu_group_converter().convert(model)
337+ 
338+ assert isinstance(model.experts, gmm_module.NpuGroupedExperts)
339+ assert model.experts.w13 is not None
340+ assert model.experts.w1 is None
341+ assert model.experts.w3 is None
342+ assert getattr(model.experts, _EXPERT_ACTIVATION_FN_ATTR) is swiglu_module.swiglu_group_activation
343+ 
344+ 
345+def test_swiglu_group_converts_mixed_raw_and_npu_routed_experts(monkeypatch):
346+ _allow_cann_ops_import(monkeypatch)
347+ converted_model = nn.Module()
348+ converted_model.experts = _grouped_experts()
349+ gmm_module.NpuGroupedExpertConverter(SimpleNamespace(name="deepseek_v4")).convert(
350+ converted_model
351+ )
352+ model = _SharedExpertContainer()
353+ model.raw_experts = _grouped_experts()
354+ model.npu_experts = converted_model.experts
355+ raw_experts = model.raw_experts
356+ npu_experts = model.npu_experts
357+ 
358+ _swiglu_group_converter().convert(model)
359+ 
360+ assert model.raw_experts is not raw_experts
361+ assert isinstance(model.raw_experts, gmm_module.NpuGroupedExperts)
362+ assert model.npu_experts is npu_experts
363+ assert getattr(model.raw_experts, _EXPERT_ACTIVATION_FN_ATTR) is swiglu_module.swiglu_group_activation
364+ assert getattr(model.npu_experts, _EXPERT_ACTIVATION_FN_ATTR) is swiglu_module.swiglu_group_activation
365+ 
366+ 
367+def test_swiglu_group_then_moe_dispatch_preserves_shared_activation(monkeypatch):
368+ _allow_cann_ops_import(monkeypatch)
369+ model = _SharedExpertContainer()
370+ 
371+ _swiglu_group_converter().convert(model)
372+ shared = model.moe.shared_experts
373+ _moe_dispatch_converter().convert(model)
374+ 
375+ assert model.moe.shared_experts is shared
376+ assert isinstance(shared, common_moe.NpuSharedExperts)
377+ assert getattr(shared, _EXPERT_ACTIVATION_FN_ATTR) is swiglu_module.swiglu_group_activation
378+ 
379+ 
380+def test_converted_shared_expert_uses_registered_operator_autograd(monkeypatch):
381+ _allow_cann_ops_import(monkeypatch)
382+ model = _SharedExpertContainer()
383+ shared = model.moe.shared_experts
384+ for linear in (shared.w1, shared.w2, shared.w3):
385+ with torch.no_grad():
386+ linear.weight.copy_(torch.eye(2))
387+ 
388+ _install_fake_ops(monkeypatch, _slice_swiglu_output)
389+ _swiglu_group_converter().convert(model)
390+ 
391+ x = torch.ones(1, 2, requires_grad=True)
392+ model.moe.shared_experts(x).sum().backward()
393+ 
394+ assert x.grad is not None
395+ assert shared.w1.weight.grad is not None
396+ assert shared.w2.weight.grad is not None
397+ assert shared.w3.weight.grad is not None
398+ 
399+ 
400+def test_npu_moe_dispatch_and_gmm_keep_native_activations():
401+ model = _FeedForwardContainer()
402+ shared = model.moe.shared_experts
403+ 
404+ _moe_dispatch_converter().convert(model)
405+ gmm_module.NpuGroupedExpertConverter(SimpleNamespace(name="deepseek_v4")).convert(model)
406+ 
407+ native_activation = getattr(gmm_module, _EXPERT_ACTIVATION_ATTR)
408+ assert getattr(model.experts, _EXPERT_ACTIVATION_FN_ATTR) is native_activation
409+ assert model.moe.shared_experts is shared
410+ assert isinstance(shared, common_moe.NpuSharedExperts)
411+ assert getattr(shared, _EXPERT_ACTIVATION_FN_ATTR) is common_moe.native_shared_expert_activation
@@ -14,6 +14,7 @@ import torch.nn as nn
14import torch_npu14import torch_npu
15 15 
16from torchtitan_npu.converters.kernels import gmm as gmm_module16from torchtitan_npu.converters.kernels import gmm as gmm_module
17+from torchtitan_npu.converters.kernels import swiglu_group as swiglu_module
17from torchtitan_npu.models.deepseek_v4 import model as model_module18from torchtitan_npu.models.deepseek_v4 import model as model_module
18from torchtitan_npu.models.deepseek_v4 import parallelize19from torchtitan_npu.models.deepseek_v4 import parallelize
19from torchtitan_npu.patches.torchao_npu import mxfp8_grouped_mm as mxfp8_gmm_module20from torchtitan_npu.patches.torchao_npu import mxfp8_grouped_mm as mxfp8_gmm_module
@@ -21,6 +22,7 @@ from torchtitan_npu.patches.torchao_npu import mxfp8_grouped_mm as mxfp8_gmm_mod
21_EXPERT_ACTIVATION_ATTR = "_expert_activation"22_EXPERT_ACTIVATION_ATTR = "_expert_activation"
22_EXPERT_ACTIVATION_FN_ATTR = "_expert_activation_fn"23_EXPERT_ACTIVATION_FN_ATTR = "_expert_activation_fn"
23_EXPERT_ACTIVATION_COMPILE_KEY_ATTR = "_expert_activation_compile_key"24_EXPERT_ACTIVATION_COMPILE_KEY_ATTR = "_expert_activation_compile_key"
25+_COMPILE_CHILDREN_EXCEPT_ATTR = "_compile_children_except"
24_RUN_GROUPED_MM_ATTR = "_run_experts_grouped_mm"26_RUN_GROUPED_MM_ATTR = "_run_experts_grouped_mm"
25_GROUPED_MM_ATTR = "_grouped_mm"27_GROUPED_MM_ATTR = "_grouped_mm"
26_DYNAMO_ATTR = "_dynamo"28_DYNAMO_ATTR = "_dynamo"
@@ -57,7 +59,7 @@ def test_compile_respects_module_graph_break_requirement(
57 monkeypatch.setattr(torch, "compile", fake_compile)59 monkeypatch.setattr(torch, "compile", fake_compile)
58 60 
59 compile_config = SimpleNamespace(backend="inductor_npu")61 compile_config = SimpleNamespace(backend="inductor_npu")
60- parallelize._compile_children_except(62+ getattr(parallelize, _COMPILE_CHILDREN_EXCEPT_ATTR)(
61 module,63 module,
62 {"inner_attention"},64 {"inner_attention"},
63 compile_config,65 compile_config,
@@ -69,10 +71,10 @@ def test_compile_respects_module_graph_break_requirement(
69 ]71 ]
70 72 
71 73 
72-def _new_npu_grouped_experts() -> gmm_module.NpuGroupedExperts:74+def _new_npu_grouped_experts(activation_fn) -> gmm_module.NpuGroupedExperts:
73 module = gmm_module.NpuGroupedExperts.__new__(gmm_module.NpuGroupedExperts)75 module = gmm_module.NpuGroupedExperts.__new__(gmm_module.NpuGroupedExperts)
74 torch.nn.Module.__init__(module)76 torch.nn.Module.__init__(module)
75- setattr(module, _EXPERT_ACTIVATION_FN_ATTR, getattr(gmm_module, _EXPERT_ACTIVATION_ATTR))77+ setattr(module, _EXPERT_ACTIVATION_FN_ATTR, activation_fn)
76 setattr(module, _EXPERT_ACTIVATION_COMPILE_KEY_ATTR, None)78 setattr(module, _EXPERT_ACTIVATION_COMPILE_KEY_ATTR, None)
77 return module79 return module
78 80 
@@ -226,7 +228,18 @@ def test_retained_output_projection_scopes_sac_to_bmm(monkeypatch):
226 assert retained_calls == [(model_module.BMM_SAC_SAVE_OPS, torch.bmm)]228 assert retained_calls == [(model_module.BMM_SAC_SAVE_OPS, torch.bmm)]
227 229 
228 230 
229-def test_compile_expert_activation_is_shared_and_idempotent(monkeypatch):231+@pytest.mark.parametrize(
232+ "activation_fn",
233+ [
234+ getattr(gmm_module, _EXPERT_ACTIVATION_ATTR),
235+ swiglu_module.swiglu_group_activation,
236+ ],
237+ ids=("native", "swiglu_group"),
238+)
239+def test_compile_expert_activation_selects_mode_and_is_shared_and_idempotent(
240+ monkeypatch,
241+ activation_fn,
242+):
230 compile_calls = []243 compile_calls = []
231 dynamic_calls = []244 dynamic_calls = []
232 compiled_calls = []245 compiled_calls = []
@@ -247,22 +260,24 @@ def test_compile_expert_activation_is_shared_and_idempotent(monkeypatch):
247 monkeypatch.setattr(getattr(torch, _DYNAMO_ATTR), "maybe_mark_dynamic", fake_maybe_mark_dynamic)260 monkeypatch.setattr(getattr(torch, _DYNAMO_ATTR), "maybe_mark_dynamic", fake_maybe_mark_dynamic)
248 261 
249 model = torch.nn.Module()262 model = torch.nn.Module()
250- expert_a = _new_npu_grouped_experts()263+ expert_a = _new_npu_grouped_experts(activation_fn)
251- expert_b = _new_npu_grouped_experts()264+ expert_b = _new_npu_grouped_experts(activation_fn)
252 model.add_module("expert_a", expert_a)265 model.add_module("expert_a", expert_a)
253 model.add_module("expert_b", expert_b)266 model.add_module("expert_b", expert_b)
254- eager_activation = getattr(gmm_module, _EXPERT_ACTIVATION_ATTR)
255 267 
256 gmm_module.compile_expert_activation(model, backend="inductor_npu", dynamic_tokens=True)268 gmm_module.compile_expert_activation(model, backend="inductor_npu", dynamic_tokens=True)
257 gmm_module.compile_expert_activation(model, backend="inductor_npu", dynamic_tokens=True)269 gmm_module.compile_expert_activation(model, backend="inductor_npu", dynamic_tokens=True)
258 270 
259 assert len(compile_calls) == 1271 assert len(compile_calls) == 1
260 fn, backend, fullgraph, options = compile_calls[0]272 fn, backend, fullgraph, options = compile_calls[0]
261- assert fn is eager_activation273+ assert fn is activation_fn
262 assert backend == "inductor_npu"274 assert backend == "inductor_npu"
263 assert fullgraph is True275 assert fullgraph is True
264 assert options["custom_partitioner_fn"].uuid() == "npu_expert_activation_default_partition"276 assert options["custom_partitioner_fn"].uuid() == "npu_expert_activation_default_partition"
265 assert getattr(expert_a, _EXPERT_ACTIVATION_FN_ATTR) is getattr(expert_b, _EXPERT_ACTIVATION_FN_ATTR)277 assert getattr(expert_a, _EXPERT_ACTIVATION_FN_ATTR) is getattr(expert_b, _EXPERT_ACTIVATION_FN_ATTR)
278+ expected_compile_key = ("inductor_npu", True)
279+ assert getattr(expert_a, _EXPERT_ACTIVATION_COMPILE_KEY_ATTR) == expected_compile_key
280+ assert getattr(expert_b, _EXPERT_ACTIVATION_COMPILE_KEY_ATTR) == expected_compile_key
266 281 
267 h = torch.empty((4, 8), device="meta")282 h = torch.empty((4, 8), device="meta")
268 scores = torch.empty((4, 1), device="meta")283 scores = torch.empty((4, 1), device="meta")
@@ -289,12 +304,23 @@ def _fake_mesh(*args, **kwargs):
289 return object()304 return object()
290 305 
291 306 
292-def _parallelize_test_model(ac_mode, compile_enabled, tp_enabled=False):307+def _parallelize_test_model(
308+ ac_mode,
309+ compile_enabled,
310+ *,
311+ tp_enabled=False,
312+ has_npu_grouped_experts=False,
313+):
293 model = torch.nn.Module()314 model = torch.nn.Module()
294 post_attention = parallelize.PostAttention.__new__(parallelize.PostAttention)315 post_attention = parallelize.PostAttention.__new__(parallelize.PostAttention)
295 torch.nn.Module.__init__(post_attention)316 torch.nn.Module.__init__(post_attention)
296 setattr(post_attention, _RETAIN_OUTPUT_PROJECTION_ATTR, False)317 setattr(post_attention, _RETAIN_OUTPUT_PROJECTION_ATTR, False)
297 model.add_module("post_attention", post_attention)318 model.add_module("post_attention", post_attention)
319+ if has_npu_grouped_experts:
320+ model.add_module(
321+ "experts",
322+ _new_npu_grouped_experts(getattr(gmm_module, _EXPERT_ACTIVATION_ATTR)),
323+ )
298 model.model_args = SimpleNamespace(use_global_tnd=False, n_layers=0, compress_ratios=())324 model.model_args = SimpleNamespace(use_global_tnd=False, n_layers=0, compress_ratios=())
299 parallel_dims = SimpleNamespace(325 parallel_dims = SimpleNamespace(
300 seq_len_divisor=1,326 seq_len_divisor=1,
@@ -332,43 +358,26 @@ def _parallelize_test_model(ac_mode, compile_enabled, tp_enabled=False):
332 return model358 return model
333 359 
334 360 
335-@pytest.mark.parametrize(361+def _patch_parallelize_dependencies(monkeypatch, converter_names):
336- "case",362+ calls = SimpleNamespace(
337- [363+ save_ops=[],
338- ("selective", True, True, False, True),364+ scoped_ac=[],
339- ("full", True, True, False, False),365+ native_ac=[],
340- ("selective", False, True, False, False),366+ bridge_compile=[],
341- ("selective", True, False, False, False),367+ model_compile=[],
342- ("selective", True, True, True, False),368+ )
343- ],
344- ids=(
345- "selective-compiled",
346- "full-compiled",
347- "selective-eager",
348- "selective-without-gmm",
349- "selective-compiled-tp",
350- ),
351-)
352-def test_parallelize_selective_ac_wires_scoped_save_ops(
353- monkeypatch,
354- case,
355-):
356- ac_mode, compile_enabled, gmm_enabled, tp_enabled, use_scoped_ac = case
357- save_ops_calls = []
358- scoped_ac_calls = []
359- native_ac_calls = []
360- bridge_compile_calls = []
361- model_compile_calls = []
362 369 
363 def record_save_ops(save_ops):370 def record_save_ops(save_ops):
364- save_ops_calls.append(set(save_ops))371+ calls.save_ops.append(set(save_ops))
365 return nullcontext()372 return nullcontext()
366 373 
367 def has_converter(_converters, name):374 def has_converter(_converters, name):
368- return gmm_enabled if name == "npu_gmm" else name == "npu_moe_dispatch"375+ if name == "npu_gmm":
376+ raise AssertionError("GMM capability must be detected from the converted model")
377+ return name in converter_names
369 378 
370- def record_scoped_ac(model, ac_config, save_ops):379+ def record_scoped_ac(_model, _ac_config, save_ops):
371- scoped_ac_calls.append(set(save_ops))380+ calls.scoped_ac.append(set(save_ops))
372 381 
373 monkeypatch.setattr(parallelize, "apply_distributed_indexer_loss_tracking", _noop)382 monkeypatch.setattr(parallelize, "apply_distributed_indexer_loss_tracking", _noop)
374 monkeypatch.setattr(parallelize, "find_float8_linear_config", lambda _converters: None)383 monkeypatch.setattr(parallelize, "find_float8_linear_config", lambda _converters: None)
@@ -378,25 +387,99 @@ def test_parallelize_selective_ac_wires_scoped_save_ops(
378 monkeypatch.setattr(parallelize, "apply_moe_ep_tp", _noop)387 monkeypatch.setattr(parallelize, "apply_moe_ep_tp", _noop)
379 monkeypatch.setattr(parallelize, "extend_selective_ac_save_ops", record_save_ops)388 monkeypatch.setattr(parallelize, "extend_selective_ac_save_ops", record_save_ops)
380 monkeypatch.setattr(parallelize, "apply_scoped_selective_ac", record_scoped_ac)389 monkeypatch.setattr(parallelize, "apply_scoped_selective_ac", record_scoped_ac)
381- monkeypatch.setattr(parallelize, "apply_ac", _record_call(native_ac_calls))390+ monkeypatch.setattr(parallelize, "apply_ac", _record_call(calls.native_ac))
382- monkeypatch.setattr(gmm_module, "compile_expert_activation", _record_call(bridge_compile_calls))391+ monkeypatch.setattr(gmm_module, "compile_expert_activation", _record_call(calls.bridge_compile))
383- monkeypatch.setattr(parallelize, "apply_compile", _record_call(model_compile_calls))392+ monkeypatch.setattr(parallelize, "apply_compile", _record_call(calls.model_compile))
393+ return calls
384 394 
385- model = _parallelize_test_model(ac_mode, compile_enabled, tp_enabled=tp_enabled)
386 395 
396+@pytest.mark.parametrize(
397+ "case",
398+ [
399+ ("selective", True, ("npu_gmm", "npu_moe_dispatch"), False, True, True),
400+ (
401+ "selective",
402+ True,
403+ ("npu_gmm", "npu_moe_dispatch", "npu_swiglu_group"),
404+ False,
405+ True,
406+ True,
407+ ),
408+ ("full", True, ("npu_gmm", "npu_moe_dispatch"), False, True, False),
409+ ("selective", False, ("npu_gmm", "npu_moe_dispatch"), False, True, False),
410+ ("selective", True, ("npu_moe_dispatch",), False, False, False),
411+ ("selective", True, ("npu_gmm", "npu_moe_dispatch"), True, True, False),
412+ ("selective", True, ("npu_gmm", "npu_swiglu_group"), False, True, False),
413+ ("selective", True, ("npu_swiglu_group",), False, True, False),
414+ (
415+ "selective",
416+ True,
417+ ("npu_swiglu_group", "npu_moe_dispatch"),
418+ False,
419+ True,
420+ True,
421+ ),
422+ ("selective", True, ("npu_gmm", "npu_moe_dispatch"), False, False, False),
423+ ],
424+ ids=(
425+ "selective-compiled",
426+ "selective-compiled-swiglu-group",
427+ "full-compiled",
428+ "selective-eager",
429+ "selective-without-gmm",
430+ "selective-compiled-tp",
431+ "selective-without-moe-dispatch",
432+ "selective-swiglu-group-only",
433+ "selective-auto-gmm-from-swiglu-group",
434+ "selective-gmm-config-without-converted-experts",
435+ ),
436+)
437+def test_parallelize_selective_ac_wires_scoped_save_ops(
438+ monkeypatch,
439+ case,
440+):
441+ (
442+ ac_mode,
443+ compile_enabled,
444+ converter_names,
445+ tp_enabled,
446+ has_npu_grouped_experts,
447+ use_scoped_ac,
448+ ) = case
449+ calls = _patch_parallelize_dependencies(monkeypatch, converter_names)
450+ 
451+ model = _parallelize_test_model(
452+ ac_mode,
453+ compile_enabled,
454+ tp_enabled=tp_enabled,
455+ has_npu_grouped_experts=has_npu_grouped_experts,
456+ )
457+ effective_gmm = any(
458+ isinstance(module, gmm_module.NpuGroupedExperts) for module in model.modules()
459+ )
460+ 
461+ save_grouped_mm = (
462+ ac_mode == "selective"
463+ and compile_enabled
464+ and effective_gmm
465+ and not tp_enabled
466+ )
387 target_ops = (467 target_ops = (
388 parallelize.BMM_SAC_SAVE_OPS468 parallelize.BMM_SAC_SAVE_OPS
389 | parallelize.ALL_TO_ALL_SAC_SAVE_OPS469 | parallelize.ALL_TO_ALL_SAC_SAVE_OPS
390 | parallelize.NPU_GMM_SAC_SAVE_OPS470 | parallelize.NPU_GMM_SAC_SAVE_OPS
391 )471 )
392- expected_scoped_ops = (472+ expected_scoped_ops = set(target_ops) if use_scoped_ac else set()
393- set(target_ops) if use_scoped_ac else set()473+ assert calls.scoped_ac == ([expected_scoped_ops] if use_scoped_ac else [])
394- )
395- assert scoped_ac_calls == ([expected_scoped_ops] if use_scoped_ac else [])
396 assert getattr(model.post_attention, _RETAIN_OUTPUT_PROJECTION_ATTR) is use_scoped_ac474 assert getattr(model.post_attention, _RETAIN_OUTPUT_PROJECTION_ATTR) is use_scoped_ac
397- assert save_ops_calls == ([] if use_scoped_ac else [set()])475+ expected_native_save_ops = (
398- assert len(native_ac_calls) == int(not use_scoped_ac)476+ set(parallelize.NPU_GMM_SAC_SAVE_OPS) if save_grouped_mm else set()
399- assert len(bridge_compile_calls) == int(compile_enabled and gmm_enabled)477+ )
400- assert len(model_compile_calls) == int(compile_enabled)478+ assert calls.save_ops == ([] if use_scoped_ac else [expected_native_save_ops])
479+ assert len(calls.native_ac) == int(not use_scoped_ac)
480+ assert len(calls.bridge_compile) == int(
481+ compile_enabled and effective_gmm
482+ )
483+ assert len(calls.model_compile) == int(compile_enabled)
401 if compile_enabled:484 if compile_enabled:
402- assert model_compile_calls[0][1] == {}485+ assert calls.model_compile[0][1] == {}
@@ -57,7 +57,14 @@ class ModelCustomConfigConverter(Configurable, ModelConverter):
57 logger.info(f"[ModelCustomConfigConverter] Applied {parallelize_plan_updater}.")57 logger.info(f"[ModelCustomConfigConverter] Applied {parallelize_plan_updater}.")
58 58 
59 state_dict_updater = self._model_config.state_dict_updater59 state_dict_updater = self._model_config.state_dict_updater
60- if state_dict_updater is not None:60+ state_dict_updater_predicate = getattr(
61+ self._model_config,
62+ "state_dict_updater_predicate",
63+ None,
64+ )
65+ if state_dict_updater is not None and (
66+ state_dict_updater_predicate is None or state_dict_updater_predicate(model)
67+ ):
61 apply_state_dict_update(state_dict_updater, self.model_spec)68 apply_state_dict_update(state_dict_updater, self.model_spec)
62 logger.info(f"[ModelCustomConfigConverter] Applied {state_dict_updater}.")69 logger.info(f"[ModelCustomConfigConverter] Applied {state_dict_updater}.")
63 70 
@@ -20,6 +20,14 @@ def get_state_dict_adapter_wrapper(cls):
20 20 
21 _updater_cls_list: list[type["StateDictUpdater"]] = []21 _updater_cls_list: list[type["StateDictUpdater"]] = []
22 22 
23+ @classmethod
24+ def add_state_dict_updater(cls, updater_cls: type["StateDictUpdater"]) -> bool:
25+ """Register an updater once and report whether it was added."""
26+ if updater_cls in cls._updater_cls_list:
27+ return False
28+ cls._updater_cls_list.append(updater_cls)
29+ return True
30+ 
23 def to_hf(self, state_dict: dict[str, Any]) -> dict[str, Any]:31 def to_hf(self, state_dict: dict[str, Any]) -> dict[str, Any]:
24 """Apply to_hf transformation"""32 """Apply to_hf transformation"""
25 for updater_cls in self._updater_cls_list:33 for updater_cls in self._updater_cls_list:
@@ -45,12 +53,14 @@ def apply_state_dict_update(updater_cls: type["StateDictUpdater"], model_spec: M
45 if state_dict_adapter is None:53 if state_dict_adapter is None:
46 raise RuntimeError("[StateDictUpdateWrapper] TrainSpec.state_dict_adapter is None.")54 raise RuntimeError("[StateDictUpdateWrapper] TrainSpec.state_dict_adapter is None.")
47 55 
48- if not hasattr(state_dict_adapter, "_updater_cls_list"):56+ if not hasattr(state_dict_adapter, "add_state_dict_updater"):
49 adapter_wrapper = get_state_dict_adapter_wrapper(state_dict_adapter)57 adapter_wrapper = get_state_dict_adapter_wrapper(state_dict_adapter)
50 model_spec.state_dict_adapter = adapter_wrapper58 model_spec.state_dict_adapter = adapter_wrapper
51 state_dict_adapter = adapter_wrapper59 state_dict_adapter = adapter_wrapper
52 60 
53 # pyrefly: ignore [missing-attribute]61 # pyrefly: ignore [missing-attribute]
54- state_dict_adapter._updater_cls_list.append(updater_cls)62+ if not state_dict_adapter.add_state_dict_updater(updater_cls):
63+ logger.info(f"[StateDictUpdateWrapper] Skip duplicate StateDictUpdater {updater_cls}.")
64+ return
55 65 
56 logger.info(f"[StateDictUpdateWrapper] Add StateDictUpdater {updater_cls}.")66 logger.info(f"[StateDictUpdateWrapper] Add StateDictUpdater {updater_cls}.")
@@ -138,9 +138,14 @@ def _expert_activation(
138 return h138 return h
139 139 
140 140 
141-def _compile_expert_activation(*, backend: str, dynamic_tokens: bool) -> _ExpertActivationFn:141+def _compile_expert_activation(
142+ activation_fn: _ExpertActivationFn,
143+ *,
144+ backend: str,
145+ dynamic_tokens: bool,
146+) -> _ExpertActivationFn:
142 compiled_activation = torch.compile(147 compiled_activation = torch.compile(
143- _expert_activation,148+ activation_fn,
144 backend=backend,149 backend=backend,
145 fullgraph=True,150 fullgraph=True,
146 options={"custom_partitioner_fn": _NpuGmmAotDefaultPartitioner()},151 options={"custom_partitioner_fn": _NpuGmmAotDefaultPartitioner()},
@@ -247,7 +252,7 @@ def npu_grouped_experts_forward(
247 252 
248 # DSv4 sets ``self.swiglu_limit`` on its GroupedExperts instance (see253 # DSv4 sets ``self.swiglu_limit`` on its GroupedExperts instance (see
249 # torchtitan_npu/models/deepseek_v4/moe.py). Other models leave this unset254 # torchtitan_npu/models/deepseek_v4/moe.py). Other models leave this unset
250- # and the clamp is skipped in ``_expert_activation``.255+ # and the selected activation skips the clamp.
251 swiglu_limit = getattr(self, "swiglu_limit", None)256 swiglu_limit = getattr(self, "swiglu_limit", None)
252 257 
253 out = _run_experts_grouped_mm(258 out = _run_experts_grouped_mm(
@@ -277,10 +282,12 @@ class NpuGroupedExperts(GroupedExperts):
277 def __init__(282 def __init__(
278 self,283 self,
279 parent: GroupedExperts,284 parent: GroupedExperts,
285+ *,
286+ activation_fn: _ExpertActivationFn = _expert_activation,
280 ):287 ):
281 self.__dict__.update(parent.__dict__)288 self.__dict__.update(parent.__dict__)
282 self.use_grouped_mm = True289 self.use_grouped_mm = True
283- self._expert_activation_fn: _ExpertActivationFn = _expert_activation290+ self._expert_activation_fn = activation_fn
284 self._expert_activation_compile_key: tuple[str, bool] | None = None291 self._expert_activation_compile_key: tuple[str, bool] | None = None
285 if self.w1 is not None and self.w3 is not None:292 if self.w1 is not None and self.w3 is not None:
286 w13_data = torch.empty(293 w13_data = torch.empty(
@@ -320,6 +327,15 @@ class NpuGroupedExperts(GroupedExperts):
320 def init_weights(self, init_std: float):327 def init_weights(self, init_std: float):
321 npu_grouped_experts_init_weights(self, init_std)328 npu_grouped_experts_init_weights(self, init_std)
322 329 
330+ def set_expert_activation(self, activation_fn: _ExpertActivationFn) -> None:
331+ self._expert_activation_fn = activation_fn
332+ self._expert_activation_compile_key = None
333+ 
334+ 
335+def has_npu_grouped_experts(model: nn.Module) -> bool:
336+ """Return whether ``model`` contains routed experts backed by NPU GMM."""
337+ return any(isinstance(module, NpuGroupedExperts) for module in model.modules())
338+ 
323 339 
324def compile_expert_activation(340def compile_expert_activation(
325 model: nn.Module,341 model: nn.Module,
@@ -327,13 +343,14 @@ def compile_expert_activation(
327 backend: str,343 backend: str,
328 dynamic_tokens: bool,344 dynamic_tokens: bool,
329) -> None:345) -> None:
330- """Compile the activation bridge for grouped experts in ``model``."""346+ """Compile the selected activation bridge once for grouped experts in ``model``."""
331 experts = [module for module in model.modules() if isinstance(module, NpuGroupedExperts)]347 experts = [module for module in model.modules() if isinstance(module, NpuGroupedExperts)]
332 compile_key = (backend, dynamic_tokens)348 compile_key = (backend, dynamic_tokens)
333 if not experts or all(getattr(module, _EXPERT_ACTIVATION_COMPILE_KEY_ATTR) == compile_key for module in experts):349 if not experts or all(getattr(module, _EXPERT_ACTIVATION_COMPILE_KEY_ATTR) == compile_key for module in experts):
334 return350 return
335 351 
336 compiled_activation = _compile_expert_activation(352 compiled_activation = _compile_expert_activation(
353+ getattr(experts[0], _EXPERT_ACTIVATION_FN_ATTR),
张德鹏

和@panchao-gitcode确认使用 experts[0]统一代表全局专家编译配置是否合理?至少前三层的hash expert层应该不一致吧

likedislike
张伟
张伟
Aug 4 Comments:
likedislike
337 backend=backend,354 backend=backend,
338 dynamic_tokens=dynamic_tokens,355 dynamic_tokens=dynamic_tokens,
339 )356 )
@@ -343,11 +360,22 @@ def compile_expert_activation(
343 360 
344 361 
345class NpuGroupedExpertConverter(ModelCustomConverter):362class NpuGroupedExpertConverter(ModelCustomConverter):
346- def convert(self, model: nn.Module):363+ def convert(self, model: nn.Module) -> None:
347- for name, module in model.named_modules():364+ has_converted_experts = has_npu_grouped_experts(model)
348- if not isinstance(module, GroupedExperts):365+ converted_experts = False
366+ for name, module in list(model.named_modules()):
367+ if isinstance(module, NpuGroupedExperts) or not isinstance(module, GroupedExperts):
349 continue368 continue
350- replace_module_with_name(model, name, NpuGroupedExperts(module))369+ activation_fn = getattr(module, _EXPERT_ACTIVATION_FN_ATTR, _expert_activation)
370+ replace_module_with_name(
371+ model,
372+ name,
373+ NpuGroupedExperts(module, activation_fn=activation_fn),
374+ )
375+ converted_experts = True
376+ 
377+ if has_converted_experts and not converted_experts:
378+ logger.warning("npu_gmm is already applied; skipping duplicate conversion.")
351 379 
352 380 
353class GMMStateDictUpdater(StateDictUpdater):381class GMMStateDictUpdater(StateDictUpdater):
@@ -18,6 +18,7 @@ from torch.distributed.tensor import DeviceMesh, DTensor
18from torch.distributed.tensor.parallel.style import ParallelStyle18from torch.distributed.tensor.parallel.style import ParallelStyle
19from torch.distributed.tensor.placement_types import Partial19from torch.distributed.tensor.placement_types import Partial
20from torchtitan.distributed.expert_parallel import ExpertParallel20from torchtitan.distributed.expert_parallel import ExpertParallel
21+from torchtitan.models.common.feed_forward import FeedForward
21from torchtitan.models.common.moe import MoE22from torchtitan.models.common.moe import MoE
22 23 
23from torchtitan_npu.converters.convert_utils import replace_module_with_name24from torchtitan_npu.converters.convert_utils import replace_module_with_name
@@ -36,6 +37,7 @@ from torchtitan_npu.distributed.activation_checkpoint import (
36 retain_op_output,37 retain_op_output,
37)38)
38from torchtitan_npu.distributed.process_group import is_fake_process_group39from torchtitan_npu.distributed.process_group import is_fake_process_group
40+from torchtitan_npu.models.common.moe import NpuSharedExperts
39from torchtitan_npu.models.deepseek_v4.moe import MoE as DeepSeekV4MoE41from torchtitan_npu.models.deepseek_v4.moe import MoE as DeepSeekV4MoE
40 42 
41NpuTokenDispatchResult = tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]43NpuTokenDispatchResult = tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]
@@ -185,14 +187,28 @@ def _npu_moe_forward_for_dsv4(self, x, input_ids):
185class NpuMoeDispatchConverter(ModelCustomConverter):187class NpuMoeDispatchConverter(ModelCustomConverter):
186 """Replace MoE modules with NPU MoE dispatch implementations."""188 """Replace MoE modules with NPU MoE dispatch implementations."""
187 189 
190+ @staticmethod
191+ def _convert_shared_experts(module: nn.Module) -> None:
192+ shared_experts = getattr(module, "shared_experts", None)
193+ if shared_experts is None or isinstance(shared_experts, NpuSharedExperts):
194+ return
195+ if not isinstance(shared_experts, FeedForward):
196+ raise ValueError("NPU MoE shared_experts must be a FeedForward module.")
197+ NpuSharedExperts.convert(shared_experts)
198+ 
188 def convert(self, model: nn.Module):199 def convert(self, model: nn.Module):
189- for name, module in model.named_modules():200+ for name, module in list(model.named_modules()):
190 if isinstance(module, (NpuMoE, NpuDeepSeekV4MoE)):201 if isinstance(module, (NpuMoE, NpuDeepSeekV4MoE)):
202+ self._convert_shared_experts(module)
191 continue203 continue
192 if isinstance(module, DeepSeekV4MoE):204 if isinstance(module, DeepSeekV4MoE):
193- replace_module_with_name(model, name, _adopt_module_state(NpuDeepSeekV4MoE, module))205+ converted = _adopt_module_state(NpuDeepSeekV4MoE, module)
194 elif isinstance(module, MoE):206 elif isinstance(module, MoE):
195- replace_module_with_name(model, name, _adopt_module_state(NpuMoE, module))207+ converted = _adopt_module_state(NpuMoE, module)
208+ else:
209+ continue
210+ self._convert_shared_experts(converted)
211+ replace_module_with_name(model, name, converted)
196 212 
197 213 
198class TileLangMoeReduceConverter(ModelCustomConverter):214class TileLangMoeReduceConverter(ModelCustomConverter):
@@ -0,0 +1,85 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
2+#
3+# This source code is licensed under the BSD-style license found in the
4+# LICENSE file in the root directory of this source tree.
5+ 
6+"""Select ``cann_ops_nn.swiglu_group`` for routed and shared experts.
7+ 
8+Routed experts automatically reuse the model and checkpoint path provided by ``npu_gmm``.
9+Shared experts remain independently convertible through ``NpuSharedExperts``.
10+The operator's Autograd integration is provided by ``cann_ops_nn``.
11+"""
12+ 
13+import importlib
14+ 
15+import torch
16+from torch import nn
17+from torchtitan.models.common.feed_forward import FeedForward
18+from torchtitan.models.common.moe import GroupedExperts
19+ 
20+from torchtitan_npu.converters.kernels import gmm
21+from torchtitan_npu.converters.model_custom_interface import (
22+ ModelCustomConfig,
23+ ModelCustomConverter,
24+)
25+from torchtitan_npu.converters.registry import register_model_converter
26+from torchtitan_npu.models.common.moe import NpuSharedExperts
27+ 
28+ 
29+def swiglu_group_activation(
xuyujun
xuyujunxuyujunAug 11

这里有试过torch.compile编译是否OK,精度能否对齐?我这测试出现“未注册 autograd kernel,可能静默错误”的运行时警告。根因是 CANN 算子只注册了 PrivateUse1 实现;没有为 dispatcher operator 注册 Autograd key,你对比使能融合算子场景下,开启和关闭compile的精度是不是有问题

likedislike
张伟
张伟
Aug 11 Comments:
likedislike
30+ h: torch.Tensor,
31+ swiglu_limit: float | None = None,
32+ routed_scores: torch.Tensor | None = None,
33+) -> torch.Tensor:
34+ """Run the documented SwigluGroup op with expert activation inputs."""
35+ weight = None if routed_scores is None else routed_scores.to(dtype=torch.float32).contiguous()
36+ clamp_limit = -1.0 if swiglu_limit is None else float(swiglu_limit)
37+ return torch.ops.cann_ops_nn.swiglu_group.default(
38+ h.contiguous(),
39+ weight=weight,
40+ group_index=None,
41+ clamp_limit=clamp_limit,
42+ )
43+ 
44+ 
45+class NpuSwigluGroupConverter(ModelCustomConverter):
46+ """Select the SwigluGroup activation for routed and shared experts."""
47+ 
48+ def convert(self, model: nn.Module) -> None:
49+ routed_experts: list[gmm.NpuGroupedExperts] = []
50+ unconverted_routed_experts: list[GroupedExperts] = []
51+ for module in model.modules():
52+ if isinstance(module, gmm.NpuGroupedExperts):
53+ routed_experts.append(module)
54+ elif isinstance(module, GroupedExperts):
55+ unconverted_routed_experts.append(module)
56+ 
57+ shared_experts = [
58+ module
59+ for name, module in model.named_modules()
60+ if name.rsplit(".", 1)[-1] == "shared_experts" and isinstance(module, FeedForward)
61+ ]
62+ if not routed_experts and not unconverted_routed_experts and not shared_experts:
63+ return
64+ 
65+ importlib.import_module("cann_ops_nn.ops")
66+ 
67+ if unconverted_routed_experts:
68+ gmm.NpuGroupedExpertConverter(self.model_spec).convert(model)
69+ routed_experts = [module for module in model.modules() if isinstance(module, gmm.NpuGroupedExperts)]
70+ 
71+ for module in routed_experts:
72+ module.set_expert_activation(swiglu_group_activation)
73+ 
74+ for shared_module in shared_experts:
75+ NpuSharedExperts.convert(
76+ shared_module,
77+ activation_fn=swiglu_group_activation,
78+ )
79+ 
80+ 
81+@register_model_converter("npu_swiglu_group")
82+class SwigluGroupModelConfig(ModelCustomConfig):
83+ model_converter = NpuSwigluGroupConverter
84+ state_dict_updater = gmm.GMMStateDictUpdater
85+ state_dict_updater_predicate = staticmethod(gmm.has_npu_grouped_experts)
@@ -4,6 +4,7 @@
4# LICENSE file in the root directory of this source tree.4# LICENSE file in the root directory of this source tree.
5 5 
6from abc import ABC, abstractmethod6from abc import ABC, abstractmethod
7+from collections.abc import Callable
7from dataclasses import dataclass8from dataclasses import dataclass
8from typing import Any9from typing import Any
9 10 
@@ -58,3 +59,4 @@ class ModelCustomConfig:
58 model_converter: type["ModelCustomConverter"] | None = None59 model_converter: type["ModelCustomConverter"] | None = None
59 parallelize_plan_updater: type["ParallelizePlanUpdater"] | None = None60 parallelize_plan_updater: type["ParallelizePlanUpdater"] | None = None
60 state_dict_updater: type["StateDictUpdater"] | None = None61 state_dict_updater: type["StateDictUpdater"] | None = None
62+ state_dict_updater_predicate: Callable[[nn.Module], bool] | None = None
@@ -8,4 +8,9 @@ from .dsa_indexer_loss import ( # noqa: F401
8 DSAIndexerLossAutoScaler,8 DSAIndexerLossAutoScaler,
9 DSAIndexerLossLoggingHelper,9 DSAIndexerLossLoggingHelper,
10)10)
11+from .moe import ( # noqa: F401
12+ NpuSharedExperts,
13+ SharedExpertActivationFn,
14+ native_shared_expert_activation,
15+)
11from .npu_varlen_attention import NPUVarlenAttention # noqa: F40116from .npu_varlen_attention import NPUVarlenAttention # noqa: F401
@@ -0,0 +1,65 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
2+#
3+# This source code is licensed under the BSD-style license found in the
4+# LICENSE file in the root directory of this source tree.
5+ 
6+"""Portable NPU MoE building blocks shared by model converters."""
7+ 
8+__all__ = ["NpuSharedExperts", "SharedExpertActivationFn", "native_shared_expert_activation"]
9+ 
10+from collections.abc import Callable
11+from typing import cast
12+ 
13+import torch
14+import torch.nn.functional as F
15+from torchtitan.models.common.feed_forward import FeedForward
16+ 
17+SharedExpertActivationFn = Callable[
18+ [torch.Tensor, float | None],
19+ torch.Tensor,
20+]
21+ 
22+ 
23+def native_shared_expert_activation(
24+ h: torch.Tensor,
25+ swiglu_limit: float | None = None,
26+) -> torch.Tensor:
27+ """Apply the native small-op shared-expert SwiGLU decomposition."""
28+ gate, up = h.chunk(2, dim=-1)
29+ if swiglu_limit is not None:
30+ gate = torch.clamp(gate, max=swiglu_limit)
31+ up = torch.clamp(up, min=-swiglu_limit, max=swiglu_limit)
32+ return F.silu(gate) * up
33+ 
34+ 
35+class NpuSharedExperts(FeedForward):
36+ """Shared-expert FeedForward with an injectable activation implementation."""
37+ 
38+ @classmethod
39+ def convert(
40+ cls,
41+ parent: FeedForward,
42+ *,
43+ activation_fn: SharedExpertActivationFn = native_shared_expert_activation,
44+ ) -> "NpuSharedExperts":
45+ if not isinstance(parent, cls):
46+ try:
47+ # In-place conversion preserves parameters, hooks, and FQNs.
48+ parent.__class__ = cls # pyrefly: ignore [bad-assignment]
49+ except TypeError as exc:
50+ raise RuntimeError("Cannot convert shared_experts to NpuSharedExperts in place") from exc
51+ converted = cast("NpuSharedExperts", parent)
52+ converted.set_expert_activation(activation_fn)
53+ return converted
54+ 
55+ def set_expert_activation(self, activation_fn: SharedExpertActivationFn) -> None:
56+ self._expert_activation_fn = activation_fn
57+ 
58+ def forward(self, x: torch.Tensor) -> torch.Tensor:
59+ packed = torch.cat((self.w1(x), self.w3(x)), dim=-1)
60+ activation_fn = getattr(self, "_expert_activation_fn", native_shared_expert_activation)
61+ hidden = activation_fn(
62+ packed,
63+ getattr(self, "swiglu_limit", None),
64+ )
65+ return self.w2(hidden)
@@ -53,7 +53,10 @@ from torchtitan.models.common import FlexAttention, VarlenAttention
53from torchtitan.models.llama3.parallelize import apply_replicate53from torchtitan.models.llama3.parallelize import apply_replicate
54from torchtitan.models.llama4.parallelize import apply_fsdp54from torchtitan.models.llama4.parallelize import apply_fsdp
55 55 
56-from torchtitan_npu.converters.kernels.gmm import NPU_GMM_SAC_SAVE_OPS56+from torchtitan_npu.converters.kernels.gmm import (
57+ NPU_GMM_SAC_SAVE_OPS,
58+ has_npu_grouped_experts,
59+)
57from torchtitan_npu.converters.kernels.rms_norm import NPURMSNorm60from torchtitan_npu.converters.kernels.rms_norm import NPURMSNorm
58from torchtitan_npu.converters.registry import has_npu_converter61from torchtitan_npu.converters.registry import has_npu_converter
59from torchtitan_npu.distributed.activation_checkpoint import (62from torchtitan_npu.distributed.activation_checkpoint import (
@@ -429,7 +432,7 @@ def parallelize_deepseek_v4(
429 )432 )
430 433 
431 model_compile_enabled = compile_config.enable and "model" in compile_config.components434 model_compile_enabled = compile_config.enable and "model" in compile_config.components
432- npu_gmm_enabled = has_npu_converter(model_converters.converters, "npu_gmm")435+ npu_gmm_enabled = has_npu_grouped_experts(model)
433 npu_moe_dispatch_enabled = has_npu_converter(model_converters.converters, "npu_moe_dispatch")436 npu_moe_dispatch_enabled = has_npu_converter(model_converters.converters, "npu_moe_dispatch")
434 # TP reduces the GMM2 output in place, which would mutate its retained local value.437 # TP reduces the GMM2 output in place, which would mutate its retained local value.
435 save_grouped_mm_outputs = (438 save_grouped_mm_outputs = (