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

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

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