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_adam.py 6.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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 adam """
  16. import numpy as np
  17. import pytest
  18. import mindspore.nn as nn
  19. from mindspore import Tensor, Parameter
  20. import mindspore.common.dtype as mstype
  21. from mindspore.common.api import _executor
  22. from mindspore.nn import TrainOneStepCell, WithLossCell
  23. from mindspore.nn.optim import Adam, AdamWeightDecay, AdamWeightDecayDynamicLR
  24. from mindspore.ops import operations as P
  25. class Net(nn.Cell):
  26. """ Net definition """
  27. def __init__(self):
  28. super(Net, self).__init__()
  29. self.weight = Parameter(Tensor(np.ones([64, 10]).astype(np.float32)), name="weight")
  30. self.bias = Parameter(Tensor(np.ones([10]).astype((np.float32))), name="bias")
  31. self.matmul = P.MatMul()
  32. self.biasAdd = P.BiasAdd()
  33. def construct(self, x):
  34. x = self.biasAdd(self.matmul(x, self.weight), self.bias)
  35. return x
  36. class NetWithoutWeight(nn.Cell):
  37. def __init__(self):
  38. super(NetWithoutWeight, self).__init__()
  39. self.matmul = P.MatMul()
  40. def construct(self, x):
  41. x = self.matmul(x, x)
  42. return x
  43. class NetWithSparseGatherV2(nn.Cell):
  44. """ NetWithSparseGatherV2 definition """
  45. def __init__(self):
  46. super(NetWithSparseGatherV2, self).__init__()
  47. self.weight1 = Parameter(Tensor(np.ones([3, 1, 2]).astype(np.float32)), name="weight1", sparse_grad=True)
  48. self.weight2 = Parameter(Tensor(np.ones([2, 1, 2]).astype((np.float32))), name="weight2")
  49. self.axis = 0
  50. self.gather = P.SparseGatherV2()
  51. def construct(self, indices, label):
  52. return self.gather(self.weight1, indices, self.axis) + self.weight2
  53. def test_adamwithoutparam():
  54. net = NetWithoutWeight()
  55. net.set_train()
  56. with pytest.raises(ValueError, match=r"Optimizer got an empty parameter list"):
  57. AdamWeightDecay(net.trainable_params(), learning_rate=0.1)
  58. def test_adamw_compile():
  59. """ test_adamw_compile """
  60. inputs = Tensor(np.ones([1, 64]).astype(np.float32))
  61. label = Tensor(np.zeros([1, 10]).astype(np.float32))
  62. net = Net()
  63. net.set_train()
  64. loss = nn.SoftmaxCrossEntropyWithLogits()
  65. optimizer = AdamWeightDecay(net.trainable_params(), learning_rate=0.1)
  66. net_with_loss = WithLossCell(net, loss)
  67. train_network = TrainOneStepCell(net_with_loss, optimizer)
  68. _executor.compile(train_network, inputs, label)
  69. def test_adam_compile():
  70. """ test adam compile """
  71. inputs = Tensor(np.ones([1, 64]).astype(np.float32))
  72. label = Tensor(np.zeros([1, 10]).astype(np.float32))
  73. net = Net()
  74. net.set_train()
  75. loss = nn.SoftmaxCrossEntropyWithLogits()
  76. optimizer = Adam(net.trainable_params(), learning_rate=0.1, weight_decay=0.9)
  77. net_with_loss = WithLossCell(net, loss)
  78. train_network = TrainOneStepCell(net_with_loss, optimizer)
  79. _executor.compile(train_network, inputs, label)
  80. def test_spares_adam_compile():
  81. """ test_sparse_adam_compile """
  82. indices = Tensor(np.array([0, 1]).astype(np.int32))
  83. label = Tensor(np.zeros([2, 1, 2]).astype(np.float32))
  84. net = NetWithSparseGatherV2()
  85. net.set_train()
  86. optimizer = Adam(net.trainable_params(), learning_rate=0.1)
  87. train_network = TrainOneStepCell(net, optimizer)
  88. _executor.compile(train_network, indices, label)
  89. def test_AdamWeightDecay_beta1():
  90. net = Net()
  91. print("**********", net.get_parameters())
  92. with pytest.raises(ValueError):
  93. AdamWeightDecay(net.get_parameters(), beta1=1.0, learning_rate=0.1)
  94. def test_AdamWeightDecay_beta2():
  95. net = Net()
  96. with pytest.raises(ValueError):
  97. AdamWeightDecay(net.get_parameters(), beta2=1.0, learning_rate=0.1)
  98. def test_AdamWeightDecay_e():
  99. net = Net()
  100. with pytest.raises(ValueError):
  101. AdamWeightDecay(net.get_parameters(), eps=-0.1, learning_rate=0.1)
  102. def test_AdamWeightDecayDynamicLR():
  103. """ test_AdamWeightDecayDynamicLR """
  104. inputs = Tensor(np.ones([1, 64]).astype(np.float32))
  105. label = Tensor(np.zeros([1, 10]).astype(np.float32))
  106. net = Net()
  107. net.set_train()
  108. loss = nn.SoftmaxCrossEntropyWithLogits()
  109. optimizer = AdamWeightDecayDynamicLR(net.trainable_params(), decay_steps=20, learning_rate=0.1)
  110. net_with_loss = WithLossCell(net, loss)
  111. train_network = TrainOneStepCell(net_with_loss, optimizer)
  112. _executor.compile(train_network, inputs, label)
  113. def test_adam_mindspore_with_empty_params():
  114. net = nn.Flatten()
  115. with pytest.raises(ValueError, match=r"Optimizer got an empty parameter list"):
  116. AdamWeightDecay(net.get_parameters())
  117. class TestSparseOps(nn.Cell):
  118. """Define sparse operator"""
  119. def __init__(self, sparse_opt):
  120. super(TestSparseOps, self).__init__()
  121. self.sparse_apply_adam = sparse_opt
  122. self.var = Parameter(Tensor(np.ones([3, 3, 3]).astype(np.float32)), name="var")
  123. self.m = Parameter(Tensor(np.ones([3, 3, 3]).astype(np.float32)), name="m")
  124. self.v = Parameter(Tensor(np.ones([3, 3, 3]).astype(np.float32)), name="v")
  125. def construct(self, beta1_power, beta2_power, lr, beta1, beta2, epsilon, grad, indices):
  126. out = self.sparse_apply_adam(self.var, self.m, self.v, beta1_power, beta2_power, lr, beta1, beta2, epsilon,
  127. grad, indices)
  128. return out
  129. def test_sparse_adam():
  130. """test sparse operator"""
  131. gradient = Tensor(np.random.rand(3, 3, 3).astype(np.float32))
  132. indices = Tensor([0, 1, 2], mstype.int32)
  133. net = TestSparseOps(P.SparseApplyAdam())
  134. _executor.compile(net, 0.9, 0.999, 0.001, 0.9, 0.999, 1e-8, gradient, indices)
  135. def test_sparse_lazy_adam():
  136. """test sparse operator"""
  137. gradient = Tensor(np.random.rand(3, 3, 3).astype(np.float32))
  138. indices = Tensor([0, 1, 2], mstype.int32)
  139. net = TestSparseOps(P.SparseApplyLazyAdam())
  140. _executor.compile(net, 0.9, 0.999, 0.001, 0.9, 0.999, 1e-8, gradient, indices)