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.

test_batchnorm.py 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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 functools
  10. import platform
  11. import numpy as np
  12. import pytest
  13. import megengine as mge
  14. import megengine.distributed as dist
  15. from megengine import Tensor
  16. from megengine.core._trace_option import use_symbolic_shape
  17. from megengine.distributed.helper import get_device_count_by_fork
  18. from megengine.module import BatchNorm1d, BatchNorm2d, SyncBatchNorm
  19. _assert_allclose = functools.partial(np.testing.assert_allclose, atol=5e-6, rtol=5e-6)
  20. @pytest.mark.skipif(
  21. platform.system() == "Darwin", reason="do not imp GPU mode at macos now"
  22. )
  23. @pytest.mark.skipif(
  24. platform.system() == "Windows", reason="windows disable MGB_ENABLE_OPR_MM"
  25. )
  26. @pytest.mark.skipif(get_device_count_by_fork("gpu") < 2, reason="need more gpu device")
  27. @pytest.mark.isolated_distributed
  28. def test_syncbn():
  29. nr_chan = 8
  30. data_shape = (3, nr_chan, 4, 16)
  31. momentum = 0.9
  32. eps = 1e-5
  33. running_mean = np.zeros((1, nr_chan, 1, 1), dtype=np.float32)
  34. running_var = np.ones((1, nr_chan, 1, 1), dtype=np.float32)
  35. steps = 4
  36. nr_ranks = 2
  37. server = dist.Server()
  38. port = server.py_server_port
  39. @dist.launcher(n_gpus=2)
  40. def worker(data, yv_expect, running_mean, running_var):
  41. rank = dist.get_rank()
  42. bn = SyncBatchNorm(nr_chan, momentum=momentum, eps=eps)
  43. for i in range(steps):
  44. yv = bn(Tensor(data[rank][i]))
  45. _assert_allclose(yv.numpy(), yv_expect[rank])
  46. _assert_allclose(bn.running_mean.numpy(), running_mean)
  47. _assert_allclose(bn.running_var.numpy(), running_var)
  48. xv = []
  49. for i in range(steps):
  50. xv.append(np.random.normal(loc=2.3, size=data_shape).astype(np.float32))
  51. xv_transposed = np.transpose(xv[i], [0, 2, 3, 1]).reshape(
  52. (data_shape[0] * data_shape[2] * data_shape[3], nr_chan)
  53. )
  54. mean = np.mean(xv_transposed, axis=0).reshape(1, nr_chan, 1, 1)
  55. var_biased = np.var(xv_transposed, axis=0).reshape((1, nr_chan, 1, 1))
  56. sd = np.sqrt(var_biased + eps)
  57. var_unbiased = np.var(xv_transposed, axis=0, ddof=1).reshape((1, nr_chan, 1, 1))
  58. running_mean = running_mean * momentum + mean * (1 - momentum)
  59. running_var = running_var * momentum + var_unbiased * (1 - momentum)
  60. yv_expect = (xv[i] - mean) / sd
  61. data = []
  62. for i in range(nr_ranks):
  63. data.append([])
  64. for j in range(steps):
  65. data[i].append(xv[j][:, :, :, i * 8 : i * 8 + 8])
  66. yv_expect = [yv_expect[:, :, :, i * 8 : i * 8 + 8] for i in range(nr_ranks)]
  67. worker(data, yv_expect, running_mean, running_var)
  68. def test_batchnorm():
  69. nr_chan = 8
  70. data_shape = (3, nr_chan, 4)
  71. momentum = 0.9
  72. bn = BatchNorm1d(nr_chan, momentum=momentum)
  73. running_mean = np.zeros((1, nr_chan, 1), dtype=np.float32)
  74. running_var = np.ones((1, nr_chan, 1), dtype=np.float32)
  75. for i in range(3):
  76. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  77. mean = np.mean(np.mean(xv, axis=0, keepdims=True), axis=2, keepdims=True)
  78. xv_transposed = np.transpose(xv, [0, 2, 1]).reshape(
  79. (data_shape[0] * data_shape[2], nr_chan)
  80. )
  81. var_biased = np.var(xv_transposed, axis=0).reshape((1, nr_chan, 1))
  82. sd = np.sqrt(var_biased + bn.eps)
  83. var_unbiased = np.var(xv_transposed, axis=0, ddof=1).reshape((1, nr_chan, 1))
  84. running_mean = running_mean * momentum + mean * (1 - momentum)
  85. running_var = running_var * momentum + var_unbiased * (1 - momentum)
  86. yv = bn(Tensor(xv))
  87. yv_expect = (xv - mean) / sd
  88. _assert_allclose(yv.numpy(), yv_expect)
  89. _assert_allclose(bn.running_mean.numpy().reshape(-1), running_mean.reshape(-1))
  90. _assert_allclose(bn.running_var.numpy().reshape(-1), running_var.reshape(-1))
  91. # test set 'training' flag to False
  92. mean_backup = bn.running_mean.numpy()
  93. var_backup = bn.running_var.numpy()
  94. bn.training = False
  95. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  96. data = Tensor(xv)
  97. yv1 = bn(data)
  98. yv2 = bn(data)
  99. np.testing.assert_equal(yv1.numpy(), yv2.numpy())
  100. np.testing.assert_equal(mean_backup, bn.running_mean.numpy())
  101. np.testing.assert_equal(var_backup, bn.running_var.numpy())
  102. yv_expect = (xv - running_mean) / np.sqrt(running_var + bn.eps)
  103. _assert_allclose(yv1.numpy(), yv_expect)
  104. @pytest.mark.skipif(
  105. platform.system() == "Darwin", reason="do not imp GPU mode at macos now"
  106. )
  107. def test_syncbn1d():
  108. nr_chan = 8
  109. data_shape = (3, nr_chan, 4)
  110. momentum = 0.9
  111. bn = SyncBatchNorm(nr_chan, momentum=momentum)
  112. running_mean = np.zeros((1, nr_chan, 1), dtype=np.float32)
  113. running_var = np.ones((1, nr_chan, 1), dtype=np.float32)
  114. for i in range(3):
  115. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  116. mean = np.mean(np.mean(xv, axis=0, keepdims=True), axis=2, keepdims=True)
  117. xv_transposed = np.transpose(xv, [0, 2, 1]).reshape(
  118. (data_shape[0] * data_shape[2], nr_chan)
  119. )
  120. var_biased = np.var(xv_transposed, axis=0).reshape((1, nr_chan, 1))
  121. sd = np.sqrt(var_biased + bn.eps)
  122. var_unbiased = np.var(xv_transposed, axis=0, ddof=1).reshape((1, nr_chan, 1))
  123. running_mean = running_mean * momentum + mean * (1 - momentum)
  124. running_var = running_var * momentum + var_unbiased * (1 - momentum)
  125. yv = bn(Tensor(xv))
  126. yv_expect = (xv - mean) / sd
  127. _assert_allclose(yv.numpy(), yv_expect)
  128. _assert_allclose(bn.running_mean.numpy().reshape(-1), running_mean.reshape(-1))
  129. _assert_allclose(bn.running_var.numpy().reshape(-1), running_var.reshape(-1))
  130. # test set 'training' flag to False
  131. mean_backup = bn.running_mean.numpy()
  132. var_backup = bn.running_var.numpy()
  133. bn.training = False
  134. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  135. data = Tensor(xv)
  136. yv1 = bn(data)
  137. yv2 = bn(data)
  138. np.testing.assert_equal(yv1.numpy(), yv2.numpy())
  139. np.testing.assert_equal(mean_backup, bn.running_mean.numpy())
  140. np.testing.assert_equal(var_backup, bn.running_var.numpy())
  141. yv_expect = (xv - running_mean) / np.sqrt(running_var + bn.eps)
  142. _assert_allclose(yv1.numpy(), yv_expect)
  143. def test_batchnorm2d():
  144. nr_chan = 8
  145. data_shape = (3, nr_chan, 16, 16)
  146. momentum = 0.9
  147. bn = BatchNorm2d(nr_chan, momentum=momentum)
  148. running_mean = np.zeros((1, nr_chan, 1, 1), dtype=np.float32)
  149. running_var = np.ones((1, nr_chan, 1, 1), dtype=np.float32)
  150. for i in range(3):
  151. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  152. xv_transposed = np.transpose(xv, [0, 2, 3, 1]).reshape(
  153. (data_shape[0] * data_shape[2] * data_shape[3], nr_chan)
  154. )
  155. mean = np.mean(xv_transposed, axis=0).reshape(1, nr_chan, 1, 1)
  156. var_biased = np.var(xv_transposed, axis=0).reshape((1, nr_chan, 1, 1))
  157. sd = np.sqrt(var_biased + bn.eps)
  158. var_unbiased = np.var(xv_transposed, axis=0, ddof=1).reshape((1, nr_chan, 1, 1))
  159. running_mean = running_mean * momentum + mean * (1 - momentum)
  160. running_var = running_var * momentum + var_unbiased * (1 - momentum)
  161. yv = bn(Tensor(xv))
  162. yv_expect = (xv - mean) / sd
  163. _assert_allclose(yv.numpy(), yv_expect)
  164. _assert_allclose(bn.running_mean.numpy(), running_mean)
  165. _assert_allclose(bn.running_var.numpy(), running_var)
  166. # test set 'training' flag to False
  167. mean_backup = bn.running_mean.numpy()
  168. var_backup = bn.running_var.numpy()
  169. bn.training = False
  170. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  171. data = Tensor(xv)
  172. yv1 = bn(data)
  173. yv2 = bn(data)
  174. np.testing.assert_equal(yv1.numpy(), yv2.numpy())
  175. np.testing.assert_equal(mean_backup, bn.running_mean.numpy())
  176. np.testing.assert_equal(var_backup, bn.running_var.numpy())
  177. yv_expect = (xv - running_mean) / np.sqrt(running_var + bn.eps)
  178. _assert_allclose(yv1.numpy(), yv_expect)
  179. @pytest.mark.skipif(
  180. platform.system() == "Darwin", reason="do not imp GPU mode at macos now"
  181. )
  182. def test_syncbn2d():
  183. nr_chan = 8
  184. data_shape = (3, nr_chan, 16, 16)
  185. momentum = 0.9
  186. bn = SyncBatchNorm(nr_chan, momentum=momentum)
  187. running_mean = np.zeros((1, nr_chan, 1, 1), dtype=np.float32)
  188. running_var = np.ones((1, nr_chan, 1, 1), dtype=np.float32)
  189. for i in range(3):
  190. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  191. xv_transposed = np.transpose(xv, [0, 2, 3, 1]).reshape(
  192. (data_shape[0] * data_shape[2] * data_shape[3], nr_chan)
  193. )
  194. mean = np.mean(xv_transposed, axis=0).reshape(1, nr_chan, 1, 1)
  195. var_biased = np.var(xv_transposed, axis=0).reshape((1, nr_chan, 1, 1))
  196. sd = np.sqrt(var_biased + bn.eps)
  197. var_unbiased = np.var(xv_transposed, axis=0, ddof=1).reshape((1, nr_chan, 1, 1))
  198. running_mean = running_mean * momentum + mean * (1 - momentum)
  199. running_var = running_var * momentum + var_unbiased * (1 - momentum)
  200. yv = bn(Tensor(xv))
  201. yv_expect = (xv - mean) / sd
  202. _assert_allclose(yv.numpy(), yv_expect)
  203. _assert_allclose(bn.running_mean.numpy(), running_mean)
  204. _assert_allclose(bn.running_var.numpy(), running_var)
  205. # test set 'training' flag to False
  206. mean_backup = bn.running_mean.numpy()
  207. var_backup = bn.running_var.numpy()
  208. bn.training = False
  209. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  210. data = Tensor(xv)
  211. yv1 = bn(data)
  212. yv2 = bn(data)
  213. np.testing.assert_equal(yv1.numpy(), yv2.numpy())
  214. np.testing.assert_equal(mean_backup, bn.running_mean.numpy())
  215. np.testing.assert_equal(var_backup, bn.running_var.numpy())
  216. yv_expect = (xv - running_mean) / np.sqrt(running_var + bn.eps)
  217. _assert_allclose(yv1.numpy(), yv_expect)
  218. def test_batchnorm_no_stats():
  219. nr_chan = 8
  220. data_shape = (3, nr_chan, 4)
  221. bn = BatchNorm1d(8, track_running_stats=False)
  222. for i in range(4):
  223. if i == 2:
  224. bn.training = False
  225. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  226. mean = np.mean(np.mean(xv, axis=0, keepdims=True), axis=2, keepdims=True)
  227. var = np.var(
  228. np.transpose(xv, [0, 2, 1]).reshape(
  229. (data_shape[0] * data_shape[2], nr_chan)
  230. ),
  231. axis=0,
  232. ).reshape((1, nr_chan, 1))
  233. sd = np.sqrt(var + bn.eps)
  234. yv = bn(Tensor(xv))
  235. yv_expect = (xv - mean) / sd
  236. _assert_allclose(yv.numpy(), yv_expect)
  237. @pytest.mark.skipif(
  238. platform.system() == "Darwin", reason="do not imp GPU mode at macos now"
  239. )
  240. def test_syncbn_no_stats():
  241. nr_chan = 8
  242. data_shape = (3, nr_chan, 4)
  243. bn = SyncBatchNorm(8, track_running_stats=False)
  244. for i in range(4):
  245. if i == 2:
  246. bn.training = False
  247. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  248. mean = np.mean(np.mean(xv, axis=0, keepdims=True), axis=2, keepdims=True)
  249. var = np.var(
  250. np.transpose(xv, [0, 2, 1]).reshape(
  251. (data_shape[0] * data_shape[2], nr_chan)
  252. ),
  253. axis=0,
  254. ).reshape((1, nr_chan, 1))
  255. sd = np.sqrt(var + bn.eps)
  256. yv = bn(Tensor(xv))
  257. yv_expect = (xv - mean) / sd
  258. _assert_allclose(yv.numpy(), yv_expect)
  259. def test_batchnorm2d_no_stats():
  260. nr_chan = 8
  261. data_shape = (3, nr_chan, 16, 16)
  262. bn = BatchNorm2d(8, track_running_stats=False)
  263. for i in range(4):
  264. if i == 2:
  265. bn.training = False
  266. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  267. xv_transposed = np.transpose(xv, [0, 2, 3, 1]).reshape(
  268. (data_shape[0] * data_shape[2] * data_shape[3], nr_chan)
  269. )
  270. mean = np.mean(xv_transposed, axis=0).reshape(1, nr_chan, 1, 1)
  271. var = np.var(xv_transposed, axis=0).reshape((1, nr_chan, 1, 1))
  272. sd = np.sqrt(var + bn.eps)
  273. yv = bn(Tensor(xv))
  274. yv_expect = (xv - mean) / sd
  275. _assert_allclose(yv.numpy(), yv_expect)
  276. @pytest.mark.skipif(
  277. platform.system() == "Darwin", reason="do not imp GPU mode at macos now"
  278. )
  279. def test_syncbn2d_no_stats():
  280. nr_chan = 8
  281. data_shape = (3, nr_chan, 16, 16)
  282. bn = SyncBatchNorm(8, track_running_stats=False)
  283. for i in range(4):
  284. if i == 2:
  285. bn.training = False
  286. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  287. xv_transposed = np.transpose(xv, [0, 2, 3, 1]).reshape(
  288. (data_shape[0] * data_shape[2] * data_shape[3], nr_chan)
  289. )
  290. mean = np.mean(xv_transposed, axis=0).reshape(1, nr_chan, 1, 1)
  291. var = np.var(xv_transposed, axis=0).reshape((1, nr_chan, 1, 1))
  292. sd = np.sqrt(var + bn.eps)
  293. yv = bn(Tensor(xv))
  294. yv_expect = (xv - mean) / sd
  295. _assert_allclose(yv.numpy(), yv_expect)

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