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 #include "TanhLayer.h"
19 #include "OperationUtils.h"
21 #include <cker/operation/Tanh.h>
32 TanhLayer::TanhLayer() : _input(nullptr), _output(nullptr)
37 void TanhLayer::PopulateLookupTable()
39 const auto input_scale = static_cast<double>(_input->data_scale());
40 const auto input_zero_point = static_cast<int32_t>(_input->data_offset());
41 const auto output_scale = static_cast<double>(_output->data_scale());
42 const auto output_zero_point = static_cast<int32_t>(_output->data_offset());
43 const float inverse_scale = 1 / output_scale;
44 int32_t maxval = std::numeric_limits<uint8_t>::max();
45 int32_t minval = std::numeric_limits<uint8_t>::min();
46 for (int32_t val = minval; val <= maxval; ++val)
48 const float dequantized = input_scale * (val - input_zero_point);
49 const float transformed = std::tanh(dequantized);
50 const float rescaled = std::round(transformed * inverse_scale);
51 const int32_t quantized = static_cast<int32_t>(rescaled + output_zero_point);
52 _table[val] = static_cast<uint8_t>(std::max(std::min(maxval, quantized), minval));
56 void TanhLayer::tanhFloat32()
58 nnfw::cker::Tanh(getTensorShape(_input), reinterpret_cast<const float *>(_input->buffer()),
59 getTensorShape(_output), reinterpret_cast<float *>(_output->buffer()));
62 void TanhLayer::tanhQuant8()
64 const int size = MatchingFlatSize(getTensorShape(_input), getTensorShape(_output));
65 const uint8_t *input_data = reinterpret_cast<const uint8_t *>(_input->buffer());
66 uint8_t *output_data = reinterpret_cast<uint8_t *>(_output->buffer());
68 for (int i = 0; i < size; ++i)
70 output_data[i] = _table[input_data[i]];
74 void TanhLayer::configure(const IPortableTensor *input, IPortableTensor *output)
78 if (_input->data_type() == OperandType::QUANT_UINT8_ASYMM)
80 PopulateLookupTable();
86 if (_input->data_type() == OperandType::FLOAT32)
90 else if (_input->data_type() == OperandType::QUANT_UINT8_ASYMM)
96 throw std::runtime_error{"Tanh: unsupported data type"};
102 } // namespace backend