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_initializer.py 11 kB

5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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_initializer """
  16. import math
  17. from functools import reduce
  18. import numpy as np
  19. import pytest as py
  20. from scipy import stats
  21. import mindspore as ms
  22. import mindspore.common.initializer as init
  23. import mindspore.nn as nn
  24. from mindspore import context
  25. from mindspore.common.parameter import Parameter
  26. from mindspore.common.tensor import Tensor
  27. from mindspore.nn import Conv2d
  28. from mindspore.ops import operations as P
  29. from ..ut_filter import non_graph_engine
  30. # pylint: disable=W0212
  31. # W0212: protected-access
  32. class InitTwo(init.Initializer):
  33. """Initialize the array to two."""
  34. def _initialize(self, arr):
  35. init._assignment(arr, 2)
  36. def _check_value(tensor, value_min, value_max):
  37. nd = tensor.asnumpy()
  38. for ele in nd.flatten():
  39. if value_min <= ele <= value_max:
  40. continue
  41. raise ValueError('value_min = %d, ele = %d, value_max = %d'
  42. % (value_min, ele, value_max))
  43. def _check_uniform(tensor, boundary_a, boundary_b):
  44. samples = tensor.asnumpy().reshape((-1))
  45. _, p = stats.kstest(samples, 'uniform', (boundary_a, (boundary_b - boundary_a)))
  46. print("p-value is %f" % p)
  47. return p > 0.0001
  48. def test_init_initializer():
  49. """
  50. Feature: Test initializer.
  51. Description: Test initializer.
  52. Expectation: Shape and value is initialized successfully..
  53. """
  54. tensor = init.initializer(InitTwo(), [2, 2], ms.int32)
  55. assert tensor.shape == (2, 2)
  56. _check_value(tensor.init_data(), 2, 2)
  57. def test_init_tensor():
  58. tensor = ms.Tensor(np.zeros([1, 2, 3]))
  59. tensor = init.initializer(tensor, [1, 2, 3], ms.float32)
  60. assert tensor.shape == (1, 2, 3)
  61. def test_init_zero_default_dtype():
  62. tensor = init.initializer(init.Zero(), [2, 2])
  63. assert tensor.dtype == ms.float32
  64. _check_value(tensor.init_data(), 0, 0)
  65. def test_init_zero():
  66. tensor = init.initializer(init.Zero(), [2, 2], ms.float32)
  67. _check_value(tensor.init_data(), 0, 0)
  68. def test_init_zero_alias_default_dtype():
  69. tensor = init.initializer('zeros', [1, 2])
  70. assert tensor.dtype == ms.float32
  71. _check_value(tensor.init_data(), 0, 0)
  72. def test_init_zero_alias():
  73. tensor = init.initializer('zeros', [1, 2], ms.float32)
  74. _check_value(tensor.init_data(), 0, 0)
  75. def test_init_one():
  76. tensor = init.initializer(init.One(), [2, 2], ms.float32)
  77. _check_value(tensor.init_data(), 1, 1)
  78. def test_init_one_alias():
  79. tensor = init.initializer('ones', [1, 2], ms.float32)
  80. _check_value(tensor.init_data(), 1, 1)
  81. def test_init_constant():
  82. tensor = init.initializer(init.Constant(1), [2, 2], ms.float32)
  83. _check_value(tensor.init_data(), 1, 1)
  84. def test_init_uniform():
  85. scale = 10
  86. tensor = init.initializer(init.Uniform(scale=scale), [5, 4], ms.float32)
  87. _check_value(tensor.init_data(), -scale, scale)
  88. def test_init_uniform_alias():
  89. scale = 100
  90. tensor = init.initializer('uniform', [5, 4], ms.float32)
  91. _check_value(tensor.init_data(), -scale, scale)
  92. def test_init_normal():
  93. tensor = init.initializer(init.Normal(), [5, 4], ms.float32)
  94. assert isinstance(tensor, Tensor), 'Normal init failed!'
  95. def test_init_truncated_normal():
  96. tensor = init.initializer(init.TruncatedNormal(), [5, 4], ms.float32)
  97. assert isinstance(tensor, Tensor), 'TruncatedNormal init failed!'
  98. def test_init_normal_alias():
  99. tensor = init.initializer('normal', [5, 4], ms.float32)
  100. assert isinstance(tensor, Tensor), 'Normal init failed!'
  101. def test_init_truncatednormal_alias():
  102. tensor = init.initializer('truncatednormal', [5, 4], ms.float32)
  103. assert isinstance(tensor, Tensor), 'TruncatedNormal init failed!'
  104. def test_init_abnormal():
  105. with py.raises(TypeError):
  106. init.initializer([''], [5, 4], ms.float32)
  107. def test_initializer_reinit():
  108. weights = init.initializer("XavierUniform", shape=(10, 1, 10, 10), dtype=ms.float16)
  109. assert isinstance(weights, Tensor), 'XavierUniform init failed!'
  110. def test_init_xavier_uniform():
  111. """ test_init_xavier_uniform """
  112. gain = 1.2
  113. tensor1 = init.initializer(init.XavierUniform(gain=gain), [20, 22], ms.float32).init_data()
  114. tensor2 = init.initializer(init.XavierUniform(), [20, 22], ms.float32).init_data()
  115. tensor3 = init.initializer(init.XavierUniform(gain=gain), [20, 22, 5, 5], ms.float32).init_data()
  116. tensor4 = init.initializer(init.XavierUniform(), [20, 22, 5, 5], ms.float32).init_data()
  117. tensor5 = init.initializer('xavier_uniform', [20, 22, 5, 5], ms.float32).init_data()
  118. tensor6 = init.initializer('xavier_uniform', [20, 22], ms.float32).init_data()
  119. tensor_dict = {tensor1: gain, tensor2: None, tensor3: gain, tensor4: None, tensor5: None, tensor6: None}
  120. for tensor, gain_value in tensor_dict.items():
  121. if gain_value is None:
  122. gain_value = 1
  123. shape = tensor.asnumpy().shape
  124. if len(shape) > 2:
  125. s = reduce(lambda x, y: x * y, shape[2:])
  126. else:
  127. s = 1
  128. n_in = shape[1] * s
  129. n_out = shape[0] * s
  130. std = gain_value * math.sqrt(2 / (n_in + n_out))
  131. boundary = std * math.sqrt(3)
  132. assert _check_uniform(tensor, -boundary, boundary)
  133. def test_init_xavier_uniform_error():
  134. with py.raises(ValueError):
  135. init.initializer(init.XavierUniform(), [6], ms.float32).init_data()
  136. def test_init_he_uniform():
  137. """ test_init_he_uniform """
  138. tensor1 = init.initializer(init.HeUniform(), [20, 22], ms.float32)
  139. tensor2 = init.initializer(init.HeUniform(), [20, 22, 5, 5], ms.float32)
  140. tensor3 = init.initializer('he_uniform', [20, 22, 5, 5], ms.float32)
  141. tensor4 = init.initializer('he_uniform', [20, 22], ms.float32)
  142. tensors = [tensor1.init_data(), tensor2.init_data(), tensor3.init_data(), tensor4.init_data()]
  143. for tensor in tensors:
  144. shape = tensor.asnumpy().shape
  145. if len(shape) > 2:
  146. s = reduce(lambda x, y: x * y, shape[2:])
  147. else:
  148. s = 1
  149. n_in = shape[1] * s
  150. std = math.sqrt(2 / n_in)
  151. boundary = std * math.sqrt(3)
  152. assert _check_uniform(tensor, -boundary, boundary)
  153. def test_init_he_uniform_error():
  154. with py.raises(ValueError):
  155. init.initializer(init.HeUniform(), [6], ms.float32).init_data()
  156. def test_init_identity():
  157. """
  158. Feature: Test identity initializer.
  159. Description: Test if error is raised when the shape of the initialized tensor is not correct.
  160. Expectation: ValueError is raised.
  161. """
  162. with py.raises(ValueError):
  163. tensor = init.initializer(init.Identity(), [5, 4, 6], ms.float32)
  164. tensor.init_data()
  165. def test_init_sparse():
  166. """
  167. Feature: Test sparse initializer.
  168. Description: Test if error is raised when the shape of the initialized tensor is not correct.
  169. Expectation: ValueError is raised.
  170. """
  171. with py.raises(ValueError):
  172. tensor = init.initializer(init.Sparse(sparsity=0.1), [5, 4, 6], ms.float32)
  173. tensor.init_data()
  174. def test_init_dirac():
  175. """
  176. Feature: Test dirac initializer.
  177. Description: Test if error is raised when the shape of the initialized tensor is not correct.
  178. or shape[0] is not divisible by group.
  179. Expectation: ValueError is raised.
  180. """
  181. with py.raises(ValueError):
  182. tensor1 = init.initializer(init.Dirac(groups=2), [5, 4, 6], ms.float32)
  183. tensor1.init_data()
  184. with py.raises(ValueError):
  185. tensor2 = init.initializer(init.Dirac(groups=1), [5, 4], ms.float32)
  186. tensor2.init_data()
  187. with py.raises(ValueError):
  188. tensor3 = init.initializer(init.Dirac(groups=1), [5, 4, 6, 7, 8, 9], ms.float32)
  189. tensor3.init_data()
  190. def test_init_orthogonal():
  191. """
  192. Feature: Test orthogonal initializer.
  193. Description: Test if error is raised when the shape of the initialized tensor is not correct.
  194. Expectation: ValueError is raised.
  195. """
  196. with py.raises(ValueError):
  197. tensor = init.initializer(init.Orthogonal(), [5,], ms.float32)
  198. tensor.init_data()
  199. def test_init_variancescaling():
  200. """
  201. Feature: Test orthogonal initializer.
  202. Description: Test if error is raised when scale is less than 0 or mode and distribution are not correct.
  203. Expectation: ValueError is raised.
  204. """
  205. with py.raises(ValueError):
  206. init.initializer(init.VarianceScaling(scale=-0.1), [5, 4, 6], ms.float32)
  207. with py.raises(ValueError):
  208. init.initializer(init.VarianceScaling(scale=0.1, mode='fans'), [5, 4, 6], ms.float32)
  209. with py.raises(ValueError):
  210. init.initializer(init.VarianceScaling(scale=0.1, mode='fan_in',
  211. distribution='uniformal'), [5, 4, 6], ms.float32)
  212. def test_conv2d_abnormal_kernel_negative():
  213. kernel = np.random.randn(64, 3, 7, 7).astype(np.float32)
  214. with py.raises(ValueError):
  215. ms.Model(
  216. Conv2d(in_channels=3, out_channels=64, kernel_size=-7, stride=3,
  217. padding=0, weight_init=ms.Tensor(kernel)))
  218. @non_graph_engine
  219. def test_conv2d_abnormal_kernel_normal():
  220. kernel = np.random.randn(64, 3, 7, 7).astype(np.float32)
  221. input_data = np.random.randn(32, 3, 224, 112).astype(np.float32)
  222. context.set_context(mode=context.GRAPH_MODE)
  223. model = ms.Model(
  224. Conv2d(in_channels=3, out_channels=64, kernel_size=7, stride=3,
  225. padding=0, weight_init=ms.Tensor(kernel)))
  226. model.predict(ms.Tensor(input_data))
  227. @non_graph_engine
  228. def test_conv2d_abnormal_kernel_truncated_normal():
  229. input_data = init.initializer(init.TruncatedNormal(), [64, 3, 7, 7], ms.float32).init_data()
  230. context.set_context(mode=context.GRAPH_MODE)
  231. model = ms.Model(
  232. Conv2d(in_channels=3, out_channels=64, kernel_size=7, stride=3,
  233. padding=0, weight_init="truncatednormal"))
  234. model.predict(input_data)
  235. class Net(nn.Cell):
  236. def __init__(self):
  237. super(Net, self).__init__()
  238. self.add = P.Add()
  239. self.t1 = Parameter(init.initializer('uniform', [5, 4], ms.float32), name="w1")
  240. self.t2 = Parameter(init.initializer(init.TruncatedNormal(), [5, 4], ms.float32), name="w2")
  241. def construct(self, x):
  242. z = self.add(x, self.t1)
  243. z = self.add(z, self.t2)
  244. return z
  245. def test_weight_shape():
  246. context.set_context(mode=context.GRAPH_MODE)
  247. a = np.arange(20).reshape(5, 4)
  248. t = Tensor(a, dtype=ms.float32)
  249. net = Net()
  250. out = net(t)
  251. print(out)