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.2 kB

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

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