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

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

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