Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / ops / impl / moe_router.py: 72%
46 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"""Compute DeepSeek V4.1 learned top-k routing before training statistics."""
17from __future__ import annotations
19from typing import Protocol
21import torch
22from torch.nn import functional as F
24from .._dependency import require_package
25from ..registry import ImplementationUnavailable, OpRegistry
26from ..spec import OpSpec
29class MoeRouterFn(Protocol):
30 """Return logits, normalized routing weights and selected expert indices."""
32 def __call__(
33 self, x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor, vision_bias: torch.Tensor | None,
34 image_mask: torch.Tensor | None, top_k: int, scoring_func: str, scale: float,
35 ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
36 """Project tokens and perform expert selection with modality corrections."""
39MOE_ROUTER = OpSpec[MoeRouterFn](config_key="moe_router", variant="deepseek_v41")
42def router_scores(logits: torch.Tensor, scoring_func: str) -> torch.Tensor:
43 """Convert router logits to the released nonnegative expert scores."""
44 if scoring_func == "sqrtsoftplus":
45 return F.softplus(logits).sqrt() # pylint: disable=not-callable
46 if scoring_func == "softmax":
47 return logits.softmax(dim=-1)
48 if scoring_func == "sigmoid":
49 return logits.sigmoid()
50 raise ValueError(f"Unsupported V4.1 router scoring function: {scoring_func!r}")
53def _torch_router(
54 x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor, vision_bias: torch.Tensor | None,
55 image_mask: torch.Tensor | None, top_k: int, scoring_func: str, scale: float,
56) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
57 """Compute expert logits, modality corrections and normalized routing weights."""
58 logits = F.linear(x.reshape(-1, x.shape[-1]).float(), weight.float()) # pylint: disable=not-callable
59 scores = router_scores(logits, scoring_func)
60 if image_mask is not None and vision_bias is not None:
61 bias = torch.where(image_mask.reshape(-1, 1), vision_bias.unsqueeze(0), bias.unsqueeze(0))
62 indices = torch.topk(scores + bias, top_k, dim=-1, sorted=False).indices
63 weights = scores.gather(1, indices)
64 if top_k > 1:
65 weights = weights / (weights.sum(dim=-1, keepdim=True) + 1.0e-20)
66 return logits, weights * scale, indices
69def _load_megagate() -> MoeRouterFn:
70 """Load the optional fused MegaGate router for the shared routing contract."""
71 require_package("hyper_multicore")
72 # Only the selected MegaGate backend needs the standalone native package.
73 # pylint: disable=import-outside-toplevel
74 from hyper_multicore._loader import NativeComponentUnavailableError
75 from hyper_multicore.modules.mega_gate.function import mega_gate
76 from hyper_multicore.modules.mega_gate.module import _plan_for_device
77 from hyper_multicore.torch.ops import _load_native
78 # pylint: enable=import-outside-toplevel
79 try:
80 _load_native()
81 except NativeComponentUnavailableError as error:
82 raise ImplementationUnavailable(str(error)) from error
84 def route(
85 x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor, vision_bias: torch.Tensor | None,
86 image_mask: torch.Tensor | None, top_k: int, scoring_func: str, scale: float,
87 ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
88 """Apply MegaGate using the shared learned routing contract."""
89 del scoring_func
90 return mega_gate(
91 x, weight, bias, _plan_for_device(x.device), vision_bias=vision_bias,
92 image_mask=None if image_mask is None else image_mask.reshape(-1).contiguous(),
93 top_k=top_k, routed_scaling_factor=scale,
94 )
96 return route
99def register_moe_router(registry: OpRegistry) -> None:
100 """Register DeepSeek's Torch router and MegaGate route kernel."""
101 registry.register_family("moe_router", specs=(MOE_ROUTER,))
102 registry.register_impl(MOE_ROUTER, name="native", devices=("cpu", "cuda", "npu"), load=lambda: _torch_router)
103 registry.register_impl(MOE_ROUTER, name="megagate", devices=("npu",), load=_load_megagate)