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.

batchnorm.py 7.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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 numpy as np
  10. from ..core import Buffer, Parameter
  11. from ..functional import batch_norm2d, sync_batch_norm
  12. from . import init
  13. from .module import Module
  14. class _BatchNorm(Module):
  15. def __init__(
  16. self,
  17. num_features,
  18. eps=1e-5,
  19. momentum=0.9,
  20. affine=True,
  21. track_running_stats=True,
  22. ):
  23. super(_BatchNorm, self).__init__()
  24. self.num_features = num_features
  25. self.eps = eps
  26. self.momentum = momentum
  27. self.affine = affine
  28. self.track_running_stats = track_running_stats
  29. if self.affine:
  30. self.weight = Parameter(np.ones(num_features, dtype=np.float32))
  31. self.bias = Parameter(np.zeros(num_features, dtype=np.float32))
  32. else:
  33. self.weight = None
  34. self.bias = None
  35. tshape = (1, self.num_features, 1, 1)
  36. if self.track_running_stats:
  37. self.running_mean = Buffer(np.zeros(tshape, dtype=np.float32))
  38. self.running_var = Buffer(np.ones(tshape, dtype=np.float32))
  39. else:
  40. self.running_mean = None
  41. self.running_var = None
  42. def reset_running_stats(self) -> None:
  43. if self.track_running_stats:
  44. init.zeros_(self.running_mean)
  45. init.ones_(self.running_var)
  46. def reset_parameters(self) -> None:
  47. self.reset_running_stats()
  48. if self.affine:
  49. init.ones_(self.weight)
  50. init.zeros_(self.bias)
  51. def _check_input_ndim(self, inp):
  52. raise NotImplementedError
  53. def forward(self, inp):
  54. self._check_input_ndim(inp)
  55. _ndims = len(inp.shape)
  56. if _ndims != 4:
  57. origin_shape = inp.shapeof()
  58. if _ndims == 2:
  59. n, c = inp.shapeof(0), inp.shapeof(1)
  60. new_shape = (n, c, 1, 1)
  61. elif _ndims == 3:
  62. n, c, h = inp.shapeof(0), inp.shapeof(1), inp.shapeof(2)
  63. new_shape = (n, c, h, 1)
  64. inp = inp.reshape(new_shape)
  65. if self.training and self.track_running_stats:
  66. exponential_average_factor = self.momentum
  67. else:
  68. exponential_average_factor = 0.0 # useless
  69. output = batch_norm2d(
  70. inp,
  71. self.running_mean,
  72. self.running_var,
  73. self.weight,
  74. self.bias,
  75. self.training or not self.track_running_stats,
  76. exponential_average_factor,
  77. self.eps,
  78. )
  79. if _ndims != 4:
  80. output = output.reshape(origin_shape)
  81. return output
  82. class SyncBatchNorm(_BatchNorm):
  83. r"""
  84. Applies Synchronization Batch Normalization.
  85. """
  86. def _check_input_ndim(self, inp):
  87. if len(inp.shape) not in {2, 3, 4}:
  88. raise ValueError(
  89. "expected 2D, 3D or 4D input (got {}D input)".format(len(inp.shape))
  90. )
  91. def forward(self, inp):
  92. self._check_input_ndim(inp)
  93. _ndims = len(inp.shape)
  94. if _ndims != 4:
  95. origin_shape = inp.shapeof()
  96. if _ndims == 2:
  97. n, c = inp.shapeof(0), inp.shapeof(1)
  98. new_shape = (n, c, 1, 1)
  99. elif _ndims == 3:
  100. n, c, h = inp.shapeof(0), inp.shapeof(1), inp.shapeof(2)
  101. new_shape = (n, c, h, 1)
  102. inp = inp.reshape(new_shape)
  103. if self.training and self.track_running_stats:
  104. exponential_average_factor = self.momentum
  105. else:
  106. exponential_average_factor = 0.0 # useless
  107. output = sync_batch_norm(
  108. inp,
  109. self.running_mean,
  110. self.running_var,
  111. self.weight,
  112. self.bias,
  113. self.training or not self.track_running_stats,
  114. exponential_average_factor,
  115. self.eps,
  116. )
  117. if _ndims != 4:
  118. output = output.reshape(origin_shape)
  119. return output
  120. class BatchNorm1d(_BatchNorm):
  121. r"""
  122. Applies Batch Normalization over a 2D/3D tensor.
  123. Refer to :class:`~.BatchNorm2d` for more information.
  124. """
  125. def _check_input_ndim(self, inp):
  126. if len(inp.shape) not in {2, 3}:
  127. raise ValueError(
  128. "expected 2D or 3D input (got {}D input)".format(len(inp.shape))
  129. )
  130. class BatchNorm2d(_BatchNorm):
  131. r"""
  132. Applies Batch Normalization over a 4D tensor.
  133. .. math::
  134. y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
  135. The mean and standard-deviation are calculated per-dimension over
  136. the mini-batches and :math:`\gamma` and :math:`\beta` are learnable
  137. parameter vectors.
  138. By default, during training this layer keeps running estimates of its
  139. computed mean and variance, which are then used for normalization during
  140. evaluation. The running estimates are kept with a default :attr:`momentum`
  141. of 0.9.
  142. If :attr:`track_running_stats` is set to ``False``, this layer will not
  143. keep running estimates, and batch statistics are instead used during
  144. evaluation time.
  145. .. note::
  146. This :attr:`momentum` argument is different from one used in optimizer
  147. classes and the conventional notion of momentum. Mathematically, the
  148. update rule for running statistics here is
  149. :math:`\hat{x}_\text{new} = \text{momentum} \times \hat{x} + (1 - \text{momentum}) \times x_t`,
  150. where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the
  151. new observed value.
  152. Because the Batch Normalization is done over the `C` dimension, computing
  153. statistics on `(N, H, W)` slices, it's common terminology to call this
  154. Spatial Batch Normalization.
  155. :type num_features: int
  156. :param num_features: usually the :math:`C` from an input of size
  157. :math:`(N, C, H, W)` or the highest ranked dimension of an input with
  158. less than 4D.
  159. :type eps: float
  160. :param eps: a value added to the denominator for numerical stability.
  161. Default: 1e-5.
  162. :type momentum: float
  163. :param momentum: the value used for the `running_mean` and `running_var`
  164. computation.
  165. Default: 0.9
  166. :type affine: bool
  167. :param affine: a boolean value that when set to ``True``, this module has
  168. learnable affine parameters. Default: ``True``
  169. :type track_running_stats: bool
  170. :param track_running_stats: when set to ``True``, this module tracks the
  171. running mean and variance. When set to ``False``, this module does not
  172. track such statistics and always uses batch statistics in both training
  173. and eval modes. Default: ``True``.
  174. Examples:
  175. .. testcode::
  176. import numpy as np
  177. import megengine as mge
  178. import megengine.module as M
  179. # With Learnable Parameters
  180. m = M.BatchNorm2d(4)
  181. inp = mge.tensor(np.random.rand(1, 4, 3, 3).astype("float32"))
  182. oup = m(inp)
  183. print(m.weight, m.bias)
  184. # Without Learnable Parameters
  185. m = M.BatchNorm2d(4, affine=False)
  186. oup = m(inp)
  187. print(m.weight, m.bias)
  188. .. testoutput::
  189. Tensor([1. 1. 1. 1.]) Tensor([0. 0. 0. 0.])
  190. None None
  191. """
  192. def _check_input_ndim(self, inp):
  193. if len(inp.shape) != 4:
  194. raise ValueError("expected 4D input (got {}D input)".format(len(inp.shape)))

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