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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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", "Int", "Number", "Number",
  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(gradient, moment, variable,
  38. learning_rate, momentum)
  39. success = F.depend(success, F.assign(variable, new_weight))
  40. return success
  41. class OptimizerByMomentum(nn.Cell):
  42. """ OptimizerByMomentum definition """
  43. def __init__(self, weights):
  44. super(OptimizerByMomentum, self).__init__()
  45. self.learning_rate = Parameter(0.1, name="learning_rate")
  46. self.momentum = Parameter(0.05, name="momentum")
  47. self.iter = Parameter(0, name="iter")
  48. self.weights = weights
  49. self.moments = weights.clone(prefix="moments", init='zeros')
  50. self.hyper_map = C.HyperMap()
  51. self.opt = P.ApplyMomentum()
  52. def construct(self, grads):
  53. success = True
  54. weights = self.weights
  55. moments = self.moments
  56. success = self.hyper_map(F.partial(run_opt, self.opt, self.iter,
  57. self.learning_rate, self.momentum),
  58. grads, weights, moments)
  59. return success
  60. class TrainStepWrap(nn.Cell):
  61. """ TrainStepWrap definition """
  62. def __init__(self, network):
  63. super(TrainStepWrap, self).__init__()
  64. self.network = network
  65. self.weights = ParameterTuple(network.get_parameters())
  66. self.optimizer = OptimizerByMomentum(self.weights)
  67. self.hyper_map = C.HyperMap()
  68. def construct(self, x, label):
  69. weights = self.weights
  70. grads = C.grad_by_list(self.network, weights)(x, label)
  71. return self.optimizer(grads)
  72. class NetWithLossClass(nn.Cell):
  73. """ NetWithLossClass definition """
  74. def __init__(self, network):
  75. super(NetWithLossClass, self).__init__(auto_prefix=False)
  76. self.loss = nn.SoftmaxCrossEntropyWithLogits()
  77. self.network = network
  78. def construct(self, x, label):
  79. predict = self.network(x)
  80. return self.loss(predict, label)
  81. class Net(nn.Cell):
  82. """ Net definition """
  83. def __init__(self):
  84. super(Net, self).__init__()
  85. self.weight = Parameter(Tensor(np.ones([64, 10]).astype(np.float32)), name="weight")
  86. self.bias = Parameter(Tensor(np.ones([10]).astype(np.float32)), name="bias")
  87. self.matmul = P.MatMul()
  88. self.biasAdd = P.BiasAdd()
  89. def construct(self, x):
  90. return self.biasAdd(self.matmul(x, self.weight), self.bias)
  91. test_case_ops = [
  92. ('Momentum', {
  93. 'block': TrainStepWrap(NetWithLossClass(Net())),
  94. 'desc_inputs': [Tensor(np.ones([1, 64]).astype(np.float32)),
  95. Tensor(np.zeros([1, 10]).astype(np.float32))]}),
  96. ]
  97. test_case_lists = [test_case_ops]
  98. test_exec_case = functools.reduce(lambda x, y: x + y, test_case_lists)
  99. # use -k to select certain testcast
  100. # pytest tests/python/ops/test_ops.py::test_backward -k LayerNorm
  101. import mindspore.context as context
  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