Imported Upstream version 1.18.0
[platform/core/ml/nnfw.git] / compiler / luci-interpreter / src / kernels / Relu6.cpp
1 /*
2  * Copyright (c) 2020 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 #include "kernels/Relu6.h"
18 #include "kernels/Utils.h"
19
20 #include "PALRelu6.h"
21
22 #include <stdexcept>
23
24 namespace luci_interpreter
25 {
26
27 namespace kernels
28 {
29
30 Relu6::Relu6(const Tensor *input, Tensor *output) : Kernel({input}, {output}) {}
31
32 void Relu6::configure()
33 {
34   LUCI_INTERPRETER_CHECK(input()->element_type() == output()->element_type());
35
36   if (input()->element_type() == DataType::U8)
37   {
38     double multiplier = input()->scale() / output()->scale();
39     quantizeMultiplier(multiplier, &_output_multiplier, &_output_shift);
40   }
41   output()->resize(input()->shape());
42 }
43
44 void Relu6::execute() const
45 {
46   switch (input()->element_type())
47   {
48     case DataType::FLOAT32:
49       evalFloat();
50       break;
51     case DataType::U8:
52       evalQuantized();
53       break;
54     default:
55       throw std::runtime_error("Unsupported type.");
56   }
57 }
58
59 void Relu6::evalFloat() const
60 {
61   const auto input_data = getTensorData<float>(input());
62   const auto input_shape = getTensorShape(input());
63   auto output_data = getTensorData<float>(output());
64   auto output_shape = getTensorShape(output());
65
66   luci_interpreter_pal::Relu6(input_shape, input_data, output_shape, output_data);
67 }
68
69 void Relu6::evalQuantized() const
70 {
71   tflite::ReluParams params;
72   params.input_offset = input()->zero_point();
73   params.output_offset = output()->zero_point();
74   params.output_multiplier = _output_multiplier;
75   params.output_shift = _output_shift;
76
77   params.quantized_activation_min =
78     std::max(static_cast<int32_t>(std::numeric_limits<uint8_t>::min()), params.output_offset);
79   params.quantized_activation_max =
80     std::min(static_cast<int32_t>(std::numeric_limits<uint8_t>::max()),
81              params.output_offset + static_cast<int32>(roundf(6.f / output()->scale())));
82
83   luci_interpreter_pal::ReluX(params, getTensorShape(input()), getTensorData<uint8_t>(input()),
84                               getTensorShape(output()), getTensorData<uint8_t>(output()));
85 }
86
87 } // namespace kernels
88 } // namespace luci_interpreter