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_pad.py 9.0 kB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. # Copyright 2020 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 pytest
  16. import numpy as np
  17. import mindspore
  18. import mindspore.nn as nn
  19. import mindspore.context as context
  20. from mindspore import Tensor
  21. from mindspore.ops.composite import GradOperation
  22. @pytest.mark.level0
  23. @pytest.mark.platform_x86_cpu_training
  24. @pytest.mark.env_onecard
  25. def test_pad_basic():
  26. """
  27. Test array is being padded with 0's
  28. """
  29. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  30. # float32
  31. test_arr = np.array([[1, 2], [3, 4]]).astype(np.float32)
  32. test_arr_expected = np.array(
  33. [[0, 0, 0, 0], [0, 1, 2, 0], [0, 3, 4, 0], [0, 0, 0, 0]]).astype(np.float32)
  34. x_test = Tensor(test_arr, dtype=mindspore.float32)
  35. pad_op = nn.Pad(mode='CONSTANT', paddings=((1, 1), (1, 1)))
  36. y_test = pad_op(x_test).asnumpy()
  37. np.testing.assert_array_equal(y_test, test_arr_expected)
  38. # float16
  39. test_arr = np.array([[1, 2], [3, 4]]).astype(np.float16)
  40. test_arr_expected = np.array(
  41. [[0, 0, 0, 0], [0, 1, 2, 0], [0, 3, 4, 0], [0, 0, 0, 0]]).astype(np.float16)
  42. x_test = Tensor(test_arr, dtype=mindspore.float16)
  43. pad_op = nn.Pad(mode='CONSTANT', paddings=((1, 1), (1, 1)))
  44. y_test = pad_op(x_test).asnumpy()
  45. np.testing.assert_array_equal(y_test, test_arr_expected)
  46. @pytest.mark.level0
  47. @pytest.mark.platform_x86_cpu_training
  48. @pytest.mark.env_onecard
  49. def test_pad_row():
  50. """
  51. Test correct row padding
  52. """
  53. context.set_context(mode=context.PYNATIVE_MODE, device_target="CPU")
  54. test_arr_1 = np.random.rand(40, 40).astype(np.float32)
  55. test_paddings_1 = ((2, 3), (0, 0))
  56. test_arr_2 = np.random.randn(3, 10, 30, 30).astype(np.float32)
  57. test_paddings_2 = ((0, 0), (0, 0), (3, 0), (0, 0))
  58. pad_op_row_1 = nn.Pad(mode='CONSTANT', paddings=test_paddings_1)
  59. pad_op_row_2 = nn.Pad(mode='CONSTANT', paddings=test_paddings_2)
  60. x_test_1 = Tensor(np.array(test_arr_1), dtype=mindspore.float32)
  61. x_test_2 = Tensor(np.array(test_arr_2), dtype=mindspore.float32)
  62. y_test_1 = pad_op_row_1(x_test_1).asnumpy()
  63. y_test_2 = pad_op_row_2(x_test_2).asnumpy()
  64. # check size
  65. assert y_test_1.shape == (45, 40)
  66. assert y_test_2.shape == (3, 10, 33, 30)
  67. # check values - select correct sections
  68. np.testing.assert_equal(y_test_1[2:-3, :], test_arr_1)
  69. np.testing.assert_equal(y_test_2[:, :, 3:, :], test_arr_2)
  70. @pytest.mark.level0
  71. @pytest.mark.platform_x86_cpu_training
  72. @pytest.mark.env_onecard
  73. def test_pad_column():
  74. """
  75. Test correct column padding
  76. """
  77. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  78. test_arr_1 = np.random.randn(40, 40).astype(np.float32)
  79. test_paddings_1 = ((0, 0), (3, 3))
  80. test_arr_2 = np.random.randn(3, 10, 30, 30).astype(np.float32)
  81. test_paddings_2 = ((0, 0), (0, 0), (0, 0), (6, 1))
  82. pad_op_col_1 = nn.Pad(mode='CONSTANT', paddings=test_paddings_1)
  83. pad_op_col_2 = nn.Pad(mode='CONSTANT', paddings=test_paddings_2)
  84. x_test_1 = Tensor(np.array(test_arr_1), dtype=mindspore.float32)
  85. x_test_2 = Tensor(np.array(test_arr_2), dtype=mindspore.float32)
  86. y_test_1 = pad_op_col_1(x_test_1).asnumpy()
  87. y_test_2 = pad_op_col_2(x_test_2).asnumpy()
  88. # check size
  89. assert y_test_1.shape == (40, 46)
  90. assert y_test_2.shape == (3, 10, 30, 37)
  91. # check values - select correct sections - should match
  92. np.testing.assert_equal(y_test_1[:, 3:-3], test_arr_1)
  93. np.testing.assert_equal(y_test_2[:, :, :, 6:-1], test_arr_2)
  94. @pytest.mark.level0
  95. @pytest.mark.platform_x86_cpu_training
  96. @pytest.mark.env_onecard
  97. def test_pad_3d_pad():
  98. """
  99. Test full 3d padding, with all 3 input types
  100. """
  101. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  102. # float32
  103. test_arr = np.random.randn(5, 3, 30, 30).astype(np.float32)
  104. test_paddings = ((0, 0), (2, 1), (0, 1), (0, 2)) # padding 3 dims now
  105. pad_op_3d = nn.Pad(mode='CONSTANT', paddings=test_paddings)
  106. x_test = Tensor(np.array(test_arr), dtype=mindspore.float32)
  107. y_test = pad_op_3d(x_test).asnumpy()
  108. assert y_test.shape == (5, 6, 31, 32)
  109. np.testing.assert_equal(test_arr, y_test[:, 2:-1, :-1, :-2])
  110. # float16
  111. test_arr = np.random.randn(5, 3, 30, 30).astype(np.float16)
  112. test_paddings = ((0, 0), (2, 1), (0, 1), (0, 2))
  113. pad_op_3d = nn.Pad(mode='CONSTANT', paddings=test_paddings)
  114. x_test = Tensor(np.array(test_arr), dtype=mindspore.float16)
  115. y_test = pad_op_3d(x_test).asnumpy()
  116. assert y_test.shape == (5, 6, 31, 32)
  117. np.testing.assert_equal(test_arr, y_test[:, 2:-1, :-1, :-2])
  118. # int32
  119. test_arr = np.random.randint(1, 3000, (5, 3, 30, 30)).astype(np.int32)
  120. test_paddings = ((0, 0), (2, 1), (0, 1), (0, 2))
  121. pad_op_3d = nn.Pad(mode='CONSTANT', paddings=test_paddings)
  122. x_test = Tensor(np.array(test_arr), dtype=mindspore.int32)
  123. y_test = pad_op_3d(x_test).asnumpy()
  124. assert y_test.shape == (5, 6, 31, 32)
  125. np.testing.assert_equal(test_arr, y_test[:, 2:-1, :-1, :-2])
  126. # For testing backprop
  127. class Grad(nn.Cell):
  128. def __init__(self, network):
  129. super(Grad, self).__init__()
  130. self.grad = GradOperation(get_all=True, sens_param=True)
  131. self.network = network
  132. def construct(self, input_, output_grad):
  133. return self.grad(self.network)(input_, output_grad)
  134. class Net(nn.Cell):
  135. def __init__(self):
  136. super(Net, self).__init__()
  137. self.pad = nn.Pad(mode="CONSTANT", paddings=(
  138. (0, 0), (4, 3), (1, 1), (0, 2)))
  139. def construct(self, x):
  140. return self.pad(x)
  141. @pytest.mark.level0
  142. @pytest.mark.platform_x86_cpu_training
  143. @pytest.mark.env_onecard
  144. def test_pad_3d_backprop():
  145. """
  146. Confirm correct 3d padding backprop
  147. """
  148. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  149. net = Grad(Net())
  150. padded_shape = (5, 10, 32, 32)
  151. # float32
  152. test_arr = np.random.randn(5, 3, 30, 30).astype(np.float32)
  153. x_test = Tensor(test_arr, dtype=mindspore.float32)
  154. dy = np.random.randn(*padded_shape).astype(np.float32)
  155. expected_dx = dy[:, 4:-3, 1:-1, :-2]
  156. dx = net(x_test, Tensor(dy))
  157. dx = dx[0].asnumpy()
  158. np.testing.assert_array_equal(dx, expected_dx)
  159. # float16
  160. test_arr = np.random.randn(5, 3, 30, 30).astype(np.float16)
  161. x_test = Tensor(test_arr, dtype=mindspore.float16)
  162. dy = np.random.randn(*padded_shape).astype(np.float16)
  163. expected_dx = dy[:, 4:-3, 1:-1, :-2]
  164. dx = net(x_test, Tensor(dy))
  165. dx = dx[0].asnumpy()
  166. np.testing.assert_array_equal(dx, expected_dx)
  167. # int32
  168. test_arr = np.random.randint(1, 3000, (5, 3, 30, 30)).astype(np.int32)
  169. x_test = Tensor(test_arr, dtype=mindspore.int32)
  170. dy = np.random.randn(*padded_shape).astype(np.int32)
  171. expected_dx = dy[:, 4:-3, 1:-1, :-2]
  172. dx = net(x_test, Tensor(dy))
  173. dx = dx[0].asnumpy()
  174. np.testing.assert_array_equal(dx, expected_dx)
  175. @pytest.mark.level0
  176. @pytest.mark.platform_x86_cpu_training
  177. @pytest.mark.env_onecard
  178. def test_pad_error_cases():
  179. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  180. # TEST 1 - Neg padding values
  181. test_op = nn.Pad(paddings=((0, 0), (-1, -1)), mode="CONSTANT")
  182. test_arr = np.random.randn(3, 3)
  183. test_arr_ms = Tensor(test_arr, dtype=mindspore.float32)
  184. with pytest.raises(ValueError):
  185. test_op(test_arr_ms)
  186. # TEST 2 - Mismatched input size and paddings - 1D tensor
  187. test_op = nn.Pad(paddings=((0, 0), (1, 0)), mode="CONSTANT")
  188. test_arr = np.random.randn(3) # 1D Tensor
  189. test_arr_ms = Tensor(test_arr, dtype=mindspore.float32)
  190. with pytest.raises(ValueError):
  191. test_op(test_arr_ms)
  192. # TEST 3 - Mismatched input size and paddings - 2D tensor, 3D padding
  193. test_op = nn.Pad(paddings=((0, 0), (1, 0)), mode="CONSTANT") # 2D Padding
  194. test_arr = np.random.randn(1, 3, 3) # 3D Tensor
  195. test_arr_ms = Tensor(test_arr, dtype=mindspore.float32)
  196. with pytest.raises(ValueError):
  197. test_op(test_arr_ms)
  198. # TEST 4 - 1D Paddings should not work
  199. with pytest.raises(TypeError):
  200. test_op = nn.Pad(paddings=((0, 2)), mode="CONSTANT")
  201. # TEST 5 - Padding beyond 4d - (added check in nn file in PR)
  202. with pytest.raises(ValueError):
  203. _ = nn.Pad(paddings=((0, 0), (0, 0,), (0, 0), (0, 0),
  204. (1, 0)), mode="CONSTANT") # 2D Padding