blob: 34e4e6f8858c685f5256f5b9034eb6dbe397ebf3 [file] [log] [blame]
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001/*
Matthew Bentham758b5ba2020-03-05 23:37:48 +00002 * Copyright (c) 2016-2020 ARM Limited.
Anthony Barbier6ff3b192017-09-04 18:44:23 +01003 *
4 * SPDX-License-Identifier: MIT
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to
8 * deal in the Software without restriction, including without limitation the
9 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 * sell copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
Michalis Spyrouf4643372019-11-29 16:17:13 +000024#ifndef ARM_COMPUTE_HELPERS_H
25#define ARM_COMPUTE_HELPERS_H
Anthony Barbier6ff3b192017-09-04 18:44:23 +010026
Anthony Barbier6ff3b192017-09-04 18:44:23 +010027#include "arm_compute/core/Coordinates.h"
Georgios Pinitas583137c2017-08-31 18:12:42 +010028#include "arm_compute/core/Error.h"
Anthony Barbier6ff3b192017-09-04 18:44:23 +010029#include "arm_compute/core/IAccessWindow.h"
30#include "arm_compute/core/Steps.h"
31#include "arm_compute/core/Strides.h"
32#include "arm_compute/core/TensorShape.h"
33#include "arm_compute/core/Types.h"
34#include "arm_compute/core/Window.h"
Matthew Bentham758b5ba2020-03-05 23:37:48 +000035#include "support/MemorySupport.h"
Georgios Pinitas583137c2017-08-31 18:12:42 +010036
Anthony Barbier6ff3b192017-09-04 18:44:23 +010037#include <array>
38#include <cstddef>
39#include <cstdint>
40#include <memory>
41#include <tuple>
42#include <type_traits>
43#include <utility>
44
45namespace arm_compute
46{
47class IKernel;
48class ITensor;
49class ITensorInfo;
50
Alex Gildayc357c472018-03-21 13:54:09 +000051/** Disable bitwise operations by default */
Anthony Barbier6ff3b192017-09-04 18:44:23 +010052template <typename T>
53struct enable_bitwise_ops
54{
Alex Gildayc357c472018-03-21 13:54:09 +000055 static constexpr bool value = false; /**< Disabled */
Anthony Barbier6ff3b192017-09-04 18:44:23 +010056};
57
Alex Gildayc357c472018-03-21 13:54:09 +000058#ifndef DOXYGEN_SKIP_THIS
Anthony Barbier6ff3b192017-09-04 18:44:23 +010059template <typename T>
60typename std::enable_if<enable_bitwise_ops<T>::value, T>::type operator&(T lhs, T rhs)
61{
62 using underlying_type = typename std::underlying_type<T>::type;
63 return static_cast<T>(static_cast<underlying_type>(lhs) & static_cast<underlying_type>(rhs));
64}
Alex Gildayc357c472018-03-21 13:54:09 +000065#endif /* DOXYGEN_SKIP_THIS */
Anthony Barbier6ff3b192017-09-04 18:44:23 +010066
Michele Di Giorgiob8fc60f2018-04-25 11:58:07 +010067/** Helper function to create and return a unique_ptr pointed to a CL/GLES kernel object
68 * It also calls the kernel's configuration.
69 *
70 * @param[in] args All the arguments that need pass to kernel's configuration.
71 *
72 * @return A unique pointer pointed to a CL/GLES kernel object
73 */
74template <typename Kernel, typename... T>
75std::unique_ptr<Kernel> create_configure_kernel(T &&... args)
76{
77 std::unique_ptr<Kernel> k = arm_compute::support::cpp14::make_unique<Kernel>();
78 k->configure(std::forward<T>(args)...);
79 return k;
80}
81
82/** Helper function to create and return a unique_ptr pointed to a CL/GLES kernel object
83 *
84 * @return A unique pointer pointed to a Kernel kernel object
85 */
86template <typename Kernel>
87std::unique_ptr<Kernel> create_kernel()
88{
89 std::unique_ptr<Kernel> k = arm_compute::support::cpp14::make_unique<Kernel>();
90 return k;
91}
92
Anthony Barbier6ff3b192017-09-04 18:44:23 +010093namespace traits
94{
95/** Check if a type T is contained in a tuple Tuple of types */
96template <typename T, typename Tuple>
97struct is_contained;
98
99template <typename T>
100struct is_contained<T, std::tuple<>> : std::false_type
101{
102};
103
104template <typename T, typename... Ts>
105struct is_contained<T, std::tuple<T, Ts...>> : std::true_type
106{
107};
108
109template <typename T, typename U, typename... Ts>
110struct is_contained<T, std::tuple<U, Ts...>> : is_contained<T, std::tuple<Ts...>>
111{
112};
113}
114
115/** Computes bilinear interpolation using the pointer to the top-left pixel and the pixel's distance between
Georgios Pinitas583137c2017-08-31 18:12:42 +0100116 * the real coordinates and the smallest following integer coordinates. Input must be in single channel format.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100117 *
Georgios Pinitas583137c2017-08-31 18:12:42 +0100118 * @param[in] pixel_ptr Pointer to the top-left pixel value of a single channel input.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100119 * @param[in] stride Stride to access the bottom-left and bottom-right pixel values
120 * @param[in] dx Pixel's distance between the X real coordinate and the smallest X following integer
121 * @param[in] dy Pixel's distance between the Y real coordinate and the smallest Y following integer
122 *
123 * @note dx and dy must be in the range [0, 1.0]
124 *
125 * @return The bilinear interpolated pixel value
126 */
Georgios Pinitas583137c2017-08-31 18:12:42 +0100127template <typename T>
128inline T delta_bilinear_c1(const T *pixel_ptr, size_t stride, float dx, float dy)
129{
130 ARM_COMPUTE_ERROR_ON(pixel_ptr == nullptr);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100131
Georgios Pinitas583137c2017-08-31 18:12:42 +0100132 const float dx1 = 1.0f - dx;
133 const float dy1 = 1.0f - dy;
134
135 const T a00 = *pixel_ptr;
136 const T a01 = *(pixel_ptr + 1);
137 const T a10 = *(pixel_ptr + stride);
138 const T a11 = *(pixel_ptr + stride + 1);
139
140 const float w1 = dx1 * dy1;
141 const float w2 = dx * dy1;
142 const float w3 = dx1 * dy;
143 const float w4 = dx * dy;
144
145 return static_cast<T>(a00 * w1 + a01 * w2 + a10 * w3 + a11 * w4);
146}
147
Vidhya Sudhan Loganathan3ac2f3a2019-01-17 15:16:19 +0000148/** Computes bilinear interpolation for quantized input and output, using the pointer to the top-left pixel and the pixel's distance between
149 * the real coordinates and the smallest following integer coordinates. Input must be quantized and in single channel format.
150 *
151 * @param[in] pixel_ptr Pointer to the top-left pixel value of a single channel input.
152 * @param[in] stride Stride to access the bottom-left and bottom-right pixel values
153 * @param[in] dx Pixel's distance between the X real coordinate and the smallest X following integer
154 * @param[in] dy Pixel's distance between the Y real coordinate and the smallest Y following integer
155 * @param[in] iq_info Input QuantizationInfo
156 * @param[in] oq_info Output QuantizationInfo
157 *
158 * @note dx and dy must be in the range [0, 1.0]
159 *
160 * @return The bilinear interpolated pixel value
161 */
Georgios Pinitas4c5469b2019-05-21 13:32:43 +0100162inline uint8_t delta_bilinear_c1_quantized(const uint8_t *pixel_ptr, size_t stride, float dx, float dy, UniformQuantizationInfo iq_info, UniformQuantizationInfo oq_info)
Vidhya Sudhan Loganathan3ac2f3a2019-01-17 15:16:19 +0000163{
164 ARM_COMPUTE_ERROR_ON(pixel_ptr == nullptr);
165
166 const float dx1 = 1.0f - dx;
167 const float dy1 = 1.0f - dy;
168
Georgios Pinitas4c5469b2019-05-21 13:32:43 +0100169 const float a00 = dequantize_qasymm8(*pixel_ptr, iq_info);
170 const float a01 = dequantize_qasymm8(*(pixel_ptr + 1), iq_info);
171 const float a10 = dequantize_qasymm8(*(pixel_ptr + stride), iq_info);
172 const float a11 = dequantize_qasymm8(*(pixel_ptr + stride + 1), iq_info);
Vidhya Sudhan Loganathan3ac2f3a2019-01-17 15:16:19 +0000173
174 const float w1 = dx1 * dy1;
175 const float w2 = dx * dy1;
176 const float w3 = dx1 * dy;
177 const float w4 = dx * dy;
178 float res = a00 * w1 + a01 * w2 + a10 * w3 + a11 * w4;
Georgios Pinitas4c5469b2019-05-21 13:32:43 +0100179 return static_cast<uint8_t>(quantize_qasymm8(res, oq_info));
Vidhya Sudhan Loganathan3ac2f3a2019-01-17 15:16:19 +0000180}
181
Anthony Barbier9a33b542017-12-12 22:08:59 +0000182/** Computes linear interpolation using the pointer to the top pixel and the pixel's distance between
183 * the real coordinates and the smallest following integer coordinates. Input must be in single channel format.
184 *
185 * @param[in] pixel_ptr Pointer to the top pixel value of a single channel input.
186 * @param[in] stride Stride to access the bottom pixel value
187 * @param[in] dy Pixel's distance between the Y real coordinate and the smallest Y following integer
188 *
189 * @note dy must be in the range [0, 1.0]
190 *
191 * @return The linear interpolated pixel value
192 */
193template <typename T>
194inline T delta_linear_c1_y(const T *pixel_ptr, size_t stride, float dy)
195{
196 ARM_COMPUTE_ERROR_ON(pixel_ptr == nullptr);
197
198 const float dy1 = 1.0f - dy;
199
200 const T a00 = *pixel_ptr;
201 const T a10 = *(pixel_ptr + stride);
202
203 const float w1 = dy1;
204 const float w3 = dy;
205
206 return static_cast<T>(a00 * w1 + a10 * w3);
207}
208/** Computes linear interpolation using the pointer to the left pixel and the pixel's distance between
209 * the real coordinates and the smallest following integer coordinates. Input must be in single channel format.
210 *
211 * @param[in] pixel_ptr Pointer to the left pixel value of a single channel input.
212 * @param[in] dx Pixel's distance between the X real coordinate and the smallest X following integer
213 *
214 * @note dx must be in the range [0, 1.0]
215 *
216 * @return The linear interpolated pixel value
217 */
218template <typename T>
219inline T delta_linear_c1_x(const T *pixel_ptr, float dx)
220{
221 ARM_COMPUTE_ERROR_ON(pixel_ptr == nullptr);
222
223 const T a00 = *pixel_ptr;
224 const T a01 = *(pixel_ptr + 1);
225
226 const float dx1 = 1.0f - dx;
227
228 const float w1 = dx1;
229 const float w2 = dx;
230
231 return static_cast<T>(a00 * w1 + a01 * w2);
232}
Georgios Pinitas583137c2017-08-31 18:12:42 +0100233/** Return the pixel at (x,y) using bilinear interpolation.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100234 *
235 * @warning Only works if the iterator was created with an IImage
236 *
Georgios Pinitas583137c2017-08-31 18:12:42 +0100237 * @param[in] first_pixel_ptr Pointer to the first pixel of a single channel input.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100238 * @param[in] stride Stride in bytes of the image;
239 * @param[in] x X position of the wanted pixel
240 * @param[in] y Y position of the wanted pixel
241 *
242 * @return The pixel at (x, y) using bilinear interpolation.
243 */
Georgios Pinitas583137c2017-08-31 18:12:42 +0100244template <typename T>
245inline T pixel_bilinear_c1(const T *first_pixel_ptr, size_t stride, float x, float y)
246{
247 ARM_COMPUTE_ERROR_ON(first_pixel_ptr == nullptr);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100248
Georgios Pinitas583137c2017-08-31 18:12:42 +0100249 const int32_t xi = std::floor(x);
250 const int32_t yi = std::floor(y);
251
252 const float dx = x - xi;
253 const float dy = y - yi;
254
255 return delta_bilinear_c1(first_pixel_ptr + xi + yi * stride, stride, dx, dy);
256}
257
258/** Return the pixel at (x,y) using bilinear interpolation by clamping when out of borders. The image must be single channel input
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100259 *
260 * @warning Only works if the iterator was created with an IImage
261 *
Georgios Pinitas583137c2017-08-31 18:12:42 +0100262 * @param[in] first_pixel_ptr Pointer to the first pixel of a single channel image.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100263 * @param[in] stride Stride in bytes of the image
264 * @param[in] width Width of the image
265 * @param[in] height Height of the image
266 * @param[in] x X position of the wanted pixel
267 * @param[in] y Y position of the wanted pixel
268 *
269 * @return The pixel at (x, y) using bilinear interpolation.
270 */
Georgios Pinitas583137c2017-08-31 18:12:42 +0100271template <typename T>
272inline uint8_t pixel_bilinear_c1_clamp(const T *first_pixel_ptr, size_t stride, size_t width, size_t height, float x, float y)
273{
274 ARM_COMPUTE_ERROR_ON(first_pixel_ptr == nullptr);
275
276 x = std::max(-1.f, std::min(x, static_cast<float>(width)));
277 y = std::max(-1.f, std::min(y, static_cast<float>(height)));
278
279 const float xi = std::floor(x);
280 const float yi = std::floor(y);
281
282 const float dx = x - xi;
283 const float dy = y - yi;
284
Anthony Barbier9a33b542017-12-12 22:08:59 +0000285 if(dx == 0.0f)
286 {
287 if(dy == 0.0f)
288 {
289 return static_cast<T>(first_pixel_ptr[static_cast<int32_t>(xi) + static_cast<int32_t>(yi) * stride]);
290 }
291 return delta_linear_c1_y(first_pixel_ptr + static_cast<int32_t>(xi) + static_cast<int32_t>(yi) * stride, stride, dy);
292 }
293 if(dy == 0.0f)
294 {
295 return delta_linear_c1_x(first_pixel_ptr + static_cast<int32_t>(xi) + static_cast<int32_t>(yi) * stride, dx);
296 }
Georgios Pinitas583137c2017-08-31 18:12:42 +0100297 return delta_bilinear_c1(first_pixel_ptr + static_cast<int32_t>(xi) + static_cast<int32_t>(yi) * stride, stride, dx, dy);
298}
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100299
300/** Return the pixel at (x,y) using area interpolation by clamping when out of borders. The image must be single channel U8
301 *
302 * @note The interpolation area depends on the width and height ration of the input and output images
303 * @note Currently average of the contributing pixels is calculated
304 *
305 * @param[in] first_pixel_ptr Pointer to the first pixel of a single channel U8 image.
306 * @param[in] stride Stride in bytes of the image
307 * @param[in] width Width of the image
308 * @param[in] height Height of the image
309 * @param[in] wr Width ratio among the input image width and output image width.
310 * @param[in] hr Height ratio among the input image height and output image height.
311 * @param[in] x X position of the wanted pixel
312 * @param[in] y Y position of the wanted pixel
313 *
314 * @return The pixel at (x, y) using area interpolation.
315 */
316inline uint8_t pixel_area_c1u8_clamp(const uint8_t *first_pixel_ptr, size_t stride, size_t width, size_t height, float wr, float hr, int x, int y);
317
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100318/** Iterator updated by @ref execute_window_loop for each window element */
319class Iterator
320{
321public:
322 /** Default constructor to create an empty iterator */
323 constexpr Iterator();
324 /** Create a container iterator for the metadata and allocation contained in the ITensor
325 *
326 * @param[in] tensor The tensor to associate to the iterator.
327 * @param[in] window The window which will be used to iterate over the tensor.
328 */
329 Iterator(const ITensor *tensor, const Window &window);
330
331 /** Increment the iterator along the specified dimension of the step value associated to the dimension.
332 *
333 * @warning It is the caller's responsibility to call increment(dimension+1) when reaching the end of a dimension, the iterator will not check for overflow.
334 *
335 * @note When incrementing a dimension 'n' the coordinates of all the dimensions in the range (0,n-1) are reset. For example if you iterate over a 2D image, everytime you change row (dimension 1), the iterator for the width (dimension 0) is reset to its start.
336 *
337 * @param[in] dimension Dimension to increment
338 */
339 void increment(size_t dimension);
340
341 /** Return the offset in bytes from the first element to the current position of the iterator
342 *
343 * @return The current position of the iterator in bytes relative to the first element.
344 */
345 constexpr int offset() const;
346
347 /** Return a pointer to the current pixel.
348 *
349 * @warning Only works if the iterator was created with an ITensor.
350 *
351 * @return equivalent to buffer() + offset()
352 */
353 constexpr uint8_t *ptr() const;
354
355 /** Move the iterator back to the beginning of the specified dimension.
356 *
357 * @param[in] dimension Dimension to reset
358 */
359 void reset(size_t dimension);
360
361private:
362 uint8_t *_ptr;
363
364 class Dimension
365 {
366 public:
367 constexpr Dimension()
368 : _dim_start(0), _stride(0)
369 {
370 }
371
372 int _dim_start;
373 int _stride;
374 };
375
376 std::array<Dimension, Coordinates::num_max_dimensions> _dims;
377};
378
379/** Iterate through the passed window, automatically adjusting the iterators and calling the lambda_functino for each element.
380 * It passes the x and y positions to the lambda_function for each iteration
381 *
382 * @param[in] w Window to iterate through.
383 * @param[in] lambda_function The function of type void(function)( const Coordinates & id ) to call at each iteration.
384 * Where id represents the absolute coordinates of the item to process.
385 * @param[in,out] iterators Tensor iterators which will be updated by this function before calling lambda_function.
386 */
387template <typename L, typename... Ts>
388inline void execute_window_loop(const Window &w, L &&lambda_function, Ts &&... iterators);
389
390/** Update window and padding size for each of the access patterns.
391 *
392 * First the window size is reduced based on all access patterns that are not
393 * allowed to modify the padding of the underlying tensor. Then the padding of
394 * the remaining tensors is increased to match the window.
395 *
396 * @param[in] win Window that is used by the kernel.
397 * @param[in] patterns Access patterns used to calculate the final window and padding.
398 *
399 * @return True if the window has been changed. Changes to the padding do not
400 * influence the returned value.
401 */
402template <typename... Ts>
403bool update_window_and_padding(Window &win, Ts &&... patterns)
404{
405 bool window_changed = false;
406
Diego Lopez Recas490b3d82017-12-19 15:42:25 +0000407 utility::for_each([&](const IAccessWindow & w)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100408 {
409 window_changed |= w.update_window_if_needed(win);
410 },
411 patterns...);
412
413 bool padding_changed = false;
414
Diego Lopez Recas35ceeb22017-12-04 18:56:10 +0000415 utility::for_each([&](IAccessWindow & w)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100416 {
417 padding_changed |= w.update_padding_if_needed(win);
418 },
419 patterns...);
420
421 return window_changed;
422}
423
424/** Calculate the maximum window for a given tensor shape and border setting
425 *
Diego Lopez Recasbcbc9702017-12-18 11:28:27 +0000426 * @param[in] valid_region Valid region object defining the shape of the tensor space for which the window is created.
427 * @param[in] steps (Optional) Number of elements processed for each step.
428 * @param[in] skip_border (Optional) If true exclude the border region from the window.
429 * @param[in] border_size (Optional) Border size.
430 *
431 * @return The maximum window the kernel can be executed on.
432 */
433Window calculate_max_window(const ValidRegion &valid_region, const Steps &steps = Steps(), bool skip_border = false, BorderSize border_size = BorderSize());
434
435/** Calculate the maximum window for a given tensor shape and border setting
436 *
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100437 * @param[in] info Tensor info object defining the shape of the object for which the window is created.
438 * @param[in] steps (Optional) Number of elements processed for each step.
439 * @param[in] skip_border (Optional) If true exclude the border region from the window.
440 * @param[in] border_size (Optional) Border size.
441 *
442 * @return The maximum window the kernel can be executed on.
443 */
Diego Lopez Recasbcbc9702017-12-18 11:28:27 +0000444inline Window calculate_max_window(const ITensorInfo &info, const Steps &steps = Steps(), bool skip_border = false, BorderSize border_size = BorderSize())
445{
446 return calculate_max_window(info.valid_region(), steps, skip_border, border_size);
447}
448
449/** Calculate the maximum window used by a horizontal kernel for a given tensor shape and border setting
450 *
451 * @param[in] valid_region Valid region object defining the shape of the tensor space for which the window is created.
452 * @param[in] steps (Optional) Number of elements processed for each step.
453 * @param[in] skip_border (Optional) If true exclude the border region from the window.
454 * @param[in] border_size (Optional) Border size. The border region will be excluded from the window.
455 *
456 * @return The maximum window the kernel can be executed on.
457 */
458Window calculate_max_window_horizontal(const ValidRegion &valid_region, const Steps &steps = Steps(), bool skip_border = false, BorderSize border_size = BorderSize());
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100459
460/** Calculate the maximum window used by a horizontal kernel for a given tensor shape and border setting
461 *
462 * @param[in] info Tensor info object defining the shape of the object for which the window is created.
463 * @param[in] steps (Optional) Number of elements processed for each step.
464 * @param[in] skip_border (Optional) If true exclude the border region from the window.
Diego Lopez Recasbcbc9702017-12-18 11:28:27 +0000465 * @param[in] border_size (Optional) Border size.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100466 *
467 * @return The maximum window the kernel can be executed on.
468 */
Diego Lopez Recasbcbc9702017-12-18 11:28:27 +0000469inline Window calculate_max_window_horizontal(const ITensorInfo &info, const Steps &steps = Steps(), bool skip_border = false, BorderSize border_size = BorderSize())
470{
471 return calculate_max_window_horizontal(info.valid_region(), steps, skip_border, border_size);
472}
473
474/** Calculate the maximum window for a given tensor shape and border setting. The window will also includes the border.
475 *
476 * @param[in] valid_region Valid region object defining the shape of the tensor space for which the window is created.
477 * @param[in] steps (Optional) Number of elements processed for each step.
478 * @param[in] border_size (Optional) Border size. The border region will be included in the window.
479 *
480 * @return The maximum window the kernel can be executed on.
481 */
482Window calculate_max_enlarged_window(const ValidRegion &valid_region, const Steps &steps = Steps(), BorderSize border_size = BorderSize());
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100483
484/** Calculate the maximum window for a given tensor shape and border setting. The window will also includes the border.
485 *
486 * @param[in] info Tensor info object defining the shape of the object for which the window is created.
487 * @param[in] steps (Optional) Number of elements processed for each step.
488 * @param[in] border_size (Optional) Border size. The border region will be included in the window.
489 *
490 * @return The maximum window the kernel can be executed on.
491 */
Diego Lopez Recasbcbc9702017-12-18 11:28:27 +0000492inline Window calculate_max_enlarged_window(const ITensorInfo &info, const Steps &steps = Steps(), BorderSize border_size = BorderSize())
493{
494 return calculate_max_enlarged_window(info.valid_region(), steps, border_size);
495}
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100496
497/** Intersect multiple valid regions.
498 *
499 * @param[in] regions Valid regions.
500 *
501 * @return Intersection of all regions.
502 */
503template <typename... Ts>
Diego Lopez Recas490b3d82017-12-19 15:42:25 +0000504ValidRegion intersect_valid_regions(const Ts &... regions)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100505{
506 auto intersect = [](const ValidRegion & r1, const ValidRegion & r2) -> ValidRegion
507 {
508 ValidRegion region;
509
510 for(size_t d = 0; d < std::min(r1.anchor.num_dimensions(), r2.anchor.num_dimensions()); ++d)
511 {
512 region.anchor.set(d, std::max(r1.anchor[d], r2.anchor[d]));
513 }
514
515 for(size_t d = 0; d < std::min(r1.shape.num_dimensions(), r2.shape.num_dimensions()); ++d)
516 {
517 region.shape.set(d, std::min(r1.shape[d], r2.shape[d]));
518 }
519
520 return region;
521 };
522
Diego Lopez Recas490b3d82017-12-19 15:42:25 +0000523 return utility::foldl(intersect, regions...);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100524}
525
526/** Create a strides object based on the provided strides and the tensor dimensions.
527 *
528 * @param[in] info Tensor info object providing the shape of the tensor for unspecified strides.
529 * @param[in] stride_x Stride to be used in X dimension (in bytes).
530 * @param[in] fixed_strides Strides to be used in higher dimensions starting at Y (in bytes).
531 *
532 * @return Strides object based on the specified strides. Missing strides are
533 * calculated based on the tensor shape and the strides of lower dimensions.
534 */
535template <typename T, typename... Ts>
536inline Strides compute_strides(const ITensorInfo &info, T stride_x, Ts &&... fixed_strides)
537{
538 const TensorShape &shape = info.tensor_shape();
539
540 // Create strides object
541 Strides strides(stride_x, fixed_strides...);
542
543 for(size_t i = 1 + sizeof...(Ts); i < info.num_dimensions(); ++i)
544 {
545 strides.set(i, shape[i - 1] * strides[i - 1]);
546 }
547
548 return strides;
549}
550
551/** Create a strides object based on the tensor dimensions.
552 *
553 * @param[in] info Tensor info object used to compute the strides.
554 *
555 * @return Strides object based on element size and tensor shape.
556 */
557template <typename... Ts>
558inline Strides compute_strides(const ITensorInfo &info)
559{
560 return compute_strides(info, info.element_size());
561}
562
Georgios Pinitas8795ffb2017-12-01 16:13:40 +0000563/** Permutes given Dimensions according to a permutation vector
564 *
565 * @warning Validity of permutation is not checked
566 *
567 * @param[in, out] dimensions Dimensions to permute
568 * @param[in] perm Permutation vector
569 */
570template <typename T>
571inline void permute(Dimensions<T> &dimensions, const PermutationVector &perm)
572{
Georgios Pinitas69af6cf2018-02-14 19:23:44 +0000573 auto dimensions_copy = utility::make_array<Dimensions<T>::num_max_dimensions>(dimensions.begin(), dimensions.end());
Georgios Pinitas8795ffb2017-12-01 16:13:40 +0000574 for(unsigned int i = 0; i < perm.num_dimensions(); ++i)
575 {
Georgios Pinitas69af6cf2018-02-14 19:23:44 +0000576 T dimension_val = (perm[i] < dimensions.num_dimensions()) ? dimensions_copy[perm[i]] : 0;
577 dimensions.set(i, dimension_val);
578 }
579}
580
581/** Permutes given TensorShape according to a permutation vector
582 *
583 * @warning Validity of permutation is not checked
584 *
585 * @param[in, out] shape Shape to permute
586 * @param[in] perm Permutation vector
587 */
588inline void permute(TensorShape &shape, const PermutationVector &perm)
589{
Giorgio Arena563494c2018-04-30 17:29:41 +0100590 TensorShape shape_copy = shape;
Georgios Pinitas69af6cf2018-02-14 19:23:44 +0000591 for(unsigned int i = 0; i < perm.num_dimensions(); ++i)
592 {
593 size_t dimension_val = (perm[i] < shape.num_dimensions()) ? shape_copy[perm[i]] : 1;
Giorgio Arena563494c2018-04-30 17:29:41 +0100594 shape.set(i, dimension_val, false); // Avoid changes in _num_dimension
Georgios Pinitas8795ffb2017-12-01 16:13:40 +0000595 }
596}
597
Vidhya Sudhan Loganathan7485d5a2018-07-04 09:34:00 +0100598/** Auto initialize the tensor info (shape, number of channels and data type) if the current assignment is empty.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100599 *
Vidhya Sudhan Loganathan7485d5a2018-07-04 09:34:00 +0100600 * @param[in,out] info Tensor info used to check and assign.
601 * @param[in] shape New shape.
602 * @param[in] num_channels New number of channels.
603 * @param[in] data_type New data type
604 * @param[in] quantization_info (Optional) New quantization info
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100605 *
606 * @return True if the tensor info has been initialized
607 */
Georgios Pinitas05078ec2017-11-02 13:06:59 +0000608bool auto_init_if_empty(ITensorInfo &info,
609 const TensorShape &shape,
610 int num_channels, DataType data_type,
Georgios Pinitas05078ec2017-11-02 13:06:59 +0000611 QuantizationInfo quantization_info = QuantizationInfo());
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100612
Georgios Pinitas283c1792017-11-10 18:14:06 +0000613/** Auto initialize the tensor info using another tensor info.
614 *
615 * @param info_sink Tensor info used to check and assign
616 * @param info_source Tensor info used to assign
617 *
618 * @return True if the tensor info has been initialized
619 */
Pablo Palmiera2b89ca2017-10-05 15:01:34 +0100620bool auto_init_if_empty(ITensorInfo &info_sink, const ITensorInfo &info_source);
Georgios Pinitas283c1792017-11-10 18:14:06 +0000621
Alex Gildayc357c472018-03-21 13:54:09 +0000622/** Set the shape to the specified value if the current assignment is empty.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100623 *
624 * @param[in,out] info Tensor info used to check and assign.
625 * @param[in] shape New shape.
626 *
627 * @return True if the shape has been changed.
628 */
629bool set_shape_if_empty(ITensorInfo &info, const TensorShape &shape);
630
Alex Gildayc357c472018-03-21 13:54:09 +0000631/** Set the format, data type and number of channels to the specified value if
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100632 * the current data type is unknown.
633 *
634 * @param[in,out] info Tensor info used to check and assign.
635 * @param[in] format New format.
636 *
637 * @return True if the format has been changed.
638 */
639bool set_format_if_unknown(ITensorInfo &info, Format format);
640
Alex Gildayc357c472018-03-21 13:54:09 +0000641/** Set the data type and number of channels to the specified value if
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100642 * the current data type is unknown.
643 *
644 * @param[in,out] info Tensor info used to check and assign.
645 * @param[in] data_type New data type.
646 *
647 * @return True if the data type has been changed.
648 */
649bool set_data_type_if_unknown(ITensorInfo &info, DataType data_type);
650
Alex Gildayc357c472018-03-21 13:54:09 +0000651/** Set the data layout to the specified value if
Isabella Gottardid17a6772018-02-27 17:41:55 +0000652 * the current data layout is unknown.
653 *
654 * @param[in,out] info Tensor info used to check and assign.
655 * @param[in] data_layout New data layout.
656 *
657 * @return True if the data type has been changed.
658 */
659bool set_data_layout_if_unknown(ITensorInfo &info, DataLayout data_layout);
660
Alex Gildayc357c472018-03-21 13:54:09 +0000661/** Set the quantization info to the specified value if
Georgios Pinitas05078ec2017-11-02 13:06:59 +0000662 * the current quantization info is empty and the data type of asymmetric quantized type
663 *
664 * @param[in,out] info Tensor info used to check and assign.
665 * @param[in] quantization_info Quantization info
666 *
667 * @return True if the quantization info has been changed.
668 */
669bool set_quantization_info_if_empty(ITensorInfo &info, QuantizationInfo quantization_info);
670
Isabella Gottardi1fab09f2017-07-13 15:55:57 +0100671/** Helper function to calculate the Valid Region for Scale.
672 *
Diego Lopez Recas00854292018-02-22 13:08:01 +0000673 * @param[in] src_info Input tensor info used to check.
674 * @param[in] dst_shape Shape of the output.
675 * @param[in] interpolate_policy Interpolation policy.
676 * @param[in] sampling_policy Sampling policy.
677 * @param[in] border_undefined True if the border is undefined.
Isabella Gottardi1fab09f2017-07-13 15:55:57 +0100678 *
Diego Lopez Recas00854292018-02-22 13:08:01 +0000679 * @return The corresponding valid region
Isabella Gottardi1fab09f2017-07-13 15:55:57 +0100680 */
Diego Lopez Recas00854292018-02-22 13:08:01 +0000681ValidRegion calculate_valid_region_scale(const ITensorInfo &src_info, const TensorShape &dst_shape,
682 InterpolationPolicy interpolate_policy, SamplingPolicy sampling_policy, bool border_undefined);
Georgios Pinitas05078ec2017-11-02 13:06:59 +0000683
Georgios Pinitas5ee66ea2017-09-07 17:29:16 +0100684/** Convert a linear index into n-dimensional coordinates.
685 *
686 * @param[in] shape Shape of the n-dimensional tensor.
687 * @param[in] index Linear index specifying the i-th element.
688 *
689 * @return n-dimensional coordinates.
690 */
691inline Coordinates index2coords(const TensorShape &shape, int index);
Georgios Pinitas05078ec2017-11-02 13:06:59 +0000692
Georgios Pinitas5ee66ea2017-09-07 17:29:16 +0100693/** Convert n-dimensional coordinates into a linear index.
694 *
695 * @param[in] shape Shape of the n-dimensional tensor.
696 * @param[in] coord N-dimensional coordinates.
697 *
698 * @return linead index
699 */
700inline int coords2index(const TensorShape &shape, const Coordinates &coord);
Isabella Gottardid17a6772018-02-27 17:41:55 +0000701
Alex Gildayc357c472018-03-21 13:54:09 +0000702/** Get the index of the given dimension.
Isabella Gottardid17a6772018-02-27 17:41:55 +0000703 *
Alex Gildayc357c472018-03-21 13:54:09 +0000704 * @param[in] data_layout The data layout.
705 * @param[in] data_layout_dimension The dimension which this index is requested for.
Isabella Gottardid17a6772018-02-27 17:41:55 +0000706 *
707 * @return The int conversion of the requested data layout index.
708 */
Isabella Gottardid56e7702018-02-28 14:29:36 +0000709inline size_t get_data_layout_dimension_index(const DataLayout data_layout, const DataLayoutDimension data_layout_dimension);
Georgios Pinitase2220552018-07-20 13:23:44 +0100710
Usama Arif8cf8c112019-03-14 15:36:54 +0000711/** Get the DataLayoutDimension of a given index and layout.
712 *
713 * @param[in] data_layout The data layout.
714 * @param[in] index The data layout index.
715 *
716 * @return The dimension which this index is requested for.
717 */
718inline DataLayoutDimension get_index_data_layout_dimension(const DataLayout data_layout, const size_t index);
719
Georgios Pinitase2220552018-07-20 13:23:44 +0100720/** Calculate the normalization dimension index for a given normalization type
721 *
722 * @param[in] layout Data layout of the input and output tensor
723 * @param[in] info Normalization info
724 *
725 * @return Normalization dimension index
726 */
727inline unsigned int get_normalization_dimension_index(DataLayout layout, const NormalizationLayerInfo &info)
728{
729 const unsigned int width_idx = get_data_layout_dimension_index(layout, DataLayoutDimension::WIDTH);
730 const unsigned int channel_idx = get_data_layout_dimension_index(layout, DataLayoutDimension::CHANNEL);
731
732 return info.is_in_map() ? width_idx : channel_idx;
733}
734
735/** Calculate the number of output tiles required by Winograd Convolution layer. This utility function can be used by the Winograd input transform
736 * to know the number of tiles on the x and y direction
737 *
738 * @param[in] in_dims Spatial dimensions of the input tensor of convolution layer
739 * @param[in] kernel_size Kernel size
740 * @param[in] output_tile_size Size of a single output tile
741 * @param[in] conv_info Convolution info (i.e. pad, stride,...)
742 *
743 * @return the number of output tiles along the x and y directions of size "output_tile_size"
744 */
745inline Size2D compute_winograd_convolution_tiles(const Size2D &in_dims, const Size2D &kernel_size, const Size2D &output_tile_size, const PadStrideInfo &conv_info)
746{
747 int num_tiles_x = std::ceil((in_dims.width - (kernel_size.width - 1) + conv_info.pad_left() + conv_info.pad_right()) / static_cast<float>(output_tile_size.width));
748 int num_tiles_y = std::ceil((in_dims.height - (kernel_size.height - 1) + conv_info.pad_top() + conv_info.pad_bottom()) / static_cast<float>(output_tile_size.height));
749
750 // Clamp in case we provide paddings but we have 1D convolution
751 num_tiles_x = std::min(num_tiles_x, static_cast<int>(in_dims.width));
752 num_tiles_y = std::min(num_tiles_y, static_cast<int>(in_dims.height));
753
754 return Size2D(num_tiles_x, num_tiles_y);
755}
756
Gian Marco Iodice8aa985e2018-11-27 15:58:08 +0000757/** Wrap-around a number within the range 0 <= x < m
758 *
759 * @param[in] x Input value
760 * @param[in] m Range
761 *
762 * @return the wrapped-around number
763 */
764template <typename T>
765inline T wrap_around(T x, T m)
766{
767 return x >= 0 ? x % m : (x % m + m) % m;
768}
Gian Marco Iodiceb0c50372019-03-15 10:13:05 +0000769
Pablo Tello93975152019-11-08 13:47:53 +0000770/** Convert negative coordinates to positive in the range [0, num_dims_input]
771 *
772 * @param[out] coords Array of coordinates to be converted.
773 * @param[in] max_value Maximum value to be used when wrapping the negative values in coords
774 */
775inline Coordinates &convert_negative_axis(Coordinates &coords, int max_value)
776{
777 for(unsigned int i = 0; i < coords.num_dimensions(); ++i)
778 {
779 coords[i] = wrap_around(coords[i], max_value);
780 }
781 return coords;
782}
783
Gian Marco Iodiceb0c50372019-03-15 10:13:05 +0000784/** Given an integer value, this function returns the next power of two
785 *
786 * @param[in] x Input value
787 *
788 * @return the next power of two
789 */
790inline unsigned int get_next_power_two(unsigned int x)
791{
792 // Decrement by 1
793 x--;
794
795 // Shift right by 1
796 x |= x >> 1u;
797 // Shift right by 2
798 x |= x >> 2u;
799 // Shift right by 4
800 x |= x >> 4u;
801 // Shift right by 8
802 x |= x >> 8u;
803 // Shift right by 16
804 x |= x >> 16u;
805
806 // Increment by 1
807 x++;
808
809 return x;
810}
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100811} // namespace arm_compute
812
813#include "arm_compute/core/Helpers.inl"
Michalis Spyrouf4643372019-11-29 16:17:13 +0000814#endif /*ARM_COMPUTE_HELPERS_H */