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

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