summaryrefslogtreecommitdiff
path: root/runtime/onert/core/src/exec/train/TrainableExecutor.cc
blob: 9c7e70c29a6216a7b89e361c915cfd04be20290b (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
/*
 * Copyright (c) 2023 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 "TrainableExecutor.h"
#ifdef RUY_PROFILER
#include "ruy/profiler/instrumentation.h"
#endif

#include <misc/polymorphic_downcast.h>

namespace onert
{
namespace exec
{
namespace train
{

TrainableExecutor::TrainableExecutor(
  std::unique_ptr<compiler::train::LoweredTrainableGraph> lowered_graph,
  backend::train::TrainableBackendContexts &&backend_contexts,
  const compiler::train::TensorRegistries &tensor_regs,
  compiler::train::TrainableCodeMap &&code_map, const std::vector<ir::OperationIndex> &order,
  const util::TracingCtx *tracing_ctx)
  : _lowered_graph{std::move(lowered_graph)}, _backend_contexts{std::move(backend_contexts)},
    _trainable_graph{_lowered_graph->trainable_graph()}, _tensor_regs{std::move(tensor_regs)},
    _mutex(), _tracing_ctx(tracing_ctx)
{
  auto build_tensor_list = [&](const auto &ind_seq, auto &tensors) {
    assert(tensors.empty());
    for (auto &&ind : ind_seq)
    {
      backend::ITensor *tensor = tensor_regs.getITensor(ind);
      assert(tensor != nullptr);
      auto io_tensor = nnfw::misc::polymorphic_downcast<backend::builtin::IOTensor *>(tensor);
      tensors.push_back(io_tensor);
    }
  };
  build_tensor_list(_trainable_graph.getInputs(), _input_tensors);
  build_tensor_list(_trainable_graph.getOutputs(), _output_tensors);

  for (auto &&index : order)
  {
    auto &trainable_code = code_map.at(index);
    _code.emplace_back(std::move(trainable_code));
  }
}

void TrainableExecutor::execute(const std::vector<backend::IPortableTensor *> &,
                                const std::vector<backend::IPortableTensor *> &)
{
  throw std::runtime_error("TrainableExecutor does not support multiple subgraphs yet");
}

void TrainableExecutor::forward(const IODescription &desc, bool training)
{
  // For thread-safe, use mutex
  // TODO: if all used backends on this executor are thread-safe,
  //       do not need to use mutex (otherwise, use mutex)
  std::lock_guard<std::mutex> lock(_mutex);

  // TODO Update IO tensors if desc has dynamic input
  // Set input(s)
  assert(_input_tensors.size() == desc.inputs.size());
  for (uint32_t i = 0; i < _input_tensors.size(); ++i)
  {
    auto tensor = _input_tensors[i];

    // TODO Check if (desc.inputs[i] == nullptr)
    // TODO Better design for ITensor? (we need const_cast as ITensor is writable)
    tensor->setUserTensor(static_cast<uint8_t *>(const_cast<void *>(desc.inputs[i]->buffer)),
                          desc.inputs[i]->size);
  }

  if (!training)
  {
    // Set output(s)
    assert(_output_tensors.size() == desc.outputs.size());
    for (uint32_t i = 0; i < _output_tensors.size(); ++i)
    {
      auto tensor = _output_tensors[i];

      if (desc.outputs[i] == nullptr)
        throw std::runtime_error{"Output " + std::to_string(i) + "'s buffer is not set."};
      tensor->setUserTensor(static_cast<uint8_t *>(desc.outputs[i]->buffer), desc.outputs[i]->size);
    }
  }

  forwardImpl(training);

  // TODO Update output(s) desc if desc has dynamic input
}

void TrainableExecutor::forwardImpl(bool training)
{
  if (_tracing_ctx)
  {
    auto profiling_subg_index = _tracing_ctx->getSubgraphIndex(&_trainable_graph.graph());

    _subject.notifySubgraphBegin(profiling_subg_index);
    for (auto &&code : _code)
    {
      const auto backend = code.lower_info->backend();
// TODO : Move ruy profiler into ExecutionObserver
#ifdef RUY_PROFILER
      ruy::profiler::ScopeLabel label(code.op->name());
#endif
      _subject.notifyJobBegin(this, profiling_subg_index, code.op_ind, backend);

      auto &tn_seq = code.tn_seq;
      tn_seq->forward(training);

      _subject.notifyJobEnd(this, profiling_subg_index, code.op_ind, backend);
    }
    _subject.notifySubgraphEnd(profiling_subg_index);
  }
  else
  {
    for (auto &&code : _code)
    {
// TODO : Move ruy profiler into ExecutionObserver
#ifdef RUY_PROFILER
      ruy::profiler::ScopeLabel label(code.op->name());
#endif
      auto &tn_seq = code.tn_seq;
      tn_seq->forward(training);
    }
  }
}

void TrainableExecutor::backward(const IODescription &, uint32_t training_step)
{
  // For thread-safe, use mutex
  // TODO: if all used backends on this executor are thread-safe,
  //       do not need to use mutex (otherwise, use mutex)
  std::lock_guard<std::mutex> lock(_mutex);

  backwardImpl(training_step);
}

void TrainableExecutor::backwardImpl(uint32_t training_step)
{
  if (_tracing_ctx)
  {
    auto profiling_subg_index = _tracing_ctx->getSubgraphIndex(&_trainable_graph.graph());

    _subject.notifySubgraphBegin(profiling_subg_index);
    for (auto it = _code.rbegin(); it != _code.rend(); ++it)
    {
      const auto &code = *it;
      const auto backend = code.lower_info->backend();
// TODO : Move ruy profiler into ExecutionObserver
#ifdef RUY_PROFILER
      ruy::profiler::ScopeLabel label(code.op->name());
#endif
      _subject.notifyJobBegin(this, profiling_subg_index, code.op_ind, backend);

      auto &tn_seq = code.tn_seq;
      tn_seq->backward(training_step);

      _subject.notifyJobEnd(this, profiling_subg_index, code.op_ind, backend);
    }
    _subject.notifySubgraphEnd(profiling_subg_index);
  }
  else
  {
    for (auto it = _code.rbegin(); it != _code.rend(); ++it)
    {
      const auto &code = *it;
// TODO : Move ruy profiler into ExecutionObserver
#ifdef RUY_PROFILER
      ruy::profiler::ScopeLabel label(code.op->name());
#endif
      auto &tn_seq = code.tn_seq;
      tn_seq->backward(training_step);
    }
  }
}

float TrainableExecutor::getLoss(const ir::IOIndex &pred_io_ind) const
{
  const auto &loss_ind = _trainable_graph.getLossIndex(pred_io_ind);
  if (loss_ind.undefined())
    throw std::runtime_error{"Loss " + std::to_string(loss_ind.value()) + " is not defined."};
  backend::ITensor *tensor = _tensor_regs.getITensor(loss_ind);
  auto loss_buf = reinterpret_cast<float *>(tensor->buffer());
  return *loss_buf;
}

} // namespace train
} // namespace exec
} // namespace onert