summaryrefslogtreecommitdiff
path: root/runtimes/neurun/src/linear/Linear.cc
blob: 59a00505d72e0749ee93cb104291c1d932160869 (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
/*
 * 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 "Linear.h"

#include "graph/Graph.h"

#include "graph/operation/LowerInfo.h"
#include "backend/interface/IStageGenerator.h"
#include "internal/Convert.h"
#include "backend/interface/IConfig.h"
#include "backend/common/operand/SubTensorInfo.h"

#include "logging.h"

namespace neurun
{
namespace linear
{

Linear::Linear(const graph::Graph &graph) : _graph(graph)
{
  // Linearize with topological sort
  //
  // Topological sort algorithm
  //   1. Iterate with DFS
  //   2. Append the node to vector when DFS for the node finishes(post order)
  //   3. Reverse the order of nodes

  graph::Graph::PostDfsConstIterator().iterate(
      graph, [&](const neurun::graph::operation::Node &node) { _operations.emplace_back(&node); });

  std::reverse(std::begin(_operations), std::end(_operations));
}

void Linear::accept(graph::operation::NodeVisitor &&visitor) const
{
  for (const auto op : _operations)
  {
    op->accept(std::move(visitor));
  }
}

backend::TensorBuilderSet Linear::planTensors()
{
  using ITensorBuilderPtr = std::shared_ptr<backend::ITensorBuilder>;
  using FnOnTensorBuilder =
      std::function<void(const graph::operand::Index &ind, ITensorBuilderPtr)>;

  const auto &operands = _graph.operands();
  auto iterTensorBuilders = [&operands](const graph::operand::Index &ind, FnOnTensorBuilder fn) {
    const auto &obj = operands.at(ind);
    for (auto backend : obj.lower_info()->def_backends())
    {
      auto tensor_builder = backend->tensor_builder();
      fn(ind, tensor_builder);
    }
  };

  backend::TensorBuilderSet tensor_builders;

  std::unordered_map<graph::operand::Index, uint32_t> uses_map;
  std::vector<graph::operand::Index> constants;

  _graph.operands().iterate(
      [&](const graph::operand::Index &ind, const graph::operand::Object &obj) {
        uses_map[ind] = obj.getUses().size();

        // If a tensor is a constant, increase the use of the tensor.
        // It makes the tensor not be dealloced.
        if (obj.getUsage() == graph::operand::OperandUsage::CONSTANT)
        {
          constants.push_back(ind);
          uses_map[ind]++;
        }

        for (auto backend : obj.lower_info()->def_backends())
        {
          bool isSubTensor = false;
          auto tensor_builder = backend->tensor_builder();

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

          if (isSubTensor)
          {
            const backend::operand::SubTensorInfo info(obj);
            tensor_builder->registerSubTensorInfo(ind, info);
          }
          else
          {
            const auto info = ::internal::asTensorInfo(obj.shape(), obj.typeInfo());
            tensor_builder->registerTensorInfo(ind, info);
          }

          // Prepare tensor builders to be returned
          tensor_builders.insert(tensor_builder);
        }
      });

  // If a tensor is model output, increase the use of the tensor.
  // This aim is same to above one.
  for (const auto &ind : _graph.getOutputs())
  {
    uses_map[ind]++;
  }

  // Allocate constant operands first
  VERBOSE(LINEAR) << "TENSORS as CONSTANT" << std::endl;
  for (const auto &ind : constants)
  {
    iterTensorBuilders(ind, [](const graph::operand::Index &ind, ITensorBuilderPtr tensor_builder) {
      tensor_builder->notifyFirstUse(ind);
    });
  }

  // Allocate Model's inputs
  VERBOSE(LINEAR) << "TENSORS as MODEL INPUT" << std::endl;
  for (const auto &ind : _graph.getInputs())
  {
    iterTensorBuilders(ind, [](const graph::operand::Index &ind, ITensorBuilderPtr tensor_builder) {
      tensor_builder->notifyFirstUse(ind);
    });
  }

  // At each operation,
  //   1. Scan USE of inputs. Decrease the USE and deallocate if the USE is 0
  //   2. Scan DEF of outputs. If the DEF, allocate it
  VERBOSE(LINEAR) << "TENSORS" << std::endl;
  for (const auto op : _operations)
  {
    for (const auto &ind : op->getOutputs())
    {
      const auto &obj = operands.at(ind);
      if (obj.getDef().size())
      {
        iterTensorBuilders(ind,
                           [](const graph::operand::Index &ind, ITensorBuilderPtr tensor_builder) {
                             tensor_builder->notifyFirstUse(ind);
                           });
      }
    }

    for (const auto &ind : op->getInputs())
    {
      uses_map[ind]--;
      if (uses_map[ind] == 0)
      {
        iterTensorBuilders(ind,
                           [](const graph::operand::Index &ind, ITensorBuilderPtr tensor_builder) {
                             tensor_builder->notifyLastUse(ind);
                           });
      }
    }
  }

#ifndef NDEBUG
  // Now, model outputs should be not deallocated
  for (const auto &ind : _graph.getOutputs())
    assert(uses_map[ind] > 0);
#endif

  // Set subtensor information
  // Todo: move this phase outside as optimization phase
  return tensor_builders;
}

} // namespace linear
} // namespace neurun