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"""Expert parameter construction and staged algorithm phases, independent of EP resources."""
16
17from __future__ import annotations
18
19import math
20import warnings
21from collections.abc import Callable, Mapping
22from dataclasses import dataclass
23from typing import Any, Literal
24
25import torch
26from torch import Tensor, nn
27from torch.nn import functional as F
28from transformers.activations import SiLUActivation
29
30from hyper_parallel.components.checkpoint.weight_conversion import Transpose, WeightConverter
31from hyper_parallel.components.functional.grouped_matmul import grouped_matmul
32from hyper_parallel.components.functional.swiglu import swiglu as npu_swiglu
33from hyper_parallel.components.functional.moe_token_permute import moe_token_permute
34from hyper_parallel.components.functional.moe_token_unpermute import moe_token_unpermute
35from hyper_parallel.components.modules.mlp import swiglu_activation
36from hyper_parallel.core.dtensor.dtensor import DTensor
37
38
39def _normalize_swiglu_limit(limit: Any) -> float | None:
40 """Validate a source/config clamp and normalize disabled values once at construction."""
41 if limit is None:
42 return None
43 if isinstance(limit, bool) or not isinstance(limit, (int, float)) or not math.isfinite(limit):
44 raise ValueError("swiglu_limit/limit must be None or a finite number")
45 if limit > 0:
46 return limit
47 warnings.warn(
48 f"swiglu_limit/limit={limit} <= 0 disables clamping; using unclamped SwiGLU.",
49 UserWarning, stacklevel=4,
50 )
51 return None
52
53
54@dataclass(frozen=True)
55class GroupedExpertsConfig:
56 """Bias-free SwiGLU dimensions, probability placement and model initialization.
57
58 Attributes:
59 num_experts: Global expert count, before any EP parameter sharding.
60 hidden_size: Input and output width.
61 intermediate_size: Width of each gate/up half.
62 routing_weight_mode: Apply final model-selected probabilities at this stage only.
63 init_method_std: Base std for normal initialization, matching Megatron's 0.02.
64 num_layers: Required global Transformer depth for FC2 scaling, before PP partitioning.
65 activation: Optional gate/up activation supplied by the model; defaults to SwiGLU.
66 top_k: Static routing width required by fused executors; optional for ordinary GMM.
67 swiglu_limit: Positive pre-SiLU clamp in FP32; None disables it, as do nonpositive values with a warning.
68 activation_dtype: SwiGLU precision when no clamp or custom activation is configured.
69 """
70
71 num_experts: int
72 hidden_size: int
73 intermediate_size: int
74 routing_weight_mode: Literal["output", "before_fc2"] = "before_fc2"
75 init_method_std: float = 0.02
76 num_layers: int | None = None
77 activation: Callable[[Tensor, Tensor], Tensor] | None = None
78 top_k: int | None = None
79 swiglu_limit: float | None = None
80 activation_dtype: Literal["input", "float32"] = "input"
81
82 def __post_init__(self) -> None:
83 if self.num_layers is None:
84 raise ValueError(
85 "num_layers is required for depth-scaled expert initialization; pass "
86 "GroupedExpertsConfig(num_layers=...) or context={'num_layers': ...} when adopting a module. "
87 "Use num_layers=1 explicitly for a standalone layer."
88 )
89 for name in ("num_experts", "hidden_size", "intermediate_size", "num_layers"):
90 value = getattr(self, name)
91 if not isinstance(value, int) or isinstance(value, bool) or value < 1:
92 raise ValueError(f"{name} must be a positive integer")
93 if self.routing_weight_mode not in ("output", "before_fc2"):
94 raise ValueError("routing_weight_mode must be output or before_fc2")
95 if self.activation_dtype not in ("input", "float32"):
96 raise ValueError("activation_dtype must be input or float32")
97 top_k_type = type(self.top_k)
98 if self.top_k is not None and (top_k_type is not int or not 1 <= self.top_k <= self.num_experts):
99 raise ValueError("top_k must be a positive integer no greater than num_experts")
100 object.__setattr__(self, "swiglu_limit", _normalize_swiglu_limit(self.swiglu_limit))
101 if self.activation is not None and self.swiglu_limit is not None:
102 raise ValueError("declare either a custom activation or swiglu_limit")
103
104
105_EXPERT_CONFIG_KEYS = {
106 "num_experts": ("num_experts", "num_local_experts", "n_routed_experts"),
107 "hidden_size": ("hidden_dim", "hidden_size"),
108 "intermediate_size": ("intermediate_dim", "moe_intermediate_size", "intermediate_size"),
109 "init_method_std": ("init_method_std", "initializer_range"),
110 "hidden_act": ("hidden_act", "hidden_activation", "mlp_hidden_act"),
111 "top_k": ("num_experts_per_tok", "top_k", "moe_topk"),
112 "swiglu_limit": ("swiglu_limit", "limit"),
113}
114_EXPERT_INPUT_KEYS = {
115 "top_k_index": "topk_ids", "topk_indices": "topk_ids", "selected_experts": "topk_ids",
116 "router_indices": "topk_ids", "topk_idx": "topk_ids",
117 "top_k_weights": "topk_weights", "routing_weights": "topk_weights", "topk_weight": "topk_weights",
118}
119
120
121def _match_expert_config_value(configs: tuple[Any, ...], name: str, default: Any = None) -> Any:
122 """Read recognized source aliases in nearest-config order without copying config objects."""
123 for config in configs:
124 for key in _EXPERT_CONFIG_KEYS[name]:
125 value = config.get(key) if isinstance(config, Mapping) else getattr(config, key, None)
126 if value is not None:
127 return value
128 return default
129
130
131def match_grouped_experts_inputs(
132 topk_ids: Tensor | None, topk_weights: Tensor | None, kwargs: Mapping[str, Tensor],
133) -> tuple[Tensor, Tensor]:
134 """Normalize recognized top-k keyword aliases without changing routing semantics.
135
136 Args:
137 topk_ids: Expert IDs passed positionally or under the canonical name.
138 topk_weights: Final probabilities passed positionally or under the canonical name.
139 kwargs: Alternate ID/probability names from supported source forward contracts.
140
141 Returns:
142 Expert IDs and final probabilities; both retain their original Tensor identity.
143
144 Raises:
145 TypeError: An input is missing, duplicated or uses an unknown keyword.
146 """
147 values = {"topk_ids": topk_ids, "topk_weights": topk_weights}
148 seen = set()
149 for key, value in kwargs.items():
150 name = _EXPERT_INPUT_KEYS.get(key)
151 if name is None:
152 raise TypeError(f"unexpected grouped expert input keyword {key!r}")
153 if values[name] is not None or name in seen:
154 raise TypeError(f"multiple values for grouped expert input {name!r}")
155 values[name] = value
156 seen.add(name)
157 if any(value is None for value in values.values()):
158 raise TypeError("grouped experts require both top-k expert IDs and routing weights")
159 return values["topk_ids"], values["topk_weights"]
160
161
162def _packed_parameters(module, module_fqn, configs, activation):
163 """Validate packed source parameters and their activation contract."""
164 parameters = dict(module.named_parameters())
165 if set(parameters) != {"gate_up_proj", "down_proj"} or list(module.named_buffers()):
166 raise ValueError(f"{module_fqn}: expected canonical experts or two bias-free packed projections")
167 if any(weight.ndim != 3 or isinstance(weight, DTensor) or weight.grad is not None
168 for weight in parameters.values()):
169 raise ValueError(f"{module_fqn}: packed experts must be converted before sharding and backward")
170 act_fn = getattr(module, "act_fn", None)
171 hidden_act = _match_expert_config_value(configs, "hidden_act", "silu")
172 if activation is None and (hidden_act != "silu" or (
173 act_fn is not None and type(act_fn) not in (nn.SiLU, SiLUActivation) and act_fn is not F.silu)):
174 raise ValueError(f"{module_fqn}: supply the activation for packed experts with non-SwiGLU math")
175 return parameters
176
177
178def _packed_dimensions(module, module_fqn, parameters, configs):
179 """Infer expert dimensions and validate the source projection layouts."""
180 gate_up, down = parameters["gate_up_proj"], parameters["down_proj"]
181 experts, hidden, width = down.shape
182 sources = (module, *configs)
183 source_dimensions = (
184 _match_expert_config_value(sources, "num_experts", experts),
185 _match_expert_config_value(sources, "hidden_size", hidden),
186 _match_expert_config_value(sources, "intermediate_size", width),
187 )
188 if source_dimensions != (experts, hidden, width) or gate_up.shape != (experts, 2 * width, hidden):
189 raise ValueError(f"{module_fqn}: expected packed gate_up_proj [E,2I,H] and down_proj [E,H,I]")
190 return experts, hidden, width
191
192
193class GroupedExpertsModule(nn.Module):
194 """Internal family member using the existing NPU grouped-GEMM autograd kernel.
195
196 Local transport is identity. EP members reuse this math over owner-local slots;
197 router, shared experts, auxiliary loss and model masks remain outside this module.
198 """
199
200 shared_expert_overlap_supported = True
201
202 def __init__(
203 self, *, config: GroupedExpertsConfig | None = None, module: nn.Module | None = None,
204 module_fqn: str = "", context: Mapping[str, Any] | None = None,
205 activation: Callable[[Tensor, Tensor], Tensor] | None = None,
206 activation_dtype: str = "input", swiglu_limit: float | None = None,
207 ) -> None:
208 """Create global parameters or adopt an unsharded expert source.
209
210 Args:
211 config: Global algorithm facts; device/dtype follow the caller's Torch context.
212 module: Existing family member or compatible packed expert source.
213 module_fqn: Source module path used in diagnostics.
214 context: Job facts and source/ancestor configuration; the replacement builder
215 supplies global num_layers for FC2 initialization. Standalone source adoption
216 requires an explicit context['num_layers'] when the source has no canonical config.
217 activation: Model-owned gate/up activation for a packed source.
218 activation_dtype: SwiGLU precision when adopting a packed source without a canonical config.
219 swiglu_limit: Explicit clamp for a packed source without a canonical config; None reads the source.
220
221 Note:
222 Fresh construction keeps nn.Module's default training=True. Source
223 construction explicitly preserves module.training, including eval mode.
224 """
225 super().__init__()
226 if (config is None) == (module is None):
227 raise ValueError("provide exactly one of config or module")
228 if module is not None:
229 source_config = getattr(module, "config", None)
230 if not isinstance(source_config, GroupedExpertsConfig):
231 configs = tuple((context or {}).get("module_configs", ())) or (source_config,)
232 parameters = _packed_parameters(module, module_fqn, configs, activation)
233 experts, hidden, intermediate = _packed_dimensions(module, module_fqn, parameters, configs)
234 if swiglu_limit is None and activation is None:
235 swiglu_limit = _match_expert_config_value((module, *configs), "swiglu_limit")
236 source_config = GroupedExpertsConfig(
237 experts, hidden, intermediate, routing_weight_mode="output", activation=activation,
238 activation_dtype=activation_dtype,
239 num_layers=(context or {}).get("num_layers"),
240 init_method_std=_match_expert_config_value(configs, "init_method_std", 0.02),
241 top_k=_match_expert_config_value((module, *configs), "top_k"),
242 swiglu_limit=swiglu_limit,
243 )
244 self.config = source_config
245 self.gate_up_proj = module.gate_up_proj
246 self.down_proj = module.down_proj
247 self.training = module.training
248 for name, child in module.named_children():
249 self.add_module(name, child)
250 else:
251 if not isinstance(config, GroupedExpertsConfig):
252 raise ValueError("config must be GroupedExpertsConfig")
253 self.config = config
254 self.gate_up_proj = nn.Parameter(torch.empty(config.num_experts, 2 * config.intermediate_size,
255 config.hidden_size))
256 self.down_proj = nn.Parameter(torch.empty(config.num_experts, config.hidden_size,
257 config.intermediate_size))
258 self.reset_parameters()
259
260 @property
261 def limit(self) -> float:
262 """Expose the resolved source clamp to model-owned expert composition."""
263 return self.config.swiglu_limit or 0.0
264
265 def apply_activation(self, gate: Tensor, up: Tensor, dtype: torch.dtype) -> Tensor:
266 """Apply the custom activation or configured SwiGLU to the first projection."""
267 if self.config.activation is not None:
268 return self.config.activation(gate, up).to(dtype)
269 precision = "float32" if self.config.swiglu_limit is not None else self.config.activation_dtype
270 return swiglu_activation(gate, up, activation_dtype=precision, limit=self.config.swiglu_limit or 0.0).to(dtype)
271
272 def reset_parameters(self) -> None:
273 """Initialize both projections normally, using Megatron's depth scaling for FC2."""
274 nn.init.normal_(self.gate_up_proj, mean=0.0, std=self.config.init_method_std)
275 output_std = self.config.init_method_std / math.sqrt(2.0 * self.config.num_layers)
276 nn.init.normal_(self.down_proj, mean=0.0, std=output_std)
277
278 def make_transforms(self) -> list[WeightConverter]:
279 """Normalize HF expert projections to ``[E,2I,H]`` and ``[E,H,I]``.
280
281 Model-owned HF mappings first merge individual gate/up/down experts
282 (including DeepSeek's w1/w3/w2 names) and normalize legacy Qwen-VL
283 layouts. Replacement conversion preserves that canonical layout and
284 transposes input-major packed projections only when shapes differ.
285 Already-canonical weights retain their values and storage.
286
287 Returns:
288 Converters for the packed projections; the builder assigns their module scope.
289 """
290 return [
291 WeightConverter(
292 source_patterns=name, target_patterns=name,
293 operations=[Transpose(dim0=-2, dim1=-1, check_dims=True)],
294 )
295 for name in ("gate_up_proj", "down_proj")
296 ]
297
298 def validate_and_flatten_inputs(self, hidden_states: Tensor, topk_ids: Tensor, topk_weights: Tensor) -> Tensor:
299 """Validate shapes/devices/dtypes and flatten tokens without detaching router weights.
300
301 IDs must be in [0,E); fixed-size slot counting rejects out-of-range/drop IDs
302 on the input device. Zero probability still represents an executed slot.
303
304 Args:
305 hidden_states: Original floating-point tokens [...,H].
306 topk_ids: Global expert IDs [T,K].
307 topk_weights: Final differentiable model probabilities [T,K].
308
309 Returns:
310 Flattened source tokens [T,H]; routes remain in the caller's local variables.
311 """
312 if hidden_states.ndim < 1 or hidden_states.shape[-1] != self.config.hidden_size:
313 raise ValueError("hidden_states must have shape [..., hidden_size]")
314 hidden = hidden_states.reshape(-1, self.config.hidden_size)
315 if topk_ids.ndim != 2 or topk_ids.shape[0] != hidden.shape[0] or topk_ids.shape[1] < 1:
316 raise ValueError("topk_ids must have shape [flattened_tokens, positive_top_k]")
317 if topk_weights.shape != topk_ids.shape:
318 raise ValueError("topk_weights must have the same [T,K] shape as topk_ids")
319 if topk_ids.dtype not in (torch.int32, torch.int64):
320 raise ValueError("topk_ids must have integer int32/int64 dtype")
321 if not hidden_states.is_floating_point() or not topk_weights.is_floating_point():
322 raise ValueError("hidden_states and topk_weights must have floating-point dtype")
323 if hidden.device != topk_ids.device or hidden.device != topk_weights.device:
324 raise ValueError("tokens, expert IDs and routing weights must be on the same device")
325 return hidden
326
327 def permute(
328 self, hidden_states: Tensor, topk_ids: Tensor, topk_weights: Tensor,
329 ) -> tuple[Tensor, Tensor, Tensor, Tensor | None, Tensor]:
330 """Use fused NPU token permutation and align slot metadata with its inverse map.
331
332 Args:
333 hidden_states: Validated source tokens [T,H].
334 topk_ids: Global selected expert IDs [T,K].
335 topk_weights: Final differentiable routing weights [T,K].
336
337 Returns:
338 Expert-major hidden [S,H], IDs [S], counts [E], optional weights [S],
339 and NPU inverse indices [S], where S=T*K.
340 """
341 ids = topk_ids.reshape(-1).to(torch.int64)
342 # Fixed-size counting also rejects invalid IDs without host scalar reads.
343 counts = ids.new_zeros(self.config.num_experts).scatter_add_(0, ids, torch.ones_like(ids))
344 if ids.numel():
345 hidden, unpermute_indices = moe_token_permute(
346 hidden_states.contiguous(), topk_ids.to(torch.int32).contiguous(),
347 )
348 else:
349 hidden, unpermute_indices = hidden_states, ids.to(torch.int32)
350 # The kernel maps original route slots to permuted rows; metadata needs the inverse.
351 order = torch.empty_like(unpermute_indices, dtype=torch.int64)
352 order.scatter_(0, unpermute_indices.to(torch.int64), torch.arange(ids.numel(), device=ids.device))
353 ids = ids[order]
354 weights = topk_weights.reshape(-1)[order] if self.config.routing_weight_mode == "before_fc2" else None
355 return hidden, ids, counts, weights, unpermute_indices
356
357 def dispatch(
358 self, hidden_states: Tensor, expert_ids: Tensor, tokens_per_expert: Tensor,
359 routing_weights: Tensor | None = None,
360 ) -> tuple[Tensor, Tensor, Tensor | None, list[int] | None, list[int] | None, Tensor | None]:
361 """Keep source slots and counts for local execution.
362
363 Args:
364 hidden_states: Source expert-major activations [S,H].
365 expert_ids: Global expert IDs [S], unused by local transport.
366 tokens_per_expert: Source expert counts [E].
367 routing_weights: Optional before_fc2 probabilities [S].
368
369 Returns:
370 Activations, counts, probabilities, then three None values for absent EP transport.
371 """
372 del expert_ids
373 return hidden_states, tokens_per_expert, routing_weights, None, None, None
374
375 def compute_experts(
376 self, hidden_states: Tensor, tokens_per_expert: Tensor, gate_up_proj: Tensor, down_proj: Tensor,
377 routing_weights: Tensor | None = None,
378 ) -> Tensor:
379 """Apply shared SwiGLU mathematics to an explicitly supplied compute table.
380
381 Args:
382 hidden_states: Expert-major activations [R,H].
383 tokens_per_expert: Counts [C] indexing the supplied weight rows.
384 gate_up_proj: Materialized FC1 weights [C,2I,H], including any per-call replicas.
385 down_proj: Materialized FC2 weights [C,H,I] with matching row order.
386 routing_weights: Optional differentiable before_fc2 probabilities [R].
387
388 Returns:
389 One hidden-size output per slot; transport and replica gradient return are external.
390 """
391 gate_up, down = gate_up_proj, down_proj
392 # GMM consumes local tensors; storage unshard/prefetch is owned by FSDP hooks.
393 gate_up = gate_up.to_local() if isinstance(gate_up, DTensor) else gate_up
394 down = down.to_local() if isinstance(down, DTensor) else down
395 if (gate_up.ndim != 3 or gate_up.shape[0] < 1
396 or gate_up.shape[1:] != (2 * self.config.intermediate_size, self.config.hidden_size)
397 or down.shape != (gate_up.shape[0], self.config.hidden_size, self.config.intermediate_size)):
398 raise ValueError("expert compute requires complete [C,2I,H] and [C,H,I] matrices; ETP is unsupported")
399 if tokens_per_expert.shape != (gate_up.shape[0],):
400 raise ValueError("tokens_per_expert must describe the current expert compute table")
401 hidden = hidden_states
402 group_list = tokens_per_expert.to(device=hidden.device, dtype=torch.int64).cumsum(0)
403 # The kernel uses input-major projections while checkpoints store linear weights.
404 gate_up, down = gate_up.transpose(-2, -1), down.transpose(-2, -1)
405 # Empty ranks avoid unsupported empty GMM calls while retaining gradients to both weights.
406 has_tokens = (
407 torch.compiler.is_compiling()
408 or not isinstance(hidden.shape[0], int)
409 or hidden.shape[0] != 0
410 )
411 fc1 = (grouped_matmul(hidden, gate_up, group_list=group_list) # pylint: disable=not-callable
412 if has_tokens else hidden @ gate_up[0])
413 if (self.config.swiglu_limit is not None or self.config.activation is not None
414 or self.config.activation_dtype != "input"):
415 activated = self.apply_activation(*fc1.chunk(2, dim=-1), hidden.dtype)
416 else:
417 activated = npu_swiglu(fc1) # pylint: disable=not-callable
418 if self.config.routing_weight_mode == "before_fc2":
419 if routing_weights is None:
420 raise ValueError("before_fc2 requires differentiable slot routing weights")
421 activated = (activated * routing_weights.unsqueeze(-1)).to(activated.dtype)
422 return (grouped_matmul(activated, down, group_list=group_list) # pylint: disable=not-callable
423 if has_tokens else activated @ down[0])
424
425 def combine(
426 self, values: Tensor, send_splits: list[int] | None, recv_splits: list[int] | None, recv_inverse: Tensor | None,
427 ) -> Tensor:
428 """Keep the same output slots for local execution.
429
430 Args:
431 values: Computed expert outputs in slot order.
432 send_splits: Unused local transport argument.
433 recv_splits: Unused local transport argument.
434 recv_inverse: Unused local transport argument.
435
436 Returns:
437 The original slot outputs [S,H].
438 """
439 del send_splits, recv_splits, recv_inverse
440 return values
441
442 def unpermute(
443 self, values: Tensor, unpermute_indices: Tensor, topk_weights: Tensor, output_shape: tuple[int, ...],
444 ) -> Tensor:
445 """Use fused NPU unpermutation/top-k sum, applying output probabilities once.
446
447 Args:
448 values: Outputs restored to source slot order by combine.
449 unpermute_indices: This call's inverse NPU mapping [S].
450 topk_weights: Original token/top-k routing weights [T,K].
451 output_shape: Original hidden-state shape [...,H].
452
453 Returns:
454 Top-k combined output in the original token order and shape [...,H].
455 """
456 if values.shape != (unpermute_indices.numel(), self.config.hidden_size):
457 raise ValueError("combine must return one hidden-size output per source slot")
458 if not values.shape[0]:
459 if self.config.routing_weight_mode == "output":
460 values = values * topk_weights.reshape(-1, 1)
461 return values.reshape(output_shape)
462 # None implies top-k=1 in the kernel; ones retain top-k summation without reweighting FC2 output.
463 probs = topk_weights if self.config.routing_weight_mode == "output" else torch.ones_like(topk_weights)
464 output = moe_token_unpermute(
465 values.contiguous(), unpermute_indices, probs.contiguous(),
466 )
467 return output.to(values.dtype).reshape(output_shape)
468
469 def forward(
470 self, hidden_states: Tensor, topk_ids: Tensor | None = None, topk_weights: Tensor | None = None,
471 **kwargs: Tensor,
472 ) -> Tensor:
473 """Consume model-selected routes; router, shared experts and aux loss stay with MoE.
474
475 Args:
476 hidden_states: Source tokens [...,H].
477 topk_ids: Global already-selected expert IDs [T,K].
478 topk_weights: Final differentiable routing weights [T,K].
479 **kwargs: Recognized source aliases, including top_k_index/top_k_weights.
480
481 Returns:
482 Routed output [...,H] in the source token order.
483 """
484 topk_ids, topk_weights = match_grouped_experts_inputs(topk_ids, topk_weights, kwargs)
485 output_shape = tuple(hidden_states.shape)
486 hidden_states = self.validate_and_flatten_inputs(hidden_states, topk_ids, topk_weights)
487 hidden, ids, counts, weights, unpermute_indices = self.permute(hidden_states, topk_ids, topk_weights)
488 hidden, counts, weights, send_splits, recv_splits, recv_inverse = self.dispatch(
489 hidden, ids, counts, weights,
490 )
491 values = self.compute_experts(hidden, counts, self.gate_up_proj, self.down_proj, weights)
492 values = self.combine(values, send_splits, recv_splits, recv_inverse)
493 return self.unpermute(values, unpermute_indices, topk_weights, output_shape)