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/transformations/add_quant_adjustments.h"
17 
18 #include <memory>
19 #include <optional>
20 #include <string>
21 #include <vector>
22 
23 #include "absl/memory/memory.h"
24 #include "absl/strings/str_cat.h"
25 #include "absl/types/any.h"
26 #include "tensorflow/lite/delegates/gpu/common/model.h"
27 #include "tensorflow/lite/delegates/gpu/common/model_transformer.h"
28 #include "tensorflow/lite/delegates/gpu/common/operations.h"
29 #include "tensorflow/lite/delegates/gpu/common/status.h"
30 #include "tensorflow/lite/delegates/gpu/common/tensor.h"
31 
32 namespace tflite {
33 namespace gpu {
34 
35 class AddQuantAdjustments : public NodeTransformation {
36  public:
ApplyToNode(Node * node,GraphFloat32 * graph)37   TransformResult ApplyToNode(Node* node, GraphFloat32* graph) final {
38     if (node->operation.type ==
39         ToString(OperationType::QUANTIZE_AND_DEQUANTIZE)) {
40       return {TransformStatus::SKIPPED, ""};
41     }
42 
43     bool transform_applied = false;
44     auto node_outputs = graph->FindOutputs(node->id);
45     for (auto output_value : node_outputs) {
46       // Skip if quantization doesn't apply.
47       if (!output_value->quant_params) continue;
48       auto consumers = graph->FindConsumers(output_value->id);
49       // No need to do anything if this isn't consumed by another node.
50       if (consumers.empty()) {
51         continue;
52       }
53 
54       // Add a new QuantizeAndDequantize node.
55       Node* quant_and_dequant_node;
56       absl::Status status =
57           graph->InsertNodeAfter(node->id, &quant_and_dequant_node);
58       if (!status.ok()) {
59         return {TransformStatus::INVALID, "Could not insert new node."};
60       }
61       quant_and_dequant_node->operation.type =
62           ToString(OperationType::QUANTIZE_AND_DEQUANTIZE);
63       QuantizeAndDequantizeAttributes attr;
64       attr.min = output_value->quant_params.value().min;
65       attr.max = output_value->quant_params.value().max;
66       attr.scale = output_value->quant_params.value().scale;
67       quant_and_dequant_node->operation.attributes = attr;
68 
69       // Add one output Value for the new node.
70       // The tensor information should rename the same.
71       Value* adjusted_value = graph->NewValue();
72       adjusted_value->tensor = output_value->tensor;
73       status =
74           graph->SetProducer(quant_and_dequant_node->id, adjusted_value->id);
75       if (!status.ok()) {
76         return {TransformStatus::INVALID,
77                 "Could not create QuantizeAndDequantize node."};
78       }
79 
80       // Replace output_value with adjusted_value on all consumers.
81       for (auto& consumer : consumers) {
82         status = graph->ReplaceInput(consumer->id, output_value->id,
83                                      adjusted_value->id);
84         if (!status.ok()) {
85           return {TransformStatus::INVALID,
86                   absl::StrCat(
87                       "Failed to associate quant-adjusted value for consumer: ",
88                       status.message())};
89         }
90       }
91 
92       // Add QuantizeAndDequantize node as a consumer of output_value.
93       status = graph->AddConsumer(quant_and_dequant_node->id, output_value->id);
94       if (!status.ok()) {
95         return {TransformStatus::INVALID,
96                 absl::StrCat(
97                     "Could not associate output to QuantizeAndDequantize: ",
98                     status.message())};
99       }
100 
101       // Remove quant params on output_value, to make the transformation
102       // idempotent.
103       output_value->quant_params.reset();
104       transform_applied = true;
105     }
106 
107     if (transform_applied) {
108       return {TransformStatus::APPLIED, ""};
109     }
110     return {TransformStatus::SKIPPED, ""};
111   }
112 };
113 
NewAddQuantAdjustments()114 std::unique_ptr<NodeTransformation> NewAddQuantAdjustments() {
115   return std::make_unique<AddQuantAdjustments>();
116 }
117 
118 }  // namespace gpu
119 }  // namespace tflite
120