summaryrefslogtreecommitdiff
path: root/runtimes/neurun/core/src/graph/pass/PermutationInsertionPass.cc
blob: 47a730bbb2b32ac6214bc7d152b94423fdef7dad (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
/*
 * Copyright (c) 2018 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 "PermutationInsertionPass.h"

#include <cassert>
#include <utility>
#include <unordered_map>

#include "model/operand/Object.h"
#include "graph/operation/LowerInfo.h"
#include "graph/Graph.h"
#include "backend/IConfig.h"
#include "util/logging.h"
#include "cpp14/memory.h"
#include "model/operation/PermuteNode.h"
#include "graph/operand/Shape4DConvert.h"
#include "compiler/BackendResolver.h"

namespace neurun
{
namespace graph
{
namespace pass
{

void PermutationInsertionPass::callback(const model::operand::Index &index,
                                        model::operand::Object &object)
{
  auto &&operand_li = _graph.getLowerInfo(index);
  assert(operand_li);

  // NOTE Later, constants also will have Def
  // Ignore constants
  if (operand_li->def_backends().size() == 0)
  {
    return;
  }

  std::list<model::OperationIndex> permute_indexes;

  // Build a map for all necessary type of operands
  std::unordered_map<const backend::Backend *, model::operand::Index> backend_to_index;
  {
    assert(operand_li->def_backends().size() == 1);
    for (auto backend : operand_li->def_backends())
    {
      backend_to_index.insert({backend, index});
    }

    auto insert_set = operand_li->use_backends() - operand_li->def_backends();
    for (auto backend : insert_set)
    {
      const auto permute_operation_index = insertPermute(index, backend);
      permute_indexes.push_back(permute_operation_index);
      VERBOSE(PermutationInsertionPass) << "Insert 'Permute' operation for operand "
                                        << index.value() << std::endl;
      const auto &permute_operation = _graph.operations().at(permute_operation_index);
      const auto permuted_operand_index = permute_operation.getOutputs().at(0);
      backend_to_index.insert({backend, permuted_operand_index});
    }
  }

  // Update operations' input that uses this operand
  {
    std::list<model::OperationIndex> remove_list;

    auto uses = object.getUses();
    for (auto use : uses.list())
    {
      // If permute operation, ignore it
      if (std::find(permute_indexes.begin(), permute_indexes.end(), use) != permute_indexes.end())
        continue;

      auto &operation = _graph.operations().at(use);
      assert(_graph.subg_ctx().hasNode(use));
      auto subg_index = _graph.subg_ctx().findNode(use);
      auto subg_li = _graph.getLowerInfo(subg_index);
      assert(subg_li);
      const backend::Backend *backend = subg_li->backend();
      assert(backend);
      auto use_node_inputs = operation.getInputs();
      assert(use_node_inputs.contains(index));

      auto new_index = backend_to_index.at(backend);
      if (index != new_index)
      {
        // Update from subgraph
        _graph.subg_ctx().at(subg_index).replaceInput(index, new_index);

        // Update from operation
        operation.replaceInput(index, new_index);

        // Update from operand
        remove_list.push_back(
            use); // Removal should be done in another loop since we are in the loop
        _graph.operands().at(new_index).appendUse(use);
      }
    }

    for (auto &operation : remove_list)
    {
      object.removeUse(operation);
    }
  }
}

model::OperationIndex
PermutationInsertionPass::insertPermute(const model::operand::Index &operand_index,
                                        const backend::Backend *backend)
{
  assert(!_graph.isBuildingPhase());

  auto &operand = _graph.operands().at(operand_index);

  // Generate output operand and permute operation
  auto out_operand_index = _graph.addOperand(operand.shape(), operand.typeInfo());
  auto &out_operand = _graph.operands().at(out_operand_index);
  out_operand.usage(model::operand::Usage::OPERATION_OUTPUT);
  // change model output if operand_index is model output index
  auto &model_outputs = _graph.getOutputs();
  if (model_outputs.contains(operand_index))
  {
    model_outputs.replace(operand_index, out_operand_index);
  }
  out_operand.usage(model::operand::Usage::OPERATION_OUTPUT);
  auto out_operand_li =
      nnfw::cpp14::make_unique<operand::LowerInfo>(operand::asShape4D(operand.shape()));
  out_operand_li->addDefBackend(backend);
  out_operand_li->addUseBackend(backend);
  _graph.setLowerInfo(out_operand_index, std::move(out_operand_li));

  // Update LowerInfo of input operand
  auto operand_lower_info = _graph.getLowerInfo(operand_index);
  operand_lower_info->removeUseBackend(backend);
  operand_lower_info->addUseBackend(operand_lower_info->def_backends().getOnlyElement());

  using PermuteNode = model::operation::PermuteNode;

  auto input_backend = _graph.getLowerInfo(operand_index)->def_backends().getOnlyElement();
  auto output_backend = _graph.getLowerInfo(out_operand_index)->def_backends().getOnlyElement();

  // Find Permutation Type
  auto type = [&]() {
    auto input_layout = input_backend->config()->getOperandLayout();
    auto output_layout = output_backend->config()->getOperandLayout();

    if (input_layout == graph::operand::Layout::NHWC &&
        output_layout == graph::operand::Layout::NCHW)
    {
      return PermuteNode::Type::NHWC_TO_NCHW;
    }
    else if (input_layout == graph::operand::Layout::NCHW &&
             output_layout == graph::operand::Layout::NHWC)
    {
      return PermuteNode::Type::NCHW_TO_NHWC;
    }
    else
    {
      return PermuteNode::Type::COPY;
    }
  }();

  // Insert permute operation to the graph
  auto insert_node = nnfw::cpp14::make_unique<PermuteNode>(operand_index, out_operand_index, type,
                                                           input_backend, output_backend);

  auto node_index = _graph.operations().append(std::move(insert_node));
  const auto &node = _graph.operations().at(node_index);

  // Subgraph
  {
    auto subg_index = _graph.subg_ctx().append(node_index, node);
    auto &subg = _graph.subg_ctx().at(subg_index);
    subg.setInputs(node.getInputs());
    subg.setOutputs(node.getOutputs());
    _graph.setLowerInfo(subg_index, nnfw::cpp14::make_unique<graph::operation::LowerInfo>(
                                        _graph.backend_resolver()->getDefaultBackend()));
  }

  // Update Use/Def info
  {
    _graph.operands().at(operand_index).appendUse(node_index);

    auto node_out_indexes = node.getOutputs();
    auto node_out_index = node_out_indexes.at(model::operand::IO::Index{0});
    _graph.operands().at(node_out_index).appendDef(node_index);
  }
  return node_index;
}
} // namespace pass
} // namespace graph
} // namespace neurun