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_lamb.py 2.5 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 lamb """
  16. import numpy as np
  17. import pytest
  18. import mindspore.nn as nn
  19. from mindspore import Tensor, Parameter
  20. from mindspore.common.api import _executor
  21. from mindspore.nn import TrainOneStepCell, WithLossCell
  22. from mindspore.nn.optim import Lamb
  23. from mindspore.ops import operations as P
  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. """ NetWithoutWeight definition """
  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. def test_lamb_compile():
  44. """ test_Lamb_compile """
  45. inputs = Tensor(np.ones([1, 64]).astype(np.float32))
  46. label = Tensor(np.zeros([1, 10]).astype(np.float32))
  47. net = Net()
  48. net.set_train()
  49. loss = nn.SoftmaxCrossEntropyWithLogits()
  50. optimizer = Lamb(net.trainable_params(), decay_steps=10)
  51. net_with_loss = WithLossCell(net, loss)
  52. train_network = TrainOneStepCell(net_with_loss, optimizer)
  53. _executor.compile(train_network, inputs, label)
  54. def test_lamb_error():
  55. net = Net()
  56. with pytest.raises(TypeError):
  57. Lamb(net.get_parameters(), decay_steps=6, warmup_steps=5.0)
  58. with pytest.raises(TypeError):
  59. Lamb(net.get_parameters(), decay_steps=1.0)
  60. with pytest.raises(ValueError):
  61. Lamb(net.get_parameters(), decay_steps=0)