ONE - On-device Neural Engine
Loading...
Searching...
No Matches
PALLogSoftmax.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2023 Samsung Electronics Co., Ltd. All Rights Reserved
3 * Copyright 2021 The TensorFlow Authors. All Rights Reserved.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18#ifndef LUCI_INTERPRETER_PAL_LOG_SOFTMAX_COMMON_H
19#define LUCI_INTERPRETER_PAL_LOG_SOFTMAX_COMMON_H
20
21#include "PALUtils.h"
22
23#include <cmath>
24
26{
27
28inline void LogSoftmax(const luci_interpreter::RuntimeShape &input_shape, const float *input_data,
29 const luci_interpreter::RuntimeShape &output_shape, float *output_data)
30{
31 const int trailing_dim = input_shape.dimensionsCount() - 1;
32 const int outer_size =
33 flatSizeSkipDim(input_shape.dimsData(), trailing_dim, input_shape.dimensionsCount());
34 const int depth = MatchingDim(input_shape, trailing_dim, output_shape, trailing_dim);
35
36 for (int i = 0; i < outer_size; ++i)
37 {
38 // Find max element value which we'll use to ensure numerical stability
39 // taking advantage of the following equality:
40 // log(exp(x[i])/sum(exp(x[i]))) == log(exp(x[i]+C)/sum(exp(x[i]+C)))
41 float max = std::numeric_limits<float>::lowest();
42 for (int c = 0; c < depth; ++c)
43 {
44 max = std::max(max, input_data[i * depth + c]);
45 }
46
47 // Compute sum.
48 float sum = 0.f;
49 for (int c = 0; c < depth; ++c)
50 {
51 sum += std::exp(input_data[i * depth + c] - max);
52 }
53
54 // Compute result.
55 const float log_sum = std::log(sum);
56 for (int c = 0; c < depth; ++c)
57 {
58 output_data[i * depth + c] = input_data[i * depth + c] - max - log_sum;
59 }
60 }
61}
62
63} // namespace luci_interpreter_pal
64
65#endif // LUCI_INTERPRETER_PAL_LOG_SOFTMAX_COMMON_H
int32_t dimensionsCount() const
Definition Tensor.h:106
const luci_interpreter::RuntimeShape output_shape
int flatSizeSkipDim(const int32_t *dims_data, int skip_dim, int num_dims)
Definition PALUtils.h:183
int MatchingDim(const luci_interpreter::RuntimeShape &shape1, int index1, const luci_interpreter::RuntimeShape &shape2, int index2)
Definition PALUtils.h:173