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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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 mindspore.nn as nn
  18. from mindspore import Tensor, Parameter
  19. from mindspore.common.api import _executor
  20. from mindspore.nn import TrainOneStepCell, WithLossCell
  21. from mindspore.nn.optim import Lamb
  22. from mindspore.ops import operations as P
  23. import mindspore.common.dtype as mstype
  24. from mindspore.nn.learning_rate_schedule import LearningRateSchedule, PolynomialDecayLR, WarmUpLR
  25. class LambLearningRate(LearningRateSchedule):
  26. def __init__(self, learning_rate, end_learning_rate, warmup_steps, decay_steps, power):
  27. super(LambLearningRate, self).__init__()
  28. self.warmup_lr = WarmUpLR(learning_rate, warmup_steps)
  29. self.decay_lr = PolynomialDecayLR(learning_rate, end_learning_rate, decay_steps, power)
  30. self.warmup_steps = Tensor(np.array([warmup_steps]).astype(np.float32))
  31. self.greater = P.Greater()
  32. self.one = Tensor(np.array([1.0]).astype(np.float32))
  33. self.cast = P.Cast()
  34. def construct(self, global_step):
  35. is_warmup = self.cast(self.greater(self.warmup_steps, global_step), mstype.float32)
  36. warmup_lr = self.warmup_lr(global_step)
  37. decay_lr = self.decay_lr(global_step)
  38. lr = (self.one - is_warmup) * decay_lr + is_warmup * warmup_lr
  39. return lr
  40. class Net(nn.Cell):
  41. """ Net definition """
  42. def __init__(self):
  43. super(Net, self).__init__()
  44. self.weight = Parameter(Tensor(np.ones([64, 10]).astype(np.float32)), name="weight")
  45. self.bias = Parameter(Tensor(np.ones([10]).astype((np.float32))), name="bias")
  46. self.matmul = P.MatMul()
  47. self.biasAdd = P.BiasAdd()
  48. def construct(self, x):
  49. x = self.biasAdd(self.matmul(x, self.weight), self.bias)
  50. return x
  51. class NetWithoutWeight(nn.Cell):
  52. """ NetWithoutWeight definition """
  53. def __init__(self):
  54. super(NetWithoutWeight, self).__init__()
  55. self.matmul = P.MatMul()
  56. def construct(self, x):
  57. x = self.matmul(x, x)
  58. return x
  59. def test_lamb_compile_dynamic_lr():
  60. """ test_Lamb_compile """
  61. inputs = Tensor(np.ones([1, 64]).astype(np.float32))
  62. label = Tensor(np.zeros([1, 10]).astype(np.float32))
  63. net = Net()
  64. net.set_train()
  65. loss = nn.SoftmaxCrossEntropyWithLogits()
  66. warmup_decay_lr = LambLearningRate(0.01, 0.0001, 10, 20, 1.0)
  67. optimizer = Lamb(net.trainable_params(), warmup_decay_lr)
  68. net_with_loss = WithLossCell(net, loss)
  69. train_network = TrainOneStepCell(net_with_loss, optimizer)
  70. _executor.compile(train_network, inputs, label)
  71. def test_lamb_compile():
  72. """ test_Lamb_compile """
  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 = Lamb(net.trainable_params(), 0.02, 0.9)
  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_lamb_group():
  83. """ test_Lamb_group_compile """
  84. inputs = Tensor(np.ones([1, 64]).astype(np.float32))
  85. label = Tensor(np.zeros([1, 10]).astype(np.float32))
  86. net = Net()
  87. net.set_train()
  88. loss = nn.SoftmaxCrossEntropyWithLogits()
  89. warmup_decay_lr = LambLearningRate(0.01, 0.0001, 10, 20, 1.0)
  90. all_params = net.trainable_params()
  91. group_params = [{'params': [all_params[0]], 'lr': warmup_decay_lr, 'weight_decay': 0.9},
  92. {'params': [all_params[1]]}]
  93. optimizer = Lamb(group_params, 0.02)
  94. net_with_loss = WithLossCell(net, loss)
  95. train_network = TrainOneStepCell(net_with_loss, optimizer)
  96. _executor.compile(train_network, inputs, label)