Imported Upstream version 1.25.0
[platform/core/ml/nnfw.git] / compute / cker / include / cker / train / operation / FullyConnected.h
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 #ifndef __NNFW_CKER_TRAIN_OPERATION_FULLY_CONNECTED_H__
18 #define __NNFW_CKER_TRAIN_OPERATION_FULLY_CONNECTED_H__
19
20 #include "cker/eigen/Utils.h"
21 #include "cker/Shape.h"
22
23 namespace nnfw
24 {
25 namespace cker
26 {
27 namespace train
28 {
29
30 template <typename T>
31 inline void FullyConnectedBiasGrad(const Shape &incomming_shape, const T *incomming_data,
32                                    const Shape &grad_shape, T *grad_data)
33 {
34   const auto bias_size = grad_shape.FlatSize();
35   if (bias_size != incomming_shape.Dims(incomming_shape.DimensionsCount() - 1) ||
36       bias_size != grad_shape.Dims(0))
37     throw std::runtime_error("cker::FullyConnectedBiasGrad: Unmatched shape");
38
39   const auto in_mat = MapAsMatrixWithLastDimAsRows(incomming_data, incomming_shape);
40   auto grad_mat = MapAsMatrixWithLastDimAsRows(grad_data, grad_shape);
41
42   grad_mat = in_mat.rowwise().sum();
43 }
44
45 } // namespace train
46 } // namespace cker
47 } // namespace nnfw
48
49 #endif // __NNFW_CKER_FULLY_CONNECTED_H__