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 11 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 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. from typing import Optional
  10. import numpy as np
  11. from ..distributed.group import WORLD, Group
  12. from ..functional.nn import batch_norm, sync_batch_norm
  13. from ..tensor import Parameter, Tensor
  14. from . import init
  15. from .module import Module
  16. class _BatchNorm(Module):
  17. def __init__(
  18. self,
  19. num_features,
  20. eps=1e-5,
  21. momentum=0.9,
  22. affine=True,
  23. track_running_stats=True,
  24. freeze=False,
  25. **kwargs
  26. ):
  27. super(_BatchNorm, self).__init__(**kwargs)
  28. self.num_features = num_features
  29. self.eps = eps
  30. self.momentum = momentum
  31. self.affine = affine
  32. self.track_running_stats = track_running_stats
  33. self._track_running_stats_saved = track_running_stats
  34. self.freeze = freeze
  35. if self.freeze:
  36. assert (
  37. self._track_running_stats_saved
  38. ), "track_running_stats must be initilized to True if freeze is True"
  39. tshape = (1, self.num_features, 1, 1)
  40. if self.affine:
  41. self.weight = Parameter(np.ones(tshape, dtype=np.float32))
  42. self.bias = Parameter(np.zeros(tshape, dtype=np.float32))
  43. else:
  44. self.weight = None
  45. self.bias = None
  46. if self.track_running_stats:
  47. self.running_mean = Tensor(np.zeros(tshape, dtype=np.float32))
  48. self.running_var = Tensor(np.ones(tshape, dtype=np.float32))
  49. else:
  50. self.running_mean = None
  51. self.running_var = None
  52. def reset_running_stats(self) -> None:
  53. if self.track_running_stats:
  54. init.zeros_(self.running_mean)
  55. init.ones_(self.running_var)
  56. def reset_parameters(self) -> None:
  57. self.reset_running_stats()
  58. if self.affine:
  59. init.ones_(self.weight)
  60. init.zeros_(self.bias)
  61. def _check_input_ndim(self, inp):
  62. raise NotImplementedError
  63. def forward(self, inp):
  64. self._check_input_ndim(inp)
  65. if self._track_running_stats_saved == False:
  66. assert (
  67. self.track_running_stats == False
  68. ), "track_running_stats can not be initilized to False and changed to True later"
  69. inp_shape = inp.shape
  70. _ndims = len(inp_shape)
  71. if _ndims != 4:
  72. origin_shape = inp_shape
  73. if _ndims == 2:
  74. n, c = inp_shape[0], inp_shape[1]
  75. new_shape = (n, c, 1, 1)
  76. elif _ndims == 3:
  77. n, c, h = inp_shape[0], inp_shape[1], inp_shape[2]
  78. new_shape = (n, c, h, 1)
  79. inp = inp.reshape(new_shape)
  80. _weight = self.weight
  81. _bias = self.bias
  82. if self.freeze:
  83. if _weight is not None:
  84. _weight = _weight.detach()
  85. if _bias is not None:
  86. _bias = _bias.detach()
  87. # Need to expand to elementwise operations here
  88. # see MGB_IMPL_OPR_GRAD(BatchNormForward) in src/opr/impl/dnn/batch_norm.cpp
  89. scale = (self.running_var + self.eps) ** (-0.5)
  90. if _weight is not None:
  91. scale *= _weight
  92. bias = -self.running_mean * scale
  93. if _bias is not None:
  94. bias += _bias
  95. return inp * scale + bias
  96. if self.training and self.track_running_stats:
  97. exponential_average_factor = self.momentum
  98. else:
  99. exponential_average_factor = 0.0 # useless
  100. output = batch_norm(
  101. inp,
  102. self.running_mean if self.track_running_stats else None,
  103. self.running_var if self.track_running_stats else None,
  104. _weight,
  105. _bias,
  106. training=self.training
  107. or ((self.running_mean is None) and (self.running_var is None)),
  108. momentum=exponential_average_factor,
  109. eps=self.eps,
  110. )
  111. if _ndims != 4:
  112. output = output.reshape(origin_shape)
  113. return output
  114. def _module_info_string(self) -> str:
  115. s = (
  116. "{num_features}, eps={eps}, momentum={momentum}, affine={affine}, "
  117. "track_running_stats={track_running_stats}"
  118. )
  119. return s.format(**self.__dict__)
  120. class SyncBatchNorm(_BatchNorm):
  121. r"""
  122. Applies Synchronized Batch Normalization for distributed training.
  123. """
  124. def __init__(
  125. self,
  126. num_features,
  127. eps=1e-5,
  128. momentum=0.9,
  129. affine=True,
  130. track_running_stats=True,
  131. freeze=False,
  132. group: Optional[Group] = WORLD,
  133. **kwargs
  134. ) -> None:
  135. super().__init__(
  136. num_features, eps, momentum, affine, track_running_stats, freeze, **kwargs
  137. )
  138. self.group = group
  139. def _check_input_ndim(self, inp):
  140. if len(inp.shape) not in {2, 3, 4}:
  141. raise ValueError(
  142. "expected 2D, 3D or 4D input (got {}D input)".format(len(inp.shape))
  143. )
  144. def forward(self, inp):
  145. self._check_input_ndim(inp)
  146. inp_shape = inp.shape
  147. _ndims = len(inp_shape)
  148. if _ndims != 4:
  149. new_shape = Tensor([1, 1, 1, 1], device=inp.device)
  150. origin_shape = inp_shape
  151. if _ndims == 2:
  152. new_shape[:2] = origin_shape[:2]
  153. elif _ndims == 3:
  154. new_shape[:3] = origin_shape[:3]
  155. else:
  156. raise ValueError(
  157. "expected 2D, 3D or 4D input (got {}D input)".format(len(inp_shape))
  158. )
  159. inp = inp.reshape(new_shape)
  160. if self.training and self.track_running_stats:
  161. exponential_average_factor = self.momentum
  162. else:
  163. exponential_average_factor = 0.0 # useless
  164. _weight = self.weight
  165. _bias = self.bias
  166. if self.freeze:
  167. if _weight is not None:
  168. _weight = _weight.detach()
  169. if _bias is not None:
  170. _bias = _bias.detach()
  171. output = sync_batch_norm(
  172. inp,
  173. self.running_mean,
  174. self.running_var,
  175. _weight,
  176. _bias,
  177. training=(self.training and not self.freeze)
  178. or ((self.running_mean is None) and (self.running_var is None)),
  179. momentum=exponential_average_factor,
  180. eps=self.eps,
  181. group=self.group,
  182. )
  183. if _ndims != 4:
  184. output = output.reshape(origin_shape)
  185. return output
  186. class BatchNorm1d(_BatchNorm):
  187. r"""
  188. Applies Batch Normalization over a 2D/3D tensor.
  189. Refer to :class:`~.BatchNorm2d` for more information.
  190. """
  191. def _check_input_ndim(self, inp):
  192. if len(inp.shape) not in {2, 3}:
  193. raise ValueError(
  194. "expected 2D or 3D input (got {}D input)".format(len(inp.shape))
  195. )
  196. class BatchNorm2d(_BatchNorm):
  197. r"""
  198. Applies Batch Normalization over a 4D tensor.
  199. .. math::
  200. y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
  201. The mean and standard-deviation are calculated per-dimension over
  202. the mini-batches and :math:`\gamma` and :math:`\beta` are learnable
  203. parameter vectors.
  204. By default, during training this layer keeps running estimates of its
  205. computed mean and variance, which are then used for normalization during
  206. evaluation. The running estimates are kept with a default :attr:`momentum`
  207. of 0.9.
  208. If :attr:`track_running_stats` is set to ``False``, this layer will not
  209. keep running estimates, batch statistics is used during
  210. evaluation time instead.
  211. .. note::
  212. This :attr:`momentum` argument is different from one used in optimizer
  213. classes and the conventional notion of momentum. Mathematically, the
  214. update rule for running statistics here is
  215. :math:`\hat{x}_\text{new} = \text{momentum} \times \hat{x} + (1 - \text{momentum}) \times x_t`,
  216. where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the
  217. new observed value.
  218. Because the Batch Normalization is done over the `C` dimension, computing
  219. statistics on `(N, H, W)` slices, it's common terminology to call this
  220. Spatial Batch Normalization.
  221. :type num_features: int
  222. :param num_features: usually :math:`C` from an input of shape
  223. :math:`(N, C, H, W)` or the highest ranked dimension of an input
  224. less than 4D.
  225. :type eps: float
  226. :param eps: a value added to the denominator for numerical stability.
  227. Default: 1e-5
  228. :type momentum: float
  229. :param momentum: the value used for the ``running_mean`` and ``running_var`` computation.
  230. Default: 0.9
  231. :type affine: bool
  232. :param affine: a boolean value that when set to True, this module has
  233. learnable affine parameters. Default: True
  234. :type track_running_stats: bool
  235. :param track_running_stats: when set to True, this module tracks the
  236. running mean and variance. When set to False, this module does not
  237. track such statistics and always uses batch statistics in both training
  238. and eval modes. Default: True
  239. :type freeze: bool
  240. :param freeze: when set to True, this module does not update the
  241. running mean and variance, and uses the running mean and variance instead of
  242. the batch mean and batch variance to normalize the input. The parameter takes effect
  243. only when the module is initilized with track_running_stats as True.
  244. Default: False
  245. Examples:
  246. .. testcode::
  247. import numpy as np
  248. import megengine as mge
  249. import megengine.module as M
  250. # With Learnable Parameters
  251. m = M.BatchNorm2d(4)
  252. inp = mge.tensor(np.random.rand(1, 4, 3, 3).astype("float32"))
  253. oup = m(inp)
  254. print(m.weight.numpy().flatten(), m.bias.numpy().flatten())
  255. # Without L`e`arnable Parameters
  256. m = M.BatchNorm2d(4, affine=False)
  257. oup = m(inp)
  258. print(m.weight, m.bias)
  259. Outputs:
  260. .. testoutput::
  261. [1. 1. 1. 1.] [0. 0. 0. 0.]
  262. None None
  263. """
  264. def _check_input_ndim(self, inp):
  265. if len(inp.shape) != 4:
  266. raise ValueError("expected 4D input (got {}D input)".format(len(inp.shape)))

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