Imported Upstream version 1.22.1
[platform/core/ml/nnfw.git] / onert-micro / luci-interpreter / pal / mcu / PALApplyActivationToVector.h
1 /*
2  * Copyright (c) 2023 Samsung Electronics Co., Ltd. All Rights Reserved
3  * Copyright 2017 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_APPLY_ACTIVATION_TO_VECTOR_H
19 #define LUCI_INTERPRETER_PAL_APPLY_ACTIVATION_TO_VECTOR_H
20
21 #include <algorithm>
22 #include <cassert>
23 #include <cmath>
24 #include <cstdlib>
25
26 #include "tensorflow/lite/c/builtin_op_data.h"
27
28 namespace luci_interpreter_pal
29 {
30
31 // Dynamic (non-fused) activation functor. perhaps it is worth having
32 // template instantiation?
33 // TODO(aselle): Make this more efficient by pulling the switch to conv_eval
34 // using template inlining.
35 class ActivationFunctor
36 {
37 public:
38   explicit ActivationFunctor(TfLiteFusedActivation act) : act_(act) {}
39
40   float operator()(float a) const
41   {
42     switch (act_)
43     {
44       case kTfLiteActNone:
45         return a;
46       case kTfLiteActRelu:
47         return a < 0.f ? 0.f : a;
48       case kTfLiteActRelu6:
49         return std::max(0.f, std::min(a, 6.f));
50       case kTfLiteActTanh:
51         return std::tanh(a);
52       case kTfLiteActSigmoid:
53         return 1.0f / (1.0f + std::exp(-a));
54       default:
55         assert(false && "Activation functor is not supported");
56     }
57   }
58
59 private:
60   TfLiteFusedActivation act_;
61 };
62
63 inline void ApplyActivationToVector(const float *vector, int v_size,
64                                     TfLiteFusedActivation activation, float *result)
65 {
66   auto activation_func = ActivationFunctor(activation);
67   for (int v = 0; v < v_size; v++)
68   {
69     *result++ = (activation_func)(*vector++);
70   }
71 }
72
73 } // namespace luci_interpreter_pal
74
75 #endif // LUCI_INTERPRETER_PAL_APPLY_ACTIVATION_TO_VECTOR_H