Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / ops / impl / rms_norm.py: 80%

35 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"""RMSNorm contracts and implementations.""" 

16 

17from typing import Protocol 

18 

19import torch 

20 

21from ..registry import OpRegistry 

22from ..spec import OpSpec 

23from .._dependency import require_package, require_symbol 

24 

25 

26class RMSNormFn(Protocol): 

27 """Normalize the last dimension and apply the caller-owned scale.""" 

28 

29 def __call__(self, x: torch.Tensor, weight: torch.Tensor, eps: float = 1e-5) -> torch.Tensor: 

30 """Return the normalized and scaled tensor.""" 

31 

32 

33RMS_NORM = OpSpec[RMSNormFn](config_key="rms_norm") 

34RMS_NORM_FP32_AFFINE = OpSpec[RMSNormFn](config_key="rms_norm", variant="fp32_affine") 

35 

36 

37def _native(x: torch.Tensor, weight: torch.Tensor, eps: float = 1e-5) -> torch.Tensor: 

38 accumulation_dtype = torch.float32 if x.dtype in (torch.float16, torch.bfloat16) else x.dtype 

39 values = x.to(accumulation_dtype) 

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

41 return (normalized * weight.to(accumulation_dtype)).to(x.dtype) 

42 

43 

44def _native_fp32_affine(x: torch.Tensor, weight: torch.Tensor, eps: float = 1e-5) -> torch.Tensor: 

45 return _native(x.float(), weight.float(), eps).to(x.dtype) 

46 

47 

48def _load_native() -> RMSNormFn: 

49 return _native 

50 

51 

52def _load_native_fp32_affine() -> RMSNormFn: 

53 return _native_fp32_affine 

54 

55 

56def _load_npu() -> RMSNormFn: 

57 require_symbol(require_package("torch_npu"), "npu_rms_norm") 

58 # The existing implementation imports the optional NPU package. 

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

60 return rms_norm 

61 

62 

63def _load_npu_fp32_affine() -> RMSNormFn: 

64 kernel = _load_npu() 

65 

66 def normalize(x: torch.Tensor, weight: torch.Tensor, eps: float = 1e-5) -> torch.Tensor: 

67 """Apply normalization and affine scaling in FP32 before restoring the input dtype.""" 

68 return kernel(x.float(), weight.float(), eps).to(x.dtype) 

69 

70 return normalize 

71 

72 

73def register_rms_norm(registry: OpRegistry) -> None: 

74 """Register the standard and FP32-affine RMSNorm contracts.""" 

75 registry.register_family("rms_norm", specs=(RMS_NORM, RMS_NORM_FP32_AFFINE)) 

76 registry.register_impl(RMS_NORM, name="native", devices=("cuda", "cpu", "npu"), load=_load_native) 

77 registry.register_impl(RMS_NORM, name="torch_npu", devices=("npu",), load=_load_npu) 

78 registry.register_impl( 

79 RMS_NORM_FP32_AFFINE, name="native", devices=("cuda", "cpu", "npu"), load=_load_native_fp32_affine, 

80 ) 

81 registry.register_impl(RMS_NORM_FP32_AFFINE, name="torch_npu", devices=("npu",), load=_load_npu_fp32_affine)