Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / mhc / mhc_pre.py: 83%

76 statements  

« 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"""Parameterized mHC pre computation.""" 

16from __future__ import annotations 

17from collections.abc import Mapping 

18from typing import Any 

19import torch 

20from torch import nn 

21from hyper_parallel.components.functional.mhc_pre import mhc_pre 

22from ._utils import (_validate_settings, _num_stream, _required_attribute, _required_config_value, 

23 _parameter, _validate_parameter_layout) 

24 

25 

26class MhcPreModule(nn.Module): 

27 """Prepare hidden states and mixing coefficients for an MHC-wrapped block.""" 

28 

29 def __init__( 

30 self, 

31 *, 

32 module: nn.Module | None = None, 

33 module_fqn: str = "", 

34 context: Mapping[str, Any] | None = None, 

35 config: Any = None, 

36 ) -> None: 

37 """Build the high-performance MHC pre module from an existing module. 

38 

39 Args: 

40 module: Source MHC pre module with the existing parameter layout. 

41 module_fqn: Fully qualified source-module name supplied by replacement. 

42 context: Replacement context supplied by Trainer. 

43 

44 Raises: 

45 TypeError: If required source attributes or settings are missing. 

46 ValueError: If parameter shapes or runtime settings are incompatible. 

47 """ 

48 super().__init__() 

49 del module_fqn, context 

50 if (module is None) == (config is None): 

51 raise ValueError("provide exactly one of config or module") 

52 if config is not None: 

53 _validate_settings(config.num_stream, config.hidden_size, config.sinkhorn_iters, 

54 config.hc_eps, config.norm_eps, config.use_gamma) 

55 self.config = config 

56 self.num_stream = config.num_stream 

57 width = config.hidden_size * config.num_stream 

58 count = (config.num_stream + 2) * config.num_stream 

59 self.phi = nn.Linear(width, count, bias=False, dtype=torch.float32) 

60 self.branch_alpha = nn.Parameter(torch.empty(3, dtype=torch.float32)) 

61 self.branch_beta = nn.Parameter(torch.empty(count, dtype=torch.float32)) 

62 self.mhc_use_gamma = config.use_gamma 

63 if config.use_gamma: 

64 self.norm_gamma = nn.Parameter(torch.empty(width, dtype=torch.float32)) 

65 self.hc_eps, self.norm_eps = config.hc_eps, config.norm_eps 

66 self.mhc_recur_norm = config.sinkhorn_iters 

67 self.reset_parameters() 

68 return 

69 self.config = getattr(module, "config", None) 

70 self.num_stream = _num_stream(module) 

71 

72 phi = _required_attribute(module, "phi") 

73 if not isinstance(phi, nn.Linear) or phi.bias is not None: 

74 raise TypeError("MhcPreModule requires a bias-free nn.Linear phi projection") 

75 if phi.in_features % self.num_stream != 0: 

76 raise ValueError("MHC pre phi input size must be divisible by num_stream") 

77 if phi.out_features != (self.num_stream + 2) * self.num_stream: 

78 raise ValueError("MHC pre phi output size must equal (num_stream + 2) * num_stream") 

79 self.phi = phi 

80 self.branch_alpha = _parameter(module, "branch_alpha") 

81 self.branch_beta = _parameter(module, "branch_beta") 

82 if self.branch_alpha.numel() != 3: 

83 raise ValueError("MHC pre branch_alpha must contain three values") 

84 expected_beta_size = 2 * self.num_stream + self.num_stream * self.num_stream 

85 if self.branch_beta.numel() != expected_beta_size: 

86 raise ValueError("MHC pre branch_beta has an incompatible size") 

87 

88 self.mhc_use_gamma = bool(_required_config_value(module, "mhc_use_gamma")) 

89 parameters = [self.branch_alpha, self.branch_beta] 

90 if self.mhc_use_gamma: 

91 self.norm_gamma = _parameter(module, "norm_gamma") 

92 if self.norm_gamma.numel() != phi.in_features: 

93 raise ValueError("MHC pre norm_gamma size must equal the phi input size") 

94 parameters.append(self.norm_gamma) 

95 elif hasattr(module, "norm_gamma"): 

96 raise ValueError("MHC pre source has norm_gamma while mhc_use_gamma is disabled") 

97 _validate_parameter_layout(phi, tuple(parameters)) 

98 

99 self.hc_eps = float(_required_attribute(module, "hc_eps")) 

100 self.norm_eps = float(_required_attribute(module, "norm_eps")) 

101 self.mhc_recur_norm = int(_required_config_value(module, "mhc_recur_norm")) 

102 if self.hc_eps <= 0 or self.norm_eps <= 0: 

103 raise ValueError("MHC eps values must be positive") 

104 if self.mhc_recur_norm <= 0: 

105 raise ValueError("mhc_recur_norm must be a positive integer") 

106 _validate_settings(self.num_stream, phi.in_features // self.num_stream, 

107 self.mhc_recur_norm, self.hc_eps, self.norm_eps, self.mhc_use_gamma) 

108 self.train(module.training) 

109 

110 def reset_parameters(self) -> None: 

111 """Initialize direct-build projection and coefficient scales explicitly.""" 

112 nn.init.normal_(self.phi.weight, std=0.02) 

113 nn.init.constant_(self.branch_alpha, 0.01) 

114 nn.init.zeros_(self.branch_beta) 

115 if self.mhc_use_gamma: 

116 nn.init.ones_(self.norm_gamma) 

117 

118 def make_transforms(self) -> list: 

119 """Declare that this member keeps parameter names and layouts unchanged. 

120 

121 Returns: 

122 An empty converter list, matching members whose initialization is 

123 fully owned by ``reset_parameters``. 

124 """ 

125 return [] 

126 

127 def forward( 

128 self, x: torch.Tensor 

129 ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor | None]: 

130 """Prepare hidden states and return the MHC mixing coefficients.""" 

131 gamma = self.norm_gamma if self.mhc_use_gamma else None 

132 return mhc_pre( 

133 x, 

134 self.phi.weight, 

135 self.branch_alpha, 

136 self.branch_beta, 

137 self.num_stream, 

138 self.mhc_recur_norm, 

139 self.norm_eps, 

140 self.hc_eps, 

141 gamma, 

142 )