blob: 1be24e1841ba092e4e90ab0b9fdb7de03bc92a62 [file] [log] [blame]
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001/*
2 * Copyright (c) 2016, 2017 ARM Limited.
3 *
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 */
24#ifndef __ARM_COMPUTE_HELPERS_H__
25#define __ARM_COMPUTE_HELPERS_H__
26
27#include "arm_compute/core/CL/CLTypes.h"
28#include "arm_compute/core/Coordinates.h"
Georgios Pinitas583137c2017-08-31 18:12:42 +010029#include "arm_compute/core/Error.h"
Anthony Barbier6ff3b192017-09-04 18:44:23 +010030#include "arm_compute/core/IAccessWindow.h"
31#include "arm_compute/core/Steps.h"
32#include "arm_compute/core/Strides.h"
33#include "arm_compute/core/TensorShape.h"
34#include "arm_compute/core/Types.h"
35#include "arm_compute/core/Window.h"
Georgios Pinitas8795ffb2017-12-01 16:13:40 +000036#include "arm_compute/core/utils/misc/utility.h"
Georgios Pinitas583137c2017-08-31 18:12:42 +010037
Anthony Barbier6ff3b192017-09-04 18:44:23 +010038#include <array>
39#include <cstddef>
40#include <cstdint>
41#include <memory>
42#include <tuple>
43#include <type_traits>
44#include <utility>
45
46namespace arm_compute
47{
48class IKernel;
49class ITensor;
50class ITensorInfo;
51
Anthony Barbier6ff3b192017-09-04 18:44:23 +010052template <typename T>
53struct enable_bitwise_ops
54{
55 static constexpr bool value = false;
56};
57
58template <typename T>
59typename std::enable_if<enable_bitwise_ops<T>::value, T>::type operator&(T lhs, T rhs)
60{
61 using underlying_type = typename std::underlying_type<T>::type;
62 return static_cast<T>(static_cast<underlying_type>(lhs) & static_cast<underlying_type>(rhs));
63}
64
65namespace traits
66{
67/** Check if a type T is contained in a tuple Tuple of types */
68template <typename T, typename Tuple>
69struct is_contained;
70
71template <typename T>
72struct is_contained<T, std::tuple<>> : std::false_type
73{
74};
75
76template <typename T, typename... Ts>
77struct is_contained<T, std::tuple<T, Ts...>> : std::true_type
78{
79};
80
81template <typename T, typename U, typename... Ts>
82struct is_contained<T, std::tuple<U, Ts...>> : is_contained<T, std::tuple<Ts...>>
83{
84};
85}
86
87/** Computes bilinear interpolation using the pointer to the top-left pixel and the pixel's distance between
Georgios Pinitas583137c2017-08-31 18:12:42 +010088 * the real coordinates and the smallest following integer coordinates. Input must be in single channel format.
Anthony Barbier6ff3b192017-09-04 18:44:23 +010089 *
Georgios Pinitas583137c2017-08-31 18:12:42 +010090 * @param[in] pixel_ptr Pointer to the top-left pixel value of a single channel input.
Anthony Barbier6ff3b192017-09-04 18:44:23 +010091 * @param[in] stride Stride to access the bottom-left and bottom-right pixel values
92 * @param[in] dx Pixel's distance between the X real coordinate and the smallest X following integer
93 * @param[in] dy Pixel's distance between the Y real coordinate and the smallest Y following integer
94 *
95 * @note dx and dy must be in the range [0, 1.0]
96 *
97 * @return The bilinear interpolated pixel value
98 */
Georgios Pinitas583137c2017-08-31 18:12:42 +010099template <typename T>
100inline T delta_bilinear_c1(const T *pixel_ptr, size_t stride, float dx, float dy)
101{
102 ARM_COMPUTE_ERROR_ON(pixel_ptr == nullptr);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100103
Georgios Pinitas583137c2017-08-31 18:12:42 +0100104 const float dx1 = 1.0f - dx;
105 const float dy1 = 1.0f - dy;
106
107 const T a00 = *pixel_ptr;
108 const T a01 = *(pixel_ptr + 1);
109 const T a10 = *(pixel_ptr + stride);
110 const T a11 = *(pixel_ptr + stride + 1);
111
112 const float w1 = dx1 * dy1;
113 const float w2 = dx * dy1;
114 const float w3 = dx1 * dy;
115 const float w4 = dx * dy;
116
117 return static_cast<T>(a00 * w1 + a01 * w2 + a10 * w3 + a11 * w4);
118}
119
120/** Return the pixel at (x,y) using bilinear interpolation.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100121 *
122 * @warning Only works if the iterator was created with an IImage
123 *
Georgios Pinitas583137c2017-08-31 18:12:42 +0100124 * @param[in] first_pixel_ptr Pointer to the first pixel of a single channel input.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100125 * @param[in] stride Stride in bytes of the image;
126 * @param[in] x X position of the wanted pixel
127 * @param[in] y Y position of the wanted pixel
128 *
129 * @return The pixel at (x, y) using bilinear interpolation.
130 */
Georgios Pinitas583137c2017-08-31 18:12:42 +0100131template <typename T>
132inline T pixel_bilinear_c1(const T *first_pixel_ptr, size_t stride, float x, float y)
133{
134 ARM_COMPUTE_ERROR_ON(first_pixel_ptr == nullptr);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100135
Georgios Pinitas583137c2017-08-31 18:12:42 +0100136 const int32_t xi = std::floor(x);
137 const int32_t yi = std::floor(y);
138
139 const float dx = x - xi;
140 const float dy = y - yi;
141
142 return delta_bilinear_c1(first_pixel_ptr + xi + yi * stride, stride, dx, dy);
143}
144
145/** 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 +0100146 *
147 * @warning Only works if the iterator was created with an IImage
148 *
Georgios Pinitas583137c2017-08-31 18:12:42 +0100149 * @param[in] first_pixel_ptr Pointer to the first pixel of a single channel image.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100150 * @param[in] stride Stride in bytes of the image
151 * @param[in] width Width of the image
152 * @param[in] height Height of the image
153 * @param[in] x X position of the wanted pixel
154 * @param[in] y Y position of the wanted pixel
155 *
156 * @return The pixel at (x, y) using bilinear interpolation.
157 */
Georgios Pinitas583137c2017-08-31 18:12:42 +0100158template <typename T>
159inline uint8_t pixel_bilinear_c1_clamp(const T *first_pixel_ptr, size_t stride, size_t width, size_t height, float x, float y)
160{
161 ARM_COMPUTE_ERROR_ON(first_pixel_ptr == nullptr);
162
163 x = std::max(-1.f, std::min(x, static_cast<float>(width)));
164 y = std::max(-1.f, std::min(y, static_cast<float>(height)));
165
166 const float xi = std::floor(x);
167 const float yi = std::floor(y);
168
169 const float dx = x - xi;
170 const float dy = y - yi;
171
172 return delta_bilinear_c1(first_pixel_ptr + static_cast<int32_t>(xi) + static_cast<int32_t>(yi) * stride, stride, dx, dy);
173}
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100174
175/** Return the pixel at (x,y) using area interpolation by clamping when out of borders. The image must be single channel U8
176 *
177 * @note The interpolation area depends on the width and height ration of the input and output images
178 * @note Currently average of the contributing pixels is calculated
179 *
180 * @param[in] first_pixel_ptr Pointer to the first pixel of a single channel U8 image.
181 * @param[in] stride Stride in bytes of the image
182 * @param[in] width Width of the image
183 * @param[in] height Height of the image
184 * @param[in] wr Width ratio among the input image width and output image width.
185 * @param[in] hr Height ratio among the input image height and output image height.
186 * @param[in] x X position of the wanted pixel
187 * @param[in] y Y position of the wanted pixel
188 *
189 * @return The pixel at (x, y) using area interpolation.
190 */
191inline 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);
192
193/** Performs clamping among a lower and upper value.
194 *
195 * @param[in] n Value to clamp.
196 * @param[in] lower Lower threshold.
197 * @param[in] upper Upper threshold.
198 *
199 * @return Clamped value.
200 */
201template <typename T>
202inline T clamp(const T &n, const T &lower, const T &upper)
203{
204 return std::max(lower, std::min(n, upper));
205}
206
207/** Base case of for_each. Does nothing. */
208template <typename F>
209inline void for_each(F &&)
210{
211}
212
213/** Call the function for each of the arguments
214 *
215 * @param[in] func Function to be called
216 * @param[in] arg Argument passed to the function
217 * @param[in] args Remaining arguments
218 */
219template <typename F, typename T, typename... Ts>
220inline void for_each(F &&func, T &&arg, Ts &&... args)
221{
222 func(arg);
223 for_each(func, args...);
224}
225
226/** Base case of foldl.
227 *
228 * @return value.
229 */
230template <typename F, typename T>
231inline T foldl(F &&, const T &value)
232{
233 return value;
234}
235
236/** Base case of foldl.
237 *
238 * @return Function evaluation for value1 and value2
239 */
240template <typename F, typename T, typename U>
241inline auto foldl(F &&func, T &&value1, U &&value2) -> decltype(func(value1, value2))
242{
243 return func(value1, value2);
244}
245
246/** Fold left.
247 *
248 * @param[in] func Function to be called
249 * @param[in] initial Initial value
250 * @param[in] value Argument passed to the function
251 * @param[in] values Remaining arguments
252 */
253template <typename F, typename I, typename T, typename... Vs>
254inline I foldl(F &&func, I &&initial, T &&value, Vs &&... values)
255{
256 return foldl(std::forward<F>(func), func(std::forward<I>(initial), std::forward<T>(value)), std::forward<Vs>(values)...);
257}
258
259/** Iterator updated by @ref execute_window_loop for each window element */
260class Iterator
261{
262public:
263 /** Default constructor to create an empty iterator */
264 constexpr Iterator();
265 /** Create a container iterator for the metadata and allocation contained in the ITensor
266 *
267 * @param[in] tensor The tensor to associate to the iterator.
268 * @param[in] window The window which will be used to iterate over the tensor.
269 */
270 Iterator(const ITensor *tensor, const Window &window);
271
272 /** Increment the iterator along the specified dimension of the step value associated to the dimension.
273 *
274 * @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.
275 *
276 * @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.
277 *
278 * @param[in] dimension Dimension to increment
279 */
280 void increment(size_t dimension);
281
282 /** Return the offset in bytes from the first element to the current position of the iterator
283 *
284 * @return The current position of the iterator in bytes relative to the first element.
285 */
286 constexpr int offset() const;
287
288 /** Return a pointer to the current pixel.
289 *
290 * @warning Only works if the iterator was created with an ITensor.
291 *
292 * @return equivalent to buffer() + offset()
293 */
294 constexpr uint8_t *ptr() const;
295
296 /** Move the iterator back to the beginning of the specified dimension.
297 *
298 * @param[in] dimension Dimension to reset
299 */
300 void reset(size_t dimension);
301
302private:
303 uint8_t *_ptr;
304
305 class Dimension
306 {
307 public:
308 constexpr Dimension()
309 : _dim_start(0), _stride(0)
310 {
311 }
312
313 int _dim_start;
314 int _stride;
315 };
316
317 std::array<Dimension, Coordinates::num_max_dimensions> _dims;
318};
319
320/** Iterate through the passed window, automatically adjusting the iterators and calling the lambda_functino for each element.
321 * It passes the x and y positions to the lambda_function for each iteration
322 *
323 * @param[in] w Window to iterate through.
324 * @param[in] lambda_function The function of type void(function)( const Coordinates & id ) to call at each iteration.
325 * Where id represents the absolute coordinates of the item to process.
326 * @param[in,out] iterators Tensor iterators which will be updated by this function before calling lambda_function.
327 */
328template <typename L, typename... Ts>
329inline void execute_window_loop(const Window &w, L &&lambda_function, Ts &&... iterators);
330
331/** Update window and padding size for each of the access patterns.
332 *
333 * First the window size is reduced based on all access patterns that are not
334 * allowed to modify the padding of the underlying tensor. Then the padding of
335 * the remaining tensors is increased to match the window.
336 *
337 * @param[in] win Window that is used by the kernel.
338 * @param[in] patterns Access patterns used to calculate the final window and padding.
339 *
340 * @return True if the window has been changed. Changes to the padding do not
341 * influence the returned value.
342 */
343template <typename... Ts>
344bool update_window_and_padding(Window &win, Ts &&... patterns)
345{
346 bool window_changed = false;
347
348 for_each([&](const IAccessWindow & w)
349 {
350 window_changed |= w.update_window_if_needed(win);
351 },
352 patterns...);
353
354 bool padding_changed = false;
355
356 for_each([&](const IAccessWindow & w)
357 {
358 padding_changed |= w.update_padding_if_needed(win);
359 },
360 patterns...);
361
362 return window_changed;
363}
364
365/** Calculate the maximum window for a given tensor shape and border setting
366 *
367 * @param[in] info Tensor info object defining the shape of the object for which the window is created.
368 * @param[in] steps (Optional) Number of elements processed for each step.
369 * @param[in] skip_border (Optional) If true exclude the border region from the window.
370 * @param[in] border_size (Optional) Border size.
371 *
372 * @return The maximum window the kernel can be executed on.
373 */
374Window calculate_max_window(const ITensorInfo &info, const Steps &steps = Steps(), bool skip_border = false, BorderSize border_size = BorderSize());
375
376/** Calculate the maximum window used by a horizontal kernel for a given tensor shape and border setting
377 *
378 * @param[in] info Tensor info object defining the shape of the object for which the window is created.
379 * @param[in] steps (Optional) Number of elements processed for each step.
380 * @param[in] skip_border (Optional) If true exclude the border region from the window.
381 * @param[in] border_size (Optional) Border size. The border region will be excluded from the window.
382 *
383 * @return The maximum window the kernel can be executed on.
384 */
385Window calculate_max_window_horizontal(const ITensorInfo &info, const Steps &steps = Steps(), bool skip_border = false, BorderSize border_size = BorderSize());
386
387/** Calculate the maximum window for a given tensor shape and border setting. The window will also includes the border.
388 *
389 * @param[in] info Tensor info object defining the shape of the object for which the window is created.
390 * @param[in] steps (Optional) Number of elements processed for each step.
391 * @param[in] border_size (Optional) Border size. The border region will be included in the window.
392 *
393 * @return The maximum window the kernel can be executed on.
394 */
395Window calculate_max_enlarged_window(const ITensorInfo &info, const Steps &steps = Steps(), BorderSize border_size = BorderSize());
396
397/** Intersect multiple valid regions.
398 *
399 * @param[in] regions Valid regions.
400 *
401 * @return Intersection of all regions.
402 */
403template <typename... Ts>
404ValidRegion intersect_valid_regions(Ts &&... regions)
405{
406 auto intersect = [](const ValidRegion & r1, const ValidRegion & r2) -> ValidRegion
407 {
408 ValidRegion region;
409
410 for(size_t d = 0; d < std::min(r1.anchor.num_dimensions(), r2.anchor.num_dimensions()); ++d)
411 {
412 region.anchor.set(d, std::max(r1.anchor[d], r2.anchor[d]));
413 }
414
415 for(size_t d = 0; d < std::min(r1.shape.num_dimensions(), r2.shape.num_dimensions()); ++d)
416 {
417 region.shape.set(d, std::min(r1.shape[d], r2.shape[d]));
418 }
419
420 return region;
421 };
422
423 return foldl(intersect, std::forward<Ts>(regions)...);
424}
425
426/** Create a strides object based on the provided strides and the tensor dimensions.
427 *
428 * @param[in] info Tensor info object providing the shape of the tensor for unspecified strides.
429 * @param[in] stride_x Stride to be used in X dimension (in bytes).
430 * @param[in] fixed_strides Strides to be used in higher dimensions starting at Y (in bytes).
431 *
432 * @return Strides object based on the specified strides. Missing strides are
433 * calculated based on the tensor shape and the strides of lower dimensions.
434 */
435template <typename T, typename... Ts>
436inline Strides compute_strides(const ITensorInfo &info, T stride_x, Ts &&... fixed_strides)
437{
438 const TensorShape &shape = info.tensor_shape();
439
440 // Create strides object
441 Strides strides(stride_x, fixed_strides...);
442
443 for(size_t i = 1 + sizeof...(Ts); i < info.num_dimensions(); ++i)
444 {
445 strides.set(i, shape[i - 1] * strides[i - 1]);
446 }
447
448 return strides;
449}
450
451/** Create a strides object based on the tensor dimensions.
452 *
453 * @param[in] info Tensor info object used to compute the strides.
454 *
455 * @return Strides object based on element size and tensor shape.
456 */
457template <typename... Ts>
458inline Strides compute_strides(const ITensorInfo &info)
459{
460 return compute_strides(info, info.element_size());
461}
462
Georgios Pinitas8795ffb2017-12-01 16:13:40 +0000463/** Permutes given Dimensions according to a permutation vector
464 *
465 * @warning Validity of permutation is not checked
466 *
467 * @param[in, out] dimensions Dimensions to permute
468 * @param[in] perm Permutation vector
469 */
470template <typename T>
471inline void permute(Dimensions<T> &dimensions, const PermutationVector &perm)
472{
473 auto copy_dimensions = utility::make_array<Dimensions<T>::num_max_dimensions>(dimensions.begin(), dimensions.end());
474 for(unsigned int i = 0; i < perm.num_dimensions(); ++i)
475 {
476 dimensions[i] = copy_dimensions[perm[i]];
477 }
478}
479
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100480/* Auto initialize the tensor info (shape, number of channels, data type and fixed point position) if the current assignment is empty.
481 *
482 * @param[in,out] info Tensor info used to check and assign.
483 * @param[in] shape New shape.
484 * @param[in] num_channels New number of channels.
485 * @param[in] data_type New data type
486 * @param[in] fixed_point_position New fixed point position
Georgios Pinitas05078ec2017-11-02 13:06:59 +0000487 * @param[in] quantization_info (Optional) New quantization info
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100488 *
489 * @return True if the tensor info has been initialized
490 */
Georgios Pinitas05078ec2017-11-02 13:06:59 +0000491bool auto_init_if_empty(ITensorInfo &info,
492 const TensorShape &shape,
493 int num_channels, DataType data_type,
494 int fixed_point_position,
495 QuantizationInfo quantization_info = QuantizationInfo());
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100496
Georgios Pinitas283c1792017-11-10 18:14:06 +0000497/** Auto initialize the tensor info using another tensor info.
498 *
499 * @param info_sink Tensor info used to check and assign
500 * @param info_source Tensor info used to assign
501 *
502 * @return True if the tensor info has been initialized
503 */
504bool auto_init_if_empty(ITensorInfo &info_sink, ITensorInfo &info_source);
505
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100506/* Set the shape to the specified value if the current assignment is empty.
507 *
508 * @param[in,out] info Tensor info used to check and assign.
509 * @param[in] shape New shape.
510 *
511 * @return True if the shape has been changed.
512 */
513bool set_shape_if_empty(ITensorInfo &info, const TensorShape &shape);
514
515/* Set the format, data type and number of channels to the specified value if
516 * the current data type is unknown.
517 *
518 * @param[in,out] info Tensor info used to check and assign.
519 * @param[in] format New format.
520 *
521 * @return True if the format has been changed.
522 */
523bool set_format_if_unknown(ITensorInfo &info, Format format);
524
525/* Set the data type and number of channels to the specified value if
526 * the current data type is unknown.
527 *
528 * @param[in,out] info Tensor info used to check and assign.
529 * @param[in] data_type New data type.
530 *
531 * @return True if the data type has been changed.
532 */
533bool set_data_type_if_unknown(ITensorInfo &info, DataType data_type);
534
535/* Set the fixed point position to the specified value if
536 * the current fixed point position is 0 and the data type is QS8 or QS16
537 *
538 * @param[in,out] info Tensor info used to check and assign.
539 * @param[in] fixed_point_position New fixed point position
540 *
541 * @return True if the fixed point position has been changed.
542 */
543bool set_fixed_point_position_if_zero(ITensorInfo &info, int fixed_point_position);
Georgios Pinitas05078ec2017-11-02 13:06:59 +0000544
545/* Set the quantization info to the specified value if
546 * the current quantization info is empty and the data type of asymmetric quantized type
547 *
548 * @param[in,out] info Tensor info used to check and assign.
549 * @param[in] quantization_info Quantization info
550 *
551 * @return True if the quantization info has been changed.
552 */
553bool set_quantization_info_if_empty(ITensorInfo &info, QuantizationInfo quantization_info);
554
Isabella Gottardi1fab09f2017-07-13 15:55:57 +0100555/** Helper function to calculate the Valid Region for Scale.
556 *
557 * @param[in] src_info Input tensor info used to check.
558 * @param[in] dst_shape Shape of the output.
559 * @param[in] policy Interpolation policy.
560 * @param[in] border_size Size of the border.
561 * @param[in] border_undefined True if the border is undefined.
562 *
563 * @return The corrispondent valid region
564 */
565ValidRegion calculate_valid_region_scale(const ITensorInfo &src_info, const TensorShape &dst_shape, InterpolationPolicy policy, BorderSize border_size, bool border_undefined);
Georgios Pinitas05078ec2017-11-02 13:06:59 +0000566
Georgios Pinitas5ee66ea2017-09-07 17:29:16 +0100567/** Convert a linear index into n-dimensional coordinates.
568 *
569 * @param[in] shape Shape of the n-dimensional tensor.
570 * @param[in] index Linear index specifying the i-th element.
571 *
572 * @return n-dimensional coordinates.
573 */
574inline Coordinates index2coords(const TensorShape &shape, int index);
Georgios Pinitas05078ec2017-11-02 13:06:59 +0000575
Georgios Pinitas5ee66ea2017-09-07 17:29:16 +0100576/** Convert n-dimensional coordinates into a linear index.
577 *
578 * @param[in] shape Shape of the n-dimensional tensor.
579 * @param[in] coord N-dimensional coordinates.
580 *
581 * @return linead index
582 */
583inline int coords2index(const TensorShape &shape, const Coordinates &coord);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100584} // namespace arm_compute
585
586#include "arm_compute/core/Helpers.inl"
587#endif /*__ARM_COMPUTE_HELPERS_H__ */