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

138 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"""Common Gated Residual (HyperConnection) module family. 

16 

17The implementation follows the Gated Residual reference contract. A hyper state is 

18stored as ``[..., hc_count * hidden_size]`` and is interpreted as 

19``[..., hc_count, hidden_size]``. ``forward`` is source-compatible with the 

20reference module: a mixer without injection returns ``mixed_input``; a mixer 

21with injection returns ``(mixed_input, hyper_input, injection_weights)``. 

22 

23The model applies each block output to the residual streams using the returned 

24injection weights, matching the reference model's responsibility boundary. 

25``combine`` exposes that same residual update as an optional convenience API. 

26""" 

27 

28from __future__ import annotations 

29 

30from collections.abc import Mapping 

31from math import isfinite 

32from typing import Any 

33 

34import torch 

35from torch import nn 

36 

37from hyper_parallel.components.functional.gated_residual import gated_residual 

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

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

40from hyper_parallel.distributed.recipe_spec import ModuleShardingSpec 

41from hyper_parallel.models.replacement import module_replacement 

42 

43 

44def _config_value(config: Any, name: str, default: Any = None) -> Any: 

45 """Read one optional field from a model configuration.""" 

46 return getattr(config, name, default) if config is not None else default 

47 

48 

49def _positive_int(value: Any, name: str) -> int: 

50 """Validate a positive integer configuration field.""" 

51 if isinstance(value, bool) or not isinstance(value, int) or value <= 0: 

52 raise ValueError(f"GatedResidual {name} must be a positive integer") 

53 return value 

54 

55 

56def _positive_float(value: Any, name: str) -> float: 

57 """Validate a finite positive floating-point configuration field.""" 

58 if isinstance(value, bool) or not isinstance(value, (int, float)) or not isfinite(value) or value <= 0: 

59 raise ValueError(f"GatedResidual {name} must be finite and positive") 

60 return float(value) 

61 

62 

63class _GroupedOffsetRMSNorm(nn.Module): 

64 """Zero-centered RMSNorm applied independently to each residual stream.""" 

65 

66 def __init__(self, hidden_size: int, group_size: int, eps: float) -> None: 

67 super().__init__() 

68 if hidden_size % group_size: 

69 raise ValueError("GatedResidual hidden_size must be divisible by group_size") 

70 self.eps = eps 

71 self.group_size = group_size 

72 # Initialize gamma to zero and apply it as (1 + gamma). 

73 self.weight = nn.Parameter(torch.zeros(hidden_size)) 

74 

75 def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: 

76 """Normalize each ``group_size`` slice in FP32 and restore input dtype.""" 

77 input_dtype = hidden_states.dtype 

