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
16 #include "tensorflow/lite/micro/micro_utils.h"
17
18 #include <cmath>
19 #include <cstdint>
20 #include <limits>
21
22 #include "tensorflow/lite/c/common.h"
23 #include "tensorflow/lite/kernels/op_macros.h"
24
25 namespace tflite {
26
ElementCount(const TfLiteIntArray & dims)27 int ElementCount(const TfLiteIntArray& dims) {
28 int result = 1;
29 for (int i = 0; i < dims.size; ++i) {
30 result *= dims.data[i];
31 }
32 return result;
33 }
34
SignedSymmetricPerChannelQuantize(const float * values,TfLiteIntArray * dims,int quantized_dimension,int8_t * quantized_values,float * scaling_factors)35 void SignedSymmetricPerChannelQuantize(const float* values,
36 TfLiteIntArray* dims,
37 int quantized_dimension,
38 int8_t* quantized_values,
39 float* scaling_factors) {
40 int input_size = ElementCount(*dims);
41 int channel_count = dims->data[quantized_dimension];
42 int per_channel_size = input_size / channel_count;
43
44 int stride;
45 int channel_stride;
46 if (quantized_dimension == 0) {
47 stride = 1;
48 channel_stride = per_channel_size;
49 } else if (quantized_dimension == 3) {
50 stride = channel_count;
51 channel_stride = 1;
52 } else {
53 TF_LITE_FATAL("quantized dimension must be 0 or 3");
54 }
55
56 // Calculate scales for each channel.
57 for (int channel = 0; channel < channel_count; channel++) {
58 float min = 0;
59 float max = 0;
60
61 for (int i = 0; i < per_channel_size; i++) {
62 int idx = channel * channel_stride + i * stride;
63 min = fminf(min, values[idx]);
64 max = fmaxf(max, values[idx]);
65 }
66 scaling_factors[channel] =
67 fmaxf(fabs(min), fabs(max)) / std::numeric_limits<int8_t>::max();
68 for (int i = 0; i < per_channel_size; i++) {
69 int idx = channel * channel_stride + i * stride;
70 const int32_t quantized_value =
71 static_cast<int32_t>(roundf(values[idx] / scaling_factors[channel]));
72 // Clamp: just in case some odd numeric offset.
73 quantized_values[idx] =
74 fminf(std::numeric_limits<int8_t>::max(),
75 fmaxf(std::numeric_limits<int8_t>::min() + 1, quantized_value));
76 }
77 }
78 }
79
80 } // namespace tflite
81