summaryrefslogtreecommitdiff
path: root/runtimes/neurun/core/src/compiler/ExecutorFactory.cc
blob: 2ff32a57ec1dbecc3729192b7624b2e89c152dc5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/*
 * Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ExecutorFactory.h"

#include <functional>
#include "exec/ExecutionObservers.h"
#include "exec/LinearExecutor.h"
#include "exec/DataflowExecutor.h"
#include "exec/ParallelExecutor.h"
#include "compiler/BackendResolver.h"
#include "backend/ExecTime.h"
#include "compiler/Linear.h"
#include "graph/dumper/Dumper.h"
#include "OperationValidator.h"
#include "SubTensorAnalyzer.h"
#include "backend/IConstantInitializer.h"
#include "backend/IKernelGenerator.h"
#include "backend/IShapeFixer.h"
#include "cpp14/memory.h"

namespace neurun
{
namespace compiler
{

ExecutorFactory &ExecutorFactory::instance()
{
  static ExecutorFactory singleton;
  return singleton;
}

ExecutorFactory::ExecutorFactory()
{
  _map["Linear"] = createLinearExecutor;
  _map["Dataflow"] = std::bind(createDataflowExecutor, std::placeholders::_1, false);
  _map["Parallel"] = std::bind(createDataflowExecutor, std::placeholders::_1, true);
}

exec::IExecutor *ExecutorFactory::create(const std::string &id, graph::Graph &graph)
{
  return _map.at(id)(graph);
}

exec::IExecutor *ExecutorFactory::createLinearExecutor(graph::Graph &graph)
{
  auto operand_context = std::make_shared<OperandContext>();
  const auto &operands = graph.operands();

  // Compilation result will be filled in operand_context and operation_sequence
  auto function_sequence = std::make_shared<exec::FunctionSequence>();

  // linearize
  auto linear = graph.linearize();

  // Dump ops
  linear->accept(neurun::graph::dumper::Dumper{});

  linear->accept(OperationValidator{operands});

  /*************************************************
   * Backend dependent analysis & optimization phase
   *************************************************/

  // SubTensorInfo should be generated after lower, before shape correction and finalize
  // because SubTensorAnalyzer assume that insert permutation is already finished
  //    lower: decide backend and insert permutation
  //    fix shapes: prepare codegen to optimization
  //    generate tensor objects: generate tensor using subtensor info
  //    generate kernels
  //    allocate tesor memory
  //    constant intialization: fill the constants with values
  // Generated SubTensorInfo is in operand(Object)
  // for easy pass SubTensorInfo to plan builder and tensor builder
  linear->accept(SubTensorAnalyzer{graph.operands()});

  /**********************************************************
   * Backend dependent analysis & optimization phase finished
   **********************************************************/

  /***********************
   * Code generation phase
   ***********************/

  // Fix shapes
  linear->iterate([&](const compiler::Linear::Element &element) {
    auto backend = element.lower_info->backend();
    auto shape_fixer = linear->getBackendContext(backend)->shape_fixer;
    shape_fixer->fix(*element.subgraph);
  });

  linear->planTensors();

  auto tensor_builders = linear->backend_resolver()->tensor_builders();

  // Prepare tensors
  for (auto &tensor_builder : tensor_builders)
  {
    tensor_builder->prepare();
  }

  // Generate initializers
  linear->generateConstantInitializers();

  class ExecutionBuilder final : public IExecutionBuilder
  {
  public:
    ExecutionBuilder(exec::FunctionSequence &functions) : _functions{functions}
    {
      // DO NOTHING
    }

  public:
    void append(std::unique_ptr<::neurun::exec::IFunction> &&f) override
    {
      _functions.append(std::move(f));
    }

  private:
    exec::FunctionSequence &_functions;
  };

  auto execution_builder = nnfw::cpp14::make_unique<ExecutionBuilder>(*function_sequence);

  // Generate kernels
  linear->iterate([&](const compiler::Linear::Element &element) {
    auto backend = element.lower_info->backend();
    auto kernel_gen = linear->getBackendContext(backend)->kernel_gen;
    kernel_gen->generate(*element.subgraph, execution_builder.get());
  });

  // Allocate Tensor Memory
  for (auto &tensor_builder : tensor_builders)
  {
    tensor_builder->allocate();
  }

  // TODO Add optimization passes

  // Initialize constant tensors
  for (const auto backend : backend::BackendManager::instance().getAll())
  {
    linear->getBackendContext(backend)->constant_initializer->run();
  }

  for (auto &tensor_builder : tensor_builders)
  {
    tensor_builder->finalize();
  }

  // Wrap tensors as Object and store them to plan
  for (auto &tensor_builder : tensor_builders)
  {
    tensor_builder->iterate([&](const model::OperandIndex &index) {
      auto object = tensor_builder->wrapTensor(index);
      operand_context->set(index, object);
    });
  }

  // Prepare each TensorManager on each backend
  auto tensor_mgrs = nnfw::cpp14::make_unique<backend::TensorManagerSet>();
  for (auto &tensor_builder : tensor_builders)
  {
    tensor_mgrs->insert(tensor_builder->releaseTensorManager());
  }

  return new exec::LinearExecutor{graph.shareModel(),     linear->releaseSubgraphs(),
                                  operand_context,        linear->releaseLowerInfo(),
                                  std::move(tensor_mgrs), linear->releaseElements(),
                                  function_sequence};
}

