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.h"
16
17 #include <string>
18
19 #include "tensorflow/lite/tools/optimize/quantization_wrapper_utils.h"
20 #include "tensorflow/lite/tools/optimize/quantize_model.h"
21
22 namespace tflite {
23 namespace optimize {
24
CreateModelForCalibration(const std::string & input_path,const std::string & output_path)25 bool CreateModelForCalibration(const std::string& input_path,
26 const std::string& output_path) {
27 ModelT model;
28 if (LoadModel(input_path, &model) != kTfLiteOk) {
29 return false;
30 }
31 flatbuffers::FlatBufferBuilder builder;
32 if (AddIntermediateTensorsToFusedOp(&builder, &model) != kTfLiteOk) {
33 return false;
34 }
35 return WriteFile(output_path, builder.GetBufferPointer(), builder.GetSize());
36 }
37
CreateQuantizedModel(const std::string & path)38 bool CreateQuantizedModel(const std::string& path) {
39 ModelT model;
40 if (LoadModel(path, &model) != kTfLiteOk) {
41 return false;
42 }
43 flatbuffers::FlatBufferBuilder builder;
44 tflite::StderrReporter error_reporter;
45 if (tflite::optimize::QuantizeModel(
46 &builder, &model, tflite::TensorType_FLOAT32,
47 tflite::TensorType_FLOAT32,
48 // TODO(b/159351372): Pass required activation type if needed
49 tflite::TensorType_INT8, &error_reporter) != kTfLiteOk) {
50 return false;
51 }
52 return WriteFile(path, builder.GetBufferPointer(), builder.GetSize());
53 }
54
55 } // namespace optimize
56 } // namespace tflite
57