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

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

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