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_momentum.py 4.6 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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_momentum """
  16. import functools
  17. import numpy as np
  18. import mindspore.nn as nn
  19. import mindspore.context as context
  20. from mindspore import Parameter, ParameterTuple, Tensor
  21. from mindspore.ops import composite as C
  22. from mindspore.ops import functional as F
  23. from mindspore.ops import operations as P
  24. from ..ut_filter import non_graph_engine
  25. from ....mindspore_test_framework.mindspore_test import mindspore_test
  26. from ....mindspore_test_framework.pipeline.forward.compile_forward \
  27. import pipeline_for_compile_forward_ge_graph_for_case_by_case_config
  28. # pylint: disable=W0613
  29. # W0613: unused-argument
  30. run_opt = C.MultitypeFuncGraph("run_opt")
  31. grad_by_list = C.GradOperation(get_by_list=True)
  32. @run_opt.register("Function", "Tensor", "Tensor", "Tensor",
  33. "Tensor", "Tensor",
  34. "Tensor")
  35. def tensor_run_opt(opt, iters, learning_rate, momentum,
  36. gradient, variable, moment):
  37. """ tensor_run_opt """
  38. success = True
  39. new_weight = opt(variable, moment, learning_rate, gradient, momentum)[0]
  40. success = F.depend(success, F.assign(variable, new_weight))
  41. return success
  42. class OptimizerByMomentum(nn.Cell):
  43. """ OptimizerByMomentum definition """
  44. def __init__(self, weights):
  45. super(OptimizerByMomentum, self).__init__()
  46. self.learning_rate = Parameter(0.1, name="learning_rate")
  47. self.momentum = Parameter(0.05, name="momentum")
  48. self.iter = Parameter(0, name="iter")
  49. self.weights = weights
  50. self.moments = weights.clone(prefix="moments", init='zeros')
  51. self.hyper_map = C.HyperMap()
  52. self.opt = P.ApplyMomentum()
  53. def construct(self, grads):
  54. success = True
  55. weights = self.weights
  56. moments = self.moments
  57. success = self.hyper_map(F.partial(run_opt, self.opt, self.iter,
  58. self.learning_rate, self.momentum),
  59. grads, weights, moments)
  60. return success
  61. class TrainStepWrap(nn.Cell):
  62. """ TrainStepWrap definition """
  63. def __init__(self, network):
  64. super(TrainStepWrap, self).__init__()
  65. self.network = network
  66. self.weights = ParameterTuple(network.get_parameters())
  67. self.optimizer = OptimizerByMomentum(self.weights)
  68. self.hyper_map = C.HyperMap()
  69. def construct(self, x, label):
  70. weights = self.weights
  71. grads = grad_by_list(self.network, weights)(x, label)
  72. return self.optimizer(grads)
  73. class NetWithLossClass(nn.Cell):
  74. """ NetWithLossClass definition """
  75. def __init__(self, network):
  76. super(NetWithLossClass, self).__init__(auto_prefix=False)
  77. self.loss = nn.SoftmaxCrossEntropyWithLogits()
  78. self.network = network
  79. def construct(self, x, label):
  80. predict = self.network(x)
  81. return self.loss(predict, label)
  82. class Net(nn.Cell):
  83. """ Net definition """
  84. def __init__(self):
  85. super(Net, self).__init__()
  86. self.weight = Parameter(Tensor(np.ones([64, 10]).astype(np.float32)), name="weight")
  87. self.bias = Parameter(Tensor(np.ones([10]).astype(np.float32)), name="bias")
  88. self.matmul = P.MatMul()
  89. self.biasAdd = P.BiasAdd()
  90. def construct(self, x):
  91. return self.biasAdd(self.matmul(x, self.weight), self.bias)
  92. test_case_ops = [
  93. ('Momentum', {
  94. 'block': TrainStepWrap(NetWithLossClass(Net())),
  95. 'desc_inputs': [Tensor(np.ones([1, 64]).astype(np.float32)),
  96. Tensor(np.zeros([1, 10]).astype(np.float32))]}),
  97. ]
  98. test_case_lists = [test_case_ops]
  99. test_exec_case = functools.reduce(lambda x, y: x + y, test_case_lists)
  100. # use -k to select certain testcast
  101. # pytest tests/python/ops/test_ops.py::test_backward -k LayerNorm
  102. @non_graph_engine
  103. @mindspore_test(pipeline_for_compile_forward_ge_graph_for_case_by_case_config)
  104. def test_exec():
  105. context.set_context(mode=context.GRAPH_MODE)
  106. return test_exec_case