1 /* Copyright 2018 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 // Loads the input tflite file into interpreter, serializes it back to a tflite
16 // buffer, and then verifies that the generated output can be loaded back into
17 // an interpreter and the model prepared (i.e., AllocateTensors returns ok).
18 //
19 // Usage:
20 // writer_test <input tflite>
21
22 #include <iostream>
23
24 #include "tensorflow/lite/kernels/register.h"
25 #include "tensorflow/lite/model.h"
26 #include "tensorflow/lite/tools/serialization/writer_lib.h"
27
main(int argc,char * argv[])28 int main(int argc, char* argv[]) {
29 if (argc != 2) {
30 fprintf(stderr, "Usage: %s input_file\n", argv[0]);
31 return 1;
32 }
33 std::unique_ptr<tflite::FlatBufferModel> model =
34 tflite::FlatBufferModel::BuildFromFile(argv[1]);
35 std::unique_ptr<tflite::Interpreter> interpreter;
36 tflite::ops::builtin::BuiltinOpResolverWithoutDefaultDelegates
37 builtin_op_resolver;
38 tflite::InterpreterBuilder(*model, builtin_op_resolver)(&interpreter);
39 tflite::ModelWriter writer(interpreter.get());
40 std::unique_ptr<uint8_t[]> output_buffer;
41 size_t output_buffer_size;
42 writer.GetBuffer(&output_buffer, &output_buffer_size);
43
44 // Verify the generated model.
45 std::unique_ptr<tflite::Interpreter> new_interpreter;
46 model = tflite::FlatBufferModel::BuildFromBuffer(
47 reinterpret_cast<char*>(output_buffer.get()), output_buffer_size);
48 tflite::InterpreterBuilder(*model, builtin_op_resolver)(&new_interpreter);
49 if (new_interpreter->AllocateTensors() != kTfLiteOk) {
50 fprintf(stderr, "AllocateTensors failed on the round-tripped model.\n");
51 return 1;
52 }
53 return 0;
54 }
55