initializer.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  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. This code is based on https://github.com/pytorch/pytorch/blob/master/torch/nn/init.py
  16. Ths copyright of pytorch/pytorch is a BSD-style license, as found in the LICENSE file.
  17. """
  18. import math
  19. import numpy as np
  20. import paddle
  21. import paddle.nn as nn
  22. __all__ = [
  23. 'uniform_',
  24. 'normal_',
  25. 'constant_',
  26. 'ones_',
  27. 'zeros_',
  28. 'xavier_uniform_',
  29. 'xavier_normal_',
  30. 'kaiming_uniform_',
  31. 'kaiming_normal_',
  32. 'linear_init_',
  33. 'conv_init_',
  34. 'reset_initialized_parameter',
  35. ]
  36. def _no_grad_uniform_(tensor, a, b):
  37. with paddle.no_grad():
  38. tensor.set_value(
  39. paddle.uniform(
  40. shape=tensor.shape, dtype=tensor.dtype, min=a, max=b))
  41. return tensor
  42. def _no_grad_normal_(tensor, mean=0., std=1.):
  43. with paddle.no_grad():
  44. tensor.set_value(paddle.normal(mean=mean, std=std, shape=tensor.shape))
  45. return tensor
  46. def _no_grad_fill_(tensor, value=0.):
  47. with paddle.no_grad():
  48. tensor.set_value(paddle.full_like(tensor, value, dtype=tensor.dtype))
  49. return tensor
  50. def uniform_(tensor, a, b):
  51. """
  52. Modified tensor inspace using uniform_
  53. Args:
  54. tensor (paddle.Tensor): paddle Tensor
  55. a (float|int): min value.
  56. b (float|int): max value.
  57. Return:
  58. tensor
  59. """
  60. return _no_grad_uniform_(tensor, a, b)
  61. def normal_(tensor, mean=0., std=1.):
  62. """
  63. Modified tensor inspace using normal_
  64. Args:
  65. tensor (paddle.Tensor): paddle Tensor
  66. mean (float|int): mean value.
  67. std (float|int): std value.
  68. Return:
  69. tensor
  70. """
  71. return _no_grad_normal_(tensor, mean, std)
  72. def constant_(tensor, value=0.):
  73. """
  74. Modified tensor inspace using constant_
  75. Args:
  76. tensor (paddle.Tensor): paddle Tensor
  77. value (float|int): value to fill tensor.
  78. Return:
  79. tensor
  80. """
  81. return _no_grad_fill_(tensor, value)
  82. def ones_(tensor):
  83. """
  84. Modified tensor inspace using ones_
  85. Args:
  86. tensor (paddle.Tensor): paddle Tensor
  87. Return:
  88. tensor
  89. """
  90. return _no_grad_fill_(tensor, 1)
  91. def zeros_(tensor):
  92. """
  93. Modified tensor inspace using zeros_
  94. Args:
  95. tensor (paddle.Tensor): paddle Tensor
  96. Return:
  97. tensor
  98. """
  99. return _no_grad_fill_(tensor, 0)
  100. def _calculate_fan_in_and_fan_out(tensor, reverse=False):
  101. """
  102. Calculate (fan_in, _fan_out) for tensor
  103. Args:
  104. tensor (Tensor): paddle.Tensor
  105. reverse (bool: False): tensor data format order, False by default as [fout, fin, ...]. e.g. : conv.weight [cout, cin, kh, kw] is False; linear.weight [cin, cout] is True
  106. Return:
  107. Tuple[fan_in, fan_out]
  108. """
  109. if tensor.ndim < 2:
  110. raise ValueError(
  111. "Fan in and fan out can not be computed for tensor with fewer than 2 dimensions"
  112. )
  113. if reverse:
  114. num_input_fmaps, num_output_fmaps = tensor.shape[0], tensor.shape[1]
  115. else:
  116. num_input_fmaps, num_output_fmaps = tensor.shape[1], tensor.shape[0]
  117. receptive_field_size = 1
  118. if tensor.ndim > 2:
  119. receptive_field_size = np.prod(tensor.shape[2:])
  120. fan_in = num_input_fmaps * receptive_field_size
  121. fan_out = num_output_fmaps * receptive_field_size
  122. return fan_in, fan_out
  123. def xavier_uniform_(tensor, gain=1., reverse=False):
  124. """
  125. Modified tensor inspace using xavier_uniform_
  126. Args:
  127. tensor (paddle.Tensor): paddle Tensor
  128. gain (float): super parameter, 1. default.
  129. reverse (bool): reverse (bool: False): tensor data format order, False by default as [fout, fin, ...].
  130. Return:
  131. tensor
  132. """
  133. fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor, reverse=reverse)
  134. std = gain * math.sqrt(2.0 / float(fan_in + fan_out))
  135. k = math.sqrt(3.0) * std
  136. return _no_grad_uniform_(tensor, -k, k)
  137. def xavier_normal_(tensor, gain=1., reverse=False):
  138. """
  139. Modified tensor inspace using xavier_normal_
  140. Args:
  141. tensor (paddle.Tensor): paddle Tensor
  142. gain (float): super parameter, 1. default.
  143. reverse (bool): reverse (bool: False): tensor data format order, False by default as [fout, fin, ...].
  144. Return:
  145. tensor
  146. """
  147. fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor, reverse=reverse)
  148. std = gain * math.sqrt(2.0 / float(fan_in + fan_out))
  149. return _no_grad_normal_(tensor, 0, std)
  150. # reference: https://pytorch.org/docs/stable/_modules/torch/nn/init.html
  151. def _calculate_correct_fan(tensor, mode, reverse=False):
  152. mode = mode.lower()
  153. valid_modes = ['fan_in', 'fan_out']
  154. if mode not in valid_modes:
  155. raise ValueError("Mode {} not supported, please use one of {}".format(
  156. mode, valid_modes))
  157. fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor, reverse)
  158. return fan_in if mode == 'fan_in' else fan_out
  159. def _calculate_gain(nonlinearity, param=None):
  160. linear_fns = [
  161. 'linear', 'conv1d', 'conv2d', 'conv3d', 'conv_transpose1d',
  162. 'conv_transpose2d', 'conv_transpose3d'
  163. ]
  164. if nonlinearity in linear_fns or nonlinearity == 'sigmoid':
  165. return 1
  166. elif nonlinearity == 'tanh':
  167. return 5.0 / 3
  168. elif nonlinearity == 'relu':
  169. return math.sqrt(2.0)
  170. elif nonlinearity == 'leaky_relu':
  171. if param is None:
  172. negative_slope = 0.01
  173. elif not isinstance(param, bool) and isinstance(
  174. param, int) or isinstance(param, float):
  175. # True/False are instances of int, hence check above
  176. negative_slope = param
  177. else:
  178. raise ValueError("negative_slope {} not a valid number".format(
  179. param))
  180. return math.sqrt(2.0 / (1 + negative_slope**2))
  181. elif nonlinearity == 'selu':
  182. return 3.0 / 4
  183. else:
  184. raise ValueError("Unsupported nonlinearity {}".format(nonlinearity))
  185. def kaiming_uniform_(tensor,
  186. a=0,
  187. mode='fan_in',
  188. nonlinearity='leaky_relu',
  189. reverse=False):
  190. """
  191. Modified tensor inspace using kaiming_uniform method
  192. Args:
  193. tensor (paddle.Tensor): paddle Tensor
  194. mode (str): ['fan_in', 'fan_out'], 'fin_in' defalut
  195. nonlinearity (str): nonlinearity method name
  196. reverse (bool): reverse (bool: False): tensor data format order, False by default as [fout, fin, ...].
  197. Return:
  198. tensor
  199. """
  200. fan = _calculate_correct_fan(tensor, mode, reverse)
  201. gain = _calculate_gain(nonlinearity, a)
  202. std = gain / math.sqrt(fan)
  203. k = math.sqrt(3.0) * std
  204. return _no_grad_uniform_(tensor, -k, k)
  205. def kaiming_normal_(tensor,
  206. a=0,
  207. mode='fan_in',
  208. nonlinearity='leaky_relu',
  209. reverse=False):
  210. """
  211. Modified tensor inspace using kaiming_normal_
  212. Args:
  213. tensor (paddle.Tensor): paddle Tensor
  214. mode (str): ['fan_in', 'fan_out'], 'fin_in' defalut
  215. nonlinearity (str): nonlinearity method name
  216. reverse (bool): reverse (bool: False): tensor data format order, False by default as [fout, fin, ...].
  217. Return:
  218. tensor
  219. """
  220. fan = _calculate_correct_fan(tensor, mode, reverse)
  221. gain = _calculate_gain(nonlinearity, a)
  222. std = gain / math.sqrt(fan)
  223. return _no_grad_normal_(tensor, 0, std)
  224. def linear_init_(module):
  225. bound = 1 / math.sqrt(module.weight.shape[0])
  226. uniform_(module.weight, -bound, bound)
  227. uniform_(module.bias, -bound, bound)
  228. def conv_init_(module):
  229. bound = 1 / np.sqrt(np.prod(module.weight.shape[1:]))
  230. uniform_(module.weight, -bound, bound)
  231. if module.bias is not None:
  232. uniform_(module.bias, -bound, bound)
  233. def bias_init_with_prob(prior_prob=0.01):
  234. """initialize conv/fc bias value according to a given probability value."""
  235. bias_init = float(-np.log((1 - prior_prob) / prior_prob))
  236. return bias_init
  237. @paddle.no_grad()
  238. def reset_initialized_parameter(model, include_self=True):
  239. """
  240. Reset initialized parameter using following method for [conv, linear, embedding, bn]
  241. Args:
  242. model (paddle.Layer): paddle Layer
  243. include_self (bool: False): include_self for Layer.named_sublayers method. Indicate whether including itself
  244. Return:
  245. None
  246. """
  247. for _, m in model.named_sublayers(include_self=include_self):
  248. if isinstance(m, nn.Conv2D):
  249. k = float(m._groups) / (m._in_channels * m._kernel_size[0] *
  250. m._kernel_size[1])
  251. k = math.sqrt(k)
  252. _no_grad_uniform_(m.weight, -k, k)
  253. if hasattr(m, 'bias') and getattr(m, 'bias') is not None:
  254. _no_grad_uniform_(m.bias, -k, k)
  255. elif isinstance(m, nn.Linear):
  256. k = math.sqrt(1. / m.weight.shape[0])
  257. _no_grad_uniform_(m.weight, -k, k)
  258. if hasattr(m, 'bias') and getattr(m, 'bias') is not None:
  259. _no_grad_uniform_(m.bias, -k, k)
  260. elif isinstance(m, nn.Embedding):
  261. _no_grad_normal_(m.weight, mean=0., std=1.)
  262. elif isinstance(m, (nn.BatchNorm2D, nn.LayerNorm)):
  263. _no_grad_fill_(m.weight, 1.)
  264. if hasattr(m, 'bias') and getattr(m, 'bias') is not None:
  265. _no_grad_fill_(m.bias, 0)