Imported Upstream version 1.7.0
[platform/core/ml/nnfw.git] / compiler / nnkit-tflite / backend / Backend.cpp
1 /*
2  * Copyright (c) 2018 Samsung Electronics Co., Ltd. All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *    http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "nnkit/support/tflite/AbstractBackend.h"
18
19 #include <tensorflow/lite/kernels/register.h>
20 #include <tensorflow/lite/model.h>
21
22 #include <stdexcept>
23
24 namespace
25 {
26
27 class GenericBackend final : public nnkit::support::tflite::AbstractBackend
28 {
29 public:
30   GenericBackend(const std::string &path)
31   {
32     ::tflite::StderrReporter error_reporter;
33
34     _model = ::tflite::FlatBufferModel::BuildFromFile(path.c_str(), &error_reporter);
35
36     ::tflite::ops::builtin::BuiltinOpResolver resolver;
37     ::tflite::InterpreterBuilder builder(*_model, resolver);
38
39     if (kTfLiteOk != builder(&_interp))
40     {
41       throw std::runtime_error{"Failed to build a tflite interpreter"};
42     }
43
44     _interp->SetNumThreads(1);
45   }
46
47 public:
48   ::tflite::Interpreter &interpreter(void) override { return *_interp; }
49
50 private:
51   std::unique_ptr<::tflite::FlatBufferModel> _model;
52   std::unique_ptr<::tflite::Interpreter> _interp;
53 };
54 }
55
56 #include <nnkit/CmdlineArguments.h>
57 #include <stdex/Memory.h>
58
59 extern "C" std::unique_ptr<nnkit::Backend> make_backend(const nnkit::CmdlineArguments &args)
60 {
61   return stdex::make_unique<GenericBackend>(args.at(0));
62 }