2 * Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "compiler/LoweredGraph.h"
21 #include "util/logging.h"
22 #include "compiler/pass/ConstantInsertionPass.h"
23 #include "compiler/pass/ConstantLoweringPass.h"
24 #include "compiler/pass/PermutationOperationPass.h"
25 #include "compiler/pass/PermutationInsertionPass.h"
26 #include "compiler/pass/PermutationEliminationPass.h"
27 #include "ir/GraphIterator.h"
28 #include "ir/verifier/Verifier.h"
29 #include "backend/Backend.h"
30 #include "backend/IConfig.h"
31 #include "compiler/BackendResolver.h"
32 #include "compiler/ManualScheduler.h"
33 #include "compiler/HEScheduler.h"
40 LoweredGraph::LoweredGraph(const ir::Graph &graph, const CompilerOptions &options) : _graph{graph}
42 bool linear_executor = (options.executor == "Linear");
44 // Build backend contexts
45 auto &backend_manager = BackendManager::get();
47 // Always create Controlflow backend context
48 auto cf_backend = backend_manager.getControlflow();
49 _backend_contexts.emplace(
50 cf_backend, cf_backend->newContext(_graph, _graph.getKernelBuilder(), linear_executor));
52 // Create contexts for other backends
53 for (auto backend_str : options.backend_list)
55 backend_manager.loadBackend(backend_str);
56 auto backend = backend_manager.get(backend_str);
58 // TODO As the default value of backend list contains "cpu", "acl_cl" and "acl_neon", and some
59 // are not available on x64 or some other platforms. So this may be a workaround for x64 and
60 // we should change it back(throw if backend is not loaded) later.
63 VERBOSE(LoweredGraph) << "Cannot load backend - " << backend_str;
67 _backend_contexts.emplace(
68 backend, backend->newContext(_graph, _graph.getKernelBuilder(), linear_executor));
70 if (backend_manager.num_backends() == 0)
71 throw std::runtime_error{"No available backends loaded."};
73 // TODO Move "schedule" phase out of here
75 std::unique_ptr<BackendResolver> backend_resolver;
76 if (options.he_scheduler)
78 auto scheduler = HEScheduler(_backend_contexts, options);
79 backend_resolver = scheduler.schedule(_graph);
80 _indexed_ranks = scheduler.getIndexedRanks();
84 auto scheduler = ManualScheduler(_backend_contexts, options);
85 backend_resolver = scheduler.schedule(_graph);
89 // operand::LowerInfo holder
90 ir::OperandIndexMap<std::unique_ptr<ir::operand::LowerInfo>> operands_lower_info;
92 _graph.operands().iterate([&](const ir::OperandIndex &index, const ir::Operand &) {
93 operands_lower_info[index] = std::make_unique<ir::operand::LowerInfo>();
96 // Make op_seqs while checking whether a node can be merged into a op_seq.
97 makeOpSequences(operands_lower_info, options, *backend_resolver);
99 _op_seqs.iterate([&](const ir::OpSequenceIndex &, ir::OpSequence &op_seq) {
100 assert(op_seq.operations().size() > 0);
101 std::reverse(std::begin(op_seq.operations()), std::end(op_seq.operations()));
104 VERBOSE(OpSequences) << "dump without permutation" << std::endl;
105 dumpOpSequences(_op_seqs, _graph.operations());
107 pass::ConstantInsertionPass ci_pass(*this);
110 pass::ConstantLoweringPass cl_pass(*this);
113 // Set LowerInfo for each operand from the operand::LowerInfo holder
114 manipulateLowerInfo(operands_lower_info, options.is_primary_subgraph);
119 // Run Permutation Passes
121 pass::PermutationOperationPass po_pass(*this);
124 pass::PermutationInsertionPass pi_pass(*this);
127 pass::PermutationEliminationPass pe_pass(*this);
130 VERBOSE(OpSequences) << "dump with permutation" << std::endl;
131 dumpOpSequences(_op_seqs, _graph.operations());
134 // Graph verifications
136 assert(ir::verifier::DAGChecker().verify(_graph));
137 assert(ir::verifier::EdgeConsistencyChecker().verify(_graph));
141 const ir::operation::LowerInfo *
142 LoweredGraph::getLowerInfo(const ir::OpSequenceIndex &op_seq_index) const
144 auto itr = _lower_info_map.op_seq.find(op_seq_index);
145 if (itr == _lower_info_map.op_seq.end())
147 return itr->second.get();
150 void LoweredGraph::setLowerInfo(const ir::OpSequenceIndex &op_seq_index,
151 std::unique_ptr<ir::operation::LowerInfo> &&lower_info)
153 _lower_info_map.op_seq.insert(std::make_pair(op_seq_index, std::move(lower_info)));
156 void LoweredGraph::removeLowerInfo(const ir::OpSequenceIndex &op_seq_index)
158 auto &op_seq_lower_info = _lower_info_map.op_seq;
159 assert(op_seq_lower_info.find(op_seq_index) != op_seq_lower_info.end());
160 for (auto it = op_seq_lower_info.begin(); it != op_seq_lower_info.end(); ++it)
162 if (it->first == op_seq_index)
164 op_seq_lower_info.erase(it);
170 const ir::operand::LowerInfo *LoweredGraph::getLowerInfo(const ir::OperandIndex &index) const
172 auto itr = _lower_info_map.operand.find(index);
173 if (itr == _lower_info_map.operand.end())
175 return itr->second.get();
178 ir::operand::LowerInfo *LoweredGraph::getLowerInfo(const ir::OperandIndex &index)
180 auto itr = _lower_info_map.operand.find(index);
181 if (itr == _lower_info_map.operand.end())
183 return itr->second.get();
186 void LoweredGraph::setLowerInfo(const ir::OperandIndex &index,
187 std::unique_ptr<ir::operand::LowerInfo> &&lower_info)
189 _lower_info_map.operand.insert(std::make_pair(index, std::move(lower_info)));
192 void LoweredGraph::removeLowerInfo(const ir::OperandIndex &index)
194 _lower_info_map.operand.erase(index);
197 void LoweredGraph::iterateTopolOpSeqs(
198 const std::function<void(const ir::OpSequenceIndex &, const ir::OpSequence &)> &fn) const
200 // Topological Sorting for ir::OpSequences
201 std::vector<ir::OpSequenceIndex> topol_sorted;
202 ir::PostDfsIterator<true>{}.iterateOpSeqs(
203 *this, [&](const ir::OpSequenceIndex &index, const ir::OpSequence &) {
204 topol_sorted.emplace_back(index);
206 std::reverse(topol_sorted.begin(), topol_sorted.end());
207 for (const auto op_seq_idx : topol_sorted)
209 const auto &op_seq = _op_seqs.at(op_seq_idx);
210 fn(op_seq_idx, op_seq);
214 void LoweredGraph::iterateTopolOpSeqs(
215 const std::function<void(const ir::OpSequenceIndex &, ir::OpSequence &)> &fn)
217 // Topological Sorting for ir::OpSequences
218 std::vector<ir::OpSequenceIndex> topol_sorted;
219 ir::PostDfsIterator<false>{}.iterateOpSeqs(
220 *this, [&](const ir::OpSequenceIndex &index, ir::OpSequence &) {
221 topol_sorted.emplace_back(index);
223 std::reverse(topol_sorted.begin(), topol_sorted.end());
224 for (const auto op_seq_idx : topol_sorted)
226 auto &op_seq = _op_seqs.at(op_seq_idx);
227 fn(op_seq_idx, op_seq);
231 ir::OpSequenceIndex LoweredGraph::appendFreshSingleOpSequence(const ir::OperationIndex &node_index,
232 const ir::Operation &node)
234 // Create a fresh op_seq with one operation, and append it to op_seqs
235 // Create a fresh op_seq
236 auto op_seq = std::make_unique<ir::OpSequence>(_graph.layout());
239 op_seq->appendOperation(node_index);
241 // Update input/output
242 op_seq->setOutputs(node.getOutputs());
243 op_seq->setInputs(node.getInputs());
245 return _op_seqs.emplace(std::move(op_seq));
248 void LoweredGraph::makeOpSequences(
249 ir::OperandIndexMap<std::unique_ptr<ir::operand::LowerInfo>> &operands_lower_info,
250 const CompilerOptions &options, const BackendResolver &backend_resolver)
252 // if SUBG_MAX_NODE == 0, no limit on nodes of a op_seq
253 const int op_seq_max_node = options.op_seq_max_node;
254 assert(op_seq_max_node >= 0);
256 bool is_profiling = options.he_profiling_mode;
257 ir::OpSequence *op_seq = nullptr;
258 ir::OpSequenceIndex op_seq_index;
260 // NOTE: The below method appends nodes while making one op_seq if needed. If something better
261 // ways, happy to update this code.
262 ir::PostDfsConstIterator{}.iterate(
263 _graph, [&](const ir::OperationIndex &node_index, const ir::Operation &node) {
264 // LowerInfo for in/output operands
265 auto backend = backend_resolver.getBackend(node_index);
267 // Get frontend's layout
268 auto frontend_layout = _graph.layout();
270 // The layout of each backend should be set at another place
271 // TODO Change setting layout of each backend at another place
272 auto backend_layout = backend->config()->supportLayout(node, frontend_layout);
274 for (auto operand : node.getInputs() | ir::Remove::UNDEFINED)
276 auto &&lower_info = operands_lower_info.at(operand);
277 lower_info->addUsePermuteFactor(ir::operand::PermuteFactor{backend, backend_layout});
279 for (auto operand : node.getOutputs())
281 auto &&lower_info = operands_lower_info.at(operand);
282 lower_info->addDefPermuteFactor(ir::operand::PermuteFactor{backend, backend_layout});
285 bool new_op_seq = (op_seq == nullptr ||
286 (op_seq_max_node != 0 &&
287 op_seq->operations().size() >= static_cast<size_t>(op_seq_max_node)));
289 // for profiling each op_seq must contain just one node,
290 // so that we can measure a node separately
291 if (new_op_seq || is_profiling ||
292 !mergeable(op_seq_index, node_index, backend_layout, backend_resolver))
294 auto new_op_seq_index = appendFreshSingleOpSequence(node_index, node);
296 // ir::OpSequence LowerInfo
297 setLowerInfo(new_op_seq_index,
298 std::make_unique<ir::operation::LowerInfo>(backend, backend_layout));
300 op_seq_index = new_op_seq_index;
301 op_seq = &(_op_seqs.at(new_op_seq_index));
303 VERBOSE(Lower) << "OpSequence#" << op_seq_index.value() << " is created for "
304 << "NODE#" << node_index.value() << "(" << node.name() << ")" << std::endl;
308 op_seq->appendOperation(node_index);
310 auto new_inputs = node.getInputs();
311 // Add inputs except outputs of the previous node
312 for (auto ind : op_seq->getInputs())
314 if (!node.getOutputs().contains(ind))
315 new_inputs.append(ind);
317 op_seq->setInputs(new_inputs);
319 VERBOSE(Lower) << "OpSequence#" << op_seq_index.value() << " merges "
320 << "NODE#" << node_index.value() << "(" << node.name() << ")" << std::endl;
325 void LoweredGraph::manipulateLowerInfo(
326 ir::OperandIndexMap<std::unique_ptr<ir::operand::LowerInfo>> &operands_lower_info,
329 const auto controlflow_backend = BackendManager::get().getControlflow();
331 // TODO Rather than handling primary graph specially,
332 // let the permute inserted and remove it later
335 // TODO Rather than using NHWC Get frontend layout of this node from IR
336 auto factor = ir::operand::PermuteFactor{controlflow_backend, ir::Layout::NHWC};
337 for (auto index : _graph.getInputs() | ir::Remove::UNDEFINED)
339 auto &&lower_info = operands_lower_info.at(index);
340 assert(lower_info->def_factors().empty());
341 lower_info->addDefPermuteFactor(factor);
343 for (auto index : _graph.getOutputs())
345 auto &&lower_info = operands_lower_info.at(index);
346 lower_info->addUsePermuteFactor(factor);
351 for (auto index : _graph.getInputs() | ir::Remove::UNDEFINED)
353 auto &&lower_info = operands_lower_info.at(index);
354 if (!(lower_info->def_factors().size() == 0 && lower_info->use_factors().size() == 0))
356 // In case of not that Graph's input is not used in any operation and not the graph's
358 // In other words, it is not unused input in Graph.
359 lower_info->addDefPermuteFactor(*lower_info->use_factors().begin());
363 // In case of that an operand is Graph's input and not input or output of any operation
364 lower_info->addDefPermuteFactor(ir::operand::PermuteFactor{
366 ir::Layout::NHWC // TODO Get frontend layout of this node from IR
371 for (auto index : _graph.getOutputs())
373 auto &&lower_info = operands_lower_info.at(index);
374 if (lower_info->def_factors().size() == 0)
376 // In case of that an operand is Graph's output and not input or output of any operation
377 lower_info->addDefPermuteFactor(ir::operand::PermuteFactor{
379 ir::Layout::NHWC // TODO Get frontend layout of this node from IR
384 // Set LowerInfo for each operand from the operand::LowerInfo holder
385 _graph.operands().iterate([&](const ir::OperandIndex &index, ir::Operand &) {
386 setLowerInfo(index, std::move(operands_lower_info[index]));
390 void LoweredGraph::dumpLowerInfo()
392 if (::onert::util::logging::ctx.enabled() == false)
395 std::map<uint32_t, std::string> dumps;
397 _graph.operands().iterate([&](const ir::OperandIndex &index, ir::Operand &object) {
398 std::stringstream sstream;
399 if (!getLowerInfo(index)->def_factors().empty() || !getLowerInfo(index)->use_factors().empty())
401 auto factors_to_string = [](const ir::operand::PermuteFactorSet &factors) {
403 for (auto factor : factors)
405 str += factor.backend()->config()->id();
406 str += "(" + to_string(factor.layout()) + ")";
409 return "{ " + str + "}";
412 auto operation_index_to_string = [](const ir::OperationIndexSet &operations) {
414 for (auto op : operations)
416 str += std::to_string(op.value());
419 return "{ " + str + "}";
422 const auto lower_info = getLowerInfo(index);
423 const auto &shape = object.shape();
424 std::string def_ops =
425 object.getDef().valid() ? std::to_string(object.getDef().value()) : "N/A";
426 std::string use_ops = operation_index_to_string(object.getUses());
427 std::string def_layouts = factors_to_string(lower_info->def_factors());
428 std::string use_layouts = factors_to_string(lower_info->use_factors());
429 sstream << "Operand #" << index.value() << " LowerInfo" << std::endl;
430 sstream << " - Shape : { ";
431 for (auto i = 0; i < shape.rank(); ++i)
433 sstream << (shape.dim(i)) << " ";
435 sstream << "}" << std::endl;
436 sstream << " - Def ir::Operations : " << def_ops << std::endl;
437 sstream << " - Use ir::Operations : " << use_ops << std::endl;
438 sstream << " - Lower Info" << std::endl;
439 sstream << " - Def Backends : " << def_layouts << std::endl;
440 sstream << " - Use Backends : " << use_layouts << std::endl;
442 dumps.emplace(index.value(), sstream.str());
445 for (const auto &e : dumps)
447 if (!e.second.empty())
449 VERBOSE(Lower) << e.second;
454 bool LoweredGraph::mergeable(const ir::OpSequenceIndex &op_seq_index,
455 const ir::OperationIndex &node_index, ir::Layout layout,
456 const BackendResolver &backend_resolver)
458 // Are they mergeable?
459 // 1. the same backend id and layout?
460 // 2. Is op_seq or node branched?
461 // 3. if 1 is true, the op_seq and a node are connected?
462 const auto &op_seq = _op_seqs.at(op_seq_index);
463 const auto &node = _graph.operations().at(node_index);
465 // The same backend id and layout?
467 const auto op_seq_backend_layout = getLowerInfo(op_seq_index)->layout();
468 const auto &op_seq_backend_id = getLowerInfo(op_seq_index)->backend()->config()->id();
469 const auto &node_backend_id = backend_resolver.getBackend(node_index)->config()->id();
470 VERBOSE(Lower) << "OpSequence#" << op_seq_index.value() << " { " << op_seq_backend_id << "("
471 << to_string(op_seq_backend_layout) << ") } "
472 << " NODE#" << node_index.value() << " (" << node.name() << ") { "
473 << node_backend_id << "(" << to_string(layout) << ") } " << std::endl;
474 if (op_seq_backend_id != node_backend_id || op_seq_backend_layout != layout)
480 std::unordered_set<ir::OperationIndex> branched_set;
482 // Check for branching up
483 for (const auto &input : op_seq.getInputs() | ir::Remove::DUPLICATED | ir::Remove::UNDEFINED)
485 const auto &input_obj = _graph.operands().at(input);
486 auto def = input_obj.getDef();
489 branched_set.insert(def);
490 if (branched_set.size() > 1)
496 branched_set.clear();
498 // Check for branching down
499 for (const auto &output : node.getOutputs() | ir::Remove::DUPLICATED)
501 // TODO Fix this workaround for the case of model outputs that are used by another operation
502 // This is needed since the branching is decided by operation, but for model outputs,
503 // there is controlflow backen(use backend) but no actual use operation exists
504 if (_graph.getOutputs().contains(output))
507 const auto &output_obj = _graph.operands().at(output);
508 for (const auto &use : output_obj.getUses())
510 branched_set.insert(use);
511 if (branched_set.size() > 1)
520 // an input of one node is an output of the other node? or vice-versa?
522 const auto &node_inputs = node.getInputs();
523 const auto &node_outputs = node.getOutputs();
525 // op_seq's operations are in order so that we just check the first and the last
526 std::vector<ir::OperationIndex> op_seq_ops{op_seq.operations()[0]};
527 if (op_seq.operations().size() > 1)
528 op_seq_ops.emplace_back(op_seq.operations()[op_seq.operations().size() - 1]);
530 for (const auto &n_index : op_seq_ops)
532 const auto &n = _graph.operations().at(n_index);
534 // node's output == op_seq's input?
535 for (const auto input : n.getInputs() | ir::Remove::UNDEFINED)
537 if (node_outputs.contains(input))
539 VERBOSE(Lower) << "OpSequence#" << op_seq_index.value() << " 's NODE#" << n_index.value()
540 << "(" << n.name() << ") is connected to NODE#" << node_index.value()
541 << "(" << node.name() << ")" << std::endl;
546 // node's input == op_seq's output?
547 for (const auto output : n.getOutputs())
549 if (node_inputs.contains(output))
551 VERBOSE(Lower) << "OpSequence#" << op_seq_index.value() << " 's NODE#" << n_index.value()
552 << " (" << n.name() << ") is connected to NODE#" << node_index.value()
559 VERBOSE(Lower) << "OpSequence#" << op_seq_index.value() << " is not connected to NODE#"
560 << node_index.value() << "(" << node.name() << ")" << std::endl;
566 } // namespace compiler