Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / moe / router.py: 77%
424 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
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"""Gate and score-corrected grouped Top-K router module families."""
16from __future__ import annotations
18from collections.abc import Mapping
19from functools import lru_cache
20from math import isfinite, prod, sqrt
21from typing import Any
23import torch
24from torch import nn
25from torch.nn import functional as F
27from hyper_parallel.components.checkpoint.weight_conversion import ConversionOps, WeightConverter, WeightRenaming
28from hyper_parallel.components.losses.aux_loss import aux_loss_auto_scale, sequence_load_balancing_loss
29from hyper_parallel.components.modules.family import SelectorSpec, VariantRule
30from hyper_parallel.components.modules.module_family import ModuleFamily, build_family, register_module_family
31from hyper_parallel.components.modules.moe.moe_utils import (
32 accumulate_router_load, local_router_metadata, router_sharding,
33 update_router_bias, validate_router_layout,
34)
35from hyper_parallel.core.dtensor.placement_types import Replicate, Shard
36from hyper_parallel.distributed.module_binding import ParallelBinding, ParallelModuleSpec
37from hyper_parallel.distributed.recipe_spec import ModuleShardingSpec
38from hyper_parallel.models.materialization import register_rebuildable_buffer
39from hyper_parallel.models.replacement import module_replacement
42def _setting(sources: tuple, names: tuple[str, ...], default: Any) -> Any:
43 for source in sources:
44 for name in names:
45 value = source.get(name) if isinstance(source, Mapping) else getattr(source, name, None)
46 if value is not None:
47 return value
48 return default
51class _InitialRouterBias(ConversionOps):
52 """Derive training-only correction bias when importing a bias-free HF router."""
54 def __init__(self, reverse: bool = False) -> None:
55 self.reverse = reverse
57 def convert(self, input_dict: dict[str, Any], source_patterns: list[str],
58 target_patterns: list[str], **kwargs: Any) -> dict[str, torch.Tensor]:
59 """Preserve the projection and initialize only newly introduced FP32 bias.
61 Args:
62 input_dict: Native projection on import, family projection/bias on export.
63 source_patterns: Collected source keys in the router scope.
64 target_patterns: Projection key and, on import, correction-bias key.
65 **kwargs: Additional checkpoint-loader context, unused.
67 Returns:
68 Unchanged projection plus zero FP32 bias on import; projection on HF export.
69 """
70 del kwargs
71 weight = input_dict[source_patterns[0]]
72 weight = weight[0] if isinstance(weight, list) else weight
73 result = {target_patterns[0]: weight}
74 if not self.reverse:
75 result[target_patterns[1]] = torch.zeros(weight.shape[0], device=weight.device, dtype=torch.float32)
76 return result
78 @property
79 def reverse_op(self) -> ConversionOps:
80 """Exclude derived correction state only when exporting a native HF checkpoint."""
81 return _InitialRouterBias(reverse=not self.reverse)
84def _router_transforms(module: nn.Module, projection: str) -> list[WeightRenaming | WeightConverter]:
85 """Keep native state and derive correction bias only when it has no source key."""
86 parameters = dict(module.named_parameters())
87 if "bias" in parameters and not module.source_has_correction_bias:
88 return [WeightConverter(source_patterns=projection, target_patterns=[projection, "bias"],
89 operations=[_InitialRouterBias()]),
90 *(WeightRenaming(source_patterns=name, target_patterns=name)
91 for name in parameters if name not in (projection, "bias"))]
92 return [WeightRenaming(source_patterns=name, target_patterns=name) for name in parameters]
95def routing_scores(logits: torch.Tensor, scoring_func: str) -> torch.Tensor:
96 """Apply nonnegative expert scoring without correction bias.
98 Args:
99 logits: Projection outputs ending in the expert dimension.
100 scoring_func: sqrtsoftplus, softmax or sigmoid.
101 """
102 if scoring_func == "sqrtsoftplus":
103 return F.softplus(logits).sqrt() # pylint: disable=not-callable
104 if scoring_func == "softmax":
105 return logits.softmax(dim=-1)
106 if scoring_func == "sigmoid":
107 return logits.sigmoid()
108 raise ValueError(f"unsupported router scoring_func: {scoring_func!r}")
111def select_topk_scores(scores: torch.Tensor, *, top_k: int, correction_bias: torch.Tensor | None = None,
112 routed_scaling_factor: float = 1.0, normalize_topk: bool = True,
113 sorted_indices: bool = False) -> tuple[torch.Tensor, torch.Tensor]:
114 """Select with correction bias, then gather unbiased weights and optionally normalize.
116 Args:
117 scores: Floating unbiased expert scores [tokens, experts].
118 top_k: Selected experts per token.
119 correction_bias: Optional selection-only [experts] or [tokens, experts] bias.
120 routed_scaling_factor: Multiplier applied to selected weights.
121 normalize_topk: Normalize selected weights to sum to one before scaling.
122 sorted_indices: Sort selected experts by selection score.
123 """
124 if scores.ndim != 2 or not scores.is_floating_point():
125 raise ValueError("scores must be a floating [tokens, experts] tensor")
126 if isinstance(top_k, bool) or not isinstance(top_k, int) or not 1 <= top_k <= scores.shape[-1]:
127 raise ValueError("top_k must be an integer in [1, num_experts]")
128 if (isinstance(routed_scaling_factor, bool) or not isinstance(routed_scaling_factor, (int, float))
129 or not isfinite(routed_scaling_factor)):
130 raise ValueError("routed_scaling_factor must be finite")
131 if not all((isinstance(normalize_topk, bool), isinstance(sorted_indices, bool))):
132 raise TypeError("normalize_topk and sorted_indices must be bool")
133 selection = scores
134 if correction_bias is not None:
135 if (correction_bias.device != scores.device or not correction_bias.is_floating_point()
136 or tuple(correction_bias.shape) not in (
137 (scores.shape[-1],), (1, scores.shape[-1]), tuple(scores.shape))):
138 raise ValueError("correction_bias must share the device and broadcast as [experts] or [tokens, experts]")
139 selection = scores + correction_bias.float()
140 indices = selection.topk(top_k, dim=-1, sorted=sorted_indices).indices
141 weights = scores.gather(1, indices)
142 if normalize_topk:
143 weights = weights / (weights.sum(dim=-1, keepdim=True) + 1e-20)
144 return weights * routed_scaling_factor, indices
147def balanced_expert_indices(indices: torch.Tensor, num_experts: int, ep_size: int = 1) -> torch.Tensor:
148 """Replace destinations with the existing deterministic owner-major routing pattern.
150 Args:
151 indices: Learned integer expert IDs [tokens, top_k]; only shape/device/dtype are used.
152 num_experts: Global expert count, divisible by the physical EP owner count.
153 ep_size: Physical expert owners, including the TP extension of EP.
155 Returns:
156 Balanced global expert IDs with the same shape, dtype and device.
157 Learned routing weights are deliberately left unchanged by callers.
158 """
159 if indices.ndim != 2 or indices.dtype not in (torch.int32, torch.int64):
160 raise ValueError("indices must be integer [tokens, top_k]")
161 if any(isinstance(value, bool) or not isinstance(value, int) or value < 1
162 for value in (num_experts, ep_size)) or num_experts % ep_size:
163 raise ValueError("num_experts must be positive and divisible by the positive EP owner count")
164 if not 1 <= indices.shape[1] <= num_experts:
165 raise ValueError("top_k must be in [1, num_experts]")
166 slots = torch.arange(indices.numel(), device=indices.device)
167 local_experts = num_experts // ep_size
168 fixed = (slots % ep_size) * local_experts + (slots // ep_size) % local_experts
169 return fixed.reshape_as(indices).to(indices.dtype)
172class GateModule(nn.Module):
173 """Own common gate configuration, projection state, initialization and routing math.
175 Projection uses FP32 operands under the enclosing Torch autocast policy.
176 The same module owns optional balancing state and parallel statistics;
177 fused execution belongs to the MegaGate variant.
178 Auxiliary loss uses unbiased TopK IDs unless fixed routing is enabled;
179 bias-update load accounting always follows the actual dispatch IDs.
180 """
182 fp32_parameter_names = ("bias", "bias_vl")
184 def __init__(self, *, config: Any = None, module: nn.Module | None = None,
185 context: Mapping[str, Any] | None = None) -> None:
186 """Construct a gate or retain a public member and its optional training state."""
187 super().__init__()
188 if (config is None) == (module is None):
189 raise ValueError("provide exactly one of config or module")
190 if module is not None:
191 self._validate_source(module)
192 source = config if config is not None else module
193 self.source_has_correction_bias = module is not None and getattr(module, "bias", None) is not None
194 self._set_routing_settings(source)
195 if module is None:
196 self.weight = nn.Parameter(torch.empty(self.num_experts, self.hidden_size))
197 # Derived gates create their correction state after the common projection.
198 GateModule.reset_parameters(self)
199 else:
200 weight = getattr(module, "weight", None)
201 if (not isinstance(weight, nn.Parameter) or not weight.is_floating_point()
202 or tuple(weight.shape) != (self.num_experts, self.hidden_size)):
203 raise ValueError("source weight must be a floating Parameter [num_experts, hidden_size]")
204 self.weight = weight
205 self.train(module.training)
206 self._init_router_training(source, context, self.weight, module)
207 if self.source_has_correction_bias:
208 self._initialize_correction_state(module, getattr(module, "bias_vl", None) is not None)
210 def _initialize_correction_state(self, module: nn.Module | None, vision_enabled: bool) -> None:
211 """Initialize or adopt text and optional image correction biases."""
212 vision_enabled = vision_enabled or getattr(self, "bias_vl", None) is not None
213 for name in ("bias", "bias_vl"):
214 if name == "bias_vl" and not vision_enabled:
215 self.register_parameter(name, None)
216 continue
217 existing = getattr(self, name, None)
218 if existing is not None:
219 continue
220 if module is None:
221 parameter = nn.Parameter(torch.zeros(self.num_experts, dtype=torch.float32, device=self.weight.device))
222 else:
223 parameter = getattr(module, name, None)
224 if (not isinstance(parameter, nn.Parameter) or tuple(parameter.shape) != (self.num_experts,)
225 or parameter.device != self.weight.device or parameter.dtype != torch.float32):
226 raise ValueError(f"source {name} must be an FP32 Parameter [num_experts] on the weight device")
227 setattr(self, name, parameter)
229 def _set_routing_settings(self, source: Any) -> None:
230 """Validate dimensions, scoring, TopK normalization and initialization policy."""
231 for name in ("hidden_size", "num_experts", "top_k"):
232 value = getattr(source, name)
233 if isinstance(value, bool) or not isinstance(value, int) or value < 1:
234 raise ValueError(f"{name} must be a positive integer")
235 setattr(self, name, value)
236 if self.top_k > self.num_experts:
237 raise ValueError("top_k cannot exceed num_experts")
238 self.scoring_func = source.scoring_func
239 if self.scoring_func not in ("sqrtsoftplus", "softmax", "sigmoid"):
240 raise ValueError("unsupported scoring_func")
241 self.routed_scaling_factor = source.routed_scaling_factor
242 if (isinstance(self.routed_scaling_factor, bool)
243 or not isinstance(self.routed_scaling_factor, (int, float))
244 or not isfinite(self.routed_scaling_factor)):
245 raise ValueError("routed_scaling_factor must be finite")
246 self.normalize_topk = getattr(source, "normalize_topk", self.top_k > 1)
247 self.sorted_indices = getattr(source, "sorted_indices", False)
248 if not all((isinstance(self.normalize_topk, bool), isinstance(self.sorted_indices, bool))):
249 raise TypeError("normalize_topk and sorted_indices must be bool")
250 self.initializer_range = source.initializer_range
251 if (isinstance(self.initializer_range, bool) or not isinstance(self.initializer_range, (int, float))
252 or not isfinite(self.initializer_range) or self.initializer_range < 0):
253 raise ValueError("initializer_range must be finite and nonnegative")
255 @classmethod
256 def _validate_source(cls, module: nn.Module) -> None:
257 """Reject source routers whose state cannot be preserved by the shared Gate."""
258 if module.__class__ is cls:
259 return
260 required = ("hidden_size", "num_experts", "top_k", "scoring_func",
261 "routed_scaling_factor", "initializer_range")
262 parameters = set(dict(module.named_parameters()))
263 buffers = set(dict(module.named_buffers()))
264 if (not all(hasattr(module, name) for name in required)
265 or not {"weight", "bias"}.issubset(parameters)
266 or parameters - {"weight", "bias", "bias_vl"}
267 or buffers - {"tokens_per_expert"} or any(module.children())):
268 raise TypeError("model routers must expose compatible routing settings, weight/bias and optional bias_vl")
270 def reset_parameters(self) -> None:
271 """Initialize the projection after direct/meta construction."""
272 nn.init.normal_(self.weight, std=self.initializer_range)
273 bias = getattr(self, "bias", None)
274 if bias is not None:
275 nn.init.zeros_(bias)
276 if getattr(self, "bias_vl", None) is not None:
277 nn.init.zeros_(self.bias_vl)
279 def make_transforms(self) -> list[WeightRenaming | WeightConverter]:
280 """Map native projection/state and derive optional training-only correction bias.
282 Returns:
283 Native state mappings and, when required, a zero FP32 bias initializer.
284 """
285 return _router_transforms(self, "weight")
287 def forward(self, hidden_states: torch.Tensor,
288 correction_bias: torch.Tensor | None = None, token_mask: torch.Tensor | None = None,
289 sequence_partition_groups: tuple | None = None,
290 sequence_ids: torch.Tensor | None = None, num_sequences: int | None = None,
291 *, image_mask: torch.Tensor | None = None) -> tuple[torch.Tensor, ...]:
292 """Return logits [T,E], learned weights [T,K] and actual dispatch IDs [T,K].
294 Args:
295 hidden_states: Source activations [..., hidden_size].
296 correction_bias: Optional additional selection-only expert bias.
297 image_mask: Boolean local token metadata selecting the image correction bias.
298 token_mask: Boolean token metadata excluding padding from balancing statistics.
299 sequence_partition_groups: Override existing token-partition groups for aux-loss.
300 sequence_ids: Int64 logical sample IDs for packed/partitioned sequences.
301 num_sequences: Number of logical samples when sequence_ids is provided.
302 """
303 if hidden_states.ndim < 2 or hidden_states.shape[-1] != self.hidden_size:
304 raise ValueError("hidden_states must end in hidden_size and include a token dimension")
305 token_mask, sequence_ids = self._metadata(hidden_states, token_mask, sequence_ids)
306 image_mask = local_router_metadata(image_mask, hidden_states, self.router_tp_mesh)
307 own_bias = getattr(self, "bias", None)
308 if image_mask is not None:
309 if getattr(self, "bias_vl", None) is None:
310 raise ValueError("image_mask requires a vision correction bias")
311 if (image_mask.shape != hidden_states.shape[:-1] or image_mask.dtype != torch.bool
312 or image_mask.device != hidden_states.device):
313 raise ValueError("image_mask must be BOOL [batch, sequence] on the hidden_states device")
314 own_bias = torch.where(image_mask.reshape(-1, 1), self.bias_vl, own_bias)
315 if own_bias is not None:
316 correction_bias = own_bias if correction_bias is None else own_bias + correction_bias
317 logits = F.linear( # pylint: disable=not-callable
318 hidden_states.reshape(-1, self.hidden_size).float(), self.weight.float())
319 scores = routing_scores(logits, self.scoring_func)
320 weights, indices = select_topk_scores(
321 scores, top_k=self.top_k, correction_bias=correction_bias,
322 routed_scaling_factor=self.routed_scaling_factor,
323 normalize_topk=self.normalize_topk, sorted_indices=self.sorted_indices)
324 weights, indices = self._finish_routing(
325 hidden_states, logits, weights, indices, token_mask, sequence_ids,
326 num_sequences, sequence_partition_groups, scores=scores, image_mask=image_mask,
327 )
328 return logits, weights, indices
330 def _finish_routing(self, hidden: torch.Tensor, logits: torch.Tensor, weights: torch.Tensor,
331 indices: torch.Tensor, token_mask: torch.Tensor | None,
332 sequence_ids: torch.Tensor | None, num_sequences: int | None,
333 sequence_partition_groups: tuple | None, *, scores: torch.Tensor | None = None,
334 image_mask: torch.Tensor | None = None) -> tuple[torch.Tensor, torch.Tensor]:
335 """Apply training to the final expert IDs and their learned weights."""
336 if self.fix_router:
337 indices = balanced_expert_indices(indices, self.num_experts, self.router_ep_size)
338 if scores is None:
339 scores = routing_scores(logits, self.scoring_func) if self.training and self.aux_loss_coeff else logits
340 weights = self._apply_router_training(
341 hidden, scores, weights, indices, token_mask, sequence_ids, num_sequences, sequence_partition_groups,
342 image_mask=image_mask,
343 )
344 return weights, indices
346 def _init_router_training(self, source: Any, context: Mapping[str, Any] | None,
347 weight: nn.Parameter, module: nn.Module | None = None) -> None:
348 """Resolve router options and install state for backward accounting."""
349 sources = (*tuple((context or {}).get("module_configs", ())), source)
350 self.fix_router = _setting(
351 sources, ("moe_router_force_load_balancing", "fix_router", "router_fix_router"), False,
352 )
353 if not isinstance(self.fix_router, bool):
354 raise ValueError("moe_router_force_load_balancing must be bool")
355 for name, aliases in (
356 ("aux_loss_coeff", (
357 "moe_aux_loss_coeff", "aux_loss_coeff", "router_aux_loss_coeff",
358 )),
359 ("expert_bias_update_rate", (
360 "moe_router_bias_update_rate", "expert_bias_update_rate", "router_bias_update_rate",
361 ))):
362 value = _setting(sources, aliases, 0.0)
363 if isinstance(value, bool) or not isinstance(value, (int, float)) or not isfinite(value) or value < 0:
364 raise ValueError(f"{aliases[0]} must be finite and nonnegative")
365 setattr(self, name, float(value))
366 self.enable_expert_bias = self.expert_bias_update_rate > 0
367 self.last_aux_loss = None
368 self.router_ep_size = 1
369 self.router_tp_mesh = None
370 self.sequence_partition_groups = ()
371 self.expert_bias_update_groups = None
372 counts = getattr(module, "tokens_per_expert", None)
373 if module is not None and counts is None and not self.enable_expert_bias:
374 # A source without bias balancing has no registered counter to preserve.
375 self.tokens_per_expert = None
376 return
377 if counts is None:
378 counts = torch.zeros(self.num_experts, dtype=torch.int64, device=weight.device)
379 devices = (weight.device, torch.device("cpu")) if weight.is_meta else (weight.device,)
380 if not all((tuple(counts.shape) in ((self.num_experts,), (2, self.num_experts)),
381 counts.dtype == torch.int64, counts.device in devices)):
382 raise ValueError("source tokens_per_expert must be int64 [E] or [2,E] on the weight device")
383 self.register_buffer("tokens_per_expert", counts, persistent=False)
384 register_rebuildable_buffer(self, "tokens_per_expert", value=torch.zeros(
385 counts.shape, dtype=torch.int64, device="cpu",
386 ))
387 if self.enable_expert_bias:
388 self._register_correction_state(module, weight)
390 def _register_correction_state(self, module: nn.Module | None, weight: nn.Parameter) -> None:
391 """Create or adopt the expert bias used for auxiliary-loss-free balancing."""
392 parameter = getattr(module, "bias", None)
393 if parameter is None:
394 parameter = nn.Parameter(torch.zeros(self.num_experts, dtype=torch.float32, device=weight.device),
395 requires_grad=False)
396 else:
397 if (not isinstance(parameter, nn.Parameter) or parameter.shape != (self.num_experts,)
398 or parameter.dtype != torch.float32 or parameter.device != weight.device):
399 raise ValueError("source bias must be an FP32 Parameter [num_experts] on the weight device")
400 parameter.requires_grad_(False)
401 self.register_parameter("bias", parameter)
403 def _apply(self, fn: Any, recurse: bool = True) -> Any:
404 """Keep selection correction state and its gradients FP32 during dtype conversion."""
405 parameters = tuple(getattr(self, name, None) for name in self.fp32_parameter_names)
406 protected = {id(value) for parameter in parameters if parameter is not None
407 for value in (parameter, parameter.grad) if value is not None}
409 def apply(tensor: torch.Tensor) -> torch.Tensor:
410 """Apply storage conversion while preserving correction precision.
412 Args:
413 tensor: Parameter, gradient or buffer visited by the module conversion.
414 """
415 converted = fn(tensor)
416 if id(tensor) not in protected or converted.dtype == torch.float32:
417 return converted
418 return converted.float() if tensor.is_meta else tensor.to(device=converted.device, dtype=torch.float32)
420 return super()._apply(apply, recurse=recurse)
422 def parallel_module_spec(self) -> ParallelModuleSpec:
423 """Declare a replicated router that borrows existing statistics meshes."""
424 return ParallelModuleSpec(
425 protocol="moe.router.statistics", binding_kind="mesh",
426 stages={"forward": ("hidden_states",)}, validate=validate_router_layout,
427 )
429 def bind_parallel(self, binding: ParallelBinding) -> None:
430 """Bind source-token statistics independently of expert transport.
432 Args:
433 binding: Job-owned mesh resources; no new process groups are created.
434 """
435 mesh = binding.mesh_binding.mesh_context
436 device_mesh = mesh.device_mesh
437 names = tuple(device_mesh.mesh_dim_names or ()) if device_mesh is not None else ()
438 tp_partitioned = mesh.sequence_parallel or mesh.ep_size > 1
439 tp_mesh = device_mesh["tp"] if "tp" in names and tp_partitioned else None
440 sequence_axes = [device_mesh["cp"]] if "cp" in names else []
441 if tp_mesh is not None:
442 sequence_axes.append(tp_mesh)
443 sequence_groups = tuple(axis.get_group() for axis in sequence_axes if axis.size() > 1)
444 dp_groups = tuple(device_mesh[name].get_group() for name in names
445 if name in ("dp", "dp_replicate", "dp_shard") and device_mesh[name].size() > 1)
446 owners = binding.mesh_binding.axis_mesh("ep").size() if mesh.ep_size > 1 else 1
447 if self.num_experts % owners:
448 raise ValueError("router expert count must be divisible by the physical EP owner count")
449 self.router_ep_size = owners
450 self.router_tp_mesh = tp_mesh
451 self.sequence_partition_groups = sequence_groups
452 self.expert_bias_update_groups = dp_groups + sequence_groups
454 def _metadata(self, hidden: torch.Tensor, token_mask: torch.Tensor | None,
455 sequence_ids: torch.Tensor | None) -> tuple:
456 return tuple(local_router_metadata(value, hidden, self.router_tp_mesh)
457 for value in (token_mask, sequence_ids))
459 def _apply_router_training(self, hidden: torch.Tensor, scores: torch.Tensor, weights: torch.Tensor,
460 indices: torch.Tensor, token_mask: torch.Tensor | None,
461 sequence_ids: torch.Tensor | None,
462 num_sequences: int | None, groups: tuple | None, *,
463 image_mask: torch.Tensor | None = None) -> torch.Tensor:
464 """Attach auxiliary gradients and count the routes consumed by backward."""
465 if token_mask is not None and (token_mask.shape != hidden.shape[:-1] or token_mask.dtype != torch.bool
466 or token_mask.device != hidden.device):
467 raise ValueError("token_mask must be boolean and match local token shape and device")
468 valid = None if token_mask is None else token_mask.reshape(-1)
469 self.last_aux_loss = None
470 if self.training and self.aux_loss_coeff:
471 auxiliary_indices = indices if self.fix_router else scores.topk(self.top_k, dim=-1, sorted=False).indices
472 auxiliary = self._sequence_auxiliary(
473 hidden, scores, auxiliary_indices, valid, sequence_ids, num_sequences, groups,
474 )
475 self.last_aux_loss = auxiliary.detach()
476 weights = aux_loss_auto_scale(weights, auxiliary * self.aux_loss_coeff)
477 if self.training and self.enable_expert_bias:
478 counts = self.tokens_per_expert
479 if counts.ndim == 2:
480 if image_mask is not None:
481 indices = indices + image_mask.reshape(-1, 1).long() * self.num_experts
482 counts = counts.view(-1)
483 weights = accumulate_router_load(weights, indices, token_mask, counts)
484 return weights
486 def _sequence_auxiliary(self, hidden: torch.Tensor, scores: torch.Tensor, indices: torch.Tensor,
487 valid: torch.Tensor | None, sequence_ids: torch.Tensor | None,
488 num_sequences: int | None, groups: tuple | None) -> torch.Tensor:
489 """Resolve token ownership and evaluate sequence load balancing."""
490 if sequence_ids is None:
491 num_sequences = prod(hidden.shape[:-2])
492 sequence_ids = torch.arange(num_sequences, device=hidden.device).repeat_interleave(hidden.shape[-2])
493 num_sequences = max(1, num_sequences)
494 elif (sequence_ids.shape != hidden.shape[:-1] or sequence_ids.dtype != torch.int64
495 or sequence_ids.device != hidden.device or num_sequences is None):
496 raise ValueError("sequence_ids must be local int64 token metadata with num_sequences")
497 return sequence_load_balancing_loss(
498 scores, indices, sequence_ids.reshape(-1), num_sequences, valid,
499 self.sequence_partition_groups if groups is None else groups,
500 )
502 @torch.no_grad()
503 def update_expert_bias(self, lr: float | None = None, num_recomputations: int = 1) -> None:
504 """Update selection state once after the step's consumed backwards.
506 Args:
507 lr: Override update speed, otherwise use the configured rate.
508 num_recomputations: Compatibility argument; backward counters need no replay correction.
509 """
510 del num_recomputations
511 rate = self.expert_bias_update_rate if lr is None else lr
512 if isinstance(rate, bool) or not isinstance(rate, (int, float)) or not isfinite(rate) or rate < 0:
513 raise ValueError("lr must be finite and nonnegative")
514 rate = float(rate)
515 if self.enable_expert_bias:
516 counts: torch.Tensor = self.tokens_per_expert
517 update_router_bias(self.bias, counts.select(0, 0) if counts.ndim == 2 else counts, rate)
518 if counts.ndim == 2 and getattr(self, "bias_vl", None) is not None:
519 update_router_bias(self.bias_vl, counts.select(0, 1), rate)
520 if self.tokens_per_expert is not None:
521 self.tokens_per_expert.zero_()
524@lru_cache(maxsize=None)
525def _plan_for_device(device: torch.device) -> Any:
526 # HyperMulticore is optional and its runtime is needed only for native NPU calls.
527 from hyper_multicore.modules.mega_gate.plan import build_mega_gate_plan # pylint: disable=import-outside-toplevel
529 return build_mega_gate_plan(device)
532class MegaGateModule(GateModule):
533 """Extend the ordinary gate with correction biases and a fused NPU route.
535 The Gate base owns the projection and common routing contract. HyperMulticore
536 supplies the native function and plan, without owning this module's state.
537 """
539 def __init__(self, *, config: Any = None, module: nn.Module | None = None,
540 module_fqn: str = "", context: Mapping[str, Any] | None = None) -> None:
541 """Adopt compatible projection, correction biases and optional modality counters."""
542 del module_fqn
543 if (config is None) == (module is None):
544 raise ValueError("provide exactly one of config or module")
545 if module is not None:
546 self._validate_source(module)
547 source = config if config is not None else module
548 if (getattr(source, "normalize_topk", source.top_k > 1) != (source.top_k > 1)
549 or getattr(source, "sorted_indices", False)):
550 raise ValueError("MegaGate requires normalize_topk=(top_k > 1) and unsorted indices")
551 vision_enabled = (getattr(source, "vision_enabled", False)
552 if config is not None else getattr(source, "bias_vl", None) is not None)
553 if not isinstance(vision_enabled, bool):
554 raise TypeError("vision_enabled must be bool")
555 super().__init__(config=config, module=module, context=context)
556 self._initialize_correction_state(module, vision_enabled)
558 def _torch_forward(self, hidden_states: torch.Tensor,
559 image_mask: torch.Tensor | None, **metadata: Any) -> tuple[torch.Tensor, ...]:
560 """Reuse ordinary Gate math and modality training state for the unfused path."""
561 return super().forward(hidden_states, image_mask=image_mask, **metadata)
563 def _native_forward(self, hidden_states: torch.Tensor,
564 image_mask: torch.Tensor | None) -> tuple[torch.Tensor, ...]:
565 # Only the fused execution path requires the optional native package.
566 from hyper_multicore.modules.mega_gate.function import mega_gate # pylint: disable=import-outside-toplevel
568 return mega_gate(hidden_states, self.weight, self.bias, _plan_for_device(hidden_states.device),
569 vision_bias=self.bias_vl if image_mask is not None else None,
570 image_mask=None if image_mask is None else image_mask.view(-1),
571 top_k=self.top_k, routed_scaling_factor=self.routed_scaling_factor)
573 # Preserve MegaGate's positional image_mask API; Gate also accepts correction_bias.
574 def forward(self, hidden_states: torch.Tensor, # pylint: disable=arguments-renamed,arguments-differ
575 image_mask: torch.Tensor | None = None, token_mask: torch.Tensor | None = None,
576 sequence_partition_groups: tuple | None = None,
577 sequence_ids: torch.Tensor | None = None, num_sequences: int | None = None) -> tuple[torch.Tensor, ...]:
578 """Use shared Gate math or the native sqrt-softplus NPU route.
580 Args:
581 hidden_states: Source activations [..., hidden_size].
582 image_mask: Boolean local token metadata for vision correction bias.
583 token_mask: Boolean local token metadata excluding padding from statistics.
584 sequence_partition_groups: Override token-partition groups for aux-loss.
585 sequence_ids: Int64 local logical sample IDs.
586 num_sequences: Logical sample count when sequence_ids is provided.
587 """
588 if hidden_states.ndim < 2 or hidden_states.shape[-1] != self.hidden_size:
589 raise ValueError("hidden_states must end in hidden_size and include a token dimension")
590 token_mask, sequence_ids = self._metadata(hidden_states, token_mask, sequence_ids)
591 image_mask = local_router_metadata(image_mask, hidden_states, self.router_tp_mesh)
592 if image_mask is not None:
593 if self.bias_vl is None:
594 raise ValueError("image_mask requires vision_enabled=True when constructing MegaGate")
595 if (image_mask.shape != hidden_states.shape[:-1] or image_mask.dtype != torch.bool
596 or image_mask.device != hidden_states.device):
597 raise ValueError("image_mask must be BOOL [batch, sequence] on the hidden_states device")
598 if self.scoring_func != "sqrtsoftplus" or hidden_states.device.type != "npu" or hidden_states.numel() == 0:
599 return self._torch_forward(hidden_states, image_mask, token_mask=token_mask,
600 sequence_ids=sequence_ids, num_sequences=num_sequences,
601 sequence_partition_groups=sequence_partition_groups)
602 if image_mask is not None and not image_mask.is_contiguous():
603 raise ValueError("image_mask must be contiguous for native MegaGate")
604 logits, weights, indices = self._native_forward(hidden_states, image_mask)
605 weights, indices = self._finish_routing(
606 hidden_states, logits, weights, indices, token_mask, sequence_ids,
607 num_sequences, sequence_partition_groups, image_mask=image_mask,
608 )
609 return logits, weights, indices
611 @classmethod
612 def from_module(cls, module: nn.Module, **configuration: Any) -> MegaGateModule:
613 """Retain declared settings without configuration overrides.
615 Args:
616 module: Existing public MegaGate source.
617 **configuration: Overrides are rejected; construct a new configured gate instead.
618 """
619 if configuration:
620 raise ValueError("family source construction preserves source settings; overrides are unsupported")
621 return cls(module=module)
624@module_replacement
625def Gate( # pylint: disable=invalid-name
626 *, config: Any = None, module: nn.Module | None = None, module_fqn: str = "",
627 context: Any = None, mesh: Any = None, implementation: str = "local", megakernel: bool = False) -> nn.Module:
628 """Build a local gate or the compatible MegaGate execution variant."""
629 return build_family(Gate, config=config, module=module, module_fqn=module_fqn,
630 context=context, mesh=mesh, implementation=implementation, megakernel=megakernel)
633register_module_family(ModuleFamily(
634 name="gate", baseline=Gate,
635 variants={"local": "hyper_parallel.components.modules.moe.router.GateModule",
636 "mega": "hyper_parallel.components.modules.moe.router.MegaGateModule"},
637 default_variant="local", sharding=router_sharding,
638 selector_specs={"implementation": SelectorSpec(str, "local"), "megakernel": SelectorSpec(bool, False)},
639 variant_rules=(VariantRule({"implementation": "mega", "megakernel": False, "parallel": False}, "mega"),
640 VariantRule({"implementation": "local", "megakernel": True, "parallel": False}, "mega"),
641 VariantRule({"implementation": "mega", "megakernel": True, "parallel": False}, "mega")),
642))
645class ScoreCorrectedTopKRouterModule(nn.Module):
646 """Own selection biases, source matrix identities and the FP32 unbiased routing weights."""
648 def __init__(
649 self,
650 *,
651 config: Any = None,
652 module: nn.Module | None = None,
653 module_fqn: str = "",
654 context: Any = None,
655 source_contract: str = "ids_weights",
656 ) -> None:
657 """Construct explicit routing settings or adopt a separate matrix/bias source."""
658 super().__init__()
659 del module_fqn, context
660 if (config is None) == (module is None):
661 raise ValueError("provide exactly one of config or module")
662 if source_contract not in ("ids_weights", "logits_weights_ids"):
663 raise ValueError("Unsupported corrected-router source contract")
664 source = config if module is None else module
665 self.source_contract = source_contract
666 self.hidden_size = config.hidden_size if module is None else module.weight.shape[1]
667 self.num_experts = config.num_experts if module is None else module.weight.shape[0]
668 self.top_k = source.top_k
669 self.scoring_func = getattr(source, "moe_router_activation_func", getattr(source, "scoring_func", None))
670 self.num_groups = getattr(source, "num_expert_group", getattr(source, "num_groups", 1))
671 self.groups_selected = getattr(source, "topk_group", getattr(source, "groups_selected", 1))
672 self.normalize_topk = getattr(source, "moe_renormalize", getattr(source, "normalize_topk", True))
673 self.routed_scaling_factor = source.routed_scaling_factor
674 self._validate_settings()
675 if module is None:
676 self.weight = nn.Parameter(torch.empty(self.num_experts, self.hidden_size))
677 self.e_score_correction_bias = nn.Parameter(torch.zeros(self.num_experts), requires_grad=False)
678 self.reset_parameters()
679 else:
680 if set(dict(module.named_parameters(recurse=False))) != {"weight", "e_score_correction_bias"}:
681 raise ValueError("Corrected router source must own its matrix and correction Parameter separately")
682 if list(module.named_children()) or module.e_score_correction_bias.shape != (self.num_experts,):
683 raise ValueError("Unsupported corrected router source structure")
684 self.weight, self.e_score_correction_bias = module.weight, module.e_score_correction_bias
685 self.training = module.training
687 def _validate_settings(self) -> None:
688 """Validate grouped top-k coverage, scoring and normalization before weight allocation."""
689 for name in ("hidden_size", "num_experts", "top_k", "num_groups", "groups_selected"):
690 value = getattr(self, name)
691 if isinstance(value, bool) or not isinstance(value, int) or value < 1:
692 raise ValueError(f"{name} must be a positive integer")
693 if (
694 self.num_experts % self.num_groups
695 or self.groups_selected > self.num_groups
696 or self.top_k > self.groups_selected * (self.num_experts // self.num_groups)
697 ):
698 raise ValueError("Router groups do not cover the requested top-k experts")
699 if self.num_groups > self.groups_selected and self.num_experts // self.num_groups < 2:
700 raise ValueError("Top-two group scoring needs at least two experts in each group")
701 if self.scoring_func not in ("softmax", "sigmoid") or not isinstance(self.normalize_topk, bool):
702 raise ValueError("Corrected routing requires sigmoid/softmax and a boolean normalization policy")
703 if not isinstance(self.routed_scaling_factor, (int, float)) or not isfinite(self.routed_scaling_factor):
704 raise ValueError("routed_scaling_factor must be finite")
706 def reset_parameters(self) -> None:
707 """Restore the source constructor matrix law and a defined neutral selection bias."""
708 nn.init.kaiming_uniform_(self.weight, a=sqrt(5))
709 nn.init.zeros_(self.e_score_correction_bias)
711 def make_transforms(self) -> list:
712 """Retain both source keys and their independent parameter identities."""
713 return []
715 def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, ...]:
716 """Select groups with biased scores and return normalized unbiased expert weights.
718 Args:
719 hidden_states: Token activations ending in the hidden dimension.
720 """
721 if hidden_states.ndim < 2 or hidden_states.shape[-1] != self.hidden_size:
722 raise ValueError("Router inputs must end in hidden_size and include token dimensions")
723 with torch.autocast(device_type=hidden_states.device.type, enabled=False):
724 # Torch exposes this C-extension callable without a Python signature.
725 logits = F.linear( # pylint: disable=not-callable
726 hidden_states.reshape(-1, self.hidden_size).float(), self.weight.float()
727 )
728 scores = routing_scores(logits, self.scoring_func)
729 selection = scores + self.e_score_correction_bias.float().unsqueeze(0)
730 if self.num_groups > self.groups_selected:
731 group_scores = selection.view(-1, self.num_groups, self.num_experts // self.num_groups)
732 group_scores = group_scores.topk(2, dim=-1).values.sum(dim=-1)
733 selected = group_scores.topk(self.groups_selected, dim=-1, sorted=False).indices
734 mask = torch.zeros_like(group_scores).scatter_(1, selected, 1)
735 mask = mask.unsqueeze(-1).expand(-1, -1, self.num_experts // self.num_groups).reshape_as(selection)
736 selection = selection.masked_fill(~mask.bool(), float("-inf"))
737 indices = selection.topk(self.top_k, dim=-1, sorted=False).indices
738 weights = scores.gather(1, indices)
739 if self.top_k > 1 and self.normalize_topk:
740 weights = weights / (weights.sum(dim=-1, keepdim=True) + 1e-20)
741 weights = weights * self.routed_scaling_factor
742 return (indices, weights) if self.source_contract == "ids_weights" else (logits, weights, indices)
745def corrected_router_sharding(*, module: nn.Module, module_fqn: str, member: Any, context: Any) -> ModuleShardingSpec:
746 """Replicate router matrices and preserve the source's local token ownership."""
747 del module_fqn, member
748 axes = {axis: Replicate() for axis in context.mesh_dim_names if axis in context.axis_sizes}
749 tokens = dict(axes)
750 rows = dict(axes)
751 for axis in ("cp", "tp"):
752 if context.axis_sizes[axis] > 1 and (axis == "cp" or context.sequence_parallel):
753 tokens[axis], rows[axis] = Shard(1), Shard(0)
754 outputs = ("indices", "weights") if module.source_contract == "ids_weights" else ("logits", "weights", "indices")
755 return ModuleShardingSpec(
756 params={name: dict(axes) for name, _ in module.named_parameters()},
757 in_src={"hidden_states": dict(tokens)},
758 in_dst={"hidden_states": dict(tokens)},
759 out_src={name: dict(rows) for name in outputs},
760 out_dst={name: dict(rows) for name in outputs},
761 out_names=outputs,
762 is_boundary=True,
763 )
766@module_replacement
767def ScoreCorrectedTopKRouter( # pylint: disable=invalid-name
768 *,
769 config: Any = None,
770 module: nn.Module | None = None,
771 module_fqn: str = "",
772 context: Any = None,
773 mesh: Any = None,
774 source_contract: str = "ids_weights",
775) -> nn.Module:
776 """Build complete group-aware corrected routing through the shared family lifecycle."""
777 return build_family(
778 ScoreCorrectedTopKRouter,
779 config=config,
780 module=module,
781 module_fqn=module_fqn,
782 context=context,
783 mesh=mesh,
784 source_contract=source_contract,
785 )
788register_module_family(
789 ModuleFamily(
790 name="score_corrected_topk_router",
791 baseline=ScoreCorrectedTopKRouter,
792 variants={"local": "hyper_parallel.components.modules.moe.router.ScoreCorrectedTopKRouterModule"},
793 default_variant="local",
794 sharding=corrected_router_sharding,
795 )
796)
799__all__ = [
800 "Gate", "GateModule", "MegaGateModule", "ScoreCorrectedTopKRouter", "ScoreCorrectedTopKRouterModule",
801 "balanced_expert_indices", "routing_scores", "select_topk_scores",
802]