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_adagrad_op.py 2.1 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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, Parameter
  20. from mindspore.ops import operations as P
  21. import mindspore.common.dtype as mstype
  22. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  23. var_np = np.random.rand(3, 3).astype(np.float32)
  24. accum_np = np.random.rand(3, 3).astype(np.float32)
  25. class Net(nn.Cell):
  26. def __init__(self):
  27. super(Net, self).__init__()
  28. self.apply_adagrad = P.ApplyAdagrad()
  29. self.var = Parameter(Tensor(var_np), name="var")
  30. self.accum = Parameter(Tensor(accum_np), name="accum")
  31. def construct(self, lr, grad):
  32. z = self.apply_adagrad(self.var, self.accum, lr, grad)
  33. return z
  34. @pytest.mark.level0
  35. @pytest.mark.platform_x86_gpu_training
  36. @pytest.mark.env_onecard
  37. def test_apply_adagrad():
  38. # numpy op
  39. grident_np = np.random.rand(3, 3).astype(np.float32)
  40. expect_accum_np = accum_np + grident_np * grident_np
  41. expect_var_np = var_np - (0.001 * grident_np * (1 / np.sqrt(expect_accum_np + 1e-6)))
  42. net = Net()
  43. lr = Tensor(0.001, mstype.float32)
  44. grad = Tensor(grident_np)
  45. out = net(lr, grad)
  46. res_var_mindspore = out[0].asnumpy()
  47. res_accum_mindspore = out[1].asnumpy()
  48. eps = np.array([1e-6 for i in range(9)]).reshape(3, 3)
  49. assert np.all(expect_var_np - res_var_mindspore < eps)
  50. assert np.all(expect_accum_np - res_accum_mindspore < eps)