blob: 465cba88ab0fffda30615e786f8db333d952de65 [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"
Anthony Barbier6ff3b192017-09-04 18:44:23 +010034
35#include <cmath>
36#include <cstddef>
37#include <limits>
38#include <memory>
SiCong Li3e363692017-07-04 15:02:10 +010039#include <random>
Anthony Barbier6ff3b192017-09-04 18:44:23 +010040#include <sstream>
41#include <string>
42#include <type_traits>
SiCong Li3e363692017-07-04 15:02:10 +010043#include <vector>
Anthony Barbier6ff3b192017-09-04 18:44:23 +010044
45namespace arm_compute
46{
47namespace test
48{
Anthony Barbier6ff3b192017-09-04 18:44:23 +010049/** Round floating-point value with half value rounding to positive infinity.
50 *
51 * @param[in] value floating-point value to be rounded.
52 *
53 * @return Floating-point value of rounded @p value.
54 */
55template <typename T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
56inline T round_half_up(T value)
57{
58 return std::floor(value + 0.5f);
59}
60
61/** Round floating-point value with half value rounding to nearest even.
62 *
63 * @param[in] value floating-point value to be rounded.
64 * @param[in] epsilon precision.
65 *
66 * @return Floating-point value of rounded @p value.
67 */
68template <typename T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
69inline T round_half_even(T value, T epsilon = std::numeric_limits<T>::epsilon())
70{
71 T positive_value = std::abs(value);
72 T ipart = 0;
73 std::modf(positive_value, &ipart);
74 // If 'value' is exactly halfway between two integers
75 if(std::abs(positive_value - (ipart + 0.5f)) < epsilon)
76 {
77 // If 'ipart' is even then return 'ipart'
78 if(std::fmod(ipart, 2.f) < epsilon)
79 {
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +010080 return support::cpp11::copysign(ipart, value);
Anthony Barbier6ff3b192017-09-04 18:44:23 +010081 }
82 // Else return the nearest even integer
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +010083 return support::cpp11::copysign(std::ceil(ipart + 0.5f), value);
Anthony Barbier6ff3b192017-09-04 18:44:23 +010084 }
85 // Otherwise use the usual round to closest
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +010086 return support::cpp11::copysign(support::cpp11::round(positive_value), value);
Anthony Barbier6ff3b192017-09-04 18:44:23 +010087}
Anthony Barbier6ff3b192017-09-04 18:44:23 +010088
89namespace traits
90{
91// *INDENT-OFF*
92// clang-format off
93template <typename T> struct promote { };
94template <> struct promote<uint8_t> { using type = uint16_t; };
95template <> struct promote<int8_t> { using type = int16_t; };
96template <> struct promote<uint16_t> { using type = uint32_t; };
97template <> struct promote<int16_t> { using type = int32_t; };
98template <> struct promote<uint32_t> { using type = uint64_t; };
99template <> struct promote<int32_t> { using type = int64_t; };
100template <> struct promote<float> { using type = float; };
Georgios Pinitas583137c2017-08-31 18:12:42 +0100101template <> struct promote<half> { using type = half; };
Pablo Tello383deec2017-06-23 10:40:05 +0100102
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100103
104template <typename T>
105using promote_t = typename promote<T>::type;
106
107template <typename T>
108using make_signed_conditional_t = typename std::conditional<std::is_integral<T>::value, std::make_signed<T>, std::common_type<T>>::type;
John Richardson3c5f9492017-10-04 15:27:37 +0100109
110template <typename T>
111using make_unsigned_conditional_t = typename std::conditional<std::is_integral<T>::value, std::make_unsigned<T>, std::common_type<T>>::type;
112
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100113// clang-format on
114// *INDENT-ON*
115}
116
117/** Look up the format corresponding to a channel.
118 *
119 * @param[in] channel Channel type.
120 *
121 * @return Format that contains the given channel.
122 */
123inline Format get_format_for_channel(Channel channel)
124{
125 switch(channel)
126 {
127 case Channel::R:
128 case Channel::G:
129 case Channel::B:
130 return Format::RGB888;
131 default:
132 throw std::runtime_error("Unsupported channel");
133 }
134}
135
136/** Return the format of a channel.
137 *
138 * @param[in] channel Channel type.
139 *
140 * @return Format of the given channel.
141 */
142inline Format get_channel_format(Channel channel)
143{
144 switch(channel)
145 {
146 case Channel::R:
147 case Channel::G:
148 case Channel::B:
149 return Format::U8;
150 default:
151 throw std::runtime_error("Unsupported channel");
152 }
153}
154
155/** Base case of foldl.
156 *
157 * @return value.
158 */
159template <typename F, typename T>
160inline T foldl(F &&, const T &value)
161{
162 return value;
163}
164
165/** Base case of foldl.
166 *
167 * @return func(value1, value2).
168 */
169template <typename F, typename T, typename U>
170inline auto foldl(F &&func, T &&value1, U &&value2) -> decltype(func(value1, value2))
171{
172 return func(value1, value2);
173}
174
175/** Fold left.
176 *
177 * @param[in] func Binary function to be called.
178 * @param[in] initial Initial value.
179 * @param[in] value Argument passed to the function.
180 * @param[in] values Remaining arguments.
181 */
182template <typename F, typename I, typename T, typename... Vs>
183inline I foldl(F &&func, I &&initial, T &&value, Vs &&... values)
184{
185 return foldl(std::forward<F>(func), func(std::forward<I>(initial), std::forward<T>(value)), std::forward<Vs>(values)...);
186}
187
SiCong Libacaf9a2017-06-19 13:41:45 +0100188/** Create a valid region based on tensor shape, border mode and border size
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100189 *
SiCong Libacaf9a2017-06-19 13:41:45 +0100190 * @param[in] shape Shape used as size of the valid region.
191 * @param[in] border_undefined (Optional) Boolean indicating if the border mode is undefined.
192 * @param[in] border_size (Optional) Border size used to specify the region to exclude.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100193 *
SiCong Libacaf9a2017-06-19 13:41:45 +0100194 * @return A valid region starting at (0, 0, ...) with size of @p shape if @p border_undefined is false; otherwise
195 * 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 +0100196 */
SiCong Libacaf9a2017-06-19 13:41:45 +0100197inline ValidRegion shape_to_valid_region(TensorShape shape, bool border_undefined = false, BorderSize border_size = BorderSize(0))
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100198{
199 Coordinates anchor;
Moritz Pflanzera1848362017-08-25 12:30:03 +0100200 anchor.set_num_dimensions(shape.num_dimensions());
201
SiCong Libacaf9a2017-06-19 13:41:45 +0100202 if(border_undefined)
203 {
204 ARM_COMPUTE_ERROR_ON(shape.num_dimensions() < 2);
Moritz Pflanzera1848362017-08-25 12:30:03 +0100205
SiCong Libacaf9a2017-06-19 13:41:45 +0100206 anchor.set(0, border_size.left);
207 anchor.set(1, border_size.top);
Moritz Pflanzera1848362017-08-25 12:30:03 +0100208
209 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));
210 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));
211
212 shape.set(0, valid_shape_x);
213 shape.set(1, valid_shape_y);
SiCong Libacaf9a2017-06-19 13:41:45 +0100214 }
Moritz Pflanzera1848362017-08-25 12:30:03 +0100215
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100216 return ValidRegion(std::move(anchor), std::move(shape));
217}
218
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100219/** Write the value after casting the pointer according to @p data_type.
220 *
221 * @warning The type of the value must match the specified data type.
222 *
223 * @param[out] ptr Pointer to memory where the @p value will be written.
224 * @param[in] value Value that will be written.
225 * @param[in] data_type Data type that will be written.
226 */
227template <typename T>
228void store_value_with_data_type(void *ptr, T value, DataType data_type)
229{
230 switch(data_type)
231 {
232 case DataType::U8:
233 *reinterpret_cast<uint8_t *>(ptr) = value;
234 break;
235 case DataType::S8:
236 case DataType::QS8:
237 *reinterpret_cast<int8_t *>(ptr) = value;
238 break;
239 case DataType::U16:
240 *reinterpret_cast<uint16_t *>(ptr) = value;
241 break;
242 case DataType::S16:
Michalis Spyrou0a8334c2017-06-14 18:00:05 +0100243 case DataType::QS16:
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100244 *reinterpret_cast<int16_t *>(ptr) = value;
245 break;
246 case DataType::U32:
247 *reinterpret_cast<uint32_t *>(ptr) = value;
248 break;
249 case DataType::S32:
250 *reinterpret_cast<int32_t *>(ptr) = value;
251 break;
252 case DataType::U64:
253 *reinterpret_cast<uint64_t *>(ptr) = value;
254 break;
255 case DataType::S64:
256 *reinterpret_cast<int64_t *>(ptr) = value;
257 break;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100258 case DataType::F16:
Georgios Pinitas583137c2017-08-31 18:12:42 +0100259 *reinterpret_cast<half *>(ptr) = value;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100260 break;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100261 case DataType::F32:
262 *reinterpret_cast<float *>(ptr) = value;
263 break;
264 case DataType::F64:
265 *reinterpret_cast<double *>(ptr) = value;
266 break;
267 case DataType::SIZET:
268 *reinterpret_cast<size_t *>(ptr) = value;
269 break;
270 default:
271 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
272 }
273}
274
275/** Saturate a value of type T against the numeric limits of type U.
276 *
277 * @param[in] val Value to be saturated.
278 *
279 * @return saturated value.
280 */
281template <typename U, typename T>
282T saturate_cast(T val)
283{
284 if(val > static_cast<T>(std::numeric_limits<U>::max()))
285 {
286 val = static_cast<T>(std::numeric_limits<U>::max());
287 }
288 if(val < static_cast<T>(std::numeric_limits<U>::lowest()))
289 {
290 val = static_cast<T>(std::numeric_limits<U>::lowest());
291 }
292 return val;
293}
294
295/** Find the signed promoted common type.
296 */
297template <typename... T>
298struct common_promoted_signed_type
299{
300 using common_type = typename std::common_type<T...>::type;
301 using promoted_type = traits::promote_t<common_type>;
302 using intermediate_type = typename traits::make_signed_conditional_t<promoted_type>::type;
303};
304
John Richardson3c5f9492017-10-04 15:27:37 +0100305/** Find the unsigned promoted common type.
306 */
307template <typename... T>
308struct common_promoted_unsigned_type
309{
310 using common_type = typename std::common_type<T...>::type;
311 using promoted_type = traits::promote_t<common_type>;
312 using intermediate_type = typename traits::make_unsigned_conditional_t<promoted_type>::type;
313};
314
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100315/** Convert a linear index into n-dimensional coordinates.
316 *
317 * @param[in] shape Shape of the n-dimensional tensor.
318 * @param[in] index Linear index specifying the i-th element.
319 *
320 * @return n-dimensional coordinates.
321 */
322inline Coordinates index2coord(const TensorShape &shape, int index)
323{
324 int num_elements = shape.total_size();
325
326 ARM_COMPUTE_ERROR_ON_MSG(index < 0 || index >= num_elements, "Index has to be in [0, num_elements]");
327 ARM_COMPUTE_ERROR_ON_MSG(num_elements == 0, "Cannot create coordinate from empty shape");
328
329 Coordinates coord{ 0 };
330
331 for(int d = shape.num_dimensions() - 1; d >= 0; --d)
332 {
333 num_elements /= shape[d];
334 coord.set(d, index / num_elements);
335 index %= num_elements;
336 }
337
338 return coord;
339}
340
341/** Linearise the given coordinate.
342 *
343 * Transforms the given coordinate into a linear offset in terms of
344 * elements.
345 *
346 * @param[in] shape Shape of the n-dimensional tensor.
347 * @param[in] coord The to be converted coordinate.
348 *
349 * @return Linear offset to the element.
350 */
351inline int coord2index(const TensorShape &shape, const Coordinates &coord)
352{
353 ARM_COMPUTE_ERROR_ON_MSG(shape.total_size() == 0, "Cannot get index from empty shape");
354 ARM_COMPUTE_ERROR_ON_MSG(coord.num_dimensions() == 0, "Cannot get index of empty coordinate");
355
356 int index = 0;
357 int dim_size = 1;
358
359 for(unsigned int i = 0; i < coord.num_dimensions(); ++i)
360 {
361 index += coord[i] * dim_size;
362 dim_size *= shape[i];
363 }
364
365 return index;
366}
367
368/** Check if a coordinate is within a valid region */
Moritz Pflanzera1848362017-08-25 12:30:03 +0100369inline bool is_in_valid_region(const ValidRegion &valid_region, Coordinates coord)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100370{
Moritz Pflanzer219c6912017-09-23 19:22:51 +0100371 for(size_t d = 0; d < Coordinates::num_max_dimensions; ++d)
Moritz Pflanzera1848362017-08-25 12:30:03 +0100372 {
373 if(coord[d] < valid_region.start(d) || coord[d] >= valid_region.end(d))
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100374 {
375 return false;
376 }
377 }
Moritz Pflanzera1848362017-08-25 12:30:03 +0100378
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100379 return true;
380}
Moritz Pflanzer94450f12017-06-30 12:48:43 +0100381
382/** Create and initialize a tensor of the given type.
383 *
384 * @param[in] shape Tensor shape.
385 * @param[in] data_type Data type.
386 * @param[in] num_channels (Optional) Number of channels.
387 * @param[in] fixed_point_position (Optional) Number of fractional bits.
388 *
389 * @return Initialized tensor of given type.
390 */
391template <typename T>
392inline T create_tensor(const TensorShape &shape, DataType data_type, int num_channels = 1, int fixed_point_position = 0)
393{
394 T tensor;
395 tensor.allocator()->init(TensorInfo(shape, num_channels, data_type, fixed_point_position));
396
397 return tensor;
398}
SiCong Li3e363692017-07-04 15:02:10 +0100399
400/** Create a vector of random ROIs.
401 *
402 * @param[in] shape The shape of the input tensor.
403 * @param[in] pool_info The ROI pooling information.
404 * @param[in] num_rois The number of ROIs to be created.
405 * @param[in] seed The random seed to be used.
406 *
407 * @return A vector that contains the requested number of random ROIs
408 */
409inline std::vector<ROI> generate_random_rois(const TensorShape &shape, const ROIPoolingLayerInfo &pool_info, unsigned int num_rois, std::random_device::result_type seed)
410{
411 ARM_COMPUTE_ERROR_ON((pool_info.pooled_width() < 4) || (pool_info.pooled_height() < 4));
412
413 std::vector<ROI> rois;
414 std::mt19937 gen(seed);
415 const int pool_width = pool_info.pooled_width();
416 const int pool_height = pool_info.pooled_height();
417 const float roi_scale = pool_info.spatial_scale();
418
419 // Calculate distribution bounds
420 const auto scaled_width = static_cast<int>((shape.x() / roi_scale) / pool_width);
421 const auto scaled_height = static_cast<int>((shape.y() / roi_scale) / pool_height);
422 const auto min_width = static_cast<int>(pool_width / roi_scale);
423 const auto min_height = static_cast<int>(pool_height / roi_scale);
424
425 // Create distributions
426 std::uniform_int_distribution<int> dist_batch(0, shape[3] - 1);
427 std::uniform_int_distribution<int> dist_x(0, scaled_width);
428 std::uniform_int_distribution<int> dist_y(0, scaled_height);
429 std::uniform_int_distribution<int> dist_w(min_width, std::max(min_width, (pool_width - 2) * scaled_width));
430 std::uniform_int_distribution<int> dist_h(min_height, std::max(min_height, (pool_height - 2) * scaled_height));
431
432 for(unsigned int r = 0; r < num_rois; ++r)
433 {
434 ROI roi;
435 roi.batch_idx = dist_batch(gen);
436 roi.rect.x = dist_x(gen);
437 roi.rect.y = dist_y(gen);
438 roi.rect.width = dist_w(gen);
439 roi.rect.height = dist_h(gen);
440 rois.push_back(roi);
441 }
442
443 return rois;
444}
445
446template <typename T, typename ArrayAccessor_T>
447inline void fill_array(ArrayAccessor_T &&array, const std::vector<T> &v)
448{
449 array.resize(v.size());
450 std::memcpy(array.buffer(), v.data(), v.size() * sizeof(T));
451}
SiCong Li86b53332017-08-23 11:02:43 +0100452
453/** Obtain numpy type string from DataType.
454 *
455 * @param[in] data_type Data type.
456 *
457 * @return numpy type string.
458 */
459inline std::string get_typestring(DataType data_type)
460{
461 // Check endianness
462 const unsigned int i = 1;
463 const char *c = reinterpret_cast<const char *>(&i);
464 std::string endianness;
465 if(*c == 1)
466 {
467 endianness = std::string("<");
468 }
469 else
470 {
471 endianness = std::string(">");
472 }
473 const std::string no_endianness("|");
474
475 switch(data_type)
476 {
477 case DataType::U8:
478 return no_endianness + "u" + support::cpp11::to_string(sizeof(uint8_t));
479 case DataType::S8:
480 return no_endianness + "i" + support::cpp11::to_string(sizeof(int8_t));
481 case DataType::U16:
482 return endianness + "u" + support::cpp11::to_string(sizeof(uint16_t));
483 case DataType::S16:
484 return endianness + "i" + support::cpp11::to_string(sizeof(int16_t));
485 case DataType::U32:
486 return endianness + "u" + support::cpp11::to_string(sizeof(uint32_t));
487 case DataType::S32:
488 return endianness + "i" + support::cpp11::to_string(sizeof(int32_t));
489 case DataType::U64:
490 return endianness + "u" + support::cpp11::to_string(sizeof(uint64_t));
491 case DataType::S64:
492 return endianness + "i" + support::cpp11::to_string(sizeof(int64_t));
493 case DataType::F32:
494 return endianness + "f" + support::cpp11::to_string(sizeof(float));
495 case DataType::F64:
496 return endianness + "f" + support::cpp11::to_string(sizeof(double));
497 case DataType::SIZET:
498 return endianness + "u" + support::cpp11::to_string(sizeof(size_t));
499 default:
500 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
501 }
502}
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100503} // namespace test
504} // namespace arm_compute
Anthony Barbierac69aa12017-07-03 17:39:37 +0100505#endif /* __ARM_COMPUTE_TEST_UTILS_H__ */