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_fused_adam.py 7.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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. import numpy as np
  16. import pytest
  17. import mindspore.context as context
  18. import mindspore.nn as nn
  19. from mindspore import Tensor
  20. from mindspore.common.api import ms_function
  21. from mindspore.ops import operations as P
  22. from mindspore.ops import functional as F
  23. from mindspore.common import dtype as mstype
  24. from mindspore.common.parameter import Parameter
  25. class Net(nn.Cell):
  26. def __init__(self, decay_flag=True):
  27. super(Net, self).__init__()
  28. self.decay_flag = decay_flag
  29. self.op_mul = P.Mul()
  30. self.op_square = P.Square()
  31. self.op_sqrt = P.Sqrt()
  32. self.op_cast = P.Cast()
  33. self.op_reshape = P.Reshape()
  34. self.op_shape = P.Shape()
  35. self.param = Parameter(Tensor(np.array([1, 3, 5]).astype(np.float32)), name='param')
  36. self.m = Parameter(Tensor(np.array([0.11, 0.33, 0.55]).astype(np.float32)), name='m')
  37. self.v = Parameter(Tensor(np.array([1.2, 3.4, 5.6]).astype(np.float32)), name='v')
  38. @ms_function
  39. def construct(self, beta1, beta2, one_sub_beta_1, one_sub_beta_2, gradient, eps, weight_decay_tensor, lr):
  40. param_fp32 = self.op_cast(self.param, mstype.float32)
  41. m_fp32 = self.op_cast(self.m, mstype.float32)
  42. v_fp32 = self.op_cast(self.v, mstype.float32)
  43. gradient_fp32 = self.op_cast(gradient, mstype.float32)
  44. next_m = self.op_mul(beta1, m_fp32) + \
  45. self.op_mul(self.op_cast(one_sub_beta_1, mstype.float32), gradient_fp32)
  46. next_v = self.op_mul(beta2, v_fp32) + self.op_mul(self.op_cast(one_sub_beta_2,
  47. mstype.float32), self.op_square(gradient_fp32))
  48. update = next_m / (eps + self.op_sqrt(next_v))
  49. if self.decay_flag:
  50. update = self.op_mul(weight_decay_tensor, param_fp32) + update
  51. update_with_lr = self.op_mul(lr, update)
  52. next_param = param_fp32 - self.op_reshape(update_with_lr, self.op_shape(param_fp32))
  53. depend_v = F.depend(next_param, F.assign(self.param, next_param))
  54. depend_v = F.depend(depend_v, F.assign(self.m, next_m))
  55. depend_v = F.depend(depend_v, F.assign(self.v, next_v))
  56. return depend_v
  57. def CalFusedAdam(beta1, beta2, one_sub_beta_1, one_sub_beta_2, gradient, eps, weight_decay_tensor, lr, param, m, v,
  58. is_weight_decay=False):
  59. m_expect = beta1 * m + one_sub_beta_1 * gradient
  60. v_expect = beta2 * v + one_sub_beta_2 * gradient * gradient
  61. update = m_expect / (np.sqrt(v_expect) + eps)
  62. if is_weight_decay:
  63. update += weight_decay_tensor * param
  64. param_expect = param - lr * update
  65. return param_expect, m_expect, v_expect
  66. def test_adam():
  67. np.random.seed(0)
  68. beta1 = np.array([0.9]).astype(np.float32)
  69. beta2 = np.array([0.999]).astype(np.float32)
  70. one_sub_beta_1 = (np.array([1.0]) - np.array([0.9])).astype(np.float32)
  71. one_sub_beta_2 = (np.array([1.0]) - np.array([0.999])).astype(np.float32)
  72. lr = np.array([0.012]).astype(np.float32)
  73. eps = np.array([1e-6]).astype(np.float32)
  74. weight_decay_tensor = np.array([0.021]).astype(np.float32)
  75. gradient = np.array([0.01, 0.03, 0.05]).astype(np.float32)
  76. m = np.array([0.11, 0.33, 0.55]).astype(np.float32)
  77. v = np.array([1.2, 3.4, 5.6]).astype(np.float32)
  78. param = np.array([1, 3, 5]).astype(np.float32)
  79. is_weight_decay = False
  80. opt = Net(is_weight_decay)
  81. _ = opt(Tensor(beta1), Tensor(beta2), Tensor(one_sub_beta_1), Tensor(one_sub_beta_2), Tensor(gradient), Tensor(eps),
  82. Tensor(weight_decay_tensor), Tensor(lr))
  83. param_expect, m_expect, v_expect = CalFusedAdam(
  84. beta1, beta2, one_sub_beta_1, one_sub_beta_2, gradient, eps, weight_decay_tensor, lr,
  85. param, m, v, is_weight_decay)
  86. assert np.allclose(opt.param.data.asnumpy(), param_expect, rtol=1.e-4, atol=1.e-8, equal_nan=True)
  87. assert np.allclose(opt.m.data.asnumpy(), m_expect, rtol=1.e-4, atol=1.e-8, equal_nan=True)
  88. assert np.allclose(opt.v.data.asnumpy(), v_expect, rtol=1.e-4, atol=1.e-8, equal_nan=True)
  89. def test_adam_weight_decay():
  90. np.random.seed(0)
  91. beta1 = np.array([0.9]).astype(np.float32)
  92. beta2 = np.array([0.999]).astype(np.float32)
  93. one_sub_beta_1 = (np.array([1.0]) - np.array([0.9])).astype(np.float32)
  94. one_sub_beta_2 = (np.array([1.0]) - np.array([0.999])).astype(np.float32)
  95. lr = np.array([0.012]).astype(np.float32)
  96. eps = np.array([1e-6]).astype(np.float32)
  97. weight_decay_tensor = np.array([0.021]).astype(np.float32)
  98. gradient = np.array([0.01, 0.03, 0.05]).astype(np.float32)
  99. m = np.array([0.11, 0.33, 0.55]).astype(np.float32)
  100. v = np.array([1.2, 3.4, 5.6]).astype(np.float32)
  101. param = np.array([1, 3, 5]).astype(np.float32)
  102. is_weight_decay = True
  103. opt = Net(is_weight_decay)
  104. _ = opt(Tensor(beta1), Tensor(beta2), Tensor(one_sub_beta_1), Tensor(one_sub_beta_2), Tensor(gradient), Tensor(eps),
  105. Tensor(weight_decay_tensor), Tensor(lr))
  106. param_expect, m_expect, v_expect = CalFusedAdam(
  107. beta1, beta2, one_sub_beta_1, one_sub_beta_2, gradient, eps, weight_decay_tensor, lr,
  108. param, m, v, is_weight_decay)
  109. assert np.allclose(opt.param.data.asnumpy(), param_expect, rtol=1.e-4, atol=1.e-8, equal_nan=True)
  110. assert np.allclose(opt.m.data.asnumpy(), m_expect, rtol=1.e-4, atol=1.e-8, equal_nan=True)
  111. assert np.allclose(opt.v.data.asnumpy(), v_expect, rtol=1.e-4, atol=1.e-8, equal_nan=True)
  112. @pytest.mark.level0
  113. @pytest.mark.platform_x86_gpu_training
  114. @pytest.mark.env_onecard
  115. def test_adam_gpu():
  116. context.set_context(mode=context.GRAPH_MODE, enable_graph_kernel=True, device_target="GPU")
  117. test_adam()
  118. @pytest.mark.level0
  119. @pytest.mark.platform_arm_ascend_training
  120. @pytest.mark.platform_x86_ascend_training
  121. @pytest.mark.env_onecard
  122. def test_adam_ascend():
  123. context.set_context(mode=context.GRAPH_MODE, enable_graph_kernel=True, device_target="Ascend")
  124. test_adam()
  125. @pytest.mark.level0
  126. @pytest.mark.platform_x86_gpu_training
  127. @pytest.mark.env_onecard
  128. def test_adam_weight_decay_gpu():
  129. context.set_context(mode=context.GRAPH_MODE, enable_graph_kernel=True, device_target="GPU")
  130. test_adam_weight_decay()
  131. @pytest.mark.level0
  132. @pytest.mark.platform_arm_ascend_training
  133. @pytest.mark.platform_x86_ascend_training
  134. @pytest.mark.env_onecard
  135. def test_adam_weight_decay_ascend():
  136. context.set_context(mode=context.GRAPH_MODE, enable_graph_kernel=True, device_target="Ascend")
  137. test_adam_weight_decay()