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

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

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