Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / moe / moe.py: 0%
24 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"""Compose module-family members into a mixture-of-experts layer."""
17from __future__ import annotations
19from typing import Any
21import torch
22from torch import nn
24from hyper_parallel.components.modules.moe.grouped_experts.grouped_experts import (
25 GroupedExpertsConfig,
26 GroupedExpertsModule,
27)
28from hyper_parallel.components.modules.moe.router import GateModule
29from hyper_parallel.components.modules.moe.shared_expert import SharedExpertModule
32class MoE(nn.Module):
33 """Combine the local router, grouped experts and an optional shared expert.
35 Args:
36 router_config: Configuration accepted by :class:`GateModule`.
37 experts_config: Configuration for the routed experts.
38 shared_expert_config: Optional configuration accepted by :class:`SharedExpertModule`.
39 """
41 def __init__(
42 self, *, router_config: Any, experts_config: GroupedExpertsConfig,
43 shared_expert_config: Any = None,
44 ) -> None:
45 """Construct the local members from their algorithm configuration."""
46 super().__init__()
47 self.gate = GateModule(config=router_config)
48 self.experts = GroupedExpertsModule(config=experts_config)
49 self.shared_experts = (
50 SharedExpertModule(config=shared_expert_config) if shared_expert_config is not None else None
51 )
53 def forward(
54 self, hidden_states: torch.Tensor, *, correction_bias: torch.Tensor | None = None,
55 token_mask: torch.Tensor | None = None, sequence_ids: torch.Tensor | None = None,
56 num_sequences: int | None = None,
57 ) -> torch.Tensor:
58 """Route the tokens and add the optional shared expert contribution.
60 Args:
61 hidden_states: Token activations of shape [..., hidden_size].
62 correction_bias: Optional selection-only expert bias.
63 token_mask: Boolean mask selecting tokens for balancing statistics.
64 sequence_ids: Logical sample IDs for packed sequences.
65 num_sequences: Number of logical samples when sequence_ids is provided.
67 Returns:
68 Expert output in the original token shape and order.
69 """
70 _, weights, indices = self.gate(
71 hidden_states, correction_bias=correction_bias, token_mask=token_mask,
72 sequence_ids=sequence_ids, num_sequences=num_sequences,
73 )
74 routed = self.experts(hidden_states, indices, weights)
75 if self.shared_experts is None:
76 return routed
77 shared = self.shared_experts(hidden_states)
78 if isinstance(shared, tuple):
79 shared, bias = shared
80 if bias is not None:
81 shared = shared + bias
82 return routed + shared