2 * Copyright (c) 2020 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 #ifndef __NNFW_CKER_LOGSOFTMAX_H__
18 #define __NNFW_CKER_LOGSOFTMAX_H__
20 #include "cker/Shape.h"
21 #include "cker/Utils.h"
22 #include "cker/Types.h"
23 #include "cker/eigen/Utils.h"
26 #include <fixedpoint/fixedpoint.h>
34 inline void LogSoftmax(const SoftmaxParams ¶ms, const Shape &input_shape,
35 const float *input_data, const Shape &output_shape, float *output_data)
37 const int rank = input_shape.DimensionsCount();
38 const int axis = (params.axis < 0) ? params.axis + rank : params.axis;
39 const double beta = params.beta;
40 const int depth = MatchingDim(input_shape, axis, output_shape, axis);
43 for (int i = 0; i < axis; ++i)
45 outer_size *= input_shape.Dims(i);
49 for (int i = axis + 1; i < rank; ++i)
51 inner_size *= input_shape.Dims(i);
54 for (int i = 0; i < outer_size; ++i)
56 for (int j = 0; j < inner_size; ++j)
58 float max = std::numeric_limits<float>::lowest();
59 for (int c = 0; c < depth; ++c)
61 max = std::max(max, input_data[(i * depth + c) * inner_size]);
65 for (int c = 0; c < depth; ++c)
67 sum += std::exp((input_data[(i * depth + c) * inner_size + j] - max) * beta);
70 const float log_sum = std::log(sum);
71 for (int c = 0; c < depth; ++c)
73 output_data[(i * depth + c) * inner_size + j] =
74 (input_data[(i * depth + c) * inner_size + j] - max) * beta - log_sum;
83 #endif // __NNFW_CKER_LOGSOFTMAX_H__