blob: cc5f1905d83fe8077ddb350ce257e2d9febfb584 [file] [log] [blame]
Michael Martis26abcd82018-08-08 10:57:25 +10001// Copyright 2018 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef ML_GRAPH_EXECUTOR_IMPL_H_
6#define ML_GRAPH_EXECUTOR_IMPL_H_
7
8#include <map>
9#include <memory>
10#include <string>
11
12#include <base/callback_forward.h>
13#include <base/macros.h>
14#include <mojo/public/cpp/bindings/array.h>
15#include <mojo/public/cpp/bindings/binding.h>
16#include <mojo/public/cpp/bindings/map.h>
17#include <tensorflow/contrib/lite/model.h>
18
Hidehiko Abeaa488c32018-08-31 23:49:41 +090019#include "ml/mojom/graph_executor.mojom.h"
Michael Martis26abcd82018-08-08 10:57:25 +100020
21namespace ml {
22
23// Allows execution of TensorFlow lite graphs using input / output specified
24// with Mojo types.
25//
26// Holds as little state as possible (with the remainder living in the parent
27// Model object and shared between all sibling GraphExecutors). Hence, a
28// GraphExecutor becomes invalid when its parent Model object is destroyed.
29//
30// A given GraphExecutorImpl may not be used concurrently from different
31// sequences.
32class GraphExecutorImpl
33 : public chromeos::machine_learning::mojom::GraphExecutor {
34 public:
35 // Creates an instance bound to |request|.
36 //
37 // The |required_inputs| and |required_outputs| arguments specify a mapping
38 // from required input / output tensor names to their indices in the TF lite
39 // graph, and must outlive this object.
40 //
41 // As is standard, |interpreter| must outlive the model with which it was
42 // constructed.
43 GraphExecutorImpl(
44 const std::map<std::string, int>& required_inputs,
45 const std::map<std::string, int>& required_outputs,
46 std::unique_ptr<tflite::Interpreter> interpreter,
47 chromeos::machine_learning::mojom::GraphExecutorRequest request);
48
49 void set_connection_error_handler(base::Closure connection_error_handler);
50
51 private:
52 // chromeos::machine_learning::mojom::GraphExecutor:
53 void Execute(mojo::Map<mojo::String,
54 chromeos::machine_learning::mojom::TensorPtr> inputs,
55 mojo::Array<mojo::String> output_names,
56 const ExecuteCallback& callback);
57
58 const std::map<std::string, int>& required_inputs_;
59 const std::map<std::string, int>& required_outputs_;
60
61 const std::unique_ptr<tflite::Interpreter> interpreter_;
62
63 mojo::Binding<chromeos::machine_learning::mojom::GraphExecutor> binding_;
64
65 DISALLOW_COPY_AND_ASSIGN(GraphExecutorImpl);
66};
67
68} // namespace ml
69
70#endif // ML_GRAPH_EXECUTOR_IMPL_H_