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_lazyadam.py 3.9 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 lazy adam """
  16. import numpy as np
  17. import pytest
  18. import mindspore.nn as nn
  19. from mindspore import Tensor, Parameter, context
  20. from mindspore.common.api import _executor
  21. from mindspore.nn import TrainOneStepCell, WithLossCell
  22. from mindspore.nn.optim import LazyAdam
  23. from mindspore.ops import operations as P
  24. @pytest.fixture(scope="module", autouse=True)
  25. def setup_teardown():
  26. context.set_context(enable_sparse=True)
  27. yield
  28. context.set_context(enable_sparse=False)
  29. class Net(nn.Cell):
  30. """ Net definition """
  31. def __init__(self):
  32. super(Net, self).__init__()
  33. self.weight = Parameter(Tensor(np.ones([64, 10]).astype(np.float32)), name="weight")
  34. self.bias = Parameter(Tensor(np.ones([10]).astype((np.float32))), name="bias")
  35. self.matmul = P.MatMul()
  36. self.biasAdd = P.BiasAdd()
  37. def construct(self, x):
  38. x = self.biasAdd(self.matmul(x, self.weight), self.bias)
  39. return x
  40. class NetWithSparseGatherV2(nn.Cell):
  41. """ NetWithSparseGatherV2 definition """
  42. def __init__(self):
  43. super(NetWithSparseGatherV2, self).__init__()
  44. self.weight1 = Parameter(Tensor(np.ones([3, 1, 2]).astype(np.float32)), name="weight1")
  45. self.weight2 = Parameter(Tensor(np.ones([2, 1, 2]).astype((np.float32))), name="weight2")
  46. self.axis = 0
  47. self.gather = P.SparseGatherV2()
  48. def construct(self, indices, label):
  49. return self.gather(self.weight1, indices, self.axis) + self.weight2
  50. def test_lazy_adam_compile():
  51. """ test lazy adam compile """
  52. inputs = Tensor(np.ones([1, 64]).astype(np.float32))
  53. label = Tensor(np.zeros([1, 10]).astype(np.float32))
  54. net = Net()
  55. net.set_train()
  56. loss = nn.SoftmaxCrossEntropyWithLogits()
  57. optimizer = LazyAdam(net.trainable_params(), learning_rate=0.1, weight_decay=0.9, loss_scale=2.0)
  58. net_with_loss = WithLossCell(net, loss)
  59. train_network = TrainOneStepCell(net_with_loss, optimizer)
  60. _executor.compile(train_network, inputs, label)
  61. def test_spares_lazy_adam_compile():
  62. """ test sparse adam compile """
  63. indices = Tensor(np.array([0, 1]).astype(np.int32))
  64. label = Tensor(np.zeros([2, 1, 2]).astype(np.float32))
  65. net = NetWithSparseGatherV2()
  66. net.set_train()
  67. optimizer = LazyAdam(net.trainable_params(), learning_rate=0.1, weight_decay=0.9, loss_scale=2.0)
  68. optimizer.target = 'CPU'
  69. train_network = TrainOneStepCell(net, optimizer)
  70. _executor.compile(train_network, indices, label)
  71. def test_spares_lazy_adam():
  72. """ test sparse adam"""
  73. indices = Tensor(np.array([0, 1]).astype(np.int32))
  74. label = Tensor(np.zeros([2, 1, 2]).astype(np.float32))
  75. net = NetWithSparseGatherV2()
  76. net.set_train()
  77. optimizer = LazyAdam(net.trainable_params(), learning_rate=0.1, weight_decay=0.9, loss_scale=2.0)
  78. optimizer.target = 'Ascend'
  79. train_network = TrainOneStepCell(net, optimizer)
  80. _executor.compile(train_network, indices, label)
  81. def test_lazy_adam_error():
  82. net = Net()
  83. with pytest.raises(ValueError):
  84. LazyAdam(net.get_parameters(), learning_rate=-0.1)
  85. with pytest.raises(TypeError):
  86. LazyAdam(net.get_parameters(), learning_rate=0.1, beta1=2)