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_op.py 15 kB

6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. # Copyright 2019 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. import numpy as np
  16. import pytest
  17. import mindspore.context as context
  18. from mindspore.common.tensor import Tensor
  19. from mindspore.common.parameter import ParameterTuple
  20. from mindspore.nn import BatchNorm2d, BatchNorm1d, SGD
  21. from mindspore.nn import Cell
  22. from mindspore.ops import composite as C
  23. class Batchnorm_Net(Cell):
  24. def __init__(self, c, weight, bias, moving_mean, moving_var_init, use_batch_statistics=None):
  25. super(Batchnorm_Net, self).__init__()
  26. self.bn = BatchNorm2d(c, eps=0.00001, momentum=0.1, beta_init=bias, gamma_init=weight,
  27. moving_mean_init=moving_mean, moving_var_init=moving_var_init,
  28. use_batch_statistics=use_batch_statistics)
  29. def construct(self, input_data):
  30. x = self.bn(input_data)
  31. return x
  32. class Grad(Cell):
  33. def __init__(self, network):
  34. super(Grad, self).__init__()
  35. self.grad = C.GradOperation(get_all=True, sens_param=True)
  36. self.network = network
  37. def construct(self, input_data, sens):
  38. gout = self.grad(self.network)(input_data, sens)
  39. return gout
  40. @pytest.mark.level0
  41. @pytest.mark.platform_x86_gpu_training
  42. @pytest.mark.env_onecard
  43. def test_train_forward():
  44. x = np.array([[
  45. [[1, 3, 3, 5], [2, 4, 6, 8], [3, 6, 7, 7], [4, 3, 8, 2]],
  46. [[5, 7, 6, 3], [3, 5, 6, 7], [9, 4, 2, 5], [7, 5, 8, 1]]]]).astype(np.float32)
  47. expect_output = np.array([[[[-0.6059, 0.3118, 0.3118, 1.2294],
  48. [-0.1471, 0.7706, 1.6882, 2.6059],
  49. [0.3118, 1.6882, 2.1471, 2.1471],
  50. [0.7706, 0.3118, 2.6059, -0.1471]],
  51. [[0.9119, 1.8518, 1.3819, -0.0281],
  52. [-0.0281, 0.9119, 1.3819, 1.8518],
  53. [2.7918, 0.4419, -0.4981, 0.9119],
  54. [1.8518, 0.9119, 2.3218, -0.9680]]]]).astype(np.float32)
  55. weight = np.ones(2).astype(np.float32)
  56. bias = np.ones(2).astype(np.float32)
  57. moving_mean = np.ones(2).astype(np.float32)
  58. moving_var_init = np.ones(2).astype(np.float32)
  59. error = np.ones(shape=[1, 2, 4, 4]) * 1.0e-4
  60. context.set_context(mode=context.PYNATIVE_MODE, device_target="GPU")
  61. bn_net = Batchnorm_Net(2, Tensor(weight), Tensor(bias),
  62. Tensor(moving_mean), Tensor(moving_var_init))
  63. bn_net.set_train()
  64. output = bn_net(Tensor(x))
  65. diff = output.asnumpy() - expect_output
  66. assert np.all(diff < error)
  67. assert np.all(-diff < error)
  68. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  69. bn_net = Batchnorm_Net(2, Tensor(weight), Tensor(bias),
  70. Tensor(moving_mean), Tensor(moving_var_init))
  71. bn_net.set_train()
  72. output = bn_net(Tensor(x))
  73. diff = output.asnumpy() - expect_output
  74. assert np.all(diff < error)
  75. assert np.all(-diff < error)
  76. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  77. bn_net = Batchnorm_Net(2, Tensor(weight), Tensor(bias),
  78. Tensor(moving_mean), Tensor(moving_var_init))
  79. bn_net.set_train(False)
  80. output = bn_net(Tensor(x))
  81. context.set_context(mode=context.PYNATIVE_MODE, device_target="GPU")
  82. bn_net = Batchnorm_Net(2, Tensor(weight), Tensor(bias),
  83. Tensor(moving_mean), Tensor(moving_var_init))
  84. bn_net.set_train(False)
  85. output = bn_net(Tensor(x))
  86. @pytest.mark.level0
  87. @pytest.mark.platform_x86_gpu_training
  88. @pytest.mark.env_onecard
  89. def test_train_backward():
  90. x = np.array([[
  91. [[1, 3, 3, 5], [2, 4, 6, 8], [3, 6, 7, 7], [4, 3, 8, 2]],
  92. [[5, 7, 6, 3], [3, 5, 6, 7], [9, 4, 2, 5], [7, 5, 8, 1]]]]).astype(np.float32)
  93. grad = np.array([[
  94. [[1, 2, 7, 1], [4, 2, 1, 3], [1, 6, 5, 2], [2, 4, 3, 2]],
  95. [[9, 4, 3, 5], [1, 3, 7, 6], [5, 7, 9, 9], [1, 4, 6, 8]]]]).astype(np.float32)
  96. expect_output = np.array([[[[-0.69126546, -0.32903028, 1.9651246, -0.88445705],
  97. [0.6369296, -0.37732816, -0.93275493, -0.11168876],
  98. [-0.7878612, 1.3614, 0.8542711, -0.52222186],
  99. [-0.37732816, 0.5886317, -0.11168876, -0.28073236]],
  100. [[1.6447213, -0.38968924, -1.0174079, -0.55067265],
  101. [-2.4305856, -1.1751484, 0.86250514, 0.5502673],
  102. [0.39576983, 0.5470243, 1.1715001, 1.6447213],
  103. [-1.7996241, -0.7051701, 0.7080077, 0.5437813]]]]).astype(np.float32)
  104. weight = Tensor(np.ones(2).astype(np.float32))
  105. bias = Tensor(np.ones(2).astype(np.float32))
  106. moving_mean = Tensor(np.ones(2).astype(np.float32))
  107. moving_var_init = Tensor(np.ones(2).astype(np.float32))
  108. error = np.ones(shape=[1, 2, 4, 4]) * 1.0e-6
  109. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  110. bn_net = Batchnorm_Net(2, weight, bias, moving_mean, moving_var_init)
  111. bn_net.set_train()
  112. bn_grad = Grad(bn_net)
  113. output = bn_grad(Tensor(x), Tensor(grad))
  114. diff = output[0].asnumpy() - expect_output
  115. assert np.all(diff < error)
  116. assert np.all(-diff < error)
  117. @pytest.mark.level0
  118. @pytest.mark.platform_x86_gpu_training
  119. @pytest.mark.env_onecard
  120. def test_train_stats_false_forward():
  121. x = np.array([[
  122. [[1, 3, 3, 5], [2, 4, 6, 8], [3, 6, 7, 7], [4, 3, 8, 2]],
  123. [[5, 7, 6, 3], [3, 5, 6, 7], [9, 4, 2, 5], [7, 5, 8, 1]]]]).astype(np.float32)
  124. expect_output = np.array([[[[3.707105, 5.121315, 5.121315, 6.535525],
  125. [4.41421, 5.8284197, 7.24263, 8.656839],
  126. [5.121315, 7.24263, 7.9497347, 7.9497347],
  127. [5.8284197, 5.121315, 8.656839, 4.41421]],
  128. [[6.535525, 7.9497347, 7.24263, 5.121315],
  129. [5.121315, 6.535525, 7.24263, 7.9497347],
  130. [9.363945, 5.8284197, 4.41421, 6.535525],
  131. [7.9497347, 6.535525, 8.656839, 3.707105]]]]).astype(np.float32)
  132. weight = np.ones(2).astype(np.float32)
  133. bias = np.ones(2).astype(np.float32) * 3
  134. moving_mean = np.zeros(2).astype(np.float32)
  135. moving_var_init = np.ones(2).astype(np.float32) * 2
  136. error = np.ones(shape=[1, 2, 4, 4]) * 1.0e-4
  137. use_batch_statistics = False
  138. context.set_context(mode=context.PYNATIVE_MODE, device_target="GPU")
  139. bn_net = Batchnorm_Net(2, Tensor(weight), Tensor(bias), Tensor(moving_mean),
  140. Tensor(moving_var_init), use_batch_statistics)
  141. bn_net.set_train()
  142. output = bn_net(Tensor(x))
  143. diff = output.asnumpy() - expect_output
  144. assert np.all(diff < error)
  145. assert np.all(-diff < error)
  146. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  147. bn_net = Batchnorm_Net(2, Tensor(weight), Tensor(bias), Tensor(moving_mean),
  148. Tensor(moving_var_init), use_batch_statistics)
  149. bn_net.set_train()
  150. output = bn_net(Tensor(x))
  151. diff = output.asnumpy() - expect_output
  152. assert np.all(diff < error)
  153. assert np.all(-diff < error)
  154. @pytest.mark.level0
  155. @pytest.mark.platform_x86_gpu_training
  156. @pytest.mark.env_onecard
  157. def test_infer_backward():
  158. expect_output = np.array([[[[-0.3224156, -0.3840524], [1.1337637, -1.0998858]],
  159. [[-0.1724273, -0.877854], [0.0422135, 0.5828123]],
  160. [[-1.1006137, 1.1447179], [0.9015862, 0.5024918]]]]).astype(np.float32)
  161. np.random.seed(1)
  162. x_np = np.random.randn(1, 3, 2, 2).astype(np.float32)
  163. input_grad_np = np.random.randn(1, 3, 2, 2).astype(np.float32)
  164. ms_input = Tensor(x_np)
  165. weight = Tensor(np.ones(3).astype(np.float32))
  166. bias = Tensor(np.zeros(3).astype(np.float32))
  167. moving_mean = Tensor(np.zeros(3).astype(np.float32))
  168. moving_var_init = Tensor(np.ones(3).astype(np.float32))
  169. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  170. ms_net = Batchnorm_Net(3, weight, bias, moving_mean, moving_var_init)
  171. ms_net.set_train(False)
  172. ms_grad = Grad(ms_net)
  173. ms_out_grad_np = ms_grad(ms_input, Tensor(input_grad_np))
  174. assert np.allclose(ms_out_grad_np[0].asnumpy(), expect_output)
  175. class BatchNorm1d_Net(Cell):
  176. def __init__(self, affine=True, gamma_init='ones', beta_init='zeros', moving_mean_init='zeros',
  177. moving_var_init='ones', use_batch_statistics=None):
  178. super(BatchNorm1d_Net, self).__init__()
  179. self.bn1 = BatchNorm1d(2, eps=0.00001, momentum=0.1, affine=affine, gamma_init=gamma_init, beta_init=beta_init,
  180. moving_mean_init=moving_mean_init, moving_var_init=moving_var_init,
  181. use_batch_statistics=use_batch_statistics)
  182. def construct(self, x):
  183. x = self.bn1(x)
  184. return x
  185. class GradByListNet(Cell):
  186. def __init__(self, network):
  187. super(GradByListNet, self).__init__()
  188. self.grad = C.GradOperation(get_all=True, sens_param=True, get_by_list=True)
  189. self.network = network
  190. self.params = ParameterTuple(network.trainable_params())
  191. def construct(self, x, dy):
  192. grad_op = self.grad(self.network, self.params)
  193. output = grad_op(x, dy)
  194. return output
  195. @pytest.mark.level0
  196. @pytest.mark.platform_x86_gpu_training
  197. @pytest.mark.env_onecard
  198. def test_1d_train():
  199. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  200. bn_net = BatchNorm1d_Net(use_batch_statistics=None)
  201. grad_net = GradByListNet(bn_net)
  202. optimizer = SGD(bn_net.trainable_params(), learning_rate=0.01, momentum=0.9)
  203. bn_net.set_train(True)
  204. x1 = np.array([[1.6243454, -0.6117564],
  205. [-0.5281718, -1.0729686],
  206. [0.86540765, -2.3015387],
  207. [1.7448118, -0.7612069],
  208. [0.3190391, -0.24937038]]).astype(np.float32)
  209. dy1 = np.array([[1.4621079, -2.0601406],
  210. [-0.3224172, -0.38405436],
  211. [1.1337694, -1.0998913],
  212. [-0.1724282, -0.8778584],
  213. [0.04221375, 0.58281523]]).astype(np.float32)
  214. x2 = np.array([[-0.19183555, -0.887629],
  215. [-0.7471583, 1.6924546],
  216. [0.05080776, -0.6369957],
  217. [0.19091548, 2.1002553],
  218. [0.12015896, 0.6172031]]).astype(np.float32)
  219. dy2 = np.array([[0.30017033, -0.35224986],
  220. [-1.1425182, -0.34934273],
  221. [-0.20889424, 0.5866232],
  222. [0.8389834, 0.9311021],
  223. [0.2855873, 0.8851412]]).astype(np.float32)
  224. x_train = [x1, x2]
  225. dy_train = [dy1, dy2]
  226. dx1 = np.array([[0.8120, -2.0371],
  227. [-0.2202, 0.5837],
  228. [0.8040, 0.1950],
  229. [-1.1823, -0.2786],
  230. [-0.2135, 1.5371]]).astype(np.float32)
  231. gamma1 = np.array([0.9821, 0.9873]).astype(np.float32)
  232. beta1 = np.array([-0.0214, 0.0384]).astype(np.float32)
  233. mean1 = np.array([0.7246, -0.8994]).astype(np.float32)
  234. variance1 = np.array([0.9036, 0.6559]).astype(np.float32)
  235. dx2 = np.array([[1.1955, -0.4247],
  236. [-0.2425, -0.6789],
  237. [-1.4563, 0.3237],
  238. [0.8752, 0.3351],
  239. [-0.3719, 0.4448]]).astype(np.float32)
  240. gamma2 = np.array([0.9370, 0.9687]).astype(np.float32)
  241. beta2 = np.array([-0.0415, 0.0559]).astype(np.float32)
  242. mean2 = np.array([-0.0314, 0.4294]).astype(np.float32)
  243. variance2 = np.array([0.2213, 1.6822]).astype(np.float32)
  244. exp_dx = [dx1, dx2]
  245. exp_gamma = [gamma1, gamma2]
  246. exp_beta = [beta1, beta2]
  247. exp_mean = [mean1, mean2]
  248. exp_variance = [variance1, variance2]
  249. for data in zip(x_train, dy_train, exp_dx, exp_gamma, exp_beta, exp_mean, exp_variance):
  250. output = grad_net(Tensor(data[0]), Tensor(data[1]))
  251. assert np.allclose(output[0][0].asnumpy(), data[2], atol=1.0e-4)
  252. optimizer(output[1])
  253. assert np.allclose(bn_net.bn1.gamma.asnumpy(), data[3], atol=1.0e-4)
  254. assert np.allclose(bn_net.bn1.beta.asnumpy(), data[4], atol=1.0e-4)
  255. assert np.allclose(bn_net.bn1.moving_mean.asnumpy(), data[5], atol=1.0e-4)
  256. assert np.allclose(bn_net.bn1.moving_variance.asnumpy(), data[6], atol=1.0e-4)
  257. @pytest.mark.level0
  258. @pytest.mark.platform_x86_gpu_training
  259. @pytest.mark.env_onecard
  260. def test_1d_eval():
  261. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  262. gamma_init = Tensor(np.array([0.93700373, 0.96870345]).astype(np.float32))
  263. beta_init = Tensor(np.array([-0.04145495, 0.05593072]).astype(np.float32))
  264. mean_init = Tensor(np.array([-0.03142229, 0.4294087]).astype(np.float32))
  265. variance_init = Tensor(np.array([0.2212921, 1.6822311]).astype(np.float32))
  266. bn_net = BatchNorm1d_Net(affine=False, gamma_init=gamma_init, beta_init=beta_init, moving_mean_init=mean_init,
  267. moving_var_init=variance_init, use_batch_statistics=None)
  268. bn_net.set_train(False)
  269. x1 = np.array([[-1.1006192, 1.1447237],
  270. [0.9015907, 0.50249434],
  271. [0.90085596, -0.68372786],
  272. [-0.12289023, -0.93576944],
  273. [-0.26788807, 0.53035545]]).astype(np.float32)
  274. x2 = np.array([[-0.7543979, 1.2528682],
  275. [0.5129298, -0.29809284],
  276. [0.48851815, -0.07557172],
  277. [1.1316293, 1.5198169],
  278. [2.1855755, -1.3964963]]).astype(np.float32)
  279. x_test = [x1, x2]
  280. y1 = np.array([[-2.1711, 0.5902],
  281. [1.8169, 0.1105],
  282. [1.8155, -0.7754],
  283. [-0.2236, -0.9637],
  284. [-0.5125, 0.1313]]).astype(np.float32)
  285. y2 = np.array([[-1.4815, 0.6710],
  286. [1.0428, -0.4874],
  287. [0.9942, -0.3212],
  288. [2.2751, 0.8703],
  289. [4.3744, -1.3078]]).astype(np.float32)
  290. y_test = [y1, y2]
  291. for x, y in zip(x_test, y_test):
  292. y_pred = bn_net(Tensor(x))
  293. assert np.allclose(y_pred.asnumpy(), y, atol=1.0e-4)