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

6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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.nn import BatchNorm2d
  20. from mindspore.nn import Cell
  21. from mindspore.ops import composite as C
  22. class Batchnorm_Net(Cell):
  23. def __init__(self, c, weight, bias, moving_mean, moving_var_init, use_batch_statistics=None):
  24. super(Batchnorm_Net, self).__init__()
  25. self.bn = BatchNorm2d(c, eps=0.00001, momentum=0.1, beta_init=bias, gamma_init=weight,
  26. moving_mean_init=moving_mean, moving_var_init=moving_var_init,
  27. use_batch_statistics=use_batch_statistics)
  28. def construct(self, input_data):
  29. x = self.bn(input_data)
  30. return x
  31. class Grad(Cell):
  32. def __init__(self, network):
  33. super(Grad, self).__init__()
  34. self.grad = C.GradOperation(get_all=True, sens_param=True)
  35. self.network = network
  36. def construct(self, input_data, sens):
  37. gout = self.grad(self.network)(input_data, sens)
  38. return gout
  39. @pytest.mark.level0
  40. @pytest.mark.platform_x86_gpu_training
  41. @pytest.mark.env_onecard
  42. def test_train_forward():
  43. x = np.array([[
  44. [[1, 3, 3, 5], [2, 4, 6, 8], [3, 6, 7, 7], [4, 3, 8, 2]],
  45. [[5, 7, 6, 3], [3, 5, 6, 7], [9, 4, 2, 5], [7, 5, 8, 1]]]]).astype(np.float32)
  46. expect_output = np.array([[[[-0.6059, 0.3118, 0.3118, 1.2294],
  47. [-0.1471, 0.7706, 1.6882, 2.6059],
  48. [0.3118, 1.6882, 2.1471, 2.1471],
  49. [0.7706, 0.3118, 2.6059, -0.1471]],
  50. [[0.9119, 1.8518, 1.3819, -0.0281],
  51. [-0.0281, 0.9119, 1.3819, 1.8518],
  52. [2.7918, 0.4419, -0.4981, 0.9119],
  53. [1.8518, 0.9119, 2.3218, -0.9680]]]]).astype(np.float32)
  54. weight = np.ones(2).astype(np.float32)
  55. bias = np.ones(2).astype(np.float32)
  56. moving_mean = np.ones(2).astype(np.float32)
  57. moving_var_init = np.ones(2).astype(np.float32)
  58. error = np.ones(shape=[1, 2, 4, 4]) * 1.0e-4
  59. context.set_context(mode=context.PYNATIVE_MODE, device_target="GPU")
  60. bn_net = Batchnorm_Net(2, Tensor(weight), Tensor(bias),
  61. Tensor(moving_mean), Tensor(moving_var_init))
  62. bn_net.set_train()
  63. output = bn_net(Tensor(x))
  64. diff = output.asnumpy() - expect_output
  65. assert np.all(diff < error)
  66. assert np.all(-diff < error)
  67. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  68. bn_net = Batchnorm_Net(2, Tensor(weight), Tensor(bias),
  69. Tensor(moving_mean), Tensor(moving_var_init))
  70. bn_net.set_train()
  71. output = bn_net(Tensor(x))
  72. diff = output.asnumpy() - expect_output
  73. assert np.all(diff < error)
  74. assert np.all(-diff < error)
  75. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  76. bn_net = Batchnorm_Net(2, Tensor(weight), Tensor(bias),
  77. Tensor(moving_mean), Tensor(moving_var_init))
  78. bn_net.set_train(False)
  79. output = bn_net(Tensor(x))
  80. context.set_context(mode=context.PYNATIVE_MODE, device_target="GPU")
  81. bn_net = Batchnorm_Net(2, Tensor(weight), Tensor(bias),
  82. Tensor(moving_mean), Tensor(moving_var_init))
  83. bn_net.set_train(False)
  84. output = bn_net(Tensor(x))
  85. @pytest.mark.level0
  86. @pytest.mark.platform_x86_gpu_training
  87. @pytest.mark.env_onecard
  88. def test_train_backward():
  89. x = np.array([[
  90. [[1, 3, 3, 5], [2, 4, 6, 8], [3, 6, 7, 7], [4, 3, 8, 2]],
  91. [[5, 7, 6, 3], [3, 5, 6, 7], [9, 4, 2, 5], [7, 5, 8, 1]]]]).astype(np.float32)
  92. grad = np.array([[
  93. [[1, 2, 7, 1], [4, 2, 1, 3], [1, 6, 5, 2], [2, 4, 3, 2]],
  94. [[9, 4, 3, 5], [1, 3, 7, 6], [5, 7, 9, 9], [1, 4, 6, 8]]]]).astype(np.float32)
  95. expect_output = np.array([[[[-0.69126546, -0.32903028, 1.9651246, -0.88445705],
  96. [0.6369296, -0.37732816, -0.93275493, -0.11168876],
  97. [-0.7878612, 1.3614, 0.8542711, -0.52222186],
  98. [-0.37732816, 0.5886317, -0.11168876, -0.28073236]],
  99. [[1.6447213, -0.38968924, -1.0174079, -0.55067265],
  100. [-2.4305856, -1.1751484, 0.86250514, 0.5502673],
  101. [0.39576983, 0.5470243, 1.1715001, 1.6447213],
  102. [-1.7996241, -0.7051701, 0.7080077, 0.5437813]]]]).astype(np.float32)
  103. weight = Tensor(np.ones(2).astype(np.float32))
  104. bias = Tensor(np.ones(2).astype(np.float32))
  105. moving_mean = Tensor(np.ones(2).astype(np.float32))
  106. moving_var_init = Tensor(np.ones(2).astype(np.float32))
  107. error = np.ones(shape=[1, 2, 4, 4]) * 1.0e-6
  108. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  109. bn_net = Batchnorm_Net(2, weight, bias, moving_mean, moving_var_init)
  110. bn_net.set_train()
  111. bn_grad = Grad(bn_net)
  112. output = bn_grad(Tensor(x), Tensor(grad))
  113. diff = output[0].asnumpy() - expect_output
  114. assert np.all(diff < error)
  115. assert np.all(-diff < error)
  116. @pytest.mark.level0
  117. @pytest.mark.platform_x86_gpu_training
  118. @pytest.mark.env_onecard
  119. def test_train_stats_false_forward():
  120. x = np.array([[
  121. [[1, 3, 3, 5], [2, 4, 6, 8], [3, 6, 7, 7], [4, 3, 8, 2]],
  122. [[5, 7, 6, 3], [3, 5, 6, 7], [9, 4, 2, 5], [7, 5, 8, 1]]]]).astype(np.float32)
  123. expect_output = np.array([[[[3.707105, 5.121315, 5.121315, 6.535525],
  124. [4.41421, 5.8284197, 7.24263, 8.656839],
  125. [5.121315, 7.24263, 7.9497347, 7.9497347],
  126. [5.8284197, 5.121315, 8.656839, 4.41421]],
  127. [[6.535525, 7.9497347, 7.24263, 5.121315],
  128. [5.121315, 6.535525, 7.24263, 7.9497347],
  129. [9.363945, 5.8284197, 4.41421, 6.535525],
  130. [7.9497347, 6.535525, 8.656839, 3.707105]]]]).astype(np.float32)
  131. weight = np.ones(2).astype(np.float32)
  132. bias = np.ones(2).astype(np.float32) * 3
  133. moving_mean = np.zeros(2).astype(np.float32)
  134. moving_var_init = np.ones(2).astype(np.float32) * 2
  135. error = np.ones(shape=[1, 2, 4, 4]) * 1.0e-4
  136. use_batch_statistics = False
  137. context.set_context(mode=context.PYNATIVE_MODE, device_target="GPU")
  138. bn_net = Batchnorm_Net(2, Tensor(weight), Tensor(bias), Tensor(moving_mean),
  139. Tensor(moving_var_init), use_batch_statistics)
  140. bn_net.set_train()
  141. output = bn_net(Tensor(x))
  142. diff = output.asnumpy() - expect_output
  143. assert np.all(diff < error)
  144. assert np.all(-diff < error)
  145. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  146. bn_net = Batchnorm_Net(2, Tensor(weight), Tensor(bias), Tensor(moving_mean),
  147. Tensor(moving_var_init), use_batch_statistics)
  148. bn_net.set_train()
  149. output = bn_net(Tensor(x))
  150. diff = output.asnumpy() - expect_output
  151. assert np.all(diff < error)
  152. assert np.all(-diff < error)
  153. @pytest.mark.level0
  154. @pytest.mark.platform_x86_gpu_training
  155. @pytest.mark.env_onecard
  156. def test_infer_backward():
  157. expect_output = np.array([[[[-0.3224156, -0.3840524], [1.1337637, -1.0998858]],
  158. [[-0.1724273, -0.877854], [0.0422135, 0.5828123]],
  159. [[-1.1006137, 1.1447179], [0.9015862, 0.5024918]]]]).astype(np.float32)
  160. np.random.seed(1)
  161. x_np = np.random.randn(1, 3, 2, 2).astype(np.float32)
  162. input_grad_np = np.random.randn(1, 3, 2, 2).astype(np.float32)
  163. ms_input = Tensor(x_np)
  164. weight = Tensor(np.ones(3).astype(np.float32))
  165. bias = Tensor(np.zeros(3).astype(np.float32))
  166. moving_mean = Tensor(np.zeros(3).astype(np.float32))
  167. moving_var_init = Tensor(np.ones(3).astype(np.float32))
  168. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  169. ms_net = Batchnorm_Net(3, weight, bias, moving_mean, moving_var_init)
  170. ms_net.set_train(False)
  171. ms_grad = Grad(ms_net)
  172. ms_out_grad_np = ms_grad(ms_input, Tensor(input_grad_np))
  173. assert np.allclose(ms_out_grad_np[0].asnumpy(), expect_output)