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

116 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 Attention Residual module family and sequence-layout contract.""" 

16 

17from __future__ import annotations 

18 

19from collections.abc import Mapping 

20from math import isfinite 

21from typing import Any 

22 

23import torch 

24from torch import nn 

25from torch.utils.checkpoint import checkpoint 

26 

27from hyper_parallel.components.functional.attention_residuals import block_attention_residuals 

28from hyper_parallel.components.modules.family import ModuleFamily 

29from hyper_parallel.components.modules.module_family import build_family, register_module_family 

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

31from hyper_parallel.distributed.module_binding import ParallelModuleSpec 

32from hyper_parallel.distributed.recipe_spec import ModuleShardingSpec 

33from hyper_parallel.models.replacement import module_replacement 

34 

35 

36_BACKEND_ALIASES = {"eager": "eager", "ascendc": "ascendc", "torch": "eager", "cann": "ascendc"} 

37 

38 

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

40 """Read an optional setting from a model config or source module.""" 

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

42 

43 

44def _resolve_backend(value: str) -> str: 

45 """Normalize legacy backend names to the shared functional API.""" 

46 if not isinstance(value, str) or value not in _BACKEND_ALIASES: 

47 raise ValueError("AttentionResidual backend must be eager or ascendc") 

48 return _BACKEND_ALIASES[value] 

49 

50 

51def _validate_dimensions(hidden_size: Any, eps: Any, initializer_range: Any) -> None: 

52 """Validate dimensions and initialization scalars before allocating parameters.""" 

53 if isinstance(hidden_size, bool) or not isinstance(hidden_size, int) or hidden_size < 1: 

54 raise ValueError("AttentionResidual hidden_size must be a positive integer") 

55 if isinstance(eps, bool) or not isinstance(eps, (int, float)) or not isfinite(eps) or eps <= 0: 

56 raise ValueError("AttentionResidual eps must be finite and positive") 

57 if (isinstance(initializer_range, bool) or not isinstance(initializer_range, (int, float)) 

58 or not isfinite(initializer_range) or initializer_range <= 0): 

59 raise ValueError("AttentionResidual initializer_range must be finite and positive") 

60 

61 

62class AttentionResidualModule(nn.Module): 

63 """Mix the current residual with the completed residual blocks for each token.""" 

64 

65 def __init__( 

66 self, 

67 *, 

68 config: Any = None, 

69 module: nn.Module | None = None, 

70 module_fqn: str = "", 

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

72 ) -> None: 

73 """Construct from model dimensions or adopt a compatible source module. 

74 

75 Args: 

76 config: Config with ``hidden_size`` and ``rms_norm_eps`` (or ``eps``), and optional 

77 ``attention_residual_backend`` (``eager`` or ``ascendc``) and 

78 ``attention_residual_recompute`` settings. The shorter ``attn_res_backend`` and 

79 ``attn_res_recompute`` names are accepted as aliases. 

80 module: Source module exposing ``projection`` and ``norm_weight`` Parameters. 

81 module_fqn: Replacement path supplied by the module replacement executor. 

82 context: Logical construction context supplied by the family builder. 

