Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / common / situ_mlp.py: 79%

87 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"""Separate-matrix SiTU MLP with source-owned names and independent Muon NS boundaries.""" 

16from __future__ import annotations 

17 

18from typing import Any 

19 

20import torch 

21from torch import nn 

22 

23from hyper_parallel.components.functional.activation_situ import situ 

24from hyper_parallel.components.modules.module_family import ModuleFamily, build_family, register_module_family 

25from hyper_parallel.core.dtensor.placement_types import Replicate, Shard 

26from hyper_parallel.distributed.recipe_spec import ModuleShardingSpec 

27from hyper_parallel.models.replacement import module_replacement 

28 

29 

30class SiTUActivation(nn.Module): 

31 """Evaluate the public FP32 SiTU equation on a gate-first packed activation.""" 

32 

33 def __init__(self, beta: float = 1.0, linear_beta: float | None = None) -> None: 

34 """Declare gate and optional up-projection saturation scales.""" 

35 super().__init__() 

36 if beta <= 0 or (linear_beta is not None and linear_beta <= 0): 

37 raise ValueError("SiTU saturation scales must be positive") 

38 self.beta, self.linear_beta = beta, linear_beta 

39 

40 def forward(self, packed: torch.Tensor) -> torch.Tensor: 

41 """Preserve the source activation's slicing and FP32 evaluation boundaries.""" 

42 width = packed.shape[-1] // 2 

43 return situ(packed[..., :width], packed[..., width:], beta=self.beta, linear_beta=self.linear_beta) 

44 

45 

46class SiTUMLPModule(nn.Module): 

47 """Own three independent matrices with gate/up/down or w1/w3/w2 source keys.""" 

48 

49 def __init__( 

50 self, 

51 *, 

52 config: Any = None, 

53 module: nn.Module | None = None, 

54 module_fqn: str = "", 

55 context: Any = None, 

56 state_layout: str = "gate_up_down", 

57 ) -> None: 

58 """Construct directly or adopt the exact source parameter identities without packing weights.""" 

59 super().__init__() 

60 del module_fqn, context 

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

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

63 if module is not None: 

64 config = module.config 

65 state_layout = "w1_w3_w2" if all(hasattr(module, name) for name in ("w1", "w3", "w2")) else "gate_up_down" 

66 self.config = config 

67 if state_layout not in ("gate_up_down", "w1_w3_w2"): 

68 raise ValueError("SiTU MLP supports gate_up_down or w1_w3_w2 source state") 

69 self.state_layout = state_layout 

70 self.projection_names = ( 

71 ("gate_proj", "up_proj", "down_proj") if state_layout == "gate_up_down" else ("w1", "w3", "w2") 

72 ) 

73 beta = getattr(config, "activation_situ_beta", None) or 1.0 

74 linear_beta = getattr(config, "activation_situ_linear_beta", None) 

75 if getattr(config, "hidden_act", None) != "situ": 

76 raise ValueError("SiTUMLP requires a SiTU source activation contract") 

77 if module is not None: 

78 self._adopt_source(module, beta, linear_beta) 

79 else: 

80 self.hidden_size, self.intermediate_size = config.hidden_size, config.intermediate_size 

81 registration_order = ("w1", "w2", "w3") if state_layout == "w1_w3_w2" else self.projection_names 

82 for name in registration_order: 

83 source, destination = ( 

84 (self.intermediate_size, self.hidden_size) 

85 if name == self.projection_names[2] 

86 else (self.hidden_size, self.intermediate_size) 

87 ) 

88 self.add_module(name, nn.Linear(source, destination, bias=getattr(config, "mlp_bias", False))) 

89 self.act_fn = SiTUActivation(beta, linear_beta) 

90 

91 def _adopt_source(self, module: nn.Module, beta: float, linear_beta: float | None) -> None: 

92 """Validate and retain separate SiTU matrices and the source activation contract.""" 

93 expected = set(self.projection_names) | {"act_fn"} 

94 if set(dict(module.named_children())) != expected or list(module.named_parameters(recurse=False)): 

95 raise ValueError("Unsupported separate-matrix SiTU source structure") 

96 gate, up, down = (getattr(module, name) for name in self.projection_names) 

