1 /* Copyright 2021 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
16 #include "tensorflow/lite/delegates/xnnpack/test_util.h"
17
18 #include <algorithm>
19 #include <limits>
20
21 #include "tensorflow/lite/kernels/internal/cppmath.h"
22
23 namespace tflite {
24 namespace xnnpack {
25
QuantizeInt8(float value,int32_t zero_point,float scale)26 int8_t QuantizeInt8(float value, int32_t zero_point, float scale) {
27 static constexpr int32_t min_val = std::numeric_limits<int8_t>::min();
28 static constexpr int32_t max_val = std::numeric_limits<int8_t>::max();
29
30 int32_t unclamped =
31 static_cast<int32_t>(TfLiteRound(value / scale)) + zero_point;
32 int32_t clamped = std::min(std::max(unclamped, min_val), max_val);
33 return static_cast<int8_t>(clamped);
34 }
35
GetInt8QuantizationScale(const std::vector<float> & data)36 float GetInt8QuantizationScale(const std::vector<float>& data) {
37 static constexpr int8_t qmin_val = std::numeric_limits<int8_t>::min();
38 static constexpr int8_t qmax_val = std::numeric_limits<int8_t>::max();
39 static constexpr float qmin_float = qmin_val;
40 static constexpr float qmax_float = qmax_val;
41
42 return (*std::max_element(data.begin(), data.end()) -
43 *std::min_element(data.begin(), data.end())) /
44 (qmax_float - qmin_float);
45 }
46
47 } // namespace xnnpack
48 } // namespace tflite
49