xref: /aosp_15_r20/external/tensorflow/tensorflow/lite/tools/optimize/quantization_wrapper_utils.cc (revision b6fb3261f9314811a0f4371741dbb8839866f948)
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 #include "tensorflow/lite/tools/optimize/quantization_wrapper_utils.h"
16 
17 #include <fstream>
18 #include <memory>
19 #include <string>
20 #include <utility>
21 
22 #include "tensorflow/lite/schema/schema_generated.h"
23 #include "tensorflow/lite/tools/optimize/operator_property.h"
24 
25 namespace tflite {
26 namespace optimize {
27 namespace {
28 
29 #ifdef TFLITE_CUSTOM_LSTM
30 constexpr bool kUseCustomLSTM = true;
31 #else
32 constexpr bool kUseCustomLSTM = false;
33 #endif
34 
MakeTensor(const string & name,std::unique_ptr<TensorT> * tensor)35 void MakeTensor(const string& name, std::unique_ptr<TensorT>* tensor) {
36   TensorT* tensor_raw = new TensorT;
37   tensor_raw->name = name;
38   tensor_raw->shape = {0};
39   tensor_raw->type = TensorType_FLOAT32;
40 
41   tensor->reset(tensor_raw);
42 }
43 
CreateTensorName(int op_index,int tensor_index)44 string CreateTensorName(int op_index, int tensor_index) {
45   return "intermediate_" + std::to_string(op_index) + "_" +
46          std::to_string(tensor_index);
47 }
48 
IntermediateTensorExists(ModelT * model)49 bool IntermediateTensorExists(ModelT* model) {
50   for (int subgraph_idx = 0; subgraph_idx < model->subgraphs.size();
51        ++subgraph_idx) {
52     SubGraphT* subgraph = model->subgraphs.at(subgraph_idx).get();
53     for (size_t op_idx = 0; op_idx < subgraph->operators.size(); op_idx++) {
54       OperatorT* op = subgraph->operators[op_idx].get();
55       if (!op->intermediates.empty()) {
56         return true;
57       }
58     }
59   }
60   return false;
61 }
62 }  // namespace
63 
LoadModel(const string & path,ModelT * model)64 TfLiteStatus LoadModel(const string& path, ModelT* model) {
65   auto input_model = FlatBufferModel::BuildFromFile(path.c_str());
66   if (!input_model) {
67     return kTfLiteError;
68   }
69   auto readonly_model = input_model->GetModel();
70   if (!readonly_model) {
71     return kTfLiteError;
72   }
73   readonly_model->UnPackTo(model);
74   return kTfLiteOk;
75 }
76 
AddIntermediateTensorsToFusedOp(flatbuffers::FlatBufferBuilder * builder,ModelT * model)77 TfLiteStatus AddIntermediateTensorsToFusedOp(
78     flatbuffers::FlatBufferBuilder* builder, ModelT* model) {
79   // Return early when the model has no operator.
80   if (model->subgraphs.size() == 1 && model->subgraphs[0]->operators.empty()) {
81     return kTfLiteOk;
82   }
83   // Return early if the model already has intermediate tensors.
84   if (IntermediateTensorExists(model)) {
85     return kTfLiteOk;
86   }
87   // Process the model.
88   for (int subgraph_idx = 0; subgraph_idx < model->subgraphs.size();
89        ++subgraph_idx) {
90     SubGraphT* subgraph = model->subgraphs.at(subgraph_idx).get();
91     for (size_t op_idx = 0; op_idx < subgraph->operators.size(); op_idx++) {
92       // Find ops that need additional tensor.
93       OperatorT* op = subgraph->operators[op_idx].get();
94       operator_property::OperatorProperty property =
95           operator_property::GetOperatorProperty(model, subgraph_idx, op_idx);
96       if (property.intermediates.empty()) {
97         continue;
98       }
99       // Add tensors.
100       const int next_tensor_index = subgraph->tensors.size();
101       int num_intermediates = property.intermediates.size();
102       if (kUseCustomLSTM) {
103         num_intermediates = 12;
104       }
105       for (int i = 0; i < num_intermediates; ++i) {
106         std::unique_ptr<TensorT> intermediate_tensor;
107         auto name = CreateTensorName(op_idx, i);
108         MakeTensor(name, &intermediate_tensor);
109         subgraph->tensors.push_back(std::move(intermediate_tensor));
110         op->intermediates.push_back(next_tensor_index + i);
111       }
112     }
113   }
114 
115   // Export the model.
116   flatbuffers::Offset<Model> output_model_location =
117       Model::Pack(*builder, model);
118   FinishModelBuffer(*builder, output_model_location);
119 
120   return kTfLiteOk;
121 }
122 
WriteFile(const std::string & out_file,const uint8_t * bytes,size_t num_bytes)123 bool WriteFile(const std::string& out_file, const uint8_t* bytes,
124                size_t num_bytes) {
125   std::fstream stream(out_file, std::ios::binary | std::ios::out);
126   for (size_t i = 0; i < num_bytes; i++) {
127     stream << bytes[i];
128   }
129   return (!stream.bad() && !stream.fail());
130 }
131 
132 }  // namespace optimize
133 }  // namespace tflite
134