97 if not all(type(item) is nn.Linear for item in (gate, up, down)): # pylint: disable=unidiomatic-typecheck 

98 raise ValueError("SiTU source projections must be plain Linear modules") 

99 if ((gate.in_features, gate.out_features, down.in_features, down.out_features) 

100 != (up.in_features, up.out_features, gate.out_features, gate.in_features)): 

101 raise ValueError("SiTU source projection dimensions do not compose") 

102 if len({(p.device, p.dtype) for item in (gate, up, down) for p in item.parameters()}) != 1: 

103 raise ValueError("SiTU source projections must share device and dtype") 

104 if module.act_fn.beta != beta or module.act_fn.linear_beta != linear_beta: 

105 raise ValueError("SiTU source activation and config disagree") 

106 self.hidden_size, self.intermediate_size = gate.in_features, gate.out_features 

107 for name, child in module.named_children(): 

108 self.add_module(name, SiTUActivation(beta, linear_beta) if name == "act_fn" else child) 

109 self.get_submodule("act_fn").training = module.act_fn.training 

110 self.training = module.training 

111 

112 def make_transforms(self) -> list: 

113 """Keep every independent source matrix and state key unchanged.""" 

114 return [] 

115 

116 def forward(self, hidden_states: torch.Tensor | None = None, *, x: torch.Tensor | None = None) -> torch.Tensor: 

117 """Project gate/up separately, evaluate public SiTU and project back to hidden width.""" 

118 if hidden_states is not None and x is not None: 

119 raise ValueError("Provide SiTU inputs through hidden_states or x, not both") 

120 hidden_states = hidden_states if x is None else x 

121 if hidden_states is None: 

122 raise ValueError("SiTU requires input activations") 

123 gate, up, down = (getattr(self, name) for name in self.projection_names) 

124 return down(self.act_fn(torch.cat((gate(hidden_states), up(hidden_states)), dim=-1))) 

125 

126 

127def situ_sharding(*, module: nn.Module, module_fqn: str, member: Any, context: Any) -> ModuleShardingSpec: 

128 """Own every source matrix while keeping the currently local computation explicit.""" 

129 del module_fqn, member 

130 placements = {axis: Replicate() for axis in context.mesh_dim_names if axis in context.axis_sizes} 

131 tokens = dict(placements) 

132 if context.axis_sizes["cp"] > 1: 

133 tokens["cp"] = Shard(1) 

134 return ModuleShardingSpec( 

135 params={name: dict(placements) for name, _ in module.named_parameters()}, 

136 in_src={"hidden_states": dict(tokens)}, 

137 in_dst={"hidden_states": dict(tokens)}, 

138 out_src={"output": dict(tokens)}, 

139 out_dst={"output": dict(tokens)}, 

140 is_boundary=True, 

141 ) 

142 

143 

144def validate_situ(*, config: Any, module: nn.Module | None, context: Any, member: Any) -> None: 

145 """Reject TP until the separate-matrix SiTU layout has an accepted parallel member.""" 

146 del config, module, context 

147 if member.axis_sizes["tp"] > 1: 

148 raise NotImplementedError("Separate-matrix SiTU currently requires TP1") 

149 

150 

151@module_replacement 

152def SiTUMLP( # pylint: disable=invalid-name 

153 *, 

154 config: Any = None, 

155 module: nn.Module | None = None, 

156 module_fqn: str = "", 

157 context: Any = None, 

158 mesh: Any = None, 

159 state_layout: str = "gate_up_down", 

160) -> nn.Module: 

161 """Build a separate-matrix SiTU MLP without changing logical optimizer matrices.""" 

162 return build_family( 

163 SiTUMLP, 

164 config=config, 

165 module=module, 

166 module_fqn=module_fqn, 

167 context=context, 

168 mesh=mesh, 

169 state_layout=state_layout, 

170 ) 

171 

172 

173register_module_family( 

174 ModuleFamily( 

175 name="situ_mlp", 

176 baseline=SiTUMLP, 

177 variants={"local": "hyper_parallel.components.modules.common.situ_mlp.SiTUMLPModule"}, 

178 default_variant="local", 

179 sharding=situ_sharding, 

180 validate=validate_situ, 

181 ) 

182)