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_parameter.py 8.2 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. """ test parameter """
  16. import numpy as np
  17. import pytest
  18. from mindspore import context, Tensor, Parameter, ParameterTuple
  19. from mindspore._checkparam import _check_str_by_regular
  20. from mindspore.common import dtype as mstype
  21. from mindspore.common.initializer import initializer
  22. def test_parameter_init():
  23. dat = np.array([[1, 2, 3], [2, 3, 4]])
  24. tensor = Tensor(dat)
  25. Parameter(tensor, name="testParameter", requires_grad=True, layerwise_parallel=False)
  26. def test_parameter_tuple_illegal():
  27. p1 = Parameter(initializer(0, [1], mstype.int32), name="global_step1")
  28. p2 = Parameter(initializer(0, [1], mstype.int32), name="global_step2")
  29. plist = [p1, p2]
  30. plist2 = [p1, "str"]
  31. ptuple = (p1, p2)
  32. ptuple_str = ("2", "1")
  33. pstr = "[2,3]"
  34. pnum = 3
  35. ParameterTuple(plist)
  36. ParameterTuple(ptuple)
  37. with pytest.raises(TypeError):
  38. ParameterTuple(p1)
  39. with pytest.raises(TypeError):
  40. ParameterTuple(plist2)
  41. with pytest.raises(TypeError):
  42. ParameterTuple(ptuple_str)
  43. with pytest.raises(TypeError):
  44. ParameterTuple(pstr)
  45. with pytest.raises(TypeError):
  46. ParameterTuple(pnum)
  47. def test_parameter_init_illegal():
  48. dat = np.array([[1, 2, 3], [2, 3, 4]])
  49. tensor = Tensor(dat)
  50. data_none = None
  51. data_bool = True
  52. data_str = "nicai"
  53. data_int = 3
  54. data_list = [1, "2", True]
  55. data_tuple = (1, 2, 3)
  56. # test data
  57. Parameter(tensor, name=data_str)
  58. Parameter(data_int, name=data_str)
  59. Parameter(dat, name=data_str)
  60. with pytest.raises(ValueError):
  61. Parameter(data_bool, name=data_str)
  62. # test name
  63. Parameter(tensor, name=data_none)
  64. with pytest.raises(ValueError):
  65. Parameter(tensor, name=dat)
  66. with pytest.raises(ValueError):
  67. Parameter(tensor, name=tensor)
  68. with pytest.raises(ValueError):
  69. Parameter(tensor, name=data_bool)
  70. with pytest.raises(ValueError):
  71. Parameter(tensor, name=data_int)
  72. with pytest.raises(ValueError):
  73. Parameter(tensor, name=data_list)
  74. with pytest.raises(ValueError):
  75. Parameter(tensor, name=data_tuple)
  76. Parameter(tensor, name=data_str, requires_grad=data_bool)
  77. with pytest.raises(TypeError):
  78. Parameter(tensor, name=data_str, requires_grad=data_none)
  79. with pytest.raises(TypeError):
  80. Parameter(tensor, name=data_str, requires_grad=dat)
  81. with pytest.raises(TypeError):
  82. Parameter(tensor, name=data_str, requires_grad=tensor)
  83. with pytest.raises(TypeError):
  84. Parameter(tensor, name=data_str, requires_grad=data_str)
  85. with pytest.raises(TypeError):
  86. Parameter(tensor, name=data_str, requires_grad=data_int)
  87. with pytest.raises(TypeError):
  88. Parameter(tensor, name=data_str, requires_grad=data_list)
  89. with pytest.raises(TypeError):
  90. Parameter(tensor, name=data_str, requires_grad=data_tuple)
  91. Parameter(tensor, name=data_str, requires_grad=data_bool, layerwise_parallel=data_bool)
  92. with pytest.raises(TypeError):
  93. Parameter(tensor, name=data_str, requires_grad=data_bool, layerwise_parallel=dat)
  94. with pytest.raises(TypeError):
  95. Parameter(tensor, name=data_str, requires_grad=data_bool, layerwise_parallel=tensor)
  96. with pytest.raises(TypeError):
  97. Parameter(tensor, name=data_str, requires_grad=data_bool, layerwise_parallel=data_none)
  98. with pytest.raises(TypeError):
  99. Parameter(tensor, name=data_str, requires_grad=data_bool, layerwise_parallel=data_str)
  100. with pytest.raises(TypeError):
  101. Parameter(tensor, name=data_str, requires_grad=data_bool, layerwise_parallel=data_int)
  102. with pytest.raises(TypeError):
  103. Parameter(tensor, name=data_str, requires_grad=data_bool, layerwise_parallel=data_list)
  104. with pytest.raises(TypeError):
  105. Parameter(tensor, name=data_str, requires_grad=data_bool, layerwise_parallel=data_tuple)
  106. def test_check_str_by_regular():
  107. str1 = "12_sf.asdf_"
  108. str2 = "x12_sf.asdf."
  109. str3 = "_x12_sf.asdf"
  110. str4 = ".12_sf.asdf"
  111. str5 = "12_sf.a$sdf."
  112. str6 = "12+sf.asdf"
  113. _check_str_by_regular(str1)
  114. _check_str_by_regular(str2)
  115. _check_str_by_regular(str3)
  116. with pytest.raises(ValueError):
  117. _check_str_by_regular(str4)
  118. with pytest.raises(ValueError):
  119. _check_str_by_regular(str5)
  120. with pytest.raises(ValueError):
  121. _check_str_by_regular(str6)
  122. def test_parameter_compute():
  123. para_1 = Parameter(initializer('ones', [1, 2, 3], mstype.int32), 'test1')
  124. para_2 = Parameter(initializer('ones', [1, 2, 3], mstype.int32), 'test2')
  125. t3 = Tensor(np.ones((1, 2, 3)))
  126. out = para_1 + para_2
  127. assert np.array_equal(out.asnumpy(), np.ones((1, 2, 3)) * 2)
  128. out = para_1 * para_2
  129. assert np.array_equal(out.asnumpy(), np.ones((1, 2, 3)))
  130. out = para_1 + t3
  131. assert np.array_equal(out.asnumpy(), np.ones((1, 2, 3)) * 2)
  132. out = para_1 * t3
  133. assert np.array_equal(out.asnumpy(), np.ones((1, 2, 3)))
  134. assert isinstance(para_1, Tensor)
  135. def test_scalar_parameter_update():
  136. fp = Parameter(0.5, 'fp')
  137. fp.default_input = 0.8
  138. assert np.array_equal(fp.default_input.asnumpy(), np.array(0.8, np.float32))
  139. fp.default_input = 1
  140. assert np.array_equal(fp.default_input.asnumpy(), np.array(1.0, np.float32))
  141. int_ = Parameter(1, 'fp')
  142. int_.default_input = 2
  143. assert np.array_equal(int_.default_input.asnumpy(), np.array(2, np.int32))
  144. with pytest.raises(TypeError):
  145. int_.default_input = 1.2
  146. def test_parameter_lazy_init():
  147. # support lazy init in SEMI_AUTO_PARALLEL mode
  148. context.reset_auto_parallel_context()
  149. context.set_auto_parallel_context(parallel_mode="semi_auto_parallel", device_num=8)
  150. # Call init_data() without set default_input.
  151. para = Parameter(initializer('ones', [1, 2, 3], mstype.float32), 'test1')
  152. assert not isinstance(para.default_input, Tensor)
  153. para = para.init_data()
  154. assert isinstance(para.default_input, Tensor)
  155. assert np.array_equal(para.default_input.asnumpy(), np.ones((1, 2, 3)))
  156. # Call init_data() after default_input is set.
  157. para = Parameter(initializer('ones', [1, 2, 3], mstype.float32), 'test2')
  158. assert not isinstance(para.default_input, Tensor)
  159. # expect type error when not init
  160. with pytest.raises(TypeError):
  161. para.default_input = Tensor(np.zeros((1, 2, 3)))
  162. # init then assign
  163. para = para.init_data()
  164. # check the type
  165. with pytest.raises(TypeError):
  166. para.default_input = Tensor(np.zeros((1, 2, 3)))
  167. # check the shape
  168. with pytest.raises(ValueError):
  169. para.default_input = Tensor(np.zeros((1, 2)))
  170. # expect change ok
  171. para.default_input = Tensor(np.zeros((1, 2, 3)).astype(np.float32))
  172. assert np.array_equal(para.default_input.asnumpy(), np.zeros((1, 2, 3)))
  173. para.default_input = initializer('ones', [1, 2, 3], mstype.float32)
  174. assert isinstance(para.default_input, Tensor)
  175. # same object and has inited
  176. assert np.array_equal(para.default_input.asnumpy(), np.ones((1, 2, 3)))
  177. # expect no effect.
  178. para.init_data()
  179. assert np.array_equal(para.default_input.asnumpy(), np.ones((1, 2, 3)))
  180. para.set_parameter_data(Tensor(np.zeros((1, 2)).astype(np.float32)), slice_shape=True)
  181. assert np.array_equal(para.default_input.asnumpy(), np.zeros((1, 2)))
  182. para.set_parameter_data(initializer('ones', [1, 2], mstype.float32), slice_shape=True)
  183. assert np.array_equal(para.default_input.asnumpy(), np.ones((1, 2)))
  184. context.reset_auto_parallel_context()