78 values = hidden_states.float().unflatten( 

79 -1, (hidden_states.shape[-1] // self.group_size, self.group_size) 

80 ) 

81 normalized = values * torch.rsqrt(values.square().mean(dim=-1, keepdim=True) + self.eps) 

82 scaled = normalized * ( 

83 1.0 + self.weight.float().unflatten(-1, (self.weight.numel() // self.group_size, self.group_size)) 

84 ) 

85 return scaled.flatten(-2).to(input_dtype) 

86 

87 

88class GatedResidualModule(nn.Module): 

89 """Configurable Gated Residual module family member.""" 

90 

91 def __init__( 

92 self, 

93 *, 

94 config: Any = None, 

95 module: nn.Module | None = None, 

96 module_fqn: str = "", 

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

98 use_combine: bool | None = None, 

99 ) -> None: 

100 """Construct from config or adopt an existing Transformers module. 

101 

102 ``use_combine`` is inferred from a source module's 

103 ``block_inject_weight``. For direct construction it defaults to true; 

104 the final model mixer can pass ``use_combine=False``. 

105 """ 

106 super().__init__() 

107 del module_fqn, context 

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

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

110 

111 source_config = config if config is not None else getattr(module, "config", None) 

112 self.config = source_config 

113 configured_backend = _config_value(source_config, "gated_residual_backend") 

114 if configured_backend is None: 

115 configured_backend = _config_value(source_config, "gated_res_backend") 

116 if configured_backend is None: 

117 configured_backend = _config_value(module, "backend", "eager") 

118 if configured_backend not in ("eager", "torch", "ascendc", "cann"): 

119 raise ValueError("GatedResidual backend must be eager or ascendc") 

120 self.backend = "eager" if configured_backend in ("eager", "torch") else "ascendc" 

121 if module is not None: 

122 self._adopt_source(module, use_combine) 

123 return 

124 

125 self.hidden_size = _positive_int(_config_value(config, "hidden_size"), "hidden_size") 

126 self.hc_count = _positive_int(_config_value(config, "hc_count", 4), "hc_count") 

127 self.hc_lowrank = _positive_int(_config_value(config, "hc_lowrank", 320), "hc_lowrank") 

128 eps = _positive_float(_config_value(config, "rms_norm_eps", 1e-6), "rms_norm_eps") 

129 self.use_combine = True if use_combine is None else use_combine 

130 if not isinstance(self.use_combine, bool): 

131 raise TypeError("GatedResidual use_combine must be bool") 

132 self.hc_norm = _GroupedOffsetRMSNorm(self.hyper_hidden_size, self.hidden_size, eps) 

133 self.input_mix_weight_down = nn.Linear(self.hyper_hidden_size, self.hc_lowrank, bias=False) 

134 self.input_mix_weight_up = nn.Linear(self.hc_lowrank, self.hyper_hidden_size, bias=False) 

135 if self.use_combine: 

136 self.block_inject_weight = nn.Linear(self.hyper_hidden_size, self.hc_count, bias=False) 

137 

138 @property 

139 def hyper_hidden_size(self) -> int: 

140 """Return the flattened residual-stream width.""" 

141 return self.hc_count * self.hidden_size 

142 

143 def combine( 

144 self, 

145 block_output: torch.Tensor, 

146 hyper_input: torch.Tensor, 

147 injection_weights: torch.Tensor, 

148 ) -> torch.Tensor: 

149 """Apply a block output to all residual streams using mixer weights. 

150 

151 The method is an optional convenience for model code. Callers may 

152 instead apply this equation themselves, as the reference decoder does. 

153 """ 

154 if not self.use_combine: 

155 raise RuntimeError("GatedResidual combine is unavailable when use_combine=False") 

156 if block_output.shape[-1] != self.hidden_size: 

157 raise ValueError( 

158 f"Expected block output width {self.hidden_size}, got {block_output.shape[-1]}" 

159 ) 

160 if hyper_input.shape[-1] != self.hyper_hidden_size: 

161 raise ValueError( 

162 f"Expected {self.hyper_hidden_size} hyper-connection features, got {hyper_input.shape[-1]}" 

163 ) 

164 if injection_weights.shape[-1] != self.hc_count: 

165 raise ValueError( 

166 f"Expected {self.hc_count} injection weights, got {injection_weights.shape[-1]}" 

167 ) 

168 leading_shape = block_output.shape[:-1] 

169 if hyper_input.shape[:-1] != leading_shape or injection_weights.shape[:-1] != leading_shape: 

170 raise ValueError("GatedResidual block output, hyper input, and injection weights must align") 

171 

172 streams = hyper_input.unflatten(-1, (self.hc_count, self.hidden_size)) 

173 injected = block_output.unsqueeze(-2) * injection_weights.unsqueeze(-1) 

174 return (streams + injected).flatten(-2) 

175 

176 def _adopt_source(self, module: nn.Module, use_combine: bool | None) -> None: 

177 """Retain source children and parameter identities during replacement.""" 

178 required = ("hc_norm", "input_mix_weight_down", "input_mix_weight_up") 

179 if any(not hasattr(module, name) for name in required): 

180 raise TypeError("GatedResidual source must expose hc_norm and input-mix projections") 

181 self.hc_norm = module.hc_norm 

182 self.input_mix_weight_down = module.input_mix_weight_down 

183 self.input_mix_weight_up = module.input_mix_weight_up 

184 source_inject = getattr(module, "block_inject_weight", None) 

185 inferred = source_inject is not None 

186 self.use_combine = inferred if use_combine is None else use_combine 

187 if not isinstance(self.use_combine, bool): 

188 raise TypeError("GatedResidual use_combine must be bool") 

189 if self.use_combine: 

190 if source_inject is None: 

191 raise ValueError("GatedResidual source has no block_inject_weight") 

192 self.block_inject_weight = source_inject 

193 

194 self.hc_count = _positive_int(getattr(module, "hc_count", None), "hc_count") 

195 self.hidden_size = _positive_int(getattr(module, "hidden_size", None), "hidden_size") 

196 self.hc_lowrank = _positive_int( 

197 getattr(module.input_mix_weight_down, "out_features", None), "hc_lowrank" 

198 ) 

199 expected = self.hyper_hidden_size 

200 if module.input_mix_weight_down.in_features != expected: 

201 raise ValueError("GatedResidual source down projection has incompatible input width") 

202 if ( 

203 module.input_mix_weight_up.in_features != self.hc_lowrank 

204 or module.input_mix_weight_up.out_features != expected 

205 ): 

206 raise ValueError("GatedResidual source up projection has incompatible shape") 

207 if self.use_combine and module.block_inject_weight.out_features != self.hc_count: 

208 raise ValueError("GatedResidual source injection projection has incompatible shape") 

209 self.train(module.training) 

210 

211 def forward( 

212 self, hyper_input: torch.Tensor, 

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

214 """Run the source-compatible mixer contract using the selected backend.""" 

215 if hyper_input.shape[-1] != self.hyper_hidden_size: 

216 raise ValueError( 

217 f"Expected {self.hyper_hidden_size} hyper-connection features, got {hyper_input.shape[-1]}" 

218 ) 

219 weight_gate = self.block_inject_weight.weight if self.use_combine else None 

220 mixed, injection = gated_residual( 

221 hyper_input, 

222 self.input_mix_weight_down.weight, 

223 self.input_mix_weight_up.weight, 

224 weight_gate, 

225 channels=self.hc_count, 

226 gamma=self.hc_norm.weight, 

227 eps=self.hc_norm.eps, 

228 backend=self.backend, 

229 ) 

230 if not self.use_combine: 

231 return mixed 

232 if injection is None: 

233 raise RuntimeError("GatedResidual combine requires injection weights") 

234 return mixed, hyper_input, injection 

235 

236 

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

238 """Declare explicit replicated parameter and sequence-token layouts. 

239 

240 The eager family currently keeps all projections replicated under TP. This 

241 is intentional: splitting the down projection requires an all-reduce between 

242 the down and up projections, which is not implicit in a module boundary. 

243 The declaration therefore preserves correctness while leaving a future 

244 collective-aware TP member free to introduce the Transformers rowwise plan. 

245 """ 

246 del module_fqn, member 

247 replicated = {axis: Replicate() for axis in context.mesh_dim_names if axis in context.axis_sizes} 

248 tokens = dict(replicated) 

249 if context.axis_sizes.get("cp", 1) > 1: 

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

251 if context.axis_sizes.get("tp", 1) > 1 and context.sequence_parallel: 

252 tokens["tp"] = Shard(1) 

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

254 outputs = ( 

255 ("mixed_input", "hyper_input", "injection_weights") 

256 if getattr(module, "use_combine", False) 

257 else ("output",) 

258 ) 

259 output_layout = {name: dict(tokens) for name in outputs} 

260 return ModuleShardingSpec( 

261 params=params, 

262 in_src={"hyper_input": dict(tokens)}, 

263 in_dst={"hyper_input": dict(tokens)}, 

264 out_src=output_layout, 

265 out_dst=output_layout, 

266 out_names=outputs, 

267 is_boundary=True, 

268 ) 

269 

270 

271@module_replacement 

272def GatedResidual( # pylint: disable=invalid-name 

273 *, 

274 config: Any = None, 

275 module: nn.Module | None = None, 

276 module_fqn: str = "", 

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

278 mesh: Any = None, 

279 use_combine: bool | None = None, 

280) -> nn.Module: 

281 """Build the config-selected Gated Residual family member from config or source.""" 

282 return build_family( 

283 GatedResidual, 

284 config=config, 

285 module=module, 

286 module_fqn=module_fqn, 

287 context=context, 

288 mesh=mesh, 

289 use_combine=use_combine, 

290 ) 

291 

292 

293register_module_family( 

294 ModuleFamily( 

295 name="gated_residual", 

296 baseline=GatedResidual, 

297 variants={"local": "hyper_parallel.components.modules.common.gated_residual.GatedResidualModule"}, 

298 default_variant="local", 

299 sharding=gated_residual_sharding, 

300 ) 

301) 

302 

303 

304__all__ = ["GatedResidual", "GatedResidualModule", "gated_residual_sharding"]