2 * Copyright (c) 2023 Samsung Electronics Co., Ltd. All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <exec/train/optimizer/SGD.h>
19 #include "OptimizerHelpers.h"
30 double SGD::getLearningRate(uint32_t) const
32 // TODO Use iteration, momentum, and nesterov
33 return _learning_rate;
36 void SGD::applyGradient(const UpdateFactors &factors) const
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());
43 const auto shape = trainable_tensor.getShape();
44 const auto &grad_shape = grad_tensor.get_info().shape();
46 // TODO Support for different shapes
47 if (shape != grad_shape)
49 throw std::runtime_error("SGD: Invalid gradient tensor");
52 switch (grad_tensor.data_type())
54 case ir::DataType::FLOAT32:
55 elementwise<float>(shape, grad_tensor, trainable_tensor,
56 [&](float src, float dst) -> float { return dst - src * lr; });
59 throw std::runtime_error("SGD: Not supported data type");
63 } // namespace optimizer