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 3.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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.common.api import _executor
  20. from mindspore import Tensor, Parameter
  21. from mindspore.nn import TrainOneStepCell, WithLossCell
  22. from mindspore.ops import operations as P
  23. from mindspore.nn.optim import AdamWeightDecay, AdamWeightDecayDynamicLR
  24. class Net(nn.Cell):
  25. """ Net definition """
  26. def __init__(self):
  27. super(Net, self).__init__()
  28. self.weight = Parameter(Tensor(np.ones([64, 10]).astype(np.float32)), name="weight")
  29. self.bias = Parameter(Tensor(np.ones([10]).astype((np.float32))), name="bias")
  30. self.matmul = P.MatMul()
  31. self.biasAdd = P.BiasAdd()
  32. def construct(self, x):
  33. x = self.biasAdd(self.matmul(x, self.weight), self.bias)
  34. return x
  35. class NetWithoutWeight(nn.Cell):
  36. def __init__(self):
  37. super(NetWithoutWeight, self).__init__()
  38. self.matmul = P.MatMul()
  39. def construct(self, x):
  40. x = self.matmul(x, x)
  41. return x
  42. def test_adamwithoutparam():
  43. net = NetWithoutWeight()
  44. net.set_train()
  45. with pytest.raises(ValueError, match=r"optimizer got an empty parameter list"):
  46. AdamWeightDecay(net.trainable_params(), learning_rate=0.1)
  47. def test_adamw_compile():
  48. """ test_adamw_compile """
  49. inputs = Tensor(np.ones([1, 64]).astype(np.float32))
  50. label = Tensor(np.zeros([1, 10]).astype(np.float32))
  51. net = Net()
  52. net.set_train()
  53. loss = nn.SoftmaxCrossEntropyWithLogits()
  54. optimizer = AdamWeightDecay(net.trainable_params(), learning_rate=0.1)
  55. net_with_loss = WithLossCell(net, loss)
  56. train_network = TrainOneStepCell(net_with_loss, optimizer)
  57. _executor.compile(train_network, inputs, label)
  58. def test_AdamWeightDecay_beta1():
  59. net = Net()
  60. print("**********", net.get_parameters())
  61. with pytest.raises(ValueError):
  62. AdamWeightDecay(net.get_parameters(), beta1=1.0, learning_rate=0.1)
  63. def test_AdamWeightDecay_beta2():
  64. net = Net()
  65. with pytest.raises(ValueError):
  66. AdamWeightDecay(net.get_parameters(), beta2=1.0, learning_rate=0.1)
  67. def test_AdamWeightDecay_e():
  68. net = Net()
  69. with pytest.raises(ValueError):
  70. AdamWeightDecay(net.get_parameters(), eps=-0.1, learning_rate=0.1)
  71. def test_AdamWeightDecayDynamicLR():
  72. """ test_AdamWeightDecayDynamicLR """
  73. inputs = Tensor(np.ones([1, 64]).astype(np.float32))
  74. label = Tensor(np.zeros([1, 10]).astype(np.float32))
  75. net = Net()
  76. net.set_train()
  77. loss = nn.SoftmaxCrossEntropyWithLogits()
  78. optimizer = AdamWeightDecayDynamicLR(net.trainable_params(), decay_steps=20, learning_rate=0.1)
  79. net_with_loss = WithLossCell(net, loss)
  80. train_network = TrainOneStepCell(net_with_loss, optimizer)
  81. _executor.compile(train_network, inputs, label)
  82. def test_adam_mindspore_flatten():
  83. net = nn.Flatten()
  84. with pytest.raises(ValueError, match=r"optimizer got an empty parameter list"):
  85. AdamWeightDecay(net.get_parameters())