exec::IExecutor *ExecutorFactory::createDataflowExecutor(graph::Graph &graph, bool parallel)
{
  auto operand_context = std::make_shared<OperandContext>();

  graph.subgraphs().iterate([&](const model::SubgraphIndex &, const model::Subgraph &subg) {
    auto subtensor_analyzer = SubTensorAnalyzer{graph.operands()};
    subg.accept(subtensor_analyzer);
  });

  // Fix shapes
  graph.subgraphs().iterate(
      [&](const model::SubgraphIndex &subg_index, const model::Subgraph &subg) {
        auto backend = graph.getLowerInfo(subg_index)->backend();
        auto shape_fixer = graph.backend_resolver()->getBackendContext(backend)->shape_fixer;
        shape_fixer->fix(subg);
      });

  graph.operands().iterate([&](const model::OperandIndex &ind, const model::Operand &obj) {
    const auto lower_info = graph.getLowerInfo(ind);
    for (auto factor : lower_info->def_factors())
    {
      bool isSubTensor = false;
      auto backend = factor.backend();
      auto tensor_builder = graph.backend_resolver()->getBackendContext(backend)->tensor_builder;

      if (backend->config()->SupportSubTensorAlloc())
      {
        const auto parentInfo = obj.parent_info();
        if (parentInfo != nullptr)
        {
          isSubTensor = true;
        }
      }

      if (isSubTensor)
      {
        const compiler::SubTensorInfo info(obj);
        tensor_builder->registerSubTensorInfo(ind, info);
      }
      else
      {
        const auto info = obj.info();
        // NOTE This assumes an operand can have one layout, and only PermutateNode can have
        // different layouts for input and output
        const auto &def = *obj.getDef().list().cbegin();
        auto frontend_layout =
            graph.subgraphs().at(graph.subgraphs().getOperation(def)).getLayout();
        if (frontend_layout == model::Layout::UNKNOWN)
        {
          const auto &use = *obj.getUses().list().cbegin();
          frontend_layout = graph.subgraphs().at(graph.subgraphs().getOperation(use)).getLayout();
        }
        const auto backend_layout = lower_info->def_factors().getOnlyElement().layout();
        tensor_builder->registerTensorInfo(ind, info, frontend_layout, backend_layout,
                                           obj.isConstant());
        // To make this never be deallocated, this is a workaround to use static memory planner
        tensor_builder->notifyFirstUse(ind);
      }
    }
  });

  auto tensor_builders = graph.backend_resolver()->tensor_builders();

  for (auto &tensor_builder : tensor_builders)
  {
    tensor_builder->prepare();
  }

  class ExecutionBuilder : public IExecutionBuilder
  {
  public:
    void append(std::unique_ptr<exec::IFunction> &&fn) override
    {
      auto itr = _code_map.find(_next_index);
      if (itr == _code_map.end())
      {
        _code_map[_next_index] = nnfw::cpp14::make_unique<exec::FunctionSequence>();
      }
      _code_map[_next_index]->append(std::move(fn));
    };

    // TODO Remove this method and make `append` to get index value as an argument
    void setNextIndex(const model::SubgraphIndex next_index) { _next_index = next_index; }

    exec::DataflowExecutor::CodeMap &&releaseCodeMap() { return std::move(_code_map); }

  private:
    model::SubgraphIndex _next_index;
    exec::DataflowExecutor::CodeMap _code_map;
  };

  auto execution_builder = nnfw::cpp14::make_unique<ExecutionBuilder>();

  // Generate kernels
  graph.subgraphs().iterate(
      [&](const model::SubgraphIndex &subg_index, const model::Subgraph &subg) {
        auto backend = graph.getLowerInfo(subg_index)->backend();
        auto constant_initializer =
            graph.backend_resolver()->getBackendContext(backend)->constant_initializer;
        constant_initializer->generate(subg, graph.operands());
        // TODO This approach is temporal. See declaration of `setNextIndex`.
        execution_builder->setNextIndex(subg_index);
        auto kernel_gen = graph.backend_resolver()->getBackendContext(backend)->kernel_gen;
        kernel_gen->generate(subg, execution_builder.get());
      });

  for (const auto &tensor_builder : tensor_builders)
  {
    tensor_builder->allocate();
  }

  // Initialize constant tensors
  for (const auto backend : backend::BackendManager::instance().getAll())
  {
    graph.backend_resolver()->getBackendContext(backend)->constant_initializer->run();
  }

  auto lower_info = graph.releaseLowerInfo();

  for (auto &tensor_builder : tensor_builders)
  {
    tensor_builder->finalize();
  }

  // Wrap tensors as Object and store them to plan
  for (auto &tensor_builder : tensor_builders)
  {
    tensor_builder->iterate([&](const model::OperandIndex &index) {
      auto object = tensor_builder->wrapTensor(index);
      operand_context->set(index, object);
    });
  }

  // Prepare each TensorManager on each backend
  auto tensor_mgrs = nnfw::cpp14::make_unique<backend::TensorManagerSet>();
  for (auto &tensor_builder : tensor_builders)
  {
    tensor_mgrs->insert(tensor_builder->releaseTensorManager());
  }

  if (parallel)
  {
    return new exec::ParallelExecutor{
        graph.shareModel(),     graph.releaseSubgraphs(),
        operand_context,        std::move(lower_info),
        std::move(tensor_mgrs), std::move(execution_builder->releaseCodeMap())};
  }
  else
  {
    auto exec = new exec::DataflowExecutor{
        graph.shareModel(),     graph.releaseSubgraphs(),
        operand_context,        std::move(lower_info),
        std::move(tensor_mgrs), std::move(execution_builder->releaseCodeMap())};
    if (util::getConfigBool(util::config::PROFILING_MODE))
    {
      auto et = std::make_shared<backend::ExecTime>(backend::BackendManager::instance().getAll());
      std::unique_ptr<exec::IExecutionObserver> obs =
          nnfw::cpp14::make_unique<exec::ProfileObserver>(et);
      exec->addObserver(std::move(obs));
    }
    return exec;
  }
}

} // namespace compiler
} // namespace neurun