Imported Upstream version 1.8.0
[platform/core/ml/nnfw.git] / compute / cker / include / cker / operation / Quantize.h
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 #ifndef __NNFW_CKER_QUANTIZE_H__
18 #define __NNFW_CKER_QUANTIZE_H__
19
20 #include "cker/Shape.h"
21 #include "cker/Types.h"
22 #include "cker/Utils.h"
23 #include <stdexcept>
24 #include <iostream>
25 namespace nnfw
26 {
27 namespace cker
28 {
29 template <typename InputT, typename OutputT>
30 inline void Quantize(const Shape &input_shape, const InputT *input_data, const Shape &output_shape,
31                      OutputT *output_data, const float output_scale, const int32_t output_offset)
32 {
33   const int flat_size = MatchingFlatSize(input_shape, output_shape);
34   int min_val = std::numeric_limits<OutputT>::min();
35   int max_val = std::numeric_limits<OutputT>::max();
36
37   for (int i = 0; i < flat_size; i++)
38   {
39     int32_t unclamped = static_cast<int32_t>(round(input_data[i] / output_scale)) + output_offset;
40     int32_t clamped = std::min(std::max(unclamped, min_val), max_val);
41     output_data[i] = clamped;
42   }
43 }
44 } // namespace cker
45 } // namespace nnfw
46
47 #endif // __NNFW_CKER_QUANTIZE_H__