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