83 """ 

84 super().__init__() 

85 del module_fqn, context 

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

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

88 

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

90 self.eps = _config_value( 

91 source_config, 

92 "rms_norm_eps", 

93 _config_value(source_config, "eps", _config_value(module, "eps")), 

94 ) 

95 initializer_range = _config_value( 

96 source_config, 

97 "initializer_range", 

98 _config_value(module, "initializer_range", 0.02), 

99 ) 

100 configured_backend = _config_value( 

101 source_config, 

102 "attention_residual_backend", 

103 _config_value(source_config, "attn_res_backend", _config_value(module, "backend", "eager")), 

104 ) 

105 if configured_backend is None: 

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

107 self.backend = _resolve_backend(configured_backend) 

108 self.recompute = _config_value( 

109 source_config, 

110 "attention_residual_recompute", 

111 _config_value(source_config, "attn_res_recompute", _config_value(module, "recompute", False)), 

112 ) 

113 if not isinstance(self.recompute, bool): 

114 raise TypeError("AttentionResidual recompute must be bool") 

115 

116 if module is not None: 

117 projection = getattr(module, "projection", None) 

118 norm_weight = getattr(module, "norm_weight", None) 

119 if not isinstance(projection, nn.Parameter) or not isinstance(norm_weight, nn.Parameter): 

120 raise TypeError("AttentionResidual source must expose projection and norm_weight Parameters") 

121 hidden_size = projection.shape[-1] if projection.ndim in (1, 2) else None 

122 _validate_dimensions(hidden_size, self.eps, initializer_range) 

123 if tuple(projection.shape) not in ((hidden_size,), (1, hidden_size)): 

124 raise ValueError("AttentionResidual projection must have shape [H] or [1, H]") 

125 if tuple(norm_weight.shape) != (hidden_size,): 

126 raise ValueError("AttentionResidual norm_weight must have shape [H]") 

127 self.projection = projection 

128 self.norm_weight = norm_weight 

129 self.initializer_range = float(initializer_range) 

130 self.train(module.training) 

131 return 

132 

133 hidden_size = _config_value(config, "hidden_size") 

134 _validate_dimensions(hidden_size, self.eps, initializer_range) 

135 self.initializer_range = float(initializer_range) 

136 self.projection = nn.Parameter(torch.empty(1, hidden_size, dtype=torch.float32)) 

137 self.norm_weight = nn.Parameter(torch.ones(hidden_size, dtype=torch.float32)) 

138 self.reset_parameters() 

139 

140 @torch.no_grad() 

141 def reset_parameters(self) -> None: 

142 """Initialize the pseudo-query to zero and RMS scale to one.""" 

143 if not getattr(self.projection, "_is_hf_initialized", False): 

144 nn.init.zeros_(self.projection) 

145 if not getattr(self.norm_weight, "_is_hf_initialized", False): 

146 nn.init.ones_(self.norm_weight) 

147 

148 def make_transforms(self) -> list: 

149 """Keep the projection parameter names and shapes unchanged.""" 

150 return [] 

151 

152 def forward(self, prefix: torch.Tensor, history: torch.Tensor) -> torch.Tensor: 

153 """Mix ``[B,S,H]`` prefix states with ``[B,S,N,H]`` completed blocks.""" 

154 if self.recompute and self.training and torch.is_grad_enabled(): 

155 return checkpoint(self._mix, prefix, history, use_reentrant=False) 

156 return self._mix(prefix, history) 

157 

158 def _mix(self, prefix: torch.Tensor, history: torch.Tensor) -> torch.Tensor: 

159 """Flatten token rows for the shared functional implementation, then restore shape.""" 

160 shape = prefix.shape 

161 result = block_attention_residuals( 

162 prefix.reshape(-1, shape[-1]), 

163 history.reshape(shape[0] * shape[1], history.shape[2], shape[-1]), 

164 self.projection, 

165 self.norm_weight, 

166 norm_eps=self.eps, 

167 backend=self.backend, 

168 ) 

169 return result.reshape(shape) 

170 

171 

172def attention_residual_sharding( 

173 *, module: nn.Module, module_fqn: str, member: Any, context: Any, 

174) -> ModuleShardingSpec: 

175 """Declare replicated parameters and the CP/TP-sequence token layout.""" 

176 del module, module_fqn, member 

177 replicated = { 

178 axis: Replicate() 

179 for axis in context.mesh_dim_names 

180 if axis in context.axis_sizes 

181 } 

182 token_layout = dict(replicated) 

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

184 token_layout["cp"] = Shard(1) 

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

186 token_layout["tp"] = Shard(1) 

187 return ModuleShardingSpec( 

188 params={name: dict(replicated) for name in ("projection", "norm_weight")}, 

189 in_src={"prefix": dict(token_layout), "history": dict(token_layout)}, 

190 in_dst={"prefix": dict(token_layout), "history": dict(token_layout)}, 

191 out_src={"output": dict(token_layout)}, 

192 out_dst={"output": dict(token_layout)}, 

193 out_names=("output",), 

194 is_boundary=True, 

195 ) 

196 

197 

198def _same_placements(actual: Mapping[str, Any] | None, expected: Mapping[str, Any]) -> bool: 

199 """Treat omitted mesh axes as replicated, matching planner semantics.""" 

200 actual = actual or {} 

201 return all( 

202 actual.get(axis, Replicate()) == expected.get(axis, Replicate()) 

203 for axis in set(actual) | set(expected) 

204 ) 

205 

206 

207def validate_attention_residual_layout(*, module: nn.Module, sharding: Any, context: Any) -> None: 

208 """Reject a plan that violates the Attention Residual parameter or token contract.""" 

209 expected = attention_residual_sharding(module=module, module_fqn="", member=None, context=context) 

210 if not sharding.is_boundary or set(sharding.params or {}) != set(expected.params): 

211 raise ValueError("AttentionResidual must own both projection parameters at a module boundary") 

212 for name, placement in expected.params.items(): 

213 if not _same_placements(sharding.params[name], placement): 

214 raise ValueError(f"unsupported AttentionResidual parameter layout for {name!r}") 

215 for field in ("in_src", "in_dst", "out_src", "out_dst"): 

216 actual = getattr(sharding, field) or {} 

217 required = getattr(expected, field) or {} 

218 if set(actual) != set(required) or any( 

219 not _same_placements(actual[name], placement) for name, placement in required.items() 

220 ): 

221 raise ValueError(f"unsupported AttentionResidual {field} layout") 

222 if tuple(sharding.out_names or ()) != ("output",): 

223 raise ValueError("AttentionResidual output contract must contain only 'output'") 

224 

225 

226def attention_residual_parallel_spec(*, module: nn.Module, member: Any) -> ParallelModuleSpec: 

227 """Expose the layout validator without binding communication resources.""" 

228 del module, member 

229 return ParallelModuleSpec( 

230 "common.attention_residual.local", 

231 validate=validate_attention_residual_layout, 

232 ) 

233 

234 

235@module_replacement 

236def AttentionResidual( # pylint: disable=invalid-name 

237 *, 

238 config: Any = None, 

239 module: nn.Module | None = None, 

240 module_fqn: str = "", 

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

242 mesh: Any = None, 

243) -> nn.Module: 

244 """Construct Attention Residual from config or a source module. 

245 

246 Backend and recompute choices are configured through the model config rather than 

247 constructor overrides. 

248 """ 

249 return build_family( 

250 AttentionResidual, 

251 config=config, 

252 module=module, 

253 module_fqn=module_fqn, 

254 context=context, 

255 mesh=mesh, 

256 ) 

257 

258 

259register_module_family(ModuleFamily( 

260 name="attention_residual", 

261 baseline=AttentionResidual, 

262 variants={"local": "hyper_parallel.components.modules.common.attention_residual.AttentionResidualModule"}, 

263 default_variant="local", 

264 sharding=attention_residual_sharding, 

265 parallel_spec=attention_residual_parallel_spec, 

266)) 

267 

268 

269__all__ = ["AttentionResidual", "AttentionResidualModule"]