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

168 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"""Root mean square normalization module.""" 

16 

17from __future__ import annotations 

18 

19from collections.abc import Mapping 

20from math import isfinite 

21from typing import Any 

22 

23import torch 

24from torch._subclasses.fake_tensor import is_fake 

25from hyper_parallel.components.checkpoint.weight_conversion import WeightConverter 

26 

27from hyper_parallel.components.checkpoint.conversion_ops import AddScalar 

28from hyper_parallel.models.replacement import module_replacement 

29from hyper_parallel.components.modules.family import SelectorSpec, VariantRule 

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

31 

32 

33def _validate_rms_settings(hidden_size: int, eps: float) -> None: 

34 """Validate normalization semantics without requiring a concrete config class.""" 

35 if isinstance(hidden_size, bool) or not isinstance(hidden_size, int) or hidden_size <= 0: 

36 raise ValueError("RMSNormModule hidden_size must be a positive integer") 

37 if isinstance(eps, bool) or not isinstance(eps, (int, float)): 

38 raise TypeError("RMSNormModule eps must be a real scalar") 

39 if not isfinite(eps) or eps <= 0: 

40 raise ValueError("RMSNormModule eps must be finite and positive") 

41 

42 

43def _hf_scale_kind(source: Any) -> str | None: 

44 """Recognize audited HF parameter representations in the source conversion owner.""" 

45 source_type = type(source) 

46 if not source_type.__module__.startswith("transformers.models."): 

47 return None 

48 if source_type.__name__ in ("Qwen3_5RMSNorm", "Qwen3_5MoeRMSNorm"): 

49 return "offset" 

50 if source_type.__name__ in ("Qwen3RMSNorm", "Qwen3MoeRMSNorm", "Qwen2MoeRMSNorm", 

51 "Qwen3VLMoeTextRMSNorm", "DeepseekV2RMSNorm", "DeepseekV3RMSNorm", "DeepseekV32RMSNorm", 

52 "KimiLinearRMSNorm", 

53 "DeepseekV4RMSNorm"): 

54 return "direct" 

55 return None 

56 

57 

58class _RMSNormPolicy(torch.nn.Module): 

59 """Declare rounding order and optional FP32 scale ownership at construction.""" 

60 

61 @property 

62 

63 def variance_epsilon(self) -> float: 

64 """Expose the source normalization epsilon to fused residual computations.""" 

65 return self.eps 

66 

67 def _set_policy(self, source: Any, cast_order: str | None, fp32_weight: bool | None) -> None: 

68 """Resolve source rounding order and FP32 scale ownership.""" 

69 if cast_order is None: 

70 cast_order = getattr(source, "rms_norm_cast_order", None) 

71 if cast_order is None: 

72 # Native models can declare FP32 multiplication explicitly; adopted HF scales retain source rounding. 

73 cast_order = "before_weight" if _hf_scale_kind(source) == "direct" else "after_weight" 

74 if cast_order not in ("before_weight", "after_weight"): 

75 raise ValueError("cast_order must be before_weight or after_weight") 

76 if fp32_weight is None: 

77 fp32_weight = getattr(source, "fp32_weight", False) 

78 if not isinstance(fp32_weight, bool): 

79 raise TypeError("fp32_weight must be bool") 

80 self.rms_norm_cast_order = cast_order 

81 self.fp32_weight = fp32_weight 

82 self.fp32_parameter_names = ("weight",) if fp32_weight else () 

83 

84 def _apply(self, fn: Any, recurse: bool = True) -> _RMSNormPolicy: 

85 """Preserve declared FP32 parameters and gradients during conversion.""" 

86 if not self.fp32_weight: 

87 return super()._apply(fn, recurse=recurse) 

88 protected = {id(self.weight)} 

89 if self.weight.grad is not None: 

90 protected.add(id(self.weight.grad)) 

91 

92 def preserve_scale(tensor: torch.Tensor) -> torch.Tensor: 

93 """Retain the declared scale and gradient precision during module conversion.""" 

94 converted = fn(tensor) 

95 if id(tensor) not in protected or converted.dtype == torch.float32: 

96 return converted 

