xref: /aosp_15_r20/external/tensorflow/tensorflow/lite/delegates/gpu/common/tasks/quantize_and_dequantize.cc (revision b6fb3261f9314811a0f4371741dbb8839866f948)
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 #include <utility>
20 
21 #include "absl/strings/str_cat.h"
22 #include "absl/types/variant.h"
23 #include "tensorflow/lite/delegates/gpu/common/tensor.h"
24 
25 namespace tflite {
26 namespace gpu {
27 
CreateQuantizeAndDequantize(const OperationDef & definition,const QuantizeAndDequantizeAttributes & attr)28 GPUOperation CreateQuantizeAndDequantize(
29     const OperationDef& definition,
30     const QuantizeAndDequantizeAttributes& attr) {
31   QuantizeAndDequantizeAttributes adjusted_attr = attr;
32   const bool is_fp16 = definition.precision == CalculationsPrecision::F16 ||
33                        definition.precision == CalculationsPrecision::F32_F16;
34   if (is_fp16 && attr.scale < 0.000062f) {
35     // The smallest positive normal number for Half-precision floating-point
36     // format is 2^-14 ~ 0.000062f. Therefore, if the scale is lesser than this
37     // number, we just reset it accordingly.
38     adjusted_attr.scale = 0.000062f;
39   }
40 
41   ElementwiseDescriptor op_desc;
42   if (definition.precision == CalculationsPrecision::F32) {
43     op_desc.args.AddFloat("min", adjusted_attr.min);
44     op_desc.args.AddFloat("max", adjusted_attr.max);
45     op_desc.args.AddFloat("scale", adjusted_attr.scale);
46   } else {
47     op_desc.args.AddHalf("min", half(adjusted_attr.min));
48     op_desc.args.AddHalf("max", half(adjusted_attr.max));
49     op_desc.args.AddHalf("scale", half(adjusted_attr.scale));
50   }
51   op_desc.code = R"(
52 FLT4 clamped_value = min(INIT_FLT4(args.max), max(INIT_FLT4(args.min), in_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 out_value = dequantized_value;)";
56 
57   return CreateGpuOperation(definition, std::move(op_desc));
58 }
59 
60 }  // namespace gpu
61 }  // namespace tflite
62