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"""MoonEP member sharing the ordinary expert algorithm and FSDP parameter lifecycle."""
16
17from __future__ import annotations
18
19from typing import Any
20
21from torch import Tensor, nn
22
23from hyper_parallel.components.modules.moe.grouped_experts.ep.ep_grouped_experts import validate_ep_layout
24from hyper_parallel.components.modules.moe.grouped_experts.grouped_experts import (
25 GroupedExpertsConfig, GroupedExpertsModule, match_grouped_experts_inputs,
26)
27from hyper_parallel.core.dtensor.dtensor import DTensor
28from hyper_parallel.distributed.expert_parallel.moonep_context import MoonEPContext
29from hyper_parallel.distributed.module_binding import ParallelBinding, ParallelModuleSpec
30
31
32class MoonEPGroupedExperts(GroupedExpertsModule):
33 """Balance execution with temporary replicas while retaining home Shard(0) Parameters."""
34
35 def __init__(
36 self, *, config: GroupedExpertsConfig | None = None, module: nn.Module | None = None,
37 module_fqn: str = "", context: Any = None, moonep_replica_capacity: int | None = None,
38 overlap_shared_expert: bool = True,
39 activation_dtype: str = "input", swiglu_limit: float | None = None,
40 ) -> None:
41 """Construct the shared algorithm without acquiring runtime resources.
42
43 Args:
44 config: Canonical expert algorithm configuration, exclusive with module.
45 module: Packed source whose parameters and training state are retained.
46 module_fqn: Source expert boundary for replacement metadata.
47 context: Builder-provided model configuration and initialization facts.
48 moonep_replica_capacity: Remote expert slots per rank; None means E/EP.
49 overlap_shared_expert: Enable context-owned shared FC1/FC2 scheduling.
50 activation_dtype: SwiGLU precision when adopting a packed source without a canonical config.
51 swiglu_limit: Clamp override when adopting a packed source without a canonical config.
52 """
53 super().__init__(
54 config=config, module=module, module_fqn=module_fqn, context=context,
55 activation_dtype=activation_dtype, swiglu_limit=swiglu_limit,
56 )
57 self.moonep_replica_capacity = moonep_replica_capacity
58 self.overlap_shared_expert = overlap_shared_expert
59 self.ep_context: MoonEPContext | None = None
60
61 def bind_parallel(self, binding: ParallelBinding) -> None:
62 """Borrow the job-owned MoonEP context with matching home ownership.
63
64 Args:
65 binding: Existing expert mesh and MoonEP runtime context.
66 """
67 context = binding.ep_context
68 if not isinstance(context, MoonEPContext) or context.num_experts != self.config.num_experts:
69 raise ValueError("MoonEP experts require a MoonEP context with the same global expert count")
70 if self.ep_context is not None and self.ep_context is not context:
71 raise ValueError("MoonEP experts already have a different communication owner")
72 self.ep_context = context
73
74 def forward(
75 self, hidden_states: Tensor, topk_ids: Tensor | None = None, topk_weights: Tensor | None = None,
76 **kwargs: Any,
77 ) -> Tensor:
78 """Run the inherited permute/compute/unpermute with a per-call MoonEP plan.
79
80 Args:
81 hidden_states: Source tokens [...,H].
82 topk_ids: Logical expert IDs [T,K], unchanged by physical balancing.
83 topk_weights: Differentiable route probabilities [T,K].
84 **kwargs: Recognized source routing aliases.
85
86 Returns:
87 Routed token outputs [...,H]; routing weights are applied exactly once.
88 """
89 if self.ep_context is None:
90 raise ValueError("MoonEP experts must be bound before forward")
91 topk_ids, topk_weights = match_grouped_experts_inputs(topk_ids, topk_weights, kwargs)
92 output_shape = tuple(hidden_states.shape)
93 hidden_states = self.validate_and_flatten_inputs(hidden_states, topk_ids, topk_weights)
94 hidden, ids, _, weights, source_inverse = self.permute(hidden_states, topk_ids, topk_weights)
95 plan = self.ep_context.plan(ids)
96 gate, down = self.gate_up_proj, self.down_proj
97 gate = gate.to_local() if isinstance(gate, DTensor) else gate
98 down = down.to_local() if isinstance(down, DTensor) else down
99 gate, down = self.ep_context.expert_weights(gate, down, plan)
100 hidden, counts, weights, receive_inverse = self.ep_context.dispatch(
101 hidden, weights, plan=plan,
102 )
103 values = self.compute_experts(hidden, counts, gate, down, weights)
104 values = self.ep_context.combine(values, plan, receive_inverse)
105 return self.unpermute(values, source_inverse, topk_weights, output_shape)
106
107 def parallel_module_spec(self) -> ParallelModuleSpec:
108 """Declare fixed home ownership and the collective MoonEP protocol."""
109 return ParallelModuleSpec(
110 "grouped_experts.forward.moonep", "ep", {"forward": ("hidden_states", "topk_ids", "topk_weights")},
111 validate=validate_ep_layout,
112 options={"num_experts": self.config.num_experts, "moonep": True,
113 "moonep_replica_capacity": self.moonep_replica_capacity,
114 "overlap_shared_expert": self.overlap_shared_expert},
115 )