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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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="do not imp GPU mode at Windows now"
  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.skipif(
  123. platform.system() == "Windows", reason="do not imp GPU mode at Windows now"
  124. )
  125. @pytest.mark.isolated_distributed
  126. def test_syncbn1d():
  127. nr_chan = 8
  128. data_shape = (3, nr_chan, 4)
  129. momentum = 0.9
  130. bn = SyncBatchNorm(nr_chan, momentum=momentum)
  131. running_mean = np.zeros((1, nr_chan, 1), dtype=np.float32)
  132. running_var = np.ones((1, nr_chan, 1), dtype=np.float32)
  133. for i in range(3):
  134. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  135. mean = np.mean(np.mean(xv, axis=0, keepdims=True), axis=2, keepdims=True)
  136. xv_transposed = np.transpose(xv, [0, 2, 1]).reshape(
  137. (data_shape[0] * data_shape[2], nr_chan)
  138. )
  139. var_biased = np.var(xv_transposed, axis=0).reshape((1, nr_chan, 1))
  140. sd = np.sqrt(var_biased + bn.eps)
  141. var_unbiased = np.var(xv_transposed, axis=0, ddof=1).reshape((1, nr_chan, 1))
  142. running_mean = running_mean * momentum + mean * (1 - momentum)
  143. running_var = running_var * momentum + var_unbiased * (1 - momentum)
  144. yv = bn(Tensor(xv))
  145. yv_expect = (xv - mean) / sd
  146. _assert_allclose(yv.numpy(), yv_expect)
  147. _assert_allclose(bn.running_mean.numpy().reshape(-1), running_mean.reshape(-1))
  148. _assert_allclose(bn.running_var.numpy().reshape(-1), running_var.reshape(-1))
  149. # test set 'training' flag to False
  150. mean_backup = bn.running_mean.numpy()
  151. var_backup = bn.running_var.numpy()
  152. bn.training = False
  153. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  154. data = Tensor(xv)
  155. yv1 = bn(data)
  156. yv2 = bn(data)
  157. np.testing.assert_equal(yv1.numpy(), yv2.numpy())
  158. np.testing.assert_equal(mean_backup, bn.running_mean.numpy())
  159. np.testing.assert_equal(var_backup, bn.running_var.numpy())
  160. yv_expect = (xv - running_mean) / np.sqrt(running_var + bn.eps)
  161. _assert_allclose(yv1.numpy(), yv_expect)
  162. def test_batchnorm2d():
  163. nr_chan = 8
  164. data_shape = (3, nr_chan, 16, 16)
  165. momentum = 0.9
  166. bn = BatchNorm2d(nr_chan, momentum=momentum)
  167. running_mean = np.zeros((1, nr_chan, 1, 1), dtype=np.float32)
  168. running_var = np.ones((1, nr_chan, 1, 1), dtype=np.float32)
  169. for i in range(3):
  170. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  171. xv_transposed = np.transpose(xv, [0, 2, 3, 1]).reshape(
  172. (data_shape[0] * data_shape[2] * data_shape[3], nr_chan)
  173. )
  174. mean = np.mean(xv_transposed, axis=0).reshape(1, nr_chan, 1, 1)
  175. var_biased = np.var(xv_transposed, axis=0).reshape((1, nr_chan, 1, 1))
  176. sd = np.sqrt(var_biased + bn.eps)
  177. var_unbiased = np.var(xv_transposed, axis=0, ddof=1).reshape((1, nr_chan, 1, 1))
  178. running_mean = running_mean * momentum + mean * (1 - momentum)
  179. running_var = running_var * momentum + var_unbiased * (1 - momentum)
  180. yv = bn(Tensor(xv))
  181. yv_expect = (xv - mean) / sd
  182. _assert_allclose(yv.numpy(), yv_expect)
  183. _assert_allclose(bn.running_mean.numpy(), running_mean)
  184. _assert_allclose(bn.running_var.numpy(), running_var)
  185. # test set 'training' flag to False
  186. mean_backup = bn.running_mean.numpy()
  187. var_backup = bn.running_var.numpy()
  188. bn.training = False
  189. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  190. data = Tensor(xv)
  191. yv1 = bn(data)
  192. yv2 = bn(data)
  193. np.testing.assert_equal(yv1.numpy(), yv2.numpy())
  194. np.testing.assert_equal(mean_backup, bn.running_mean.numpy())
  195. np.testing.assert_equal(var_backup, bn.running_var.numpy())
  196. yv_expect = (xv - running_mean) / np.sqrt(running_var + bn.eps)
  197. _assert_allclose(yv1.numpy(), yv_expect)
  198. @pytest.mark.skipif(
  199. platform.system() == "Darwin", reason="do not imp GPU mode at macos now"
  200. )
  201. @pytest.mark.skipif(
  202. platform.system() == "Windows", reason="do not imp GPU mode at Windows now"
  203. )
  204. @pytest.mark.isolated_distributed
  205. def test_syncbn2d():
  206. nr_chan = 8
  207. data_shape = (3, nr_chan, 16, 16)
  208. momentum = 0.9
  209. bn = SyncBatchNorm(nr_chan, momentum=momentum)
  210. running_mean = np.zeros((1, nr_chan, 1, 1), dtype=np.float32)
  211. running_var = np.ones((1, nr_chan, 1, 1), dtype=np.float32)
  212. for i in range(3):
  213. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  214. xv_transposed = np.transpose(xv, [0, 2, 3, 1]).reshape(
  215. (data_shape[0] * data_shape[2] * data_shape[3], nr_chan)
  216. )
  217. mean = np.mean(xv_transposed, axis=0).reshape(1, nr_chan, 1, 1)
  218. var_biased = np.var(xv_transposed, axis=0).reshape((1, nr_chan, 1, 1))
  219. sd = np.sqrt(var_biased + bn.eps)
  220. var_unbiased = np.var(xv_transposed, axis=0, ddof=1).reshape((1, nr_chan, 1, 1))
  221. running_mean = running_mean * momentum + mean * (1 - momentum)
  222. running_var = running_var * momentum + var_unbiased * (1 - momentum)
  223. yv = bn(Tensor(xv))
  224. yv_expect = (xv - mean) / sd
  225. _assert_allclose(yv.numpy(), yv_expect)
  226. _assert_allclose(bn.running_mean.numpy(), running_mean)
  227. _assert_allclose(bn.running_var.numpy(), running_var)
  228. # test set 'training' flag to False
  229. mean_backup = bn.running_mean.numpy()
  230. var_backup = bn.running_var.numpy()
  231. bn.training = False
  232. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  233. data = Tensor(xv)
  234. yv1 = bn(data)
  235. yv2 = bn(data)
  236. np.testing.assert_equal(yv1.numpy(), yv2.numpy())
  237. np.testing.assert_equal(mean_backup, bn.running_mean.numpy())
  238. np.testing.assert_equal(var_backup, bn.running_var.numpy())
  239. yv_expect = (xv - running_mean) / np.sqrt(running_var + bn.eps)
  240. _assert_allclose(yv1.numpy(), yv_expect)
  241. def test_batchnorm_no_stats():
  242. nr_chan = 8
  243. data_shape = (3, nr_chan, 4)
  244. bn = BatchNorm1d(8, track_running_stats=False)
  245. for i in range(4):
  246. if i == 2:
  247. bn.training = False
  248. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  249. mean = np.mean(np.mean(xv, axis=0, keepdims=True), axis=2, keepdims=True)
  250. var = np.var(
  251. np.transpose(xv, [0, 2, 1]).reshape(
  252. (data_shape[0] * data_shape[2], nr_chan)
  253. ),
  254. axis=0,
  255. ).reshape((1, nr_chan, 1))
  256. sd = np.sqrt(var + bn.eps)
  257. yv = bn(Tensor(xv))
  258. yv_expect = (xv - mean) / sd
  259. _assert_allclose(yv.numpy(), yv_expect)
  260. @pytest.mark.skipif(
  261. platform.system() == "Darwin", reason="do not imp GPU mode at macos now"
  262. )
  263. @pytest.mark.skipif(
  264. platform.system() == "Windows", reason="do not imp GPU mode at Windows now"
  265. )
  266. @pytest.mark.isolated_distributed
  267. def test_syncbn_no_stats():
  268. nr_chan = 8
  269. data_shape = (3, nr_chan, 4)
  270. bn = SyncBatchNorm(8, track_running_stats=False)
  271. for i in range(4):
  272. if i == 2:
  273. bn.training = False
  274. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  275. mean = np.mean(np.mean(xv, axis=0, keepdims=True), axis=2, keepdims=True)
  276. var = np.var(
  277. np.transpose(xv, [0, 2, 1]).reshape(
  278. (data_shape[0] * data_shape[2], nr_chan)
  279. ),
  280. axis=0,
  281. ).reshape((1, nr_chan, 1))
  282. sd = np.sqrt(var + bn.eps)
  283. yv = bn(Tensor(xv))
  284. yv_expect = (xv - mean) / sd
  285. _assert_allclose(yv.numpy(), yv_expect)
  286. def test_batchnorm2d_no_stats():
  287. nr_chan = 8
  288. data_shape = (3, nr_chan, 16, 16)
  289. bn = BatchNorm2d(8, track_running_stats=False)
  290. for i in range(4):
  291. if i == 2:
  292. bn.training = False
  293. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  294. xv_transposed = np.transpose(xv, [0, 2, 3, 1]).reshape(
  295. (data_shape[0] * data_shape[2] * data_shape[3], nr_chan)
  296. )
  297. mean = np.mean(xv_transposed, axis=0).reshape(1, nr_chan, 1, 1)
  298. var = np.var(xv_transposed, axis=0).reshape((1, nr_chan, 1, 1))
  299. sd = np.sqrt(var + bn.eps)
  300. yv = bn(Tensor(xv))
  301. yv_expect = (xv - mean) / sd
  302. _assert_allclose(yv.numpy(), yv_expect)
  303. @pytest.mark.skipif(
  304. platform.system() == "Darwin", reason="do not imp GPU mode at macos now"
  305. )
  306. @pytest.mark.skipif(
  307. platform.system() == "Windows", reason="do not imp GPU mode at Windows now"
  308. )
  309. @pytest.mark.isolated_distributed
  310. def test_syncbn2d_no_stats():
  311. nr_chan = 8
  312. data_shape = (3, nr_chan, 16, 16)
  313. bn = SyncBatchNorm(8, track_running_stats=False)
  314. for i in range(4):
  315. if i == 2:
  316. bn.training = False
  317. xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
  318. xv_transposed = np.transpose(xv, [0, 2, 3, 1]).reshape(
  319. (data_shape[0] * data_shape[2] * data_shape[3], nr_chan)
  320. )
  321. mean = np.mean(xv_transposed, axis=0).reshape(1, nr_chan, 1, 1)
  322. var = np.var(xv_transposed, axis=0).reshape((1, nr_chan, 1, 1))
  323. sd = np.sqrt(var + bn.eps)
  324. yv = bn(Tensor(xv))
  325. yv_expect = (xv - mean) / sd
  326. _assert_allclose(yv.numpy(), yv_expect)

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