fast_norm.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. """ 'Fast' Normalization Functions
  2. For GroupNorm and LayerNorm these functions bypass typical AMP upcast to float32.
  3. Additionally, for LayerNorm, the APEX fused LN is used if available (which also does not upcast)
  4. Hacked together by / Copyright 2022 Ross Wightman
  5. """
  6. from typing import List, Optional
  7. import torch
  8. from torch.nn import functional as F
  9. try:
  10. from apex.normalization.fused_layer_norm import fused_layer_norm_affine
  11. has_apex = True
  12. except ImportError:
  13. has_apex = False
  14. try:
  15. from apex.normalization.fused_layer_norm import fused_rms_norm_affine, fused_rms_norm
  16. has_apex_rmsnorm = True
  17. except ImportError:
  18. has_apex_rmsnorm = False
  19. has_torch_rms_norm = hasattr(F, 'rms_norm')
  20. # fast (ie lower precision LN) can be disabled with this flag if issues crop up
  21. _USE_FAST_NORM = False # defaulting to False for now
  22. def get_autocast_dtype(device: str = 'cuda'):
  23. try:
  24. return torch.get_autocast_dtype(device)
  25. except (AttributeError, TypeError):
  26. # dispatch to older device specific fns, only covering cuda/cpu devices here
  27. if device == 'cpu':
  28. return torch.get_autocast_cpu_dtype()
  29. else:
  30. assert device == 'cuda'
  31. return torch.get_autocast_gpu_dtype()
  32. def is_autocast_enabled(device: str = 'cuda'):
  33. try:
  34. return torch.is_autocast_enabled(device)
  35. except TypeError:
  36. # dispatch to older device specific fns, only covering cuda/cpu devices here
  37. if device == 'cpu':
  38. return torch.is_autocast_cpu_enabled()
  39. else:
  40. assert device == 'cuda'
  41. return torch.is_autocast_enabled() # defaults cuda (only cuda on older pytorch)
  42. def is_fast_norm():
  43. return _USE_FAST_NORM
  44. def set_fast_norm(enable=True):
  45. global _USE_FAST_NORM
  46. _USE_FAST_NORM = enable
  47. def fast_group_norm(
  48. x: torch.Tensor,
  49. num_groups: int,
  50. weight: Optional[torch.Tensor] = None,
  51. bias: Optional[torch.Tensor] = None,
  52. eps: float = 1e-5
  53. ) -> torch.Tensor:
  54. if torch.jit.is_scripting():
  55. # currently cannot use is_autocast_enabled within torchscript
  56. return F.group_norm(x, num_groups, weight, bias, eps)
  57. if is_autocast_enabled(x.device.type):
  58. # normally native AMP casts GN inputs to float32
  59. # here we use the low precision autocast dtype
  60. dt = get_autocast_dtype(x.device.type)
  61. x, weight, bias = x.to(dt), weight.to(dt), bias.to(dt) if bias is not None else None
  62. with torch.amp.autocast(device_type=x.device.type, enabled=False):
  63. return F.group_norm(x, num_groups, weight, bias, eps)
  64. def fast_layer_norm(
  65. x: torch.Tensor,
  66. normalized_shape: List[int],
  67. weight: Optional[torch.Tensor] = None,
  68. bias: Optional[torch.Tensor] = None,
  69. eps: float = 1e-5
  70. ) -> torch.Tensor:
  71. if torch.jit.is_scripting():
  72. # currently cannot use is_autocast_enabled within torchscript
  73. return F.layer_norm(x, normalized_shape, weight, bias, eps)
  74. if has_apex:
  75. return fused_layer_norm_affine(x, weight, bias, normalized_shape, eps)
  76. if is_autocast_enabled(x.device.type):
  77. # normally native AMP casts LN inputs to float32
  78. # apex LN does not, this is behaving like Apex
  79. dt = get_autocast_dtype(x.device.type)
  80. x, weight, bias = x.to(dt), weight.to(dt), bias.to(dt) if bias is not None else None
  81. with torch.amp.autocast(device_type=x.device.type, enabled=False):
  82. return F.layer_norm(x, normalized_shape, weight, bias, eps)
  83. def rms_norm(
  84. x: torch.Tensor,
  85. normalized_shape: List[int],
  86. weight: Optional[torch.Tensor] = None,
  87. eps: float = 1e-5,
  88. ):
  89. norm_ndim = len(normalized_shape)
  90. v = x.pow(2)
  91. if torch.jit.is_scripting():
  92. # ndim = len(x.shape)
  93. # dims = list(range(ndim - norm_ndim, ndim)) # this doesn't work on pytorch <= 1.13.x
  94. # NOTE -ve dims cause torchscript to crash in some cases, out of options to work around
  95. assert norm_ndim == 1
  96. v = torch.mean(v, dim=-1).unsqueeze(-1) # ts crashes with -ve dim + keepdim=True
  97. else:
  98. dims = tuple(range(-1, -norm_ndim - 1, -1))
  99. v = torch.mean(v, dim=dims, keepdim=True)
  100. x = x * torch.rsqrt(v + eps)
  101. if weight is not None:
  102. x = x * weight
  103. return x
  104. def fast_rms_norm(
  105. x: torch.Tensor,
  106. normalized_shape: List[int],
  107. weight: Optional[torch.Tensor] = None,
  108. eps: float = 1e-5,
  109. ) -> torch.Tensor:
  110. if torch.jit.is_scripting():
  111. # this must be by itself, cannot merge with has_apex_rmsnorm
  112. return rms_norm(x, normalized_shape, weight, eps)
  113. if has_apex_rmsnorm:
  114. if weight is None:
  115. return fused_rms_norm(x, normalized_shape, eps)
  116. else:
  117. return fused_rms_norm_affine(x, weight, normalized_shape, eps)
  118. if is_autocast_enabled(x.device.type):
  119. # normally native AMP casts LN inputs to float32 and leaves the output as float32
  120. # apex LN does not, this is behaving like Apex
  121. dt = get_autocast_dtype(x.device.type)
  122. x, weight = x.to(dt), weight.to(dt)
  123. with torch.amp.autocast(device_type=x.device.type, enabled=False):
  124. if has_torch_rms_norm:
  125. x = F.rms_norm(x, normalized_shape, weight, eps)
  126. else:
  127. x = rms_norm(x, normalized_shape, weight, eps)
  128. return x
  129. def rms_norm2d(
  130. x: torch.Tensor,
  131. normalized_shape: List[int],
  132. weight: Optional[torch.Tensor] = None,
  133. eps: float = 1e-5,
  134. ):
  135. assert len(normalized_shape) == 1
  136. v = x.pow(2)
  137. v = torch.mean(v, dim=1, keepdim=True)
  138. x = x * torch.rsqrt(v + eps)
  139. if weight is not None:
  140. x = x * weight.reshape(1, -1, 1, 1)
  141. return x
  142. def fast_rms_norm2d(
  143. x: torch.Tensor,
  144. normalized_shape: List[int],
  145. weight: Optional[torch.Tensor] = None,
  146. eps: float = 1e-5,
  147. ) -> torch.Tensor:
  148. if torch.jit.is_scripting():
  149. # this must be by itself, cannot merge with has_apex_rmsnorm
  150. return rms_norm2d(x, normalized_shape, weight, eps)
  151. if has_apex_rmsnorm:
  152. x = x.permute(0, 2, 3, 1)
  153. if weight is None:
  154. x = fused_rms_norm(x, normalized_shape, eps)
  155. else:
  156. x = fused_rms_norm_affine(x, weight, normalized_shape, eps)
  157. x = x.permute(0, 3, 1, 2)
  158. if is_autocast_enabled(x.device.type):
  159. # normally native AMP casts norm inputs to float32 and leaves the output as float32
  160. # apex does not, this is behaving like Apex
  161. dt = get_autocast_dtype(x.device.type)
  162. x, weight = x.to(dt), weight.to(dt)
  163. with torch.amp.autocast(device_type=x.device.type, enabled=False):
  164. x = rms_norm2d(x, normalized_shape, weight, eps)
  165. return x
  166. def simple_norm(
  167. x: torch.Tensor,
  168. normalized_shape: List[int],
  169. weight: Optional[torch.Tensor] = None,
  170. eps: float = 1e-5,
  171. ):
  172. norm_ndim = len(normalized_shape)
  173. if torch.jit.is_scripting():
  174. # ndim = len(x.shape)
  175. # dims = list(range(ndim - norm_ndim, ndim)) # this doesn't work on pytorch <= 1.13.x
  176. # NOTE -ve dims cause torchscript to crash in some cases, out of options to work around
  177. assert norm_ndim == 1
  178. v = torch.var(x, dim=-1).unsqueeze(-1) # ts crashes with -ve dim + keepdim=True
  179. else:
  180. dims = tuple(range(-1, -norm_ndim - 1, -1))
  181. v = torch.var(x, dim=dims, keepdim=True)
  182. x = x * torch.rsqrt(v + eps)
  183. if weight is not None:
  184. x = x * weight
  185. return x
  186. def fast_simple_norm(
  187. x: torch.Tensor,
  188. normalized_shape: List[int],
  189. weight: Optional[torch.Tensor] = None,
  190. eps: float = 1e-5,
  191. ) -> torch.Tensor:
  192. if torch.jit.is_scripting():
  193. # this must be by itself, cannot merge with has_apex_rmsnorm
  194. return simple_norm(x, normalized_shape, weight, eps)
  195. if is_autocast_enabled(x.device.type):
  196. # normally native AMP casts LN inputs to float32
  197. # apex LN does not, this is behaving like Apex
  198. dt = get_autocast_dtype(x.device.type)
  199. x, weight = x.to(dt), weight.to(dt)
  200. with torch.amp.autocast(device_type=x.device.type, enabled=False):
  201. x = simple_norm(x, normalized_shape, weight, eps)
  202. return x