97 return (converted.float() if tensor.is_meta 

98 else tensor.to(device=converted.device, dtype=torch.float32)) 

99 

100 return super()._apply(preserve_scale, recurse=recurse) 

101 

102 

103class RMSNormModule(_RMSNormPolicy): 

104 """NPU-fused direct-scale RMSNorm with source-compatible precision and state.""" 

105 

106 def __init__( 

107 self, 

108 hidden_size: int | None = None, 

109 eps: float = 1e-5, 

110 *, 

111 module: torch.nn.Module | None = None, 

112 module_fqn: str = "", 

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

114 config: Any = None, 

115 cast_order: str | None = None, 

116 fp32_weight: bool | None = None, 

117 ) -> None: 

118 """Build a direct-scale RMSNormModule or replace an existing module. 

119 

120 Args: 

121 hidden_size: Size of the normalized dimension for direct construction. 

122 eps: Epsilon added to the variance. 

123 module: Optional source module whose parameter layout is preserved. 

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

125 context: Replacement context supplied by Trainer. 

126 config: Complete direct construction configuration, exclusive with source arguments. 

127 cast_order: Rounding boundary relative to scale multiplication. 

128 fp32_weight: Keep the scale FP32 during model dtype conversion. 

129 

130 Raises: 

131 TypeError: If the source module does not expose a supported RMSNormModule contract. 

132 ValueError: If neither a source module nor a positive hidden size is supplied. 

133 """ 

134 super().__init__() 

135 del module_fqn, context 

136 self._set_policy(config if config is not None else module, cast_order, fp32_weight) 

137 if config is not None: 

138 if module is not None or hidden_size is not None: 

139 raise ValueError("config cannot be combined with module or hidden_size") 

140 _validate_rms_settings(config.hidden_size, config.eps) 

141 hidden_size, eps = config.hidden_size, config.eps 

142 if module is not None: 

143 if _hf_scale_kind(module) == "offset" or isinstance(module, OffsetRMSNormModule): 

144 raise ValueError("unit-offset source requires OffsetRMSNorm, not direct-scale RMSNorm") 

145 if not isinstance(getattr(module, "weight", None), torch.nn.Parameter): 

146 raise TypeError("RMSNormModule source module must expose an nn.Parameter weight") 

147 source_eps = getattr(module, "eps", None) 

148 if source_eps is None: 

149 source_eps = getattr(module, "variance_epsilon", None) 

150 if source_eps is None: 

151 raise TypeError( 

152 "RMSNormModule source module must expose eps or variance_epsilon" 

153 ) 

154 self.eps = float(source_eps) 

155 if module.weight.ndim != 1: 

156 raise ValueError("RMSNormModule source weight must be one-dimensional") 

157 _validate_rms_settings(module.weight.numel(), self.eps) 

158 if self.fp32_weight and module.weight.dtype != torch.float32: 

159 raise ValueError("fp32_weight source must already own an FP32 scale") 

160 self.weight = module.weight 

161 self.train(module.training) 

162 return 

163 _validate_rms_settings(hidden_size, eps) 

164 self.eps = eps 

165 self.weight = torch.nn.Parameter(torch.ones(hidden_size, dtype=torch.float32 if self.fp32_weight else None)) 

166 

167 def _normalize(self, x: torch.Tensor, scale: torch.Tensor) -> torch.Tensor: 

168 return _npu_rms_norm(x, scale, self.eps, self.rms_norm_cast_order) 

169 

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

171 """Apply the concrete member with the declared precision contract.""" 

172 return self._normalize(hidden_states, self.weight) 

173 

174 def reset_parameters(self) -> None: 

175 """Restore the direct scale after meta materialization.""" 

176 torch.nn.init.ones_(self.weight) 

177 

178 def make_transforms(self) -> list: 

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

180 

181 Returns: 

182 An empty converter list, matching members whose initialization is 

183 fully owned by ``reset_parameters``. 

184 """ 

185 return [] 

186 

187 

188class OffsetRMSNormModule(_RMSNormPolicy): 

189 """NPU-fused unit-offset RMSNorm preserving offset checkpoint state.""" 

190 

191 def __init__(self, *, config: Any = None, module: torch.nn.Module | None = None, 

192 module_fqn: str = "", context: Any = None, 

193 cast_order: str | None = None, fp32_weight: bool | None = None, 

194 source_representation: str = "offset") -> None: 

195 """Retain offset Parameters; checkpoints use the source's offset representation.""" 

