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"""Low-precision grouped-expert ModuleFamily members reusing staged Local, EP, and MoonEP."""
16
17from __future__ import annotations
18
19from abc import ABC, abstractmethod
20from collections.abc import Callable, Mapping
21import inspect
22from typing import Any
23
24import torch
25from torch import Tensor, nn
26
27from hyper_parallel.components.modules.moe.grouped_experts.ep.ep_grouped_experts import EPGroupedExperts
28from hyper_parallel.components.modules.moe.grouped_experts.ep.moonep_grouped_experts import MoonEPGroupedExperts
29from hyper_parallel.components.modules.moe.grouped_experts.grouped_experts import (
30 GroupedExpertsConfig,
31 GroupedExpertsModule,
32)
33from hyper_parallel.components.quantization.config import (
34 GROUPED_NDIM,
35 GROUP_LIST_COUNTS,
36 LowPrecisionDtypeScheme,
37 MX_BLOCK_SIZE_32,
38)
39from hyper_parallel.components.quantization.functional import build_low_precision_strategy
40from hyper_parallel.components.quantization.functional.base_gmm_func import (
41 GroupedLinear,
42 _GroupedLinearFunction,
43)
44from hyper_parallel.components.quantization.functional.fake_w4a8_gmm_func import FakeW4A8GroupedLinear
45from hyper_parallel.components.quantization.functional.hifloat8_gmm_func import HiFloat8GroupedLinear
46from hyper_parallel.components.quantization.functional.mxfp8_fused_grouped_swiglu import fused_grouped_swiglu
47from hyper_parallel.components.quantization.functional.strategy_factory import _validate_tile_alignment
48from hyper_parallel.components.quantization.ops.npu_mxfp8 import (
49 LowPrecisionCapabilityError,
50 validate_npu_gmm_runtime,
51 validate_npu_swiglu_runtime,
52)
53from hyper_parallel.components.quantization.ops.npu_w4a8 import W4A8CapabilityError
54from hyper_parallel.components.quantization.quantizers.mxfp8 import MXFP8Quantizer
55from hyper_parallel.core.dtensor.dtensor import DTensor
56
57_GATE_UP_BRANCHES = 2
58_LOW_PRECISION_MODES = ("w8a8", "fused_mxfp8", "w4a8", "fake_w4a8", "hif8")
59
60
61def _scheme_for_mode(low_precision_mode: str, context: Mapping[str, Any]) -> LowPrecisionDtypeScheme:
62 """Resolve the LowPrecisionDtypeScheme corresponding to a named family variant."""
63 configured = context.get("low_precision")
64 block_size = getattr(configured, "block_size", MX_BLOCK_SIZE_32)
65 if low_precision_mode == "w8a8":
66 return LowPrecisionDtypeScheme(weight_format="mxfp8", act_format="mxfp8", block_size=block_size)
67 if low_precision_mode == "w4a8":
68 return LowPrecisionDtypeScheme(weight_format="mxfp4", act_format="mxfp8", block_size=block_size)
69 if low_precision_mode == "fake_w4a8":
70 return LowPrecisionDtypeScheme(
71 weight_format="mxfp4", act_format="mxfp8", is_fake_quantize=True, block_size=block_size,
72 )
73 if low_precision_mode == "hif8":
74 return LowPrecisionDtypeScheme(weight_format="hif8", act_format="hif8")
75 if isinstance(configured, LowPrecisionDtypeScheme):
76 return configured
77 raise ValueError(f"Unsupported low-precision grouped-expert mode: {low_precision_mode!r}")
78
79
80def _is_deepseek_v4_experts(module: nn.Module) -> bool:
81 """Identify DeepSeek-V4/V4.1 packed experts without eagerly importing Transformers models."""
82 cls = type(module)
83 return cls.__name__ == "DeepseekV4Experts" and cls.__module__.startswith("transformers.models.deepseek_v4.")
84
85
86def _validate_custom_gate_source(module: nn.Module | None, prefix: str) -> None:
87 """Reject non-DeepSeek custom _apply_gate hooks before adopting source parameters."""
88 if module is None or isinstance(module, GroupedExpertsModule) or _is_deepseek_v4_experts(module):
89 return
90 apply_gate = getattr(module, "_apply_gate", None)
91 apply_gate_fn = getattr(apply_gate, "__func__", apply_gate)
92 if apply_gate_fn is not None and getattr(apply_gate_fn, "__name__", "") != "_default_apply_gate":
93 raise ValueError(f"{prefix}: custom _apply_gate requires a dedicated replacement")
94
95
96class _ExpertExecutor(ABC):
97 """Polymorphic local compute executor bound once at expert construction time."""
98
99 @abstractmethod
100 def execute(
101 self,
102 owner: _LowPrecisionExpertsMixin,
103 hidden_states: Tensor,
104 gate_up: Tensor,
105 down: Tensor,
106 counts: Tensor,
107 routing_weights: Tensor | None,
108 ) -> Tensor:
109 """Execute quantized expert projections on canonical [C, 2I, H] and [C, H, I] weights."""
110
111
112class _GroupedLinearExecutor(_ExpertExecutor):
113 """Two-stage (FC1 -> SwiGLU -> FC2) executor delegating format math to GroupedLinear."""
114
115 def __init__(
116 self,
117 owner: _LowPrecisionExpertsMixin,
118 *,
119 low_precision_mode: str,
120 context: Mapping[str, Any],
121 tile_shapes: tuple[tuple[int, ...], tuple[int, ...]],
122 block_size: int,
123 strategy: GroupedLinear | None = None,
124 **_: Any,
125 ) -> None:
126 if strategy is None:
127 scheme = _scheme_for_mode(low_precision_mode, context)
128 strategy = build_low_precision_strategy(scheme, tile_shapes=tile_shapes)
129 else:
130 if isinstance(strategy, nn.Module) or not isinstance(strategy, GroupedLinear):
131 raise TypeError("grouped_linear must be a non-Module GroupedLinear instance")
132 if not isinstance(strategy, HiFloat8GroupedLinear):
133 fmt_name = "fake_w4a8" if isinstance(strategy, FakeW4A8GroupedLinear) else strategy.FORMAT_NAME
134 _validate_tile_alignment(fmt_name, block_size, tile_shapes)
135 owner.grouped_linear = strategy
136
137 def execute(
138 self,
139 owner: _LowPrecisionExpertsMixin,
140 hidden_states: Tensor,
141 gate_up: Tensor,
142 down: Tensor,
143 counts: Tensor,
144 routing_weights: Tensor | None,
145 ) -> Tensor:
146 try:
147 projected = _GroupedLinearFunction.apply(
148 hidden_states, gate_up, counts, owner.grouped_linear, GROUP_LIST_COUNTS,
149 )
150 activated = owner._apply_swiglu(projected) # pylint: disable=protected-access
151 if owner.config.routing_weight_mode == "before_fc2":
152 if routing_weights is None:
153 raise ValueError("before_fc2 requires differentiable slot routing weights")
154 activated = (activated * routing_weights.unsqueeze(-1)).to(activated.dtype)
155 return _GroupedLinearFunction.apply(
156 activated, down, counts, owner.grouped_linear, GROUP_LIST_COUNTS,
157 )
158 except (LowPrecisionCapabilityError, W4A8CapabilityError) as exc:
159 target = owner.fqn or "<unknown>"
160 raise LowPrecisionCapabilityError(
161 f"Low-precision grouped-expert target {target!r} cannot run: {exc}"
162 ) from exc
163
164
165class _FusedSwiGLUExecutor(_ExpertExecutor):
166 """Cross-layer fused executor running FC1 + dual-axis MXFP8 SwiGLU + FC2 in one autograd node."""
167
168 def __init__(
169 self,
170 owner: _LowPrecisionExpertsMixin,
171 *,
172 prefix: str,
173 tile_shapes: tuple[tuple[int, ...], tuple[int, ...]],
174 block_size: int,
175 **_: Any,
176 ) -> None:
177 cfg = owner.config
178 if cfg.activation is not None:
179 raise ValueError(f"{prefix} requires standard or clamped SwiGLU activation")
180 if cfg.routing_weight_mode != "output":
181 raise ValueError(f"{prefix}: fused MXFP8 SwiGLU requires routing_weight_mode='output'")
182 if cfg.activation_dtype != "input":
183 raise ValueError(f"{prefix}: fused MXFP8 SwiGLU requires activation_dtype='input'")
184 _validate_tile_alignment("mxfp8", block_size, tile_shapes)
185 try:
186 validate_npu_gmm_runtime()
187 validate_npu_swiglu_runtime(clamp_limit=owner.clamp_limit)
188 except RuntimeError as exc:
189 raise RuntimeError(f"{prefix}: {exc}") from exc
190 owner._quantizer = MXFP8Quantizer() # pylint: disable=protected-access
191
192 def execute(
193 self,
194 owner: _LowPrecisionExpertsMixin,
195 hidden_states: Tensor,
196 gate_up: Tensor,
197 down: Tensor,
198 counts: Tensor,
199 routing_weights: Tensor | None,
200 ) -> Tensor:
201 del routing_weights
202 return fused_grouped_swiglu(
203 hidden_states,
204 gate_up,
205 down,
206 counts,
207 owner.quantizer,
208 clamp_limit=owner.clamp_limit,
209 )
210
211
212_EXECUTOR_CLASSES: dict[str, type[_ExpertExecutor]] = {
213 "fused_mxfp8": _FusedSwiGLUExecutor,
214 "w8a8": _GroupedLinearExecutor,
215 "w4a8": _GroupedLinearExecutor,
216 "fake_w4a8": _GroupedLinearExecutor,
217 "hif8": _GroupedLinearExecutor,
218 "strategy": _GroupedLinearExecutor,
219}
220
221
222class _LowPrecisionExpertsMixin:
223 """Override only ``compute_experts`` via a bound executor while reusing staged Local/EP/MoonEP."""
224
225 config: GroupedExpertsConfig
226 gate_up_proj: nn.Parameter
227 down_proj: nn.Parameter
228 grouped_linear: GroupedLinear
229 _quantizer: MXFP8Quantizer
230 executor: _ExpertExecutor
231 clamp_limit: float | None
232 fqn: str = ""
233
234 @property
235 def quantizer(self) -> Any:
236 """Expose the active quantizer for fused executors and single-quantizer strategies."""
237 if "_quantizer" in self.__dict__:
238 return self._quantizer
239 grouped_linear = self.__dict__.get("grouped_linear")
240 if grouped_linear is not None and hasattr(grouped_linear, "quantizer"):
241 return grouped_linear.quantizer
242 raise AttributeError(f"{type(self).__name__!r} has no single quantizer attribute")
243
244 @quantizer.setter
245 def quantizer(self, value: Any) -> None:
246 if "_quantizer" in self.__dict__:
247 self._quantizer = value
248 return
249 grouped_linear = self.__dict__.get("grouped_linear")
250 if grouped_linear is not None and hasattr(grouped_linear, "quantizer"):
251 grouped_linear.quantizer = value
252 return
253 self._quantizer = value
254
255 def _init_low_precision_executor(
256 self,
257 *,
258 low_precision_mode: str,
259 module_fqn: str = "",
260 context: Mapping[str, Any] | None = None,
261 strategy: GroupedLinear | None = None,
262 ) -> None:
263 """Resolve and bind the polymorphic compute executor for this expert instance."""
264 effective_context = context or {}
265 prefix = f"{module_fqn or '<root>'}: {type(self).__name__}"
266 self.fqn = module_fqn
267 self.clamp_limit = self.config.swiglu_limit
268 self.activation_func = self._apply_swiglu
269 executor_cls = _EXECUTOR_CLASSES.get(low_precision_mode)
270 if executor_cls is None:
271 raise ValueError(f"Unsupported low-precision grouped-expert mode: {low_precision_mode!r}")
272 tile_shapes = (tuple(self.gate_up_proj.shape), tuple(self.down_proj.shape))
273 block_size = getattr(effective_context.get("low_precision"), "block_size", MX_BLOCK_SIZE_32)
274 self.executor = executor_cls(
275 self,
276 low_precision_mode=low_precision_mode,
277 prefix=prefix,
278 context=effective_context,
279 tile_shapes=tile_shapes,
280 block_size=block_size,
281 strategy=strategy,
282 )
283
284 def _apply_swiglu(self, projected: Tensor) -> Tensor:
285 """Apply canonical Family SwiGLU activation and precision rules."""
286 gate, up = projected.chunk(_GATE_UP_BRANCHES, dim=-1)
287 return self.apply_activation(gate, up, projected.dtype) # type: ignore[attr-defined]
288
289 def compute_experts(
290 self,
291 hidden_states: Tensor,
292 tokens_per_expert: Tensor,
293 gate_up_proj: Tensor,
294 down_proj: Tensor,
295 routing_weights: Tensor | None = None,
296 ) -> Tensor:
297 """Execute quantized grouped-expert projections on owner-local or replicated slots.
298
299 Args:
300 hidden_states: Expert-major BF16/FP activations ``[R, H]``.
301 tokens_per_expert: Per-expert slot counts ``[C]`` matching ``gate_up_proj``.
302 gate_up_proj: Canonical ``[C, 2I, H]`` weights (unwrapped if ``DTensor``).
303 down_proj: Canonical ``[C, H, I]`` weights (unwrapped if ``DTensor``).
304 routing_weights: Optional differentiable ``before_fc2`` slot probabilities ``[R]``.
305
306 Returns:
307 Expert-major outputs ``[R, H]`` in ``hidden_states.dtype``.
308 """
309 cfg = self.config
310 gate_up = gate_up_proj.to_local() if isinstance(gate_up_proj, DTensor) else gate_up_proj
311 down = down_proj.to_local() if isinstance(down_proj, DTensor) else down_proj
312 if (
313 gate_up.ndim != GROUPED_NDIM
314 or gate_up.shape[0] < 1
315 or gate_up.shape[1:] != (2 * cfg.intermediate_size, cfg.hidden_size)
316 or down.shape != (gate_up.shape[0], cfg.hidden_size, cfg.intermediate_size)
317 ):
318 raise ValueError("expert compute requires complete [C,2I,H] and [C,H,I] matrices; ETP is unsupported")
319 if tokens_per_expert.ndim != 1 or tokens_per_expert.shape != (gate_up.shape[0],):
320 raise ValueError(f"{self.fqn}: counts must contain one count per local expert")
321 if tokens_per_expert.dtype not in (torch.int32, torch.int64):
322 raise ValueError(f"{self.fqn}: counts must be integers")
323 if tokens_per_expert.device.type == "cpu":
324 if bool((tokens_per_expert < 0).any()) or int(tokens_per_expert.sum()) != hidden_states.shape[0]:
325 raise ValueError(f"{self.fqn}: counts must be non-negative and sum to token count")
326 counts = tokens_per_expert.to(device=hidden_states.device)
327 return self.executor.execute(self, hidden_states, gate_up, down, counts, routing_weights)
328
329 def forward_expert_major(
330 self,
331 x: Tensor,
332 num_tokens_per_expert: Tensor,
333 scores: Tensor | None = None,
334 ) -> Tensor:
335 """Delegate expert-major calls directly to ``compute_experts``."""
336 return self.compute_experts(
337 x, num_tokens_per_expert, self.gate_up_proj, self.down_proj, scores,
338 )
339
340
341class LowPrecisionGroupedExperts(_LowPrecisionExpertsMixin, GroupedExpertsModule):
342 """Local (EP=1) low-precision experts member reusing staged GroupedExpertsModule."""
343
344 def __init__(
345 self,
346 *,
347 config: GroupedExpertsConfig | None = None,
348 module: nn.Module | None = None,
349 module_fqn: str = "",
350 context: Mapping[str, Any] | None = None,
351 activation: Callable[[Tensor, Tensor], Tensor] | None = None,
352 activation_dtype: str = "input",
353 swiglu_limit: float | None = None,
354 low_precision_mode: str = "w8a8",
355 strategy: GroupedLinear | None = None,
356 ) -> None:
357 """Construct canonical local parameters and bind the low-precision compute executor."""
358 _validate_custom_gate_source(module, f"{module_fqn or '<root>'}: LowPrecisionGroupedExperts")
359 GroupedExpertsModule.__init__(
360 self,
361 config=config,
362 module=module,
363 module_fqn=module_fqn,
364 context=context,
365 activation=activation,
366 activation_dtype=activation_dtype,
367 swiglu_limit=swiglu_limit,
368 )
369 self._init_low_precision_executor(
370 low_precision_mode="strategy" if strategy is not None else low_precision_mode,
371 module_fqn=module_fqn,
372 context=context,
373 strategy=strategy,
374 )
375
376
377class EPLowPrecisionGroupedExperts(_LowPrecisionExpertsMixin, EPGroupedExperts):
378 """EP>1 low-precision experts member reusing BF16 All-to-All and SharedExpert overlap."""
379
380 def __init__(
381 self,
382 *,
383 config: GroupedExpertsConfig | None = None,
384 module: nn.Module | None = None,
385 module_fqn: str = "",
386 context: Mapping[str, Any] | None = None,
387 overlap_shared_expert: bool = True,
388 activation_dtype: str = "input",
389 swiglu_limit: float | None = None,
390 low_precision_mode: str = "w8a8",
391 strategy: GroupedLinear | None = None,
392 ) -> None:
393 """Construct EP-capable parameters and bind the local low-precision compute executor."""
394 _validate_custom_gate_source(module, f"{module_fqn or '<root>'}: EPLowPrecisionGroupedExperts")
395 EPGroupedExperts.__init__(
396 self,
397 config=config,
398 module=module,
399 module_fqn=module_fqn,
400 context=context,
401 overlap_shared_expert=overlap_shared_expert,
402 activation_dtype=activation_dtype,
403 swiglu_limit=swiglu_limit,
404 )
405 self._init_low_precision_executor(
406 low_precision_mode="strategy" if strategy is not None else low_precision_mode,
407 module_fqn=module_fqn,
408 context=context,
409 strategy=strategy,
410 )
411
412
413class MoonEPLowPrecisionGroupedExperts(_LowPrecisionExpertsMixin, MoonEPGroupedExperts):
414 """MoonEP low-precision experts member reusing dynamic BF16 expert replicas and overlap."""
415
416 def __init__(
417 self,
418 *,
419 config: GroupedExpertsConfig | None = None,
420 module: nn.Module | None = None,
421 module_fqn: str = "",
422 context: Any = None,
423 moonep_replica_capacity: int | None = None,
424 overlap_shared_expert: bool = True,
425 activation_dtype: str = "input",
426 swiglu_limit: float | None = None,
427 low_precision_mode: str = "w8a8",
428 strategy: GroupedLinear | None = None,
429 ) -> None:
430 """Construct MoonEP-capable parameters and bind the local low-precision compute executor."""
431 _validate_custom_gate_source(module, f"{module_fqn or '<root>'}: MoonEPLowPrecisionGroupedExperts")
432 MoonEPGroupedExperts.__init__(
433 self,
434 config=config,
435 module=module,
436 module_fqn=module_fqn,
437 context=context,
438 moonep_replica_capacity=moonep_replica_capacity,
439 overlap_shared_expert=overlap_shared_expert,
440 activation_dtype=activation_dtype,
441 swiglu_limit=swiglu_limit,
442 )
443 self._init_low_precision_executor(
444 low_precision_mode="strategy" if strategy is not None else low_precision_mode,
445 module_fqn=module_fqn,
446 context=context,
447 strategy=strategy,
448 )
449
450
451def _make_family_member_builder(
452 target_cls: type[nn.Module], low_precision_mode: str,
453) -> Callable[..., nn.Module]:
454 """Create a signature-preserving ModuleFamily member constructor for one (topology, mode) pair."""
455 init_sig = inspect.signature(target_cls.__init__)
456 excluded = {"self", "low_precision_mode", "strategy"}
457 allowed_params = [param for name, param in init_sig.parameters.items() if name not in excluded]
458
459 def builder(**kwargs: Any) -> nn.Module:
460 return target_cls(low_precision_mode=low_precision_mode, **kwargs)
461
462 builder.__signature__ = inspect.Signature(parameters=allowed_params) # type: ignore[attr-defined]
463 builder.__name__ = f"build_{target_cls.__name__}_{low_precision_mode}"
464 builder.__qualname__ = builder.__name__
465 builder.__doc__ = f"Build {target_cls.__name__} bound to low-precision mode {low_precision_mode!r}."
466 return builder
467
468
469for _topology_prefix, _cls in (
470 ("local", LowPrecisionGroupedExperts),
471 ("ep", EPLowPrecisionGroupedExperts),
472 ("moonep", MoonEPLowPrecisionGroupedExperts),
473):
474 for _mode in _LOW_PRECISION_MODES:
475 _fn_name = f"build_{_topology_prefix}_{_mode}_experts"
476 globals()[_fn_name] = _make_family_member_builder(_cls, _mode)
477
478__all__ = [
479 "EPLowPrecisionGroupedExperts",
480 "LowPrecisionGroupedExperts",
481 "MoonEPLowPrecisionGroupedExperts",
482]