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

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

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