196 super().__init__() 

197 del module_fqn, context 

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

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

200 self._set_policy(config if config is not None else module, cast_order, fp32_weight) 

201 if source_representation not in ("offset", "scale"): 

202 raise ValueError("source_representation must be offset or scale") 

203 if config is not None and source_representation != "offset": 

204 raise ValueError("direct construction stores offsets; scale conversion requires a source") 

205 self.source_representation = source_representation 

206 if _hf_scale_kind(module) == "direct" and source_representation != "scale": 

207 raise ValueError("direct-scale HF source requires RMSNorm, not OffsetRMSNorm") 

208 if config is not None: 

209 self.eps = config.eps 

210 _validate_rms_settings(config.hidden_size, self.eps) 

211 self.weight = torch.nn.Parameter(torch.zeros( 

212 config.hidden_size, dtype=torch.float32 if self.fp32_weight else None)) 

213 else: 

214 self._adopt_source(module) 

215 

216 def _adopt_source(self, module: torch.nn.Module) -> None: 

217 """Validate offset ownership and convert only an explicitly declared direct scale.""" 

218 weight = getattr(module, "weight", None) 

219 if not isinstance(weight, torch.nn.Parameter) or weight.ndim != 1: 

220 raise TypeError("offset source must expose a one-dimensional Parameter weight") 

221 self.eps = module.eps 

222 _validate_rms_settings(weight.numel(), self.eps) 

223 if self.fp32_weight and weight.dtype != torch.float32: 

224 raise ValueError("fp32_weight source must already own an FP32 offset") 

225 if self.source_representation == "scale": 

226 if isinstance(module, OffsetRMSNormModule) or _hf_scale_kind(module) == "offset": 

227 raise ValueError("offset source must not be declared as a direct scale") 

228 weight = torch.nn.Parameter(weight.detach() - 1.0, requires_grad=weight.requires_grad) 

229 self.weight = weight 

230 self.train(module.training) 

231 

232 def reset_parameters(self) -> None: 

233 """Initialize the stored offset, not the effective scale.""" 

234 torch.nn.init.zeros_(self.weight) 

235 

236 def make_transforms(self) -> list[WeightConverter]: 

237 """Describe only an explicitly requested legacy direct-scale conversion.""" 

238 if self.source_representation == "scale": 

239 return [WeightConverter(source_patterns=["weight"], target_patterns="weight", 

240 operations=[AddScalar(-1.0)])] 

241 return [] 

242 

243 def _normalize(self, x: torch.Tensor, scale: torch.Tensor) -> torch.Tensor: 

244 return _npu_rms_norm(x, scale, self.eps, self.rms_norm_cast_order) 

245 

246 def forward(self, x: torch.Tensor) -> torch.Tensor: 

247 """Add the offset in FP32 before applying the declared rounding order.""" 

248 return self._normalize(x, 1.0 + self.weight.float()) 

249 

250 

251def _npu_rms_norm(x: torch.Tensor, scale: torch.Tensor, eps: float, cast_order: str) -> torch.Tensor: 

252 """Execute fused NPU normalization with the declared source rounding boundary.""" 

253 # Census traces installed fused modules with CPU FakeTensors and operator stand-ins. 

254 if x.device.type != "npu" and not is_fake(x): 

255 raise ValueError("NPU RMSNorm requires NPU tensors; select use_fused_ops=False for Torch execution") 

256 # Native members must not load the optional NPU package. 

257 from hyper_parallel.components.functional.rms_norm import rms_norm # pylint: disable=import-outside-toplevel 

258 

259 if cast_order == "before_weight": 

260 # The NPU kernel accumulates internally; retain the input dtype for saved activations. 

261 normalized = rms_norm(x, torch.ones_like(scale, dtype=x.dtype), eps) 

262 return scale * normalized 

263 return rms_norm(x.float(), scale.float(), eps).to(x.dtype) 

264 

265 

