ONE - On-device Neural Engine
Loading...
Searching...
No Matches
PermuteLayer.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17#include "PermuteLayer.h"
18
19#include <ruy/context.h> // from @ruy
20
22{
23
24PermuteLayer::PermuteLayer(const std::vector<ITensor *> &src_tensors,
25 const std::vector<ITensor *> &dst_tensors,
26 const std::vector<ir::PermuteType> &types,
27 const std::shared_ptr<ExternalContext> &external_context)
28 : _external_context{external_context}, _tasks_map{}
29{
30 assert(src_tensors.size() == dst_tensors.size());
31 assert(src_tensors.size() == types.size());
32 _src_tensors = src_tensors;
33 _dst_tensors = dst_tensors;
34 _permute_types = types;
35 _src_tensors_offsets.resize(src_tensors.size());
36 _dst_tensors_offsets.resize(dst_tensors.size());
37 _permute_types.resize(src_tensors.size());
38}
39
41{
42 // Remove copying of tensor as nullptr
43 auto src_it = _src_tensors.begin();
44 auto dst_it = _dst_tensors.begin();
45 auto src_offsets_it = _src_tensors_offsets.begin();
46 auto dst_offsets_it = _dst_tensors_offsets.begin();
47 auto type_it = _permute_types.begin();
48 while (src_it != _src_tensors.end())
49 {
50 if ((*src_it == *dst_it) || (*src_it == nullptr || *dst_it == nullptr))
51 {
52 src_it = _src_tensors.erase(src_it);
53 dst_it = _dst_tensors.erase(dst_it);
54 src_offsets_it = _src_tensors_offsets.erase(src_offsets_it);
55 dst_offsets_it = _dst_tensors_offsets.erase(dst_offsets_it);
56 type_it = _permute_types.erase(type_it);
57 }
58 else
59 {
60 auto src = *src_it;
61 auto dst = *dst_it;
62 src_offsets_it->resize(0);
63 dst_offsets_it->resize(0);
64 const auto permute_type = *type_it;
65
66 src_it++;
67 dst_it++;
68 src_offsets_it++;
69 dst_offsets_it++;
70 type_it++;
71
72 if (underlying_type(src->data_type()) != underlying_type(dst->data_type()))
73 continue;
74
75 // TODO Support different types
76 auto fn = [&](backend::ITensor &src_tensor) {
77 dst->access([&](backend::ITensor &dst_tensor) {
78 // NOTE The buffer of both tensor can be nullptr in this step
79 const auto data_size = ir::sizeOfDataType(src_tensor.data_type());
80
81 if (permute_type == ir::PermuteType::SAME)
82 {
83 if ((!src_tensor.has_padding() && !dst_tensor.has_padding()))
84 {
85 const auto num_elements = src_tensor.getShape().num_elements();
86 const int thread_count =
87 _external_context->ruy_context()->max_num_threads() < static_cast<int>(num_elements)
88 ? _external_context->ruy_context()->max_num_threads()
89 : num_elements;
90
91 std::vector<PermuteWorkerTask> tasks;
92 auto start = 0;
93 for (auto i = 0; i < thread_count; ++i)
94 {
95 int end = start + (num_elements - start) / (thread_count - i);
96 tasks.emplace_back(src_tensor.buffer(), dst_tensor.buffer(), start * data_size,
97 start * data_size, (end - start) * data_size);
98 start = end;
99 }
100 assert(tasks.size() >= 1);
101 _tasks_map[src] = std::move(tasks);
102 }
103 else
104 {
105 auto loop_shape = src_tensor.getShape();
106
107 auto copy_axis = loop_shape.rank() - 1;
108 copy_axis = copy_axis < 0 ? 1 : copy_axis;
109 const auto copy_len = loop_shape.dim(copy_axis) * data_size;
110 loop_shape.dim(copy_axis) = 1;
111
112 appendPermuteTasks(src, dst, loop_shape, copy_len, permute_type);
113 }
114 }
115 else
116 {
117 assert(src_tensor.getShape().rank() == 4 &&
118 (permute_type == ir::PermuteType::NHWC_TO_NCHW ||
119 permute_type == ir::PermuteType::NCHW_TO_NHWC));
120 const auto loop_shape = src_tensor.getShape();
121 const auto copy_len = data_size;
122
123 appendPermuteTasks(src, dst, loop_shape, copy_len, permute_type);
124 }
125 });
126 };
127 src->access(fn);
128 }
129 }
130}
131
132void PermuteLayer::appendPermuteTasks(const ITensor *src_tensor, ITensor *dst_tensor,
133 const ir::Shape &loop_shape, size_t size,
134 const ir::PermuteType &permute_type)
135{
136 size_t distributed_dim = 0;
137 auto src_shape = src_tensor->getShape();
138 if (permute_type == ir::PermuteType::SAME)
139 {
140 for (int i = 1; i < src_shape.rank() - 1; ++i)
141 {
142 distributed_dim = src_shape.dim(distributed_dim) < src_shape.dim(i) ? i : distributed_dim;
143 }
144 }
145 const auto distributed_dim_val = src_shape.dim(distributed_dim);
146 const int thread_count =
147 _external_context->ruy_context()->max_num_threads() < static_cast<int>(distributed_dim_val)
148 ? _external_context->ruy_context()->max_num_threads()
149 : distributed_dim_val;
150 // NOTE Do not remove this assertion. It would cause performance degradation by new threads to be
151 // created in the context's thread pool
152 assert(thread_count <= _external_context->ruy_context()->max_num_threads());
153
154 std::vector<PermuteWorkerTask> tasks;
155 int start = 0;
156 auto one_thread_loop_shape = loop_shape;
157 for (auto i = 0; i < thread_count; ++i)
158 {
159 ir::Coordinates start_coords(one_thread_loop_shape.rank());
160 start_coords.set(distributed_dim, start);
161 int end = start + (distributed_dim_val - start) / (thread_count - i);
162 one_thread_loop_shape.dim(distributed_dim) = end - start;
163 tasks.emplace_back(*src_tensor, *dst_tensor, start_coords, one_thread_loop_shape, size,
164 permute_type);
165 start = end;
166 }
167 assert(tasks.size() >= 1);
168 _tasks_map[src_tensor] = std::move(tasks);
169}
170
171void PermuteLayer::runPermuteTasks(backend::ITensor *src, uint8_t *dst_buffer)
172{
173 assert(src->getShape().num_elements() * ir::sizeOfDataType(src->data_type()) <=
174 src->total_size());
175 std::vector<PermuteWorkerTask> &tasks = _tasks_map.at(src);
176 for (size_t i = 0; i < tasks.size(); ++i)
177 {
178 tasks.at(i).setBuffers(src->buffer(), dst_buffer);
179 }
180 assert(tasks.size() >= 1);
181 _external_context->ruy_context()->mutable_thread_pool()->Execute(tasks.size(), tasks.data());
182}
183
185{
186 assert(_src_tensors.size() == _dst_tensors.size());
187 // PermuteLayer infers dynamic shape inside itself whenever run is called for the following
188 // reasons:
189 // 1. PermuteLayer has to access dynamic tensor manager for input/output tensors of other backends
190 // 2. Other controlflow operation(If/While) uses this layout for copying tensors of other
191 // subgraphs(with other backends)
192 // 3. This infering code is placed here to avoid duplicated code that can be caused by above 2
193 // reasons
194
195 // check if output is not dynamic
196 for (size_t i = 0; i < _src_tensors.size(); ++i)
197 {
198 auto dst_tensor = _dst_tensors.at(i);
199 auto src_tensor = _src_tensors.at(i);
200 auto permute_type = _permute_types.at(i);
201 if (src_tensor->is_dynamic() || dst_tensor->is_dynamic())
202 {
203 // getting output shape
204 auto src_shape = src_tensor->getShape();
205
206 // set output shape and output buffer
207 ir::Shape new_shape = ir::convertShape(src_shape, permute_type);
208
209 try
210 {
211 if (!dst_tensor->applyShape(new_shape))
212 throw std::runtime_error{
213 "Error: PermuteLayer: output's TensorManager does not support dynamic tensor"};
214 assert(dst_tensor->buffer() != nullptr);
215 }
216 catch (const std::out_of_range &e)
217 {
218 std::cerr << "Error: out_of_range in PermuteLayer: output's TensorManager does not support "
219 "dynamic tensor"
220 << '\n';
221 throw;
222 }
223 }
224 assert(ir::convertShape(src_tensor->getShape(), permute_type) == dst_tensor->getShape());
225 }
226 assert(_src_tensors.size() == _dst_tensors.size());
227 assert(_src_tensors.size() == _src_tensors_offsets.size());
228 assert(_dst_tensors.size() == _dst_tensors_offsets.size());
229 auto src_it = _src_tensors.begin();
230 auto dst_it = _dst_tensors.begin();
231 auto src_offsets_it = _src_tensors_offsets.begin();
232 auto dst_offsets_it = _dst_tensors_offsets.begin();
233 auto type_it = _permute_types.begin();
234 while (src_it != _src_tensors.end())
235 {
236 auto src = *src_it;
237 auto dst = *dst_it;
238 auto &src_offsets = *src_offsets_it;
239 auto &dst_offsets = *dst_offsets_it;
240 auto permute_type = *type_it;
241
242 if (src->total_size() == 0)
243 {
244 assert(dst->total_size() == 0);
245 }
246 else
247 {
248 if (src != dst)
249 {
250 // Conditions to run permutation with multithreading
251 // 1. The tasks for multithreathing was created
252 // 2. The tasks's size > 1
253 // 3. Both tensors are not dynamic
254 // 4. Data types of both tensors are different
255 if (_tasks_map.find(src) == _tasks_map.end() || _tasks_map.at(src).size() == 1 ||
256 src->is_dynamic() || dst->is_dynamic() ||
257 underlying_type(src->data_type()) != underlying_type(dst->data_type()))
258 {
259 permute(src, dst, src->getShape().rank(), src_offsets, dst_offsets, permute_type);
260 }
261 // If dst is subtensor, we have to use clEnqueueMapBuffer instead of clEnqueueWirteBuffer
262 else if (dst->needMemoryMap() && !dst->is_subtensor())
263 {
264 if (!src->has_padding() && !dst->has_padding() && permute_type == ir::PermuteType::SAME)
265 {
266 // This is more effective than multi-threading
267 src->access([&](backend::ITensor &) { dst->enqueueWriteBuffer(src->buffer(), false); });
268 }
269 else
270 {
271 // TODO Optimize this block in case of that padding size of dst is big.
272 _buffers_map[dst].reserve(dst->total_size());
273 auto dst_buffer = _buffers_map[dst].data();
274
275 src->access([&](backend::ITensor &) { runPermuteTasks(src, dst_buffer); });
276 dst->enqueueWriteBuffer(dst_buffer, false);
277 }
278 }
279 else if (src->needMemoryMap() && !src->is_subtensor() && !src->has_padding() &&
280 !dst->has_padding() && permute_type == ir::PermuteType::SAME)
281 {
282 // This is more effective than multi-threading
283 assert(!dst->needMemoryMap());
284 dst->access([&](backend::ITensor &) { src->enqueueReadBuffer(dst->buffer(), true); });
285 }
286 else
287 {
288 auto fn = [&](backend::ITensor &) {
289 dst->access([&](backend::ITensor &) { runPermuteTasks(src, dst->buffer()); });
290 };
291 src->access(fn);
292 }
293 }
294 }
295 src_it++;
296 dst_it++;
297 src_offsets_it++;
298 dst_offsets_it++;
299 type_it++;
300 }
301}
302
303} // namespace onert::backend::builtin::kernel
PermuteLayer(const std::vector< ITensor * > &src_tensors, const std::vector< ITensor * > &dst_tensors, const std::vector< ir::PermuteType > &types, const std::shared_ptr< ExternalContext > &external_context)
std::vector< std::vector< size_t > > _dst_tensors_offsets
std::unordered_map< const backend::ITensor *, std::vector< uint8_t > > _buffers_map
std::vector< ir::PermuteType > _permute_types
void permute(backend::ITensor *src_tensor, backend::ITensor *dst_tensor, size_t rank, std::vector< size_t > &src_offsets, std::vector< size_t > &dst_offsets, const ir::PermuteType &permute_type)
const std::type_info & underlying_type(ir::DataType type) const
std::vector< std::vector< size_t > > _src_tensors_offsets
std::vector< backend::ITensor * > _src_tensors
std::vector< backend::ITensor * > _dst_tensors
Class to represent position(offset) of tensor. Assume that the front is higher dimensional....
Definition Coordinates.h:35
size_t sizeOfDataType(DataType data_type)
Definition DataType.cc:27
Shape convertShape(const Shape &shape, const PermuteType &type)
Converts shape when its rank is 4.
Definition Shape.cc:62
PermuteType
Definition Layout.h:36
int32_t size[5]
Definition Slice.cpp:35
CLTensor src_tensor
CLTensor dst_tensor