1 /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 #ifndef TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_QUANTIZE_H_
16 #define TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_QUANTIZE_H_
17
18 #include <algorithm>
19 #include <limits>
20
21 #include "tensorflow/lite/kernels/internal/common.h"
22 #include "tensorflow/lite/kernels/internal/compatibility.h"
23 #include "tensorflow/lite/kernels/internal/cppmath.h"
24 #include "tensorflow/lite/kernels/internal/types.h"
25
26 namespace tflite {
27
28 namespace reference_ops {
29
30 template <typename InputT, typename OutputT>
AffineQuantize(const tflite::QuantizationParams & op_params,const RuntimeShape & input_shape,const InputT * input_data,const RuntimeShape & output_shape,OutputT * output_data)31 inline void AffineQuantize(const tflite::QuantizationParams& op_params,
32 const RuntimeShape& input_shape,
33 const InputT* input_data,
34 const RuntimeShape& output_shape,
35 OutputT* output_data) {
36 const int32_t zero_point = op_params.zero_point;
37 const double scale = op_params.scale;
38 const int flat_size = MatchingFlatSize(input_shape, output_shape);
39 static constexpr int32_t min_val = std::numeric_limits<OutputT>::min();
40 static constexpr int32_t max_val = std::numeric_limits<OutputT>::max();
41
42 for (int i = 0; i < flat_size; i++) {
43 const InputT val = input_data[i];
44 int32_t unclamped =
45 static_cast<int32_t>(TfLiteRound(val / static_cast<float>(scale))) +
46 zero_point;
47 int32_t clamped = std::min(std::max(unclamped, min_val), max_val);
48 output_data[i] = clamped;
49 }
50 }
51
52 } // namespace reference_ops
53
54 } // namespace tflite
55 #endif // TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_QUANTIZE_H_
56