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 stage declarations and delegation; the default member owns all expert mathematics."""
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.module_family import FamilyShardingContext
25from hyper_parallel.components.modules.moe.grouped_experts.grouped_experts import (
26 GroupedExpertsConfig,
27 GroupedExpertsModule,
28)
29from hyper_parallel.core.dtensor.placement_types import Shard
30from hyper_parallel.distributed.expert_parallel.ep_context import EPContext
31from hyper_parallel.distributed.module_binding import ParallelBinding, ParallelModuleSpec
32from hyper_parallel.distributed.recipe_spec import ModuleShardingSpec
33
34
35def validate_ep_layout(
36 *, module: GroupedExpertsModule, sharding: ModuleShardingSpec, context: FamilyShardingContext,
37) -> None:
38 """Validate the final canonical expert boundary, rather than a model's source layout.
39
40 Source adapters must convert names, shapes and mathematics before this point.
41 Dense TP is allowed; each EP owner keeps complete experts (ETP=1).
42 """
43 if set(sharding.params) != {"gate_up_proj", "down_proj"}:
44 raise ValueError("EP experts require complete canonical expert ownership")
45 if any(axes != {"ep": Shard(0)} for axes in sharding.params.values()):
46 raise ValueError("TP-extend-EP requires only contiguous expert Shard(0), without expert TP sharding")
47 config = module.config
48 expected = {"gate_up_proj": (config.num_experts, 2 * config.intermediate_size, config.hidden_size),
49 "down_proj": (config.num_experts, config.hidden_size, config.intermediate_size)}
50 if any(tuple(module.get_parameter(name).shape) != shape for name, shape in expected.items()):
51 raise ValueError("TP-extend-EP requires complete canonical expert matrices")
52 if module.config.num_experts % context.axis_sizes["ep"]:
53 raise ValueError("EP size must divide the global expert count")
54
55
56class EPGroupedExperts(GroupedExpertsModule):
57 """Reuse the default algorithm and override only transport/binding stages."""
58
59 def __init__(
60 self, *, config: GroupedExpertsConfig | None = None, module: nn.Module | None = None,
61 module_fqn: str = "", context: Mapping[str, Any] | None = None,
62 overlap_shared_expert: bool = True,
63 activation_dtype: str = "input", swiglu_limit: float | None = None,
64 ) -> None:
65 """Construct canonical parameters without acquiring communication resources.
66
67 Args:
68 config: Canonical global algorithm configuration, exclusive with module.
69 module: Canonical member or packed expert source, exclusive with config.
70 module_fqn: Source module path used in diagnostics.
71 context: Job facts and source/ancestor configuration.
72 overlap_shared_expert: Enable context-owned shared FC1/FC2 scheduling.
73 activation_dtype: SwiGLU precision when adopting a packed source without a canonical config.
74 swiglu_limit: Clamp override when adopting a packed source without a canonical config.
75 """
76 super().__init__(config=config, module=module, module_fqn=module_fqn, context=context,
77 activation_dtype=activation_dtype, swiglu_limit=swiglu_limit)
78 self.ep_context: EPContext | None = None
79 self.overlap_shared_expert = overlap_shared_expert
80
81 def bind_parallel(self, binding: ParallelBinding) -> None:
82 """Borrow the common binder's EP context, rejecting missing or conflicting resources.
83
84 Args:
85 binding: Job-owned EP resources with matching global expert ownership.
86 """
87 # MoonEP subclasses EPContext but its dispatch consumes a different plan protocol.
88 if binding.ep_context.__class__ is not EPContext or binding.ep_context.num_experts != self.config.num_experts:
89 raise ValueError("binding requires an EP context with the same global expert count")
90 if self.ep_context is not None and self.ep_context is not binding.ep_context:
91 raise ValueError("EP experts already have a different communication owner")
92 self.ep_context = binding.ep_context
93
94 def dispatch(
95 self, hidden_states: Tensor, expert_ids: Tensor, tokens_per_expert: Tensor,
96 routing_weights: Tensor | None = None,
97 ) -> tuple[Tensor, Tensor, Tensor | None, list[int], list[int], Tensor]:
98 """Send locally prepared slots through the borrowed EP context.
99
100 Args:
101 hidden_states: Source expert-major activations [S,H].
102 expert_ids: Global expert IDs [S], sorted in ascending order.
103 tokens_per_expert: Source counts [E]; EP recomputes counts from the transported IDs.
104 routing_weights: Optional differentiable before_fc2 probabilities [S].
105
106 Returns:
107 Owner-local hidden/counts/weights, this call's split lists and received-row inverse mapping.
108 """
109 del tokens_per_expert
110 if self.ep_context is None:
111 raise RuntimeError("bind_parallel must run before EP dispatch")
112 return self.ep_context.dispatch(hidden_states, expert_ids, routing_weights)
113
114 def combine(
115 self, values: Tensor, send_splits: list[int] | None, recv_splits: list[int] | None, recv_inverse: Tensor | None,
116 ) -> Tensor:
117 """Return slots using this call's explicit inverse-transport arguments.
118
119 Args:
120 values: Owner-local expert outputs in expert-major order.
121 send_splits: Per-peer source send sizes from dispatch.
122 recv_splits: Per-peer source receive sizes from dispatch.
123 recv_inverse: Mapping from peer-major rows to local expert-major rows [R].
124
125 Returns:
126 Source expert-major outputs [S,H], before token unpermutation.
127 """
128 if self.ep_context is None or send_splits is None or recv_splits is None or recv_inverse is None:
129 raise RuntimeError("EP combine requires a bound context and this call's transport arguments")
130 return self.ep_context.combine(values, send_splits, recv_splits, recv_inverse)
131
132 def parallel_module_spec(self) -> ParallelModuleSpec:
133 """Describe transport signatures and ownership without allocating runtime resources.
134
135 Returns:
136 An EP protocol declaration. The binder validates the class methods and
137 layout, constructs a context on the job's EP mesh, then calls bind_parallel.
138 """
139 return ParallelModuleSpec(
140 protocol="grouped_experts.slots.ep",
141 binding_kind="ep",
142 stages={
143 "dispatch": ("hidden_states", "expert_ids", "tokens_per_expert", "routing_weights"),
144 "combine": ("values", "send_splits", "recv_splits", "recv_inverse"),
145 },
146 validate=validate_ep_layout,
147 options={"num_experts": self.config.num_experts, "overlap_shared_expert": self.overlap_shared_expert},
148 )