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"""Unified routed-expert family registering local, EP, Mega, MoonEP, and low-precision members."""
16
17from __future__ import annotations
18
19import warnings
20from typing import Any
21
22from torch import nn
23
24from hyper_parallel.components.modules.module_family import (
25 FamilyShardingContext,
26 ModuleFamily,
27 ResolvedFamily,
28 SelectorSpec,
29 VariantRule,
30 build_family,
31 register_module_family,
32)
33from hyper_parallel.components.modules.moe.grouped_experts.grouped_experts import (
34 GroupedExpertsConfig,
35 GroupedExpertsModule,
36)
37from hyper_parallel.core.dtensor.placement_types import Shard
38from hyper_parallel.distributed.recipe_spec import ModuleShardingSpec
39from hyper_parallel.models.replacement import module_replacement
40
41_LOW_PRECISION_PACKAGE = "hyper_parallel.components.modules.moe.grouped_experts.low_precision_grouped_experts"
42_DEFAULT_LOW_PRECISION_SELECTORS: dict[str, Any] = {
43 "use_mxfp8": False,
44 "fused": False,
45 "weight_format": "",
46 "act_format": "",
47 "is_fake_quantize": False,
48}
49
50
51def _low_precision_rule(**overrides: Any) -> dict[str, Any]:
52 """Build a complete low-precision selector dict by overriding baseline defaults."""
53 return {**_DEFAULT_LOW_PRECISION_SELECTORS, **overrides}
54
55
56_LOW_PRECISION_SELECTOR_MODES: tuple[tuple[dict[str, Any], str], ...] = (
57 (_low_precision_rule(use_mxfp8=True), "w8a8"),
58 (_low_precision_rule(use_mxfp8=True, fused=True), "fused_mxfp8"),
59 (_low_precision_rule(weight_format="mxfp8", act_format="mxfp8"), "w8a8"),
60 (_low_precision_rule(weight_format="mxfp8", act_format="mxfp8", fused=True), "fused_mxfp8"),
61 (_low_precision_rule(weight_format="mxfp4", act_format="mxfp8"), "w4a8"),
62 (_low_precision_rule(weight_format="mxfp4", act_format="mxfp8", is_fake_quantize=True), "fake_w4a8"),
63 (_low_precision_rule(weight_format="hif8", act_format="hif8"), "hif8"),
64)
65
66
67def validate_grouped_experts(
68 *, config: GroupedExpertsConfig | None, module: nn.Module | None, context: Any, member: ResolvedFamily,
69) -> None:
70 """Validate expert ownership and backend-specific transport options."""
71 del context
72 if not isinstance(member.arguments.get("overlap_shared_expert", True), bool):
73 raise ValueError("overlap_shared_expert must be bool")
74 if module is not None and not isinstance(module, GroupedExpertsModule):
75 gate_up = getattr(module, "gate_up_proj", None)
76 if not isinstance(gate_up, nn.Parameter) or gate_up.ndim != 3:
77 raise ValueError("staged experts require a canonical member or a packed expert source")
78 num_experts = gate_up.shape[0]
79 else:
80 facts = config if module is None else module.config
81 if not isinstance(facts, GroupedExpertsConfig):
82 raise ValueError("staged experts require canonical GroupedExpertsConfig")
83 num_experts = facts.num_experts
84 if num_experts % member.axis_sizes["ep"]:
85 raise ValueError("EP size must divide the global expert count")
86 if member.axis_sizes["ep"] == 1 and any((member.selectors["megakernel"], member.selectors["moonep"])):
87 warnings.warn(
88 "megakernel=True or moonep=True requires EP>1; EP=1 falls back to ordinary GroupedExperts. "
89 "Mega transport options are ignored.",
90 UserWarning, stacklevel=3,
91 )
92 elif not member.selectors["megakernel"] and (
93 member.arguments.get("dispatch_mode", "push") != "push"
94 or member.arguments.get("initial_capacity_factor") is not None
95 or member.arguments.get("capacity_growth_factor") is not None):
96 raise ValueError("Mega transport options require megakernel=True")
97
98
99def grouped_experts_sharding(
100 *, module: nn.Module, module_fqn: str, member: ResolvedFamily, context: FamilyShardingContext,
101) -> ModuleShardingSpec:
102 """Use the same ownership rule as the PR #1523 expert example.
103
104 Every canonical parameter starts with E, so EP uses Shard(0) for both projections.
105 Local parameters and boundary I/O have explicit empty layout declarations;
106 explicit stages own activation transport, and FSDP owns storage sharding.
107 """
108 del module_fqn, context
109 placements = {"ep": Shard(0)} if member.selectors["parallel"] else {}
110 return ModuleShardingSpec(
111 params={name: dict(placements) for name, _ in module.named_parameters()},
112 in_src={}, in_dst={}, is_boundary=False,
113 )
114
115
116@module_replacement
117def GroupedExperts( # pylint: disable=invalid-name
118 *, config: GroupedExpertsConfig | None = None, module: nn.Module | None = None,
119 module_fqn: str = "", context: Any = None, mesh: Any = None,
120 megakernel: bool = False, moonep: bool = False, overlap_shared_expert: bool = True,
121 activation_dtype: str = "input", swiglu_limit: float | None = None,
122 dispatch_mode: str = "push", initial_capacity_factor: float | None = None,
123 capacity_growth_factor: float | None = None, moonep_replica_capacity: int | None = None,
124 use_mxfp8: bool = False, fused: bool = False,
125 weight_format: str = "", act_format: str = "", is_fake_quantize: bool = False,
126) -> nn.Module:
127 """Construct the local/EP/MoonEP/Mega/low-precision member through the shared builder.
128
129 Args:
130 config: Global algorithm configuration, mutually exclusive with module.
131 module: Existing canonical member or an unsharded packed SwiGLU expert module.
132 module_fqn: Model-owned expert boundary.
133 context: Framework construction facts.
134 mesh: Existing job mesh, outside serialized family arguments.
135 megakernel: Select fused Mega transport/compute for EP>1; EP=1 warns and uses local GMM.
136 moonep: Select collective MoonEP with dynamic execution replicas.
137 overlap_shared_expert: Let ordinary/Moon EP schedule a bound shared family member.
138 activation_dtype: SwiGLU precision for packed source adoption by non-fused members.
139 swiglu_limit: Clamp override for packed source adoption; None reads the source.
140 dispatch_mode: Mega transport policy, push or pull.
141 initial_capacity_factor: Mega push receive-capacity factor; None uses the backend default.
142 capacity_growth_factor: Mega push growth factor; None uses the backend default.
143 moonep_replica_capacity: Maximum remote expert rows per rank; None means E/EP.
144 use_mxfp8: Explicit MXFP8 selector when not using a named dtype scheme.
145 fused: Select fused MXFP8 SwiGLU dual-axis quantization when paired with MXFP8.
146 weight_format: Quantized weight format selector injected from a dtype scheme.
147 act_format: Quantized activation format selector injected from a dtype scheme.
148 is_fake_quantize: Fake-quantization selector injected from a dtype scheme.
149 """
150 return build_family(GroupedExperts, config=config, module=module, module_fqn=module_fqn,
151 context=context, mesh=mesh, megakernel=megakernel, moonep=moonep,
152 overlap_shared_expert=overlap_shared_expert,
153 activation_dtype=activation_dtype, swiglu_limit=swiglu_limit,
154 dispatch_mode=dispatch_mode, initial_capacity_factor=initial_capacity_factor,
155 capacity_growth_factor=capacity_growth_factor, moonep_replica_capacity=moonep_replica_capacity,
156 use_mxfp8=use_mxfp8, fused=fused, weight_format=weight_format,
157 act_format=act_format, is_fake_quantize=is_fake_quantize)
158
159
160register_module_family(ModuleFamily(
161 name="routed_grouped_experts", baseline=GroupedExperts,
162 variants={
163 "local": "hyper_parallel.components.modules.moe.grouped_experts.grouped_experts.GroupedExpertsModule",
164 "ep": "hyper_parallel.components.modules.moe.grouped_experts.ep.ep_grouped_experts.EPGroupedExperts",
165 "ep_mega": ("hyper_parallel.components.modules.moe.grouped_experts.ep."
166 "ep_mega_grouped_experts.EPMegaGroupedExperts"),
167 "ep_moonep": ("hyper_parallel.components.modules.moe.grouped_experts.ep."
168 "moonep_grouped_experts.MoonEPGroupedExperts"),
169 **{
170 f"{prefix}_{mode}": f"{_LOW_PRECISION_PACKAGE}.build_{builder_prefix}_{mode}_experts"
171 for prefix, builder_prefix in (("local", "local"), ("ep", "ep"), ("ep_moonep", "moonep"))
172 for mode in ("w8a8", "fused_mxfp8", "w4a8", "fake_w4a8", "hif8")
173 },
174 },
175 default_variant="local", parallel_axis="ep",
176 selector_specs={
177 "megakernel": SelectorSpec(bool, False),
178 "moonep": SelectorSpec(bool, False),
179 "use_mxfp8": SelectorSpec(bool, False),
180 "fused": SelectorSpec(bool, False, aliases=("use_fused_mxfp8",)),
181 "weight_format": SelectorSpec(str, ""),
182 "act_format": SelectorSpec(str, ""),
183 "is_fake_quantize": SelectorSpec(bool, False),
184 },
185 variant_rules=(
186 VariantRule(
187 {"megakernel": False, "moonep": False, **_DEFAULT_LOW_PRECISION_SELECTORS, "parallel": True}, "ep",
188 ),
189 VariantRule(
190 {"megakernel": True, "moonep": False, **_DEFAULT_LOW_PRECISION_SELECTORS, "parallel": False}, "local",
191 ),
192 VariantRule(
193 {"megakernel": True, "moonep": False, **_DEFAULT_LOW_PRECISION_SELECTORS, "parallel": True}, "ep_mega",
194 ),
195 VariantRule(
196 {"megakernel": False, "moonep": True, **_DEFAULT_LOW_PRECISION_SELECTORS, "parallel": False}, "local",
197 ),
198 VariantRule(
199 {"megakernel": False, "moonep": True, **_DEFAULT_LOW_PRECISION_SELECTORS, "parallel": True}, "ep_moonep",
200 ),
201 *(
202 rule
203 for selectors, mode in _LOW_PRECISION_SELECTOR_MODES
204 for rule in (
205 VariantRule({"megakernel": False, "moonep": False, **selectors, "parallel": False}, f"local_{mode}"),
206 VariantRule({"megakernel": False, "moonep": True, **selectors, "parallel": False}, f"local_{mode}"),
207 VariantRule({"megakernel": False, "moonep": False, **selectors, "parallel": True}, f"ep_{mode}"),
208 VariantRule({"megakernel": False, "moonep": True, **selectors, "parallel": True}, f"ep_moonep_{mode}"),
209 )
210 ),
211 ),
212 sharding=grouped_experts_sharding, validate=validate_grouped_experts,
213))