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_optimizer.py 4.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. # Copyright 2020-2022 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 optimizer """
  16. import numpy as np
  17. import pytest
  18. import mindspore as ms
  19. from mindspore import Tensor
  20. from mindspore.common.parameter import Parameter
  21. from mindspore.nn.optim import Optimizer, SGD, Adam, AdamWeightDecay
  22. class IterableObjc:
  23. def __iter__(self):
  24. cont = 0
  25. while cont < 3:
  26. cont += 1
  27. yield Parameter(Tensor(cont), name="cont" + str(cont))
  28. params = IterableObjc()
  29. class TestOptimizer():
  30. def test_init(self):
  31. Optimizer(0.5, params)
  32. with pytest.raises(ValueError):
  33. Optimizer(-0.5, params)
  34. def test_construct(self):
  35. opt_2 = Optimizer(0.5, params)
  36. with pytest.raises(NotImplementedError):
  37. opt_2.construct()
  38. class TestAdam():
  39. """ TestAdam definition """
  40. def test_init(self):
  41. Adam(params, learning_rate=1e-3, beta1=0.9, beta2=0.999, eps=1e-8, use_locking=False,
  42. use_nesterov=False, weight_decay=0.0, loss_scale=1.0)
  43. def test_construct(self):
  44. with pytest.raises(RuntimeError):
  45. gradient = Tensor(np.zeros([1, 2, 3]))
  46. adam = Adam(params, learning_rate=1e-3, beta1=0.9, beta2=0.999, eps=1e-8, use_locking=False,
  47. use_nesterov=False, weight_decay=0.0, loss_scale=1.0)
  48. adam(gradient)
  49. class TestSGD():
  50. """ TestSGD definition """
  51. def test_init(self):
  52. with pytest.raises(ValueError):
  53. SGD(params, learning_rate=0.1, momentum=-0.1, dampening=0, weight_decay=0, nesterov=False)
  54. with pytest.raises(ValueError):
  55. SGD(params, learning_rate=0.12, momentum=-0.1, dampening=0, weight_decay=0, nesterov=False)
  56. SGD(params)
  57. class TestNullParam():
  58. """ TestNullParam definition """
  59. def test_optim_init(self):
  60. with pytest.raises(ValueError):
  61. Optimizer(0.1, None)
  62. def test_AdamWightDecay_init(self):
  63. with pytest.raises(ValueError):
  64. AdamWeightDecay(None)
  65. def test_Sgd_init(self):
  66. with pytest.raises(ValueError):
  67. SGD(None)
  68. class TestUnsupportParam():
  69. """ TestUnsupportParam definition """
  70. def test_optim_init(self):
  71. with pytest.raises(TypeError):
  72. Optimizer(0.1, (1, 2, 3))
  73. def test_AdamWightDecay_init(self):
  74. with pytest.raises(TypeError):
  75. AdamWeightDecay(9)
  76. def test_Sgd_init(self):
  77. with pytest.raises(TypeError):
  78. paramsTensor = Parameter(Tensor(np.zeros([1, 2, 3])), "x")
  79. SGD(paramsTensor)
  80. class TestFlattenParams:
  81. """ Test Optimizer with flatten parameters """
  82. def __init__(self):
  83. self.p1 = None
  84. self.p2 = None
  85. self.p3 = None
  86. self.params = []
  87. def setup_method(self):
  88. self.p1 = Parameter(Tensor([1], ms.float32), name="p1")
  89. self.p2 = Parameter(Tensor([2], ms.float32), name="p2")
  90. self.p3 = Parameter(Tensor([3], ms.float32), name="p3")
  91. self.params = [self.p1, self.p2, self.p3]
  92. def test_not_flattened_params(self):
  93. """
  94. Feature: Flatten weights.
  95. Description: Optimizer with not flattened parameters.
  96. Expectation: The Optimizer works as expected.
  97. """
  98. opt = Optimizer(0.1, self.params)
  99. assert not opt._use_flattened_params # pylint: disable=W0212
  100. assert len(opt.parameters) == 3
  101. assert len(opt.cache_enable) == 3
  102. def test_with_flattened_params(self):
  103. """
  104. Feature: Flatten weights.
  105. Description: Optimizer with flattened parameters.
  106. Expectation: The Optimizer works as expected.
  107. """
  108. Tensor._flatten_tensors(self.params) # pylint: disable=W0212
  109. opt = Optimizer(0.1, self.params)
  110. assert opt._use_flattened_params # pylint: disable=W0212
  111. assert len(opt.parameters) == 1
  112. assert len(opt.cache_enable) == 1
  113. assert opt.parameters[0].dtype == ms.float32
  114. assert opt.parameters[0].shape == (3,)
  115. assert opt.parameters[0].size == 3
  116. assert np.allclose(opt.parameters[0].asnumpy(), np.array([1, 2, 3]))
  117. self.p1.asnumpy()[0] = 6
  118. self.p2.asnumpy()[0] = 6
  119. self.p3.asnumpy()[0] = 6
  120. assert np.allclose(opt.parameters[0].asnumpy(), np.array([6, 6, 6]))