Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / moe / grouped_experts / ep / ep_mega_grouped_experts.py: 96%

103 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-12-05 05:12 +0800

1# Copyright 2026 Huawei Technologies Co., Ltd 

2# 

3# Licensed under the Apache License, Version 2.0 (the "License"); 

4# you may not use this file except in compliance with the License. 

5# You may obtain a copy of the License at 

6# 

7# http://www.apache.org/licenses/LICENSE-2.0 

8# 

9# Unless required by applicable law or agreed to in writing, software 

10# distributed under the License is distributed on an "AS IS" BASIS, 

11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

12# See the License for the specific language governing permissions and 

13# limitations under the License. 

14# ============================================================================ 

15"""EP-only MegaMoE execution and its parameterless runtime holder.""" 

16 

17from __future__ import annotations 

18 

19from collections.abc import Mapping 

20from typing import Any 

21 

22from torch import Tensor, nn 

23 

24from hyper_parallel.components.modules.moe.grouped_experts.grouped_experts import ( 

25 GroupedExpertsConfig, GroupedExpertsModule, match_grouped_experts_inputs, 

26) 

27from hyper_parallel.components.modules.moe.grouped_experts.ep.ep_grouped_experts import validate_ep_layout 

28from hyper_parallel.core.dtensor.dtensor import DTensor 

29from hyper_parallel.distributed.module_binding import ParallelBinding, ParallelModuleSpec 

30 

31 

32class _MegaExpertsRuntime: 

33 """Keep native scratch resources without registering a second parameter owner.""" 

34 

35 def __init__(self, config: Any, *, dispatch_mode: str = "push", 

36 initial_capacity_factor: float | None = None, 

37 capacity_growth_factor: float | None = None) -> None: 

38 """Record algorithm facts and the existing Mega transport options.""" 

39 if config.top_k is None: 

40 raise ValueError("MegaKernel requires config.top_k from the model or explicit standalone config") 

41 if config.activation is not None: 

42 raise ValueError( 

43 "MegaKernel supports SwiGLU with optional swiglu_limit, not arbitrary activation callables" 

44 ) 

45 if dispatch_mode not in ("push", "pull"): 

46 raise ValueError("Mega dispatch_mode must be push or pull") 

47 self.config = config 

48 self.tuning = {"dispatch_mode": dispatch_mode, "initial_capacity_factor": initial_capacity_factor, 

49 "capacity_growth_factor": capacity_growth_factor} 

50 self.executor = None 

51 

52 def configure(self, group: Any) -> None: 

53 """Borrow the existing ordered EP group and the upstream numerical implementation. 

54 

55 Args: 

56 group: Job-owned process group with contiguous expert ownership. 

57 """ 

58 if self.executor is not None: 

59 return 

60 # The optional accelerator package is loaded only for an explicitly selected Mega member. 

61 from hyper_multicore import MegaMoeExperts, MegaMoeNumericsOptions, SwiGLUParameters # pylint: disable=C0415 

62 from hyper_multicore.experimental import MegaMoeTuningOptions # pylint: disable=C0415 

63 

64 config = self.config 

65 executor = MegaMoeExperts( 

66 hidden_size=config.hidden_size, intermediate_size=config.intermediate_size, 

67 num_experts=config.num_experts, top_k=config.top_k, ep_group=group, 

68 activation=SwiGLUParameters(clamp_limit=config.swiglu_limit, clamp_after_silu=False), 

69 numerics_options=MegaMoeNumericsOptions( 

70 apply_probs_before_fc2=config.routing_weight_mode == "before_fc2", 

71 ), 

72 tuning_options=MegaMoeTuningOptions(**self.tuning), 

73 ) 

74 if any(True for _ in executor.parameters()): 

75 executor.close() 

76 raise RuntimeError("MegaKernel requires the parameterless HyperMulticore executor API") 

77 self.executor = executor 

78 

79 def __call__(self, hidden: Tensor, ids: Tensor, weights: Tensor, 

80 gate_up: Tensor, down: Tensor) -> Tensor: 

81 """Pass current canonical weights directly; the native executor infers EOI layout.""" 

82 if self.executor is None: 

83 raise RuntimeError("prepare_module_runtimes must run before MegaKernel forward") 

84 return self.executor( 

85 hidden, ids, weights, 

86 expert_weights=(gate_up, down), 

87 ) 

88 

89 @staticmethod 

90 def share(runtimes: list["_MegaExpertsRuntime"]) -> None: 

91 """Reuse the established serial-layer workspace sharing implementation. 

92 

93 Args: 

94 runtimes: Configured peers with compatible serial execution resources. 

95 """ 

96 # The native package owns allocation, sharing and in-flight lifetime validation. 

97 from hyper_multicore import MegaMoeExperts # pylint: disable=C0415 

98 

99 MegaMoeExperts.share_execution_resources([runtime.executor for runtime in runtimes]) 

100 

101 def close(self) -> None: 

102 """Release native storage after its final reader has completed.""" 

103 if self.executor is not None: 

104 self.executor.close() 

105 self.executor = None 

106 

107 

108def _validate_mega_layout(*, module, sharding, context) -> None: 

109 if context.axis_sizes["ep"] <= 1: 

110 raise ValueError("MegaMoE requires EP>1; use ordinary GroupedExperts for EP=1") 

111 validate_ep_layout(module=module, sharding=sharding, context=context) 

112 

113 

114class EPMegaGroupedExperts(GroupedExpertsModule): 

115 """Run one fused token-level call; the kernel owns its transport and restoration.""" 

116 

117 shared_expert_overlap_supported = False 

118 

