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

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

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