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/gl/kernels/quantize_and_dequantize.h"
17
18 #include <any>
19 #include <memory>
20 #include <string>
21
22 #include "absl/memory/memory.h"
23 #include "tensorflow/lite/delegates/gpu/common/data_type.h"
24 #include "tensorflow/lite/delegates/gpu/common/shape.h"
25 #include "tensorflow/lite/delegates/gpu/common/status.h"
26 #include "tensorflow/lite/delegates/gpu/common/types.h"
27
28 namespace tflite {
29 namespace gpu {
30 namespace gl {
31 namespace {
32
33 class QuantizeAndDequantize : public NodeShader {
34 public:
GenerateCode(const GenerationContext & ctx,GeneratedCode * generated_code) const35 absl::Status GenerateCode(const GenerationContext& ctx,
36 GeneratedCode* generated_code) const final {
37 std::string code = R"(
38 value_0 = clamp(value_0, vec4($quant_min$), vec4($quant_max$));
39 value_0 = (value_0 - vec4($quant_min$)) / vec4($quant_scale$);
40 value_0 = floor(value_0 + vec4(0.5));
41 value_0 = value_0 * vec4($quant_scale$) + vec4($quant_min$);
42 )";
43
44 const auto& attr =
45 std::any_cast<const QuantizeAndDequantizeAttributes&>(ctx.op_attr);
46 *generated_code = {
47 /*parameters=*/{{"quant_min", attr.min},
48 {"quant_max", attr.max},
49 {"quant_scale", attr.scale}},
50 /*objects=*/{},
51 /*shared_variables=*/{},
52 /*workload=*/uint3(),
53 /*workgroup=*/uint3(),
54 /*source_code=*/code,
55 /*input=*/IOStructure::AUTO,
56 /*output=*/IOStructure::AUTO,
57 };
58 return absl::OkStatus();
59 }
60 };
61
62 } // namespace
63
NewQuantizeAndDequantizeNodeShader()64 std::unique_ptr<NodeShader> NewQuantizeAndDequantizeNodeShader() {
65 return std::make_unique<QuantizeAndDequantize>();
66 }
67
68 } // namespace gl
69 } // namespace gpu
70 } // namespace tflite
71