119 def __init__(self, *, config: GroupedExpertsConfig | None = None, module: nn.Module | None = None, 

120 module_fqn: str = "", context: Mapping[str, Any] | None = None, 

121 dispatch_mode: str = "push", initial_capacity_factor: float | None = None, 

122 capacity_growth_factor: float | None = None) -> None: 

123 """Adopt canonical state and record a parameterless native runtime holder. 

124 

125 Args: 

126 config: Global expert dimensions and routing/activation semantics. 

127 module: Unsharded packed source, exclusive with config. 

128 module_fqn: Expert checkpoint scope. 

129 context: Model configuration and parallel topology facts. 

130 dispatch_mode: Existing Mega push or pull transport policy. 

131 initial_capacity_factor: Optional push receive-capacity factor. 

132 capacity_growth_factor: Optional push growth factor. 

133 """ 

134 super().__init__(config=config, module=module, module_fqn=module_fqn, context=context) 

135 self._runtime = _MegaExpertsRuntime( 

136 self.config, dispatch_mode=dispatch_mode, initial_capacity_factor=initial_capacity_factor, 

137 capacity_growth_factor=capacity_growth_factor, 

138 ) 

139 self._ep_group: Any = None 

140 self._parallel_bound = False 

141 

142 def bind_parallel(self, binding: ParallelBinding) -> None: 

143 """Borrow the actual expert group; preserve the existing fused backend limits. 

144 

145 Args: 

146 binding: Existing job topology; no new process group or ordinary EPContext. 

147 """ 

148 mesh = binding.mesh_binding.mesh_context 

149 if mesh.ep_size <= 1: 

150 raise ValueError("MegaMoE requires EP>1; use ordinary GroupedExperts for EP=1") 

151 if mesh.pp_size > 1: 

152 raise ValueError("the existing MegaMoe lifecycle requires PP=1") 

153 if mesh.tp_size > 1 and not mesh.sequence_parallel: 

154 raise ValueError("MegaMoe with dense TP requires EP>1 and sequence_parallel=true") 

155 axis = binding.mesh_binding.axis_mesh("ep") 

156 group = axis.get_group() 

157 if self._parallel_bound and self._ep_group is not group: 

158 raise ValueError("MegaKernel already has a different communication owner") 

159 self._ep_group = group 

160 self._parallel_bound = True 

161 

162 def parallel_module_spec(self) -> ParallelModuleSpec: 

163 """Declare canonical ownership and a fused token-level protocol.""" 

164 return ParallelModuleSpec( 

165 protocol="grouped_experts.forward.mega", binding_kind="mesh", 

166 stages={"forward": ("hidden_states", "topk_ids", "topk_weights")}, validate=_validate_mega_layout, 

167 ) 

168 

169 def runtime_group_key(self) -> tuple: 

170 """Group only serial native executors with compatible scratch requirements.""" 

171 config = self.config 

172 if not self._parallel_bound: 

173 raise RuntimeError("bind_parallel must run before preparing MegaKernel runtimes") 

174 return (type(self), self._ep_group, config, self.gate_up_proj.device, self.gate_up_proj.dtype, 

175 tuple(self._runtime.tuning.items())) 

176 

177 def _bound_runtime(self) -> tuple[_MegaExpertsRuntime, Any]: 

178 """Return the native holder and EP group after parallel binding.""" 

179 if not self._parallel_bound: 

180 raise RuntimeError("bind_parallel must run before preparing MegaKernel runtimes") 

181 return self._runtime, self._ep_group 

182 

183 @classmethod 

184 def prepare_runtime_group(cls, experts: list["EPMegaGroupedExperts"]) -> None: 

185 """Configure after materialization and share scratch across compatible serial layers. 

186 

187 Args: 

188 experts: Peers with the same runtime_group_key, before their first forward. 

189 """ 

190 peers = [cls._bound_runtime(expert) for expert in experts] 

191 if all(runtime.executor is not None for runtime, _ in peers): 

192 return 

193 created = [] 

194 try: 

195 for runtime, group in peers: 

196 if runtime.executor is None: 

197 runtime.configure(group) 

198 created.append(runtime) 

199 _MegaExpertsRuntime.share([runtime for runtime, _ in peers]) 

200 except Exception: 

201 for runtime in created: 

202 runtime.close() 

203 raise 

204 

205 def close_runtime(self) -> None: 

206 """Close this native executor after its final backward.""" 

207 self._runtime.close() 

208 

209 def forward(self, hidden_states: Tensor, topk_ids: Tensor | None = None, 

210 topk_weights: Tensor | None = None, **kwargs: Tensor) -> Tensor: 

211 """Keep original token routes and current FSDP-restored parameters in one fused call. 

212 

213 Args: 

214 hidden_states: Source token activations [..., H]. 

215 topk_ids: Global expert IDs [T, K], where T is the flattened token count. 

216 topk_weights: Final model-selected routing probabilities [T, K]. 

217 **kwargs: Recognized aliases for the top-k ID and probability inputs. 

218 

219 Returns: 

220 Expert contributions restored to the original hidden_states shape. 

221 """ 

222 topk_ids, topk_weights = match_grouped_experts_inputs(topk_ids, topk_weights, kwargs) 

223 self.validate_and_flatten_inputs(hidden_states, topk_ids, topk_weights) 

224 if topk_ids.shape[1] != self.config.top_k: 

225 raise ValueError("MegaKernel top-k width must match its configured native executor") 

226 parameters = tuple(value.to_local() if isinstance(value, DTensor) else value 

227 for value in (self.gate_up_proj, self.down_proj)) 

228 return self._runtime(hidden_states, topk_ids, topk_weights, *parameters)