266def _native_rms_norm(x: torch.Tensor, scale: torch.Tensor, eps: float, cast_order: str) -> torch.Tensor: 

267 """Preserve FP32 accumulation and the source rounding boundary using Torch operations.""" 

268 values = x.float() 

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

270 if cast_order == "before_weight": 

271 return scale * normalized.to(x.dtype) 

272 return (normalized * scale.float()).to(x.dtype) 

273 

274 

275class NativeRMSNormModule(RMSNormModule): 

276 """Ordinary Torch direct-scale member sharing the fused member's parameter contract.""" 

277 

278 def _normalize(self, x: torch.Tensor, scale: torch.Tensor) -> torch.Tensor: 

279 return _native_rms_norm(x, scale, self.eps, self.rms_norm_cast_order) 

280 

281 

282class NativeOffsetRMSNormModule(OffsetRMSNormModule): 

283 """Ordinary Torch unit-offset member retaining offset parameters without conversion.""" 

284 

285 def _normalize(self, x: torch.Tensor, scale: torch.Tensor) -> torch.Tensor: 

286 return _native_rms_norm(x, scale, self.eps, self.rms_norm_cast_order) 

287 

288 

289@module_replacement 

290def RMSNorm( # pylint: disable=invalid-name 

291 *, config: Any = None, module: torch.nn.Module | None = None, 

292 module_fqn: str = "", context: Mapping[str, Any] | None = None, mesh: Any = None, 

293 cast_order: str | None = None, fp32_weight: bool | None = None, use_fused_ops: bool = False, 

294) -> torch.nn.Module: 

295 """Build a tracked RMSNormModule family member from config or a direct-scale source. 

296 

297 ``use_fused_ops=False`` selects the ordinary Torch member by default; 

298 ``use_fused_ops=True`` explicitly selects the NPU-fused member without fallback. 

299 Existing RMSNormModule class construction remains available for type compatibility. 

300 Offset source conversion continues through OffsetRMSNormModule. 

301 """ 

302 return build_family(RMSNorm, config=config, module=module, module_fqn=module_fqn, 

303 context=context, mesh=mesh, cast_order=cast_order, fp32_weight=fp32_weight, 

304 use_fused_ops=use_fused_ops) 

305 

306 

307register_module_family(ModuleFamily( 

308 name="rms_norm", baseline=RMSNorm, 

309 variants={"local": "hyper_parallel.components.modules.common.rms_norm.NativeRMSNormModule", 

310 "npu": "hyper_parallel.components.modules.common.rms_norm.RMSNormModule"}, 

311 selector_specs={"use_fused_ops": SelectorSpec(bool, False)}, 

312 variant_rules=(VariantRule({"use_fused_ops": True, "parallel": False}, "npu"),), 

313 default_variant="local", 

314)) 

315 

316 

317@module_replacement 

318def OffsetRMSNorm( # pylint: disable=invalid-name 

319 *, config: Any = None, module: torch.nn.Module | None = None, 

320 module_fqn: str = "", context: Mapping[str, Any] | None = None, mesh: Any = None, 

321 cast_order: str | None = None, fp32_weight: bool | None = None, 

322 source_representation: str = "offset", use_fused_ops: bool = False, 

323) -> torch.nn.Module: 

324 """Select native/NPU execution while preserving the offset checkpoint representation.""" 

325 return build_family(OffsetRMSNorm, config=config, module=module, module_fqn=module_fqn, 

326 context=context, mesh=mesh, cast_order=cast_order, fp32_weight=fp32_weight, 

327 source_representation=source_representation, use_fused_ops=use_fused_ops) 

328 

329 

330register_module_family(ModuleFamily( 

331 name="offset_rms_norm", baseline=OffsetRMSNorm, 

332 variants={"local": "hyper_parallel.components.modules.common.rms_norm.NativeOffsetRMSNormModule", 

333 "npu": "hyper_parallel.components.modules.common.rms_norm.OffsetRMSNormModule"}, 

334 selector_specs={"use_fused_ops": SelectorSpec(bool, False)}, 

335 variant_rules=(VariantRule({"use_fused_ops": True, "parallel": False}, "npu"),), 

336 default_variant="local", 

337))