1 /* Copyright 2020 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/gpu/common/tasks/quantize_and_dequantize.h"
17
18 #include <string>
19
20 #include "absl/strings/str_cat.h"
21 #include "absl/types/variant.h"
22 #include "tensorflow/lite/delegates/gpu/common/tensor.h"
23
24 namespace tflite {
25 namespace gpu {
26
CreateQuantizeAndDequantize(const OperationDef & definition,const QuantizeAndDequantizeAttributes & attr)27 GPUOperation CreateQuantizeAndDequantize(
28 const OperationDef& definition,
29 const QuantizeAndDequantizeAttributes& attr) {
30 QuantizeAndDequantizeAttributes adjusted_attr = attr;
31 const bool is_fp16 = definition.precision == CalculationsPrecision::F16 ||
32 definition.precision == CalculationsPrecision::F32_F16;
33 if (is_fp16 && attr.scale < 0.000062f) {
34 // The smallest positive normal number for Half-precision floating-point
35 // format is 2^-14 ~ 0.000062f. Therefore, if the scale is lesser than this
36 // number, we just reset it accordingly.
37 adjusted_attr.scale = 0.000062f;
38 }
39
40 GPUOperation op(definition);
41 op.elementwise_ = true;
42 if (definition.precision == CalculationsPrecision::F32) {
43 op.args_.AddFloat("min", adjusted_attr.min);
44 op.args_.AddFloat("max", adjusted_attr.max);
45 op.args_.AddFloat("scale", adjusted_attr.scale);
46 } else {
47 op.args_.AddHalf("min", half(adjusted_attr.min));
48 op.args_.AddHalf("max", half(adjusted_attr.max));
49 op.args_.AddHalf("scale", half(adjusted_attr.scale));
50 }
51 op.code_ = R"(
52 FLT4 clamped_value = min(INIT_FLT4(args.max), max(INIT_FLT4(args.min), in_out_value));
53 FLT4 quantized_value = round((clamped_value - INIT_FLT4(args.min)) / INIT_FLT4(args.scale));
54 FLT4 dequantized_value = quantized_value * INIT_FLT4(args.scale) + INIT_FLT4(args.min);
55 in_out_value = dequantized_value;)";
56
57 return op;
58 }
59
60 } // namespace gpu
61 } // namespace tflite
62