Imported Upstream version 1.25.0
[platform/core/ml/nnfw.git] / runtime / onert / core / src / exec / train / optimizer / SGD.cc
1 /*
2  * Copyright (c) 2023 Samsung Electronics Co., Ltd. All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <exec/train/optimizer/SGD.h>
18
19 #include "OptimizerHelpers.h"
20
21 namespace onert
22 {
23 namespace exec
24 {
25 namespace train
26 {
27 namespace optimizer
28 {
29
30 double SGD::getLearningRate(uint32_t) const
31 {
32   // TODO Use iteration, momentum, and nesterov
33   return _learning_rate;
34 }
35
36 void SGD::applyGradient(const UpdateFactors &factors) const
37 {
38   const auto lr = getLearningRate(std::get<size_t>(factors));
39   const auto &grad_tensor = std::get<const backend::IPortableTensor &>(factors);
40   auto &trainable_tensor = std::get<backend::train::ITrainableTensor &>(factors);
41   assert(trainable_tensor.data_type() == grad_tensor.data_type());
42
43   const auto shape = trainable_tensor.getShape();
44   const auto &grad_shape = grad_tensor.get_info().shape();
45
46   // TODO Support for different shapes
47   if (shape != grad_shape)
48   {
49     throw std::runtime_error("SGD: Invalid gradient tensor");
50   }
51
52   switch (grad_tensor.data_type())
53   {
54     case ir::DataType::FLOAT32:
55       elementwise<float>(shape, grad_tensor, trainable_tensor,
56                          [&](float src, float dst) -> float { return dst - src * lr; });
57       break;
58     default:
59       throw std::runtime_error("SGD: Not supported data type");
60   }
61 }
62
63 } // namespace optimizer
64 } // namespace train
65 } // namespace exec
66 } // namespace onert