blob: f1725d7d74a02b954dd2753ed677c508c8a48043 [file] [log] [blame]
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001/*
2 * Copyright (c) 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_TEST_UTILS_H__
25#define __ARM_COMPUTE_TEST_UTILS_H__
26
27#include "arm_compute/core/Coordinates.h"
28#include "arm_compute/core/Error.h"
29#include "arm_compute/core/FixedPoint.h"
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +010030#include "arm_compute/core/TensorInfo.h"
Anthony Barbier6ff3b192017-09-04 18:44:23 +010031#include "arm_compute/core/TensorShape.h"
32#include "arm_compute/core/Types.h"
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +010033#include "support/ToolchainSupport.h"
Moritz Pflanzere33eb642017-07-31 14:48:45 +010034#include "tests/validation_new/half.h"
Anthony Barbier6ff3b192017-09-04 18:44:23 +010035
36#include <cmath>
37#include <cstddef>
38#include <limits>
39#include <memory>
SiCong Li3e363692017-07-04 15:02:10 +010040#include <random>
Anthony Barbier6ff3b192017-09-04 18:44:23 +010041#include <sstream>
42#include <string>
43#include <type_traits>
SiCong Li3e363692017-07-04 15:02:10 +010044#include <vector>
Anthony Barbier6ff3b192017-09-04 18:44:23 +010045
46namespace arm_compute
47{
48namespace test
49{
Anthony Barbier6ff3b192017-09-04 18:44:23 +010050/** Round floating-point value with half value rounding to positive infinity.
51 *
52 * @param[in] value floating-point value to be rounded.
53 *
54 * @return Floating-point value of rounded @p value.
55 */
56template <typename T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
57inline T round_half_up(T value)
58{
59 return std::floor(value + 0.5f);
60}
61
62/** Round floating-point value with half value rounding to nearest even.
63 *
64 * @param[in] value floating-point value to be rounded.
65 * @param[in] epsilon precision.
66 *
67 * @return Floating-point value of rounded @p value.
68 */
69template <typename T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
70inline T round_half_even(T value, T epsilon = std::numeric_limits<T>::epsilon())
71{
72 T positive_value = std::abs(value);
73 T ipart = 0;
74 std::modf(positive_value, &ipart);
75 // If 'value' is exactly halfway between two integers
76 if(std::abs(positive_value - (ipart + 0.5f)) < epsilon)
77 {
78 // If 'ipart' is even then return 'ipart'
79 if(std::fmod(ipart, 2.f) < epsilon)
80 {
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +010081 return support::cpp11::copysign(ipart, value);
Anthony Barbier6ff3b192017-09-04 18:44:23 +010082 }
83 // Else return the nearest even integer
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +010084 return support::cpp11::copysign(std::ceil(ipart + 0.5f), value);
Anthony Barbier6ff3b192017-09-04 18:44:23 +010085 }
86 // Otherwise use the usual round to closest
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +010087 return support::cpp11::copysign(support::cpp11::round(positive_value), value);
Anthony Barbier6ff3b192017-09-04 18:44:23 +010088}
Anthony Barbier6ff3b192017-09-04 18:44:23 +010089
90namespace traits
91{
92// *INDENT-OFF*
93// clang-format off
94template <typename T> struct promote { };
95template <> struct promote<uint8_t> { using type = uint16_t; };
96template <> struct promote<int8_t> { using type = int16_t; };
97template <> struct promote<uint16_t> { using type = uint32_t; };
98template <> struct promote<int16_t> { using type = int32_t; };
99template <> struct promote<uint32_t> { using type = uint64_t; };
100template <> struct promote<int32_t> { using type = int64_t; };
101template <> struct promote<float> { using type = float; };
Moritz Pflanzere49e2662017-07-21 15:55:28 +0100102template <> struct promote<half_float::half> { using type = half_float::half; };
Pablo Tello383deec2017-06-23 10:40:05 +0100103
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100104
105template <typename T>
106using promote_t = typename promote<T>::type;
107
108template <typename T>
109using make_signed_conditional_t = typename std::conditional<std::is_integral<T>::value, std::make_signed<T>, std::common_type<T>>::type;
110// clang-format on
111// *INDENT-ON*
112}
113
114/** Look up the format corresponding to a channel.
115 *
116 * @param[in] channel Channel type.
117 *
118 * @return Format that contains the given channel.
119 */
120inline Format get_format_for_channel(Channel channel)
121{
122 switch(channel)
123 {
124 case Channel::R:
125 case Channel::G:
126 case Channel::B:
127 return Format::RGB888;
128 default:
129 throw std::runtime_error("Unsupported channel");
130 }
131}
132
133/** Return the format of a channel.
134 *
135 * @param[in] channel Channel type.
136 *
137 * @return Format of the given channel.
138 */
139inline Format get_channel_format(Channel channel)
140{
141 switch(channel)
142 {
143 case Channel::R:
144 case Channel::G:
145 case Channel::B:
146 return Format::U8;
147 default:
148 throw std::runtime_error("Unsupported channel");
149 }
150}
151
152/** Base case of foldl.
153 *
154 * @return value.
155 */
156template <typename F, typename T>
157inline T foldl(F &&, const T &value)
158{
159 return value;
160}
161
162/** Base case of foldl.
163 *
164 * @return func(value1, value2).
165 */
166template <typename F, typename T, typename U>
167inline auto foldl(F &&func, T &&value1, U &&value2) -> decltype(func(value1, value2))
168{
169 return func(value1, value2);
170}
171
172/** Fold left.
173 *
174 * @param[in] func Binary function to be called.
175 * @param[in] initial Initial value.
176 * @param[in] value Argument passed to the function.
177 * @param[in] values Remaining arguments.
178 */
179template <typename F, typename I, typename T, typename... Vs>
180inline I foldl(F &&func, I &&initial, T &&value, Vs &&... values)
181{
182 return foldl(std::forward<F>(func), func(std::forward<I>(initial), std::forward<T>(value)), std::forward<Vs>(values)...);
183}
184
SiCong Libacaf9a2017-06-19 13:41:45 +0100185/** Create a valid region based on tensor shape, border mode and border size
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100186 *
SiCong Libacaf9a2017-06-19 13:41:45 +0100187 * @param[in] shape Shape used as size of the valid region.
188 * @param[in] border_undefined (Optional) Boolean indicating if the border mode is undefined.
189 * @param[in] border_size (Optional) Border size used to specify the region to exclude.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100190 *
SiCong Libacaf9a2017-06-19 13:41:45 +0100191 * @return A valid region starting at (0, 0, ...) with size of @p shape if @p border_undefined is false; otherwise
192 * return A valid region starting at (@p border_size.left, @p border_size.top, ...) with reduced size of @p shape.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100193 */
SiCong Libacaf9a2017-06-19 13:41:45 +0100194inline ValidRegion shape_to_valid_region(TensorShape shape, bool border_undefined = false, BorderSize border_size = BorderSize(0))
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100195{
196 Coordinates anchor;
Moritz Pflanzera1848362017-08-25 12:30:03 +0100197 anchor.set_num_dimensions(shape.num_dimensions());
198
SiCong Libacaf9a2017-06-19 13:41:45 +0100199 if(border_undefined)
200 {
201 ARM_COMPUTE_ERROR_ON(shape.num_dimensions() < 2);
Moritz Pflanzera1848362017-08-25 12:30:03 +0100202
SiCong Libacaf9a2017-06-19 13:41:45 +0100203 anchor.set(0, border_size.left);
204 anchor.set(1, border_size.top);
Moritz Pflanzera1848362017-08-25 12:30:03 +0100205
206 const int valid_shape_x = std::max(0, static_cast<int>(shape.x()) - static_cast<int>(border_size.left) - static_cast<int>(border_size.right));
207 const int valid_shape_y = std::max(0, static_cast<int>(shape.y()) - static_cast<int>(border_size.top) - static_cast<int>(border_size.bottom));
208
209 shape.set(0, valid_shape_x);
210 shape.set(1, valid_shape_y);
SiCong Libacaf9a2017-06-19 13:41:45 +0100211 }
Moritz Pflanzera1848362017-08-25 12:30:03 +0100212
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100213 return ValidRegion(std::move(anchor), std::move(shape));
214}
215
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100216/** Write the value after casting the pointer according to @p data_type.
217 *
218 * @warning The type of the value must match the specified data type.
219 *
220 * @param[out] ptr Pointer to memory where the @p value will be written.
221 * @param[in] value Value that will be written.
222 * @param[in] data_type Data type that will be written.
223 */
224template <typename T>
225void store_value_with_data_type(void *ptr, T value, DataType data_type)
226{
227 switch(data_type)
228 {
229 case DataType::U8:
230 *reinterpret_cast<uint8_t *>(ptr) = value;
231 break;
232 case DataType::S8:
233 case DataType::QS8:
234 *reinterpret_cast<int8_t *>(ptr) = value;
235 break;
236 case DataType::U16:
237 *reinterpret_cast<uint16_t *>(ptr) = value;
238 break;
239 case DataType::S16:
Michalis Spyrou0a8334c2017-06-14 18:00:05 +0100240 case DataType::QS16:
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100241 *reinterpret_cast<int16_t *>(ptr) = value;
242 break;
243 case DataType::U32:
244 *reinterpret_cast<uint32_t *>(ptr) = value;
245 break;
246 case DataType::S32:
247 *reinterpret_cast<int32_t *>(ptr) = value;
248 break;
249 case DataType::U64:
250 *reinterpret_cast<uint64_t *>(ptr) = value;
251 break;
252 case DataType::S64:
253 *reinterpret_cast<int64_t *>(ptr) = value;
254 break;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100255 case DataType::F16:
Moritz Pflanzere49e2662017-07-21 15:55:28 +0100256 *reinterpret_cast<half_float::half *>(ptr) = value;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100257 break;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100258 case DataType::F32:
259 *reinterpret_cast<float *>(ptr) = value;
260 break;
261 case DataType::F64:
262 *reinterpret_cast<double *>(ptr) = value;
263 break;
264 case DataType::SIZET:
265 *reinterpret_cast<size_t *>(ptr) = value;
266 break;
267 default:
268 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
269 }
270}
271
272/** Saturate a value of type T against the numeric limits of type U.
273 *
274 * @param[in] val Value to be saturated.
275 *
276 * @return saturated value.
277 */
278template <typename U, typename T>
279T saturate_cast(T val)
280{
281 if(val > static_cast<T>(std::numeric_limits<U>::max()))
282 {
283 val = static_cast<T>(std::numeric_limits<U>::max());
284 }
285 if(val < static_cast<T>(std::numeric_limits<U>::lowest()))
286 {
287 val = static_cast<T>(std::numeric_limits<U>::lowest());
288 }
289 return val;
290}
291
292/** Find the signed promoted common type.
293 */
294template <typename... T>
295struct common_promoted_signed_type
296{
297 using common_type = typename std::common_type<T...>::type;
298 using promoted_type = traits::promote_t<common_type>;
299 using intermediate_type = typename traits::make_signed_conditional_t<promoted_type>::type;
300};
301
302/** Convert a linear index into n-dimensional coordinates.
303 *
304 * @param[in] shape Shape of the n-dimensional tensor.
305 * @param[in] index Linear index specifying the i-th element.
306 *
307 * @return n-dimensional coordinates.
308 */
309inline Coordinates index2coord(const TensorShape &shape, int index)
310{
311 int num_elements = shape.total_size();
312
313 ARM_COMPUTE_ERROR_ON_MSG(index < 0 || index >= num_elements, "Index has to be in [0, num_elements]");
314 ARM_COMPUTE_ERROR_ON_MSG(num_elements == 0, "Cannot create coordinate from empty shape");
315
316 Coordinates coord{ 0 };
317
318 for(int d = shape.num_dimensions() - 1; d >= 0; --d)
319 {
320 num_elements /= shape[d];
321 coord.set(d, index / num_elements);
322 index %= num_elements;
323 }
324
325 return coord;
326}
327
328/** Linearise the given coordinate.
329 *
330 * Transforms the given coordinate into a linear offset in terms of
331 * elements.
332 *
333 * @param[in] shape Shape of the n-dimensional tensor.
334 * @param[in] coord The to be converted coordinate.
335 *
336 * @return Linear offset to the element.
337 */
338inline int coord2index(const TensorShape &shape, const Coordinates &coord)
339{
340 ARM_COMPUTE_ERROR_ON_MSG(shape.total_size() == 0, "Cannot get index from empty shape");
341 ARM_COMPUTE_ERROR_ON_MSG(coord.num_dimensions() == 0, "Cannot get index of empty coordinate");
342
343 int index = 0;
344 int dim_size = 1;
345
346 for(unsigned int i = 0; i < coord.num_dimensions(); ++i)
347 {
348 index += coord[i] * dim_size;
349 dim_size *= shape[i];
350 }
351
352 return index;
353}
354
Georgios Pinitasce093142017-06-19 16:11:53 +0100355/** Check if Coordinates dimensionality can match the respective shape one.
356 *
357 * @param coords Coordinates
358 * @param shape Shape to match dimensionality
359 *
360 * @return True if Coordinates can match the dimensionality of the shape else false.
361 */
362inline bool match_shape(Coordinates &coords, const TensorShape &shape)
363{
Moritz Pflanzera1848362017-08-25 12:30:03 +0100364 auto check_nz = [](int i)
Georgios Pinitasce093142017-06-19 16:11:53 +0100365 {
366 return i != 0;
367 };
368
Moritz Pflanzera1848362017-08-25 12:30:03 +0100369 const int coords_dims = coords.num_dimensions();
370 const int shape_dims = shape.num_dimensions();
Georgios Pinitasce093142017-06-19 16:11:53 +0100371
372 // Increase coordinates scenario
373 if(coords_dims < shape_dims)
374 {
375 coords.set_num_dimensions(shape_dims);
376 return true;
377 }
378 // Decrease coordinates scenario
379 if(coords_dims > shape_dims && !std::any_of(coords.begin() + shape_dims, coords.end(), check_nz))
380 {
381 coords.set_num_dimensions(shape_dims);
382 return true;
383 }
384
385 return (coords_dims == shape_dims);
386}
387
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100388/** Check if a coordinate is within a valid region */
Moritz Pflanzera1848362017-08-25 12:30:03 +0100389inline bool is_in_valid_region(const ValidRegion &valid_region, Coordinates coord)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100390{
Moritz Pflanzera1848362017-08-25 12:30:03 +0100391 const bool match = match_shape(coord, valid_region.shape);
392
393 if(!match)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100394 {
Moritz Pflanzera1848362017-08-25 12:30:03 +0100395 return false;
396 }
397
398 for(int d = 0; static_cast<size_t>(d) < coord.num_dimensions(); ++d)
399 {
400 if(coord[d] < valid_region.start(d) || coord[d] >= valid_region.end(d))
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100401 {
402 return false;
403 }
404 }
Moritz Pflanzera1848362017-08-25 12:30:03 +0100405
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100406 return true;
407}
Moritz Pflanzer94450f12017-06-30 12:48:43 +0100408
409/** Create and initialize a tensor of the given type.
410 *
411 * @param[in] shape Tensor shape.
412 * @param[in] data_type Data type.
413 * @param[in] num_channels (Optional) Number of channels.
414 * @param[in] fixed_point_position (Optional) Number of fractional bits.
415 *
416 * @return Initialized tensor of given type.
417 */
418template <typename T>
419inline T create_tensor(const TensorShape &shape, DataType data_type, int num_channels = 1, int fixed_point_position = 0)
420{
421 T tensor;
422 tensor.allocator()->init(TensorInfo(shape, num_channels, data_type, fixed_point_position));
423
424 return tensor;
425}
SiCong Li3e363692017-07-04 15:02:10 +0100426
427/** Create a vector of random ROIs.
428 *
429 * @param[in] shape The shape of the input tensor.
430 * @param[in] pool_info The ROI pooling information.
431 * @param[in] num_rois The number of ROIs to be created.
432 * @param[in] seed The random seed to be used.
433 *
434 * @return A vector that contains the requested number of random ROIs
435 */
436inline std::vector<ROI> generate_random_rois(const TensorShape &shape, const ROIPoolingLayerInfo &pool_info, unsigned int num_rois, std::random_device::result_type seed)
437{
438 ARM_COMPUTE_ERROR_ON((pool_info.pooled_width() < 4) || (pool_info.pooled_height() < 4));
439
440 std::vector<ROI> rois;
441 std::mt19937 gen(seed);
442 const int pool_width = pool_info.pooled_width();
443 const int pool_height = pool_info.pooled_height();
444 const float roi_scale = pool_info.spatial_scale();
445
446 // Calculate distribution bounds
447 const auto scaled_width = static_cast<int>((shape.x() / roi_scale) / pool_width);
448 const auto scaled_height = static_cast<int>((shape.y() / roi_scale) / pool_height);
449 const auto min_width = static_cast<int>(pool_width / roi_scale);
450 const auto min_height = static_cast<int>(pool_height / roi_scale);
451
452 // Create distributions
453 std::uniform_int_distribution<int> dist_batch(0, shape[3] - 1);
454 std::uniform_int_distribution<int> dist_x(0, scaled_width);
455 std::uniform_int_distribution<int> dist_y(0, scaled_height);
456 std::uniform_int_distribution<int> dist_w(min_width, std::max(min_width, (pool_width - 2) * scaled_width));
457 std::uniform_int_distribution<int> dist_h(min_height, std::max(min_height, (pool_height - 2) * scaled_height));
458
459 for(unsigned int r = 0; r < num_rois; ++r)
460 {
461 ROI roi;
462 roi.batch_idx = dist_batch(gen);
463 roi.rect.x = dist_x(gen);
464 roi.rect.y = dist_y(gen);
465 roi.rect.width = dist_w(gen);
466 roi.rect.height = dist_h(gen);
467 rois.push_back(roi);
468 }
469
470 return rois;
471}
472
473template <typename T, typename ArrayAccessor_T>
474inline void fill_array(ArrayAccessor_T &&array, const std::vector<T> &v)
475{
476 array.resize(v.size());
477 std::memcpy(array.buffer(), v.data(), v.size() * sizeof(T));
478}
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100479} // namespace test
480} // namespace arm_compute
Anthony Barbierac69aa12017-07-03 17:39:37 +0100481#endif /* __ARM_COMPUTE_TEST_UTILS_H__ */