You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

init.py 9.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import math
  10. from functools import reduce
  11. from typing import Optional, Tuple, Union
  12. import numpy as np
  13. from ..core import Tensor, Graph
  14. from ..random import gaussian, uniform
  15. def fill_(tensor: Tensor, val: Union[float, int]) -> None:
  16. """Fill the given ``tensor`` with value ``val``.
  17. :param tensor: An n-dimentional tensor to be initialized
  18. :param val: The value to be filled throughout the tensor
  19. """
  20. tensor.set_value(np.full(tensor.shape, val, tensor.dtype))
  21. def zeros_(tensor: Tensor) -> None:
  22. """Fill the given ``tensor`` with scalar value `0`.
  23. :param tensor: An n-dimentional tensor to be initialized
  24. """
  25. fill_(tensor, 0)
  26. def ones_(tensor: Tensor) -> None:
  27. """Fill the given ``tensor`` with the scalar value `1`.
  28. :param tensor: An n-dimentional tensor to be initialized
  29. """
  30. fill_(tensor, 1)
  31. def uniform_(tensor: Tensor, a: float = 0.0, b: float = 1.0) -> None:
  32. r"""Fill the given ``tensor`` with random value sampled from uniform distribution
  33. :math:`\mathcal{U}(\text{a}, \text{b})`.
  34. :param tensor: An n-dimentional tensor to be initialized
  35. :param a: Lower bound of the sampling interval
  36. :param b: Upper bound of the sampling interval
  37. """
  38. with Graph(eager_evaluation=True):
  39. tensor.set_value((b - a) * uniform(tensor.shape) + a)
  40. def normal_(tensor: Tensor, mean: float = 0.0, std: float = 1.0) -> None:
  41. r"""Fill the given ``tensor`` with random value sampled from normal distribution
  42. :math:`\mathcal{N}(\text{mean}, \text{std}^2)`.
  43. :param tensor: An n-dimentional tensor to be initialized
  44. :param mean: The mean of the normal distribution
  45. :param std: The standard deviation of the normal distribution
  46. """
  47. with Graph(eager_evaluation=True):
  48. tensor.set_value(gaussian(tensor.shape, mean=mean, std=std))
  49. def calculate_gain(
  50. nonlinearity: str, param: Optional[Union[int, float]] = None
  51. ) -> float:
  52. r"""Return a recommended gain value (see the table below) for the given nonlinearity
  53. function.
  54. ================= ====================================================
  55. nonlinearity gain
  56. ================= ====================================================
  57. Linear / Identity :math:`1`
  58. Conv{1,2,3}D :math:`1`
  59. Sigmoid :math:`1`
  60. Tanh :math:`\frac{5}{3}`
  61. ReLU :math:`\sqrt{2}`
  62. Leaky Relu :math:`\sqrt{\frac{2}{1 + \text{negative_{slope}}^2}}`
  63. ================= ====================================================
  64. :param nonlinearity: Name of the non-linear function
  65. :param param: Optional parameter for leaky_relu. Only effective when
  66. ``nonlinearity`` is "leaky_relu".
  67. """
  68. linear_fns = [
  69. "linear",
  70. "conv1d",
  71. "conv2d",
  72. "conv3d",
  73. "conv_transpose1d",
  74. "conv_transpose2d",
  75. "conv_transpose3d",
  76. ]
  77. if nonlinearity in linear_fns or nonlinearity == "sigmoid":
  78. return 1
  79. if nonlinearity == "tanh":
  80. return 5.0 / 3
  81. if nonlinearity == "relu":
  82. return math.sqrt(2.0)
  83. if nonlinearity == "leaky_relu":
  84. if param is None:
  85. negative_slope = 0.01
  86. elif (
  87. not isinstance(param, bool)
  88. and isinstance(param, int)
  89. or isinstance(param, float)
  90. ):
  91. # True/False are instances of int, hence check above
  92. negative_slope = param
  93. else:
  94. raise ValueError("negative_slope {} not a valid number".format(param))
  95. return math.sqrt(2.0 / (1 + negative_slope ** 2))
  96. raise ValueError("Unsupported nonlinearity {}".format(nonlinearity))
  97. def calculate_fan_in_and_fan_out(tensor: Tensor) -> Tuple[float, float]:
  98. """
  99. Calculate fan_in / fan_out value for given weight tensor. This function assumes
  100. input tensor is stored in NCHW format.
  101. :param tensor: Weight tensor in NCHW format
  102. """
  103. shape = tensor.shape
  104. ndim = len(shape)
  105. if ndim < 2:
  106. raise ValueError(
  107. "fan_in and fan_out can not be computed for tensor with fewer than 2 "
  108. "dimensions"
  109. )
  110. if ndim == 2: # Linear
  111. fan_in = shape[1]
  112. fan_out = shape[0]
  113. else:
  114. num_input_fmaps = shape[1]
  115. num_output_fmaps = shape[0]
  116. receptive_field_size = 1
  117. if ndim > 2:
  118. receptive_field_size = reduce(lambda x, y: x * y, shape[2:], 1)
  119. fan_in = num_input_fmaps * receptive_field_size
  120. fan_out = num_output_fmaps * receptive_field_size
  121. return fan_in, fan_out
  122. def calculate_correct_fan(tensor: Tensor, mode: str) -> float:
  123. """
  124. Calculate fan_in or fan_out value for given weight tensor, depending on given
  125. ``mode``.
  126. See :func:`calculate_fan_in_and_fan_out` for details.
  127. :param tensor: Weight tensor in NCHW format
  128. :param mode: ``'fan_in'`` or ``'fan_out'``
  129. """
  130. mode = mode.lower()
  131. valid_modes = ["fan_in", "fan_out"]
  132. if mode not in valid_modes:
  133. raise ValueError(
  134. "Mode {} not supported, please use one of {}".format(mode, valid_modes)
  135. )
  136. fan_in, fan_out = calculate_fan_in_and_fan_out(tensor)
  137. return fan_in if mode == "fan_in" else fan_out
  138. def xavier_uniform_(tensor: Tensor, gain: float = 1.0) -> None:
  139. r"""Fill ``tensor`` with random values sampled from :math:`\mathcal{U}(-a, a)`
  140. where
  141. .. math::
  142. a = \text{gain} \times \sqrt{\frac{6}{\text{fan_in} + \text{fan_out}}}
  143. Also known as Glorot initialization. Detailed information can be retrieved from
  144. `Understanding the difficulty of training deep feedforward neural networks` -
  145. Glorot, X. & Bengio, Y. (2010).
  146. :param tensor: An n-dimentional tensor to be initialized
  147. :param gain: Scaling factor for :math:`a`.
  148. """
  149. fan_in, fan_out = calculate_fan_in_and_fan_out(tensor)
  150. std = gain * math.sqrt(2.0 / float(fan_in + fan_out))
  151. a = math.sqrt(3.0) * std
  152. uniform_(tensor, -a, a)
  153. def xavier_normal_(tensor: Tensor, gain: float = 1.0) -> None:
  154. r"""Fill ``tensor`` with random values sampled from
  155. :math:`\mathcal{N}(0, \text{std}^2)` where
  156. .. math::
  157. \text{std} = \text{gain} \times \sqrt{\frac{2}{\text{fan_in} + \text{fan_out}}}
  158. Also known as Glorot initialization. Detailed information can be retrieved from
  159. `Understanding the difficulty of training deep feedforward neural networks` -
  160. Glorot, X. & Bengio, Y. (2010).
  161. :param tensor: An n-dimentional tensor to be initialized
  162. :param gain: Scaling factor for :math:`std`.
  163. """
  164. fan_in, fan_out = calculate_fan_in_and_fan_out(tensor)
  165. std = gain * math.sqrt(2.0 / float(fan_in + fan_out))
  166. normal_(tensor, 0.0, std)
  167. def msra_uniform_(
  168. tensor: Tensor, a: float = 0, mode: str = "fan_in", nonlinearity: str = "leaky_relu"
  169. ) -> None:
  170. r"""Fill ``tensor`` wilth random values sampled from
  171. :math:`\mathcal{U}(-\text{bound}, \text{bound})` where
  172. .. math::
  173. \text{bound} = \sqrt{\frac{6}{(1 + a^2) \times \text{fan_in}}}
  174. Detailed information can be retrieved from
  175. `Delving deep into rectifiers: Surpassing human-level performance on ImageNet
  176. classification`
  177. :param tensor: An n-dimentional tensor to be initialized
  178. :param a: Optional parameter for calculating gain for leaky_relu. See
  179. :func:`calculate_gain` for details.
  180. :param mode: ``'fan_in'`` or ``'fan_out'``, used to calculate :math:`gain`, the
  181. scaling factor for :math:`bound`. See :func:`calculate_fan_in_and_fan_out` for
  182. details.
  183. :param nonlinearity: Name of the non-linear function used to calculate :math:`gain`.
  184. See :func:`calculate_gain` for details.
  185. """
  186. fan = calculate_correct_fan(tensor, mode)
  187. gain = calculate_gain(nonlinearity, a)
  188. std = gain / math.sqrt(fan)
  189. bound = math.sqrt(3.0) * std
  190. uniform_(tensor, -bound, bound)
  191. def msra_normal_(
  192. tensor: Tensor, a: float = 0, mode: str = "fan_in", nonlinearity: str = "leaky_relu"
  193. ) -> None:
  194. r"""Fill ``tensor`` wilth random values sampled from
  195. :math:`\mathcal{N}(0, \text{std}^2)` where
  196. .. math::
  197. \text{std} = \sqrt{\frac{2}{(1 + a^2) \times \text{fan_in}}}
  198. Detailed information can be retrieved from
  199. `Delving deep into rectifiers: Surpassing human-level performance on ImageNet
  200. classification`
  201. :param tensor: An n-dimentional tensor to be initialized
  202. :param a: Optional parameter for calculating gain for leaky_relu. See
  203. :func:`calculate_gain` for details.
  204. :param mode: ``'fan_in'`` or ``'fan_out'``, used to calculate :math:`gain`, the
  205. scaling factor for :math:`gain`. See :func:`calculate_fan_in_and_fan_out` for
  206. details.
  207. :param nonlinearity: Name of the non-linear function used to calculate :math:`gain`.
  208. See :func:`calculate_gain` for details.
  209. """
  210. fan = calculate_correct_fan(tensor, mode)
  211. gain = calculate_gain(nonlinearity, a)
  212. std = gain / math.sqrt(fan)
  213. normal_(tensor, 0, std)

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台

Contributors (1)