From 188708170a51887868a7170c9ee963372bfb9ced Mon Sep 17 00:00:00 2001 From: giuros01 Date: Thu, 13 Sep 2018 09:31:40 +0100 Subject: [COMPMID-1331] Add support for RoIAlign operator in CL Change-Id: Ie215daacd10477309dbf8af1bb2b05b7a0a8f203 Reviewed-on: https://eu-gerrit-1.euhpc.arm.com/150773 Tested-by: bsgcomp Reviewed-by: Isabella Gottardi Reviewed-by: Pablo Tello --- arm_compute/core/CL/CLKernels.h | 1 + .../core/CL/kernels/CLROIAlignLayerKernel.h | 91 ++++++++++ arm_compute/core/Types.h | 21 ++- arm_compute/runtime/CL/CLFunctions.h | 1 + arm_compute/runtime/CL/functions/CLROIAlignLayer.h | 74 ++++++++ src/core/CL/CLKernelLibrary.cpp | 5 + src/core/CL/cl_kernels/roi_align_layer.cl | 181 ++++++++++++++++++++ src/core/CL/kernels/CLROIAlignLayerKernel.cpp | 141 ++++++++++++++++ src/runtime/CL/functions/CLROIAlignLayer.cpp | 47 ++++++ tests/datasets/ROIPoolingLayerDataset.h | 4 +- tests/validation/CL/ROIAlignLayer.cpp | 104 ++++++++++++ tests/validation/fixtures/ROIAlignLayerFixture.h | 124 ++++++++++++++ tests/validation/reference/ROIAlignLayer.cpp | 186 +++++++++++++++++++++ tests/validation/reference/ROIAlignLayer.h | 45 +++++ utils/TypePrinter.h | 13 ++ 15 files changed, 1030 insertions(+), 8 deletions(-) create mode 100644 arm_compute/core/CL/kernels/CLROIAlignLayerKernel.h create mode 100644 arm_compute/runtime/CL/functions/CLROIAlignLayer.h create mode 100644 src/core/CL/cl_kernels/roi_align_layer.cl create mode 100644 src/core/CL/kernels/CLROIAlignLayerKernel.cpp create mode 100644 src/runtime/CL/functions/CLROIAlignLayer.cpp create mode 100644 tests/validation/CL/ROIAlignLayer.cpp create mode 100644 tests/validation/fixtures/ROIAlignLayerFixture.h create mode 100644 tests/validation/reference/ROIAlignLayer.cpp create mode 100644 tests/validation/reference/ROIAlignLayer.h diff --git a/arm_compute/core/CL/CLKernels.h b/arm_compute/core/CL/CLKernels.h index f39d7b71f6..f6759b9f1e 100644 --- a/arm_compute/core/CL/CLKernels.h +++ b/arm_compute/core/CL/CLKernels.h @@ -102,6 +102,7 @@ #include "arm_compute/core/CL/kernels/CLPixelWiseMultiplicationKernel.h" #include "arm_compute/core/CL/kernels/CLPoolingLayerKernel.h" #include "arm_compute/core/CL/kernels/CLQuantizationLayerKernel.h" +#include "arm_compute/core/CL/kernels/CLROIAlignLayerKernel.h" #include "arm_compute/core/CL/kernels/CLROIPoolingLayerKernel.h" #include "arm_compute/core/CL/kernels/CLReductionOperationKernel.h" #include "arm_compute/core/CL/kernels/CLRemapKernel.h" diff --git a/arm_compute/core/CL/kernels/CLROIAlignLayerKernel.h b/arm_compute/core/CL/kernels/CLROIAlignLayerKernel.h new file mode 100644 index 0000000000..6908675ec1 --- /dev/null +++ b/arm_compute/core/CL/kernels/CLROIAlignLayerKernel.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2018 ARM Limited. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef __ARM_COMPUTE_CLROIALIGNLAYERKERNEL_H__ +#define __ARM_COMPUTE_CLROIALIGNLAYERKERNEL_H__ + +#include "arm_compute/core/CL/ICLArray.h" +#include "arm_compute/core/CL/ICLKernel.h" + +namespace arm_compute +{ +class ICLTensor; + +/** Interface for the RoIAlign kernel. + */ +class CLROIAlignLayerKernel : public ICLKernel +{ +public: + /** Constructor */ + CLROIAlignLayerKernel(); + /** Prevent instances of this class from being copied (As this class contains pointers) */ + CLROIAlignLayerKernel(const CLROIAlignLayerKernel &) = delete; + /** Prevent instances of this class from being copied (As this class contains pointers) */ + CLROIAlignLayerKernel &operator=(const CLROIAlignLayerKernel &) = delete; + /** Default Move Constructor. */ + CLROIAlignLayerKernel(CLROIAlignLayerKernel &&) = default; + /** Default move assignment operator. */ + CLROIAlignLayerKernel &operator=(CLROIAlignLayerKernel &&) = default; + /** Default destructor */ + ~CLROIAlignLayerKernel() = default; + + /** Set the input and output tensors. + * + * @param[in] input Source tensor. Data types supported: F16/F32. + * @param[in] rois Array containing @ref ROI. + * @param[out] output Destination tensor. Data types supported: Same as @p input. + * @param[in] pool_info Contains pooling operation information described in @ref ROIPoolingLayerInfo. + * + * @note The x and y dimensions of @p output tensor must be the same as @p pool_info 's pooled + * width and pooled height. + * @note The z dimensions of @p output tensor and @p input tensor must be the same. + * @note The fourth dimension of @p output tensor must be the same as the number of elements in @p rois array. + */ + void configure(const ICLTensor *input, const ICLROIArray *rois, ICLTensor *output, const ROIPoolingLayerInfo &pool_info); + /** Static function to check if given info will lead to a valid configuration of @ref CLROIAlignLayerKernel + * + * @param[in] input Source tensor info. Data types supported: F16/F32. + * @param[in] num_rois Length of the array containing @ref ROI. + * @param[out] output Destination tensor info. Data types supported: Same as @p input. + * @param[in] pool_info Contains pooling operation information described in @ref ROIPoolingLayerInfo. + * + * @note The x and y dimensions of @p output tensor must be the same as @p pool_info 's pooled + * width and pooled height. + * @note The z dimensions of @p output tensor and @p input tensor must be the same. + * @note The fourth dimension of @p output tensor must be the same as the number of elements in @p rois array. + * + * @return a Status + */ + static Status validate(const ITensorInfo *input, size_t num_rois, ITensorInfo *output, const ROIPoolingLayerInfo &pool_info); + + // Inherited methods overridden: + void run(const Window &window, cl::CommandQueue &queue); + +private: + const ICLTensor *_input; + ICLTensor *_output; + const ICLROIArray *_rois; + ROIPoolingLayerInfo _pool_info; +}; +} // namespace arm_compute +#endif /*__ARM_COMPUTE_CLROIALIGNLAYERKERNEL_H__*/ diff --git a/arm_compute/core/Types.h b/arm_compute/core/Types.h index 4c81e1f700..9b81eccafb 100644 --- a/arm_compute/core/Types.h +++ b/arm_compute/core/Types.h @@ -808,17 +808,18 @@ private: }; /** ROI Pooling Layer Information class */ -class ROIPoolingLayerInfo +class ROIPoolingLayerInfo final { public: - /** Default Constructor + /** Constructor * - * @param[in] pooled_width Pooled width of the layer. - * @param[in] pooled_height Pooled height of the layer. - * @param[in] spatial_scale Spatial scale to be applied to the ROI coordinates and dimensions. + * @param[in] pooled_width Pooled width of the layer. + * @param[in] pooled_height Pooled height of the layer. + * @param[in] spatial_scale Spatial scale to be applied to the ROI coordinates and dimensions. + * @param[in] sampling_ratio Number of samples to include in each pooling region (if set to zero, a ceil(roi_dims/pooling_dims)) */ - ROIPoolingLayerInfo(unsigned int pooled_width, unsigned int pooled_height, float spatial_scale) - : _pooled_width(pooled_width), _pooled_height(pooled_height), _spatial_scale(spatial_scale) + ROIPoolingLayerInfo(unsigned int pooled_width, unsigned int pooled_height, float spatial_scale, unsigned int sampling_ratio = 0) + : _pooled_width(pooled_width), _pooled_height(pooled_height), _spatial_scale(spatial_scale), _sampling_ratio(sampling_ratio) { } /** Get the pooled width of the layer */ @@ -836,11 +837,17 @@ public: { return _spatial_scale; } + /** Get sampling ratio */ + unsigned int sampling_ratio() const + { + return _sampling_ratio; + } private: unsigned int _pooled_width; unsigned int _pooled_height; float _spatial_scale; + unsigned int _sampling_ratio; }; /** Activation Layer Information class */ diff --git a/arm_compute/runtime/CL/CLFunctions.h b/arm_compute/runtime/CL/CLFunctions.h index 8dadcc1e87..d87a8285f4 100644 --- a/arm_compute/runtime/CL/CLFunctions.h +++ b/arm_compute/runtime/CL/CLFunctions.h @@ -102,6 +102,7 @@ #include "arm_compute/runtime/CL/functions/CLPoolingLayer.h" #include "arm_compute/runtime/CL/functions/CLQuantizationLayer.h" #include "arm_compute/runtime/CL/functions/CLRNNLayer.h" +#include "arm_compute/runtime/CL/functions/CLROIAlignLayer.h" #include "arm_compute/runtime/CL/functions/CLROIPoolingLayer.h" #include "arm_compute/runtime/CL/functions/CLReductionOperation.h" #include "arm_compute/runtime/CL/functions/CLRemap.h" diff --git a/arm_compute/runtime/CL/functions/CLROIAlignLayer.h b/arm_compute/runtime/CL/functions/CLROIAlignLayer.h new file mode 100644 index 0000000000..6cf9bd2c29 --- /dev/null +++ b/arm_compute/runtime/CL/functions/CLROIAlignLayer.h @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2018 ARM Limited. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef __ARM_COMPUTE_CLROIALIGNLAYER_H__ +#define __ARM_COMPUTE_CLROIALIGNLAYER_H__ + +#include "arm_compute/core/CL/ICLArray.h" +#include "arm_compute/core/CL/kernels/CLROIPoolingLayerKernel.h" +#include "arm_compute/runtime/CL/ICLSimpleFunction.h" + +namespace arm_compute +{ +class ICLTensor; + +/** Basic function to run @ref CLROIAlignLayerKernel. + * + * This function calls the following OpenCL kernels: + * -# @ref CLROIAlignLayerKernel + * + */ +class CLROIAlignLayer : public ICLSimpleFunction +{ +public: + /** Set the input and output tensors. + * + * @param[in] input Source tensor. Data types supported: F16/F32. + * @param[in] rois Array containing @ref ROI. + * @param[out] output Destination tensor. Data types supported: Same as @p input. + * @param[in] pool_info Contains pooling operation information described in @ref ROIPoolingLayerInfo. + * + * @note The x and y dimensions of @p output tensor must be the same as @p pool_info 's pooled + * width and pooled height. + * @note The z dimensions of @p output tensor and @p input tensor must be the same. + * @note The fourth dimension of @p output tensor must be the same as the number of elements in @p rois array. + */ + void configure(const ICLTensor *input, const ICLROIArray *rois, ICLTensor *output, const ROIPoolingLayerInfo &pool_info); + /** Static function to check if given info will lead to a valid configuration of @ref CLROIAlignLayer + * + * @param[in] input Source tensor info. Data types supported: F16/F32. + * @param[in] num_rois Length of the array containing @ref ROI. + * @param[out] output Destination tensor info. Data types supported: Same as @p input. + * @param[in] pool_info Contains pooling operation information described in @ref ROIPoolingLayerInfo. + * + * @note The x and y dimensions of @p output tensor must be the same as @p pool_info 's pooled + * width and pooled height. + * @note The z dimensions of @p output tensor and @p input tensor must be the same. + * @note The fourth dimension of @p output tensor must be the same as the number of elements in @p rois array. + * + * @return a Status + */ + static Status validate(const ITensorInfo *input, size_t num_rois, ITensorInfo *output, const ROIPoolingLayerInfo &pool_info); +}; +} // namespace arm_compute +#endif /* __ARM_COMPUTE_CLROIALIGNLAYER_H__ */ diff --git a/src/core/CL/CLKernelLibrary.cpp b/src/core/CL/CLKernelLibrary.cpp index 87b588e16c..ce4b85551d 100644 --- a/src/core/CL/CLKernelLibrary.cpp +++ b/src/core/CL/CLKernelLibrary.cpp @@ -358,6 +358,7 @@ const std::map CLKernelLibrary::_kernel_program_map = { "RGBA8888_to_NV12_bt709", "color_convert.cl" }, { "RGBA8888_to_RGB888_bt709", "color_convert.cl" }, { "RGBA8888_to_YUV444_bt709", "color_convert.cl" }, + { "roi_align_layer", "roi_align_layer.cl" }, { "roi_pooling_layer", "roi_pooling_layer.cl" }, { "scale_nearest_neighbour_nchw", "scale.cl" }, { "scale_nearest_neighbour_nhwc", "scale.cl" }, @@ -760,6 +761,10 @@ const std::map CLKernelLibrary::_program_source_map = { "reshape_layer.cl", #include "./cl_kernels/reshape_layer.clembed" + }, + { + "roi_align_layer.cl", +#include "./cl_kernels/roi_align_layer.clembed" }, { "roi_pooling_layer.cl", diff --git a/src/core/CL/cl_kernels/roi_align_layer.cl b/src/core/CL/cl_kernels/roi_align_layer.cl new file mode 100644 index 0000000000..4625e53ed5 --- /dev/null +++ b/src/core/CL/cl_kernels/roi_align_layer.cl @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2018 ARM Limited. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#include "helpers.h" + +// This specifies the value to shift the result of roi_dims / pooled_dims before ceiling. +// It is close to the epsilon machine (for a floating point system, x and x+EPS are the same number). +#define EPS_GRID 0.00001f + +#if defined(DATA_TYPE) && defined(POOLED_DIM_X) && defined(POOLED_DIM_Y) && defined(MAX_DIM_X) && defined(MAX_DIM_Y) && defined(MAX_DIM_Z) && defined(SPATIAL_SCALE) // Check for compile time constants + +/** Performs a roi align on a single output pixel. + * + * @param[in] input Pointer to input Tensor3D struct. + * @param[in] region_start_x Start x index projected onto the input tensor. + * @param[in] region_end_x End x index projected onto the input tensor. + * @param[in] region_start_y Start y index projected onto the input tensor. + * @param[in] region_end_y End y index projected onto the input tensor. + * @param[in] pz z index of the input tensor. + * + * @return An average pooled value from the region specified in the input tensor. + */ +inline DATA_TYPE roi_align_1x1(const Tensor3D *input, float region_start_x, + float bin_size_x, + float grid_size_x, + float region_end_x, + float region_start_y, + float bin_size_y, + float grid_size_y, + float region_end_y, + int pz) +{ + // Iterate through the pooling region + float sum = 0; + for(int iy = 0; iy < grid_size_y; ++iy) + { + for(int ix = 0; ix < grid_size_x; ++ix) + { + // Align the window in the middle of every bin + const float y = region_start_y + (iy + 0.5f) * bin_size_y / (float)grid_size_y; + const float x = region_start_x + (ix + 0.5f) * bin_size_x / (float)grid_size_x; + + // Interpolation in the unit square + const int y_low = (int)y; + const int x_low = (int)x; + const int y_high = y_low + 1; + const int x_high = x_low + 1; + + const float ly = y - y_low; + const float lx = x - x_low; + const float hy = 1.f - ly; + const float hx = 1.f - lx; + + const float w1 = hy * hx; + const float w2 = hy * lx; + const float w3 = ly * hx; + const float w4 = ly * lx; + + const DATA_TYPE data1 = *(__global DATA_TYPE *)tensor3D_offset(input, x_low, y_low, pz); + const DATA_TYPE data2 = *(__global DATA_TYPE *)tensor3D_offset(input, x_high, y_low, pz); + const DATA_TYPE data3 = *(__global DATA_TYPE *)tensor3D_offset(input, x_low, y_high, pz); + const DATA_TYPE data4 = *(__global DATA_TYPE *)tensor3D_offset(input, x_high, y_high, pz); + sum += w1 * data1 + w2 * data2 + w3 * data3 + w4 * data4; + } + } + + return (DATA_TYPE)(sum / (grid_size_x * grid_size_y)); +} + +/** Performs a roi align function. + * + * @note Datatype must be passed using -DDATA_TYPE e.g. -DDATA_TYPE=float. Supported data types are F16, F32; + * @note Datasize must be passed using -DDATA_SIZE e.g. -DDATA_SIZE=32; + * @note Input dimensions must be passed using -DMAX_DIM_X, -DMAX_DIM_Y and -DMAX_DIM_Z; + * @note Pooled region dimensions must be passed using -DPOOLED_DIM_X and -DPOOLED_DIM_Y; + * @note Spatial scale must be passed using -DSPATIAL_SCALE; + * @note Sampling ratio (i.e., the number of samples in each bin) may be passed using -DSAMPLING_RATIO. If not defined each roi + * will have a default sampling ratio of roi_dims/pooling_dims + * + * @param[in] input_ptr Pointer to the source image. Supported data types: F16, F32 + * @param[in] input_stride_x Stride of the source image in X dimension (in bytes) + * @param[in] input_step_x input_stride_x * number of elements along X processed per workitem(in bytes) + * @param[in] input_stride_y Stride of the source image in Y dimension (in bytes) + * @param[in] input_step_y input_stride_y * number of elements along Y processed per workitem(in bytes) + * @param[in] input_stride_z Stride of the source tensor in Z dimension (in bytes) + * @param[in] input_step_z input_stride_z * number of elements along Z processed per workitem(in bytes) + * @param[in] input_offset_first_element_in_bytes The offset of the first element in the pooled region of the source image as specifed by ROI + * @param[in] rois_ptr Pointer to the rois array. Layout: {x, y, width, height, batch_indx} + * @param[in] rois_stride_x Stride of the rois array in X dimension (in bytes) + * @param[in] rois_step_x rois_stride_x * number of elements along X processed per workitem(in bytes) + * @param[in] rois_offset_first_element_in_bytes The offset of the first element in the rois array + * @param[out] output_ptr Pointer to the destination image. Supported data types: F16, F32 + * @param[in] output_stride_x Stride of the destination image in X dimension (in bytes) + * @param[in] output_step_x output_stride_x * number of elements along X processed per workitem(in bytes) + * @param[in] output_stride_y Stride of the destination image in Y dimension (in bytes) + * @param[in] output_step_y output_stride_y * number of elements along Y processed per workitem(in bytes) + * @param[in] output_stride_z Stride of the destination tensor in Z dimension (in bytes) + * @param[in] output_step_z output_stride_z * number of elements along Z processed per workitem(in bytes) + * @param[in] output_offset_first_element_in_bytes The offset of the first element in the destination image + * @param[in] input_stride_w Stride of the source image in W dimension (in bytes) + * @param[in] output_stride_w Stride of the destination image in W dimension (in bytes) + */ +__kernel void roi_align_layer( + TENSOR3D_DECLARATION(input), + VECTOR_DECLARATION(rois), + TENSOR3D_DECLARATION(output), + unsigned int input_stride_w, unsigned int output_stride_w) +{ + // Get pixels pointer + Tensor3D input = CONVERT_TO_TENSOR3D_STRUCT_NO_STEP(input); + Vector rois = CONVERT_TO_VECTOR_STRUCT_NO_STEP(rois); + Tensor3D output = CONVERT_TO_TENSOR3D_STRUCT_NO_STEP(output); + + const int px = get_global_id(0); + const int py = get_global_id(1); + const int pw = get_global_id(2); + + // Load roi parameters + // roi is laid out as follows: + // { x, y, width, height, batch_index } + const ushort4 roi = vload4(0, (__global ushort *)vector_offset(&rois, pw)); + const ushort roi_batch = *((__global ushort *)vector_offset(&rois, pw) + 4); + const float2 roi_anchor = convert_float2(roi.s01) * convert_float(SPATIAL_SCALE); + const float2 roi_dims = fmax(convert_float2(roi.s23) * convert_float(SPATIAL_SCALE), 1.f); + + // Calculate pooled region start and end + const float2 spatial_indx = (float2)(px, py); + const float2 pooled_dims = (float2)(POOLED_DIM_X, POOLED_DIM_Y); + const float2 max_spatial_dims = (float2)(MAX_DIM_X, MAX_DIM_Y); + + const float2 bin_size = roi_dims / pooled_dims; + float2 region_start = spatial_indx * bin_size + roi_anchor; + float2 region_end = (spatial_indx + 1) * bin_size + roi_anchor; + + region_start = clamp(region_start, 0, max_spatial_dims); + region_end = clamp(region_end, 0, max_spatial_dims); + +#if defined(SAMPLING_RATIO) + const float2 roi_bin_grid = SAMPLING_RATIO; +#else // !defined(SAMPLING_RATIO) + // Note that we subtract EPS_GRID before ceiling. This is to avoid situations where 1.000001 gets ceiled to 2. + const float2 roi_bin_grid = ceil(roi_dims / pooled_dims - EPS_GRID); +#endif // defined(SAMPLING_RATIO) + + // Move input and output pointer across the fourth dimension + input.ptr += roi_batch * input_stride_w; + output.ptr += pw * output_stride_w; + for(int pz = 0; pz < MAX_DIM_Z; ++pz) + { + *(__global DATA_TYPE *)tensor3D_offset(&output, px, py, pz) = (__global DATA_TYPE)roi_align_1x1(&input, + region_start.x, + bin_size.x, + roi_bin_grid.x, + region_end.x, + region_start.y, + bin_size.y, + roi_bin_grid.y, + region_end.y, pz); + } +} +#endif // Check for compile time constants diff --git a/src/core/CL/kernels/CLROIAlignLayerKernel.cpp b/src/core/CL/kernels/CLROIAlignLayerKernel.cpp new file mode 100644 index 0000000000..2e1e85488b --- /dev/null +++ b/src/core/CL/kernels/CLROIAlignLayerKernel.cpp @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2018 ARM Limited. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#include "arm_compute/core/CL/kernels/CLROIAlignLayerKernel.h" + +#include "arm_compute/core/AccessWindowStatic.h" +#include "arm_compute/core/CL/CLHelpers.h" +#include "arm_compute/core/CL/CLKernelLibrary.h" +#include "arm_compute/core/CL/CLValidate.h" +#include "arm_compute/core/CL/ICLArray.h" +#include "arm_compute/core/CL/ICLTensor.h" +#include "arm_compute/core/CL/OpenCL.h" +#include "arm_compute/core/Helpers.h" +#include "arm_compute/core/TensorInfo.h" +#include "arm_compute/core/Utils.h" +#include "arm_compute/core/Window.h" + +namespace arm_compute +{ +namespace +{ +Status validate_arguments(const ITensorInfo *input, size_t num_rois, const ITensorInfo *output, const ROIPoolingLayerInfo &pool_info) +{ + ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(input, output); + ARM_COMPUTE_RETURN_ERROR_ON_F16_UNSUPPORTED(input); + ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input, 1, DataType::F32, DataType::F16); + ARM_COMPUTE_RETURN_ERROR_ON((pool_info.pooled_width() == 0) || (pool_info.pooled_height() == 0)); + ARM_COMPUTE_RETURN_ERROR_ON(num_rois == 0); + + if(output->total_size() != 0) + { + ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, output); + ARM_COMPUTE_RETURN_ERROR_ON((output->dimension(0) != pool_info.pooled_width()) || (output->dimension(1) != pool_info.pooled_height())); + ARM_COMPUTE_RETURN_ERROR_ON(input->dimension(2) != output->dimension(2)); + ARM_COMPUTE_RETURN_ERROR_ON(num_rois != output->dimension(3)); + } + + return Status{}; +} +} // namespace + +CLROIAlignLayerKernel::CLROIAlignLayerKernel() + : _input(nullptr), _output(nullptr), _rois(nullptr), _pool_info(0, 0, 0.f) +{ +} + +void CLROIAlignLayerKernel::configure(const ICLTensor *input, const ICLROIArray *rois, ICLTensor *output, const ROIPoolingLayerInfo &pool_info) +{ + ARM_COMPUTE_ERROR_ON_NULLPTR(input, output, rois); + ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input->info(), rois->num_values(), output->info(), pool_info)); + + TensorShape output_shape(pool_info.pooled_width(), pool_info.pooled_height(), input->info()->dimension(2), rois->num_values()); + auto_init_if_empty(*output->info(), output_shape, 1, input->info()->data_type()); + + _input = input; + _output = output; + _rois = rois; + _pool_info = pool_info; + + // Set build options + std::set build_opts; + build_opts.emplace(("-DDATA_TYPE=" + get_cl_type_from_data_type(input->info()->data_type()))); + build_opts.emplace(("-DDATA_SIZE=" + get_data_size_from_data_type(input->info()->data_type()))); + build_opts.emplace(("-DMAX_DIM_X=" + support::cpp11::to_string(_input->info()->dimension(Window::DimX)))); + build_opts.emplace(("-DMAX_DIM_Y=" + support::cpp11::to_string(_input->info()->dimension(Window::DimY)))); + build_opts.emplace(("-DMAX_DIM_Z=" + support::cpp11::to_string(_input->info()->dimension(Window::DimZ)))); + build_opts.emplace(("-DPOOLED_DIM_X=" + support::cpp11::to_string(pool_info.pooled_width()))); + build_opts.emplace(("-DPOOLED_DIM_Y=" + support::cpp11::to_string(pool_info.pooled_height()))); + build_opts.emplace(("-DSPATIAL_SCALE=" + float_to_string_with_full_precision(pool_info.spatial_scale()))); + if(pool_info.sampling_ratio() > 0) + { + build_opts.emplace(("-DSAMPLING_RATIO=" + support::cpp11::to_string(pool_info.sampling_ratio()))); + } + + // Create kernel + std::string kernel_name = "roi_align_layer"; + _kernel = static_cast(CLKernelLibrary::get().create_kernel(kernel_name, build_opts)); + + // Set static kernel arguments + unsigned int idx = 2 * num_arguments_per_3D_tensor() + num_arguments_per_1D_array(); + add_argument(idx, _input->info()->strides_in_bytes()[3]); + add_argument(idx, _output->info()->strides_in_bytes()[3]); + + // Configure kernel window + const unsigned int num_elems_processed_per_iteration = 1; + Window window = calculate_max_window(*output->info(), Steps(num_elems_processed_per_iteration)); + AccessWindowStatic input_access(input->info(), + input->info()->valid_region().start(0), + input->info()->valid_region().start(1), + input->info()->valid_region().end(0), + input->info()->valid_region().end(1)); + AccessWindowStatic output_access(output->info(), 0, 0, pool_info.pooled_width(), pool_info.pooled_height()); + + output_access.set_valid_region(window, ValidRegion(Coordinates(), output->info()->tensor_shape())); + ICLKernel::configure_internal(window); +} + +Status CLROIAlignLayerKernel::validate(const ITensorInfo *input, size_t num_rois, ITensorInfo *output, const ROIPoolingLayerInfo &pool_info) +{ + ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, num_rois, output, pool_info)); + return Status{}; +} + +void CLROIAlignLayerKernel::run(const Window &window, cl::CommandQueue &queue) +{ + ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this); + ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(IKernel::window(), window); + + Window slice = window.first_slice_window_3D(); + // Parallelize spatially and across the fourth dimension of the output tensor (also across ROIArray) + slice.set(Window::DimZ, window[3]); + + // Set arguments + unsigned int idx = 0; + add_3D_tensor_argument(idx, _input, slice); + add_1D_array_argument(idx, _rois, Strides(sizeof(ROI)), 1U, slice); + add_3D_tensor_argument(idx, _output, slice); + enqueue(queue, *this, slice); +} + +} // namespace arm_compute diff --git a/src/runtime/CL/functions/CLROIAlignLayer.cpp b/src/runtime/CL/functions/CLROIAlignLayer.cpp new file mode 100644 index 0000000000..1528759840 --- /dev/null +++ b/src/runtime/CL/functions/CLROIAlignLayer.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2018 ARM Limited. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#include "arm_compute/runtime/CL/functions/CLROIAlignLayer.h" + +#include "arm_compute/core/CL/ICLArray.h" +#include "arm_compute/core/CL/kernels/CLROIAlignLayerKernel.h" +#include "support/ToolchainSupport.h" + +namespace arm_compute +{ +Status CLROIAlignLayer::validate(const ITensorInfo *input, size_t num_rois, ITensorInfo *output, const ROIPoolingLayerInfo &pool_info) +{ + ARM_COMPUTE_RETURN_ON_ERROR(CLROIAlignLayerKernel::validate(input, num_rois, output, pool_info)); + + return Status{}; +} + +void CLROIAlignLayer::configure(const ICLTensor *input, const ICLROIArray *rois, ICLTensor *output, const ROIPoolingLayerInfo &pool_info) +{ + // Configure ROI pooling kernel + auto k = arm_compute::support::cpp14::make_unique(); + k->configure(input, rois, output, pool_info); + _kernel = std::move(k); +} + +} // namespace arm_compute diff --git a/tests/datasets/ROIPoolingLayerDataset.h b/tests/datasets/ROIPoolingLayerDataset.h index a1879d3b54..eb1d165202 100644 --- a/tests/datasets/ROIPoolingLayerDataset.h +++ b/tests/datasets/ROIPoolingLayerDataset.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 ARM Limited. + * Copyright (c) 2017-2018 ARM Limited. * * SPDX-License-Identifier: MIT * @@ -112,6 +112,8 @@ class SmallROIPoolingLayerDataset final : public ROIPoolingLayerDataset public: SmallROIPoolingLayerDataset() { + add_config(TensorShape(50U, 47U, 1U), ROIPoolingLayerInfo(7U, 7U, 1.f / 8.f), 1U); + add_config(TensorShape(50U, 47U, 3U), ROIPoolingLayerInfo(7U, 7U, 1.f / 8.f), 1U); add_config(TensorShape(50U, 47U, 3U), ROIPoolingLayerInfo(7U, 7U, 1.f / 8.f), 40U); add_config(TensorShape(50U, 47U, 10U), ROIPoolingLayerInfo(7U, 7U, 1.f / 8.f), 80U); add_config(TensorShape(50U, 47U, 80U), ROIPoolingLayerInfo(7U, 7U, 1.f / 8.f), 80U); diff --git a/tests/validation/CL/ROIAlignLayer.cpp b/tests/validation/CL/ROIAlignLayer.cpp new file mode 100644 index 0000000000..8be16b4ad1 --- /dev/null +++ b/tests/validation/CL/ROIAlignLayer.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2018 ARM Limited. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#include "arm_compute/runtime/CL/CLScheduler.h" +#include "arm_compute/runtime/CL/functions/CLROIAlignLayer.h" +#include "tests/CL/CLAccessor.h" +#include "tests/CL/CLArrayAccessor.h" +#include "tests/Globals.h" +#include "tests/datasets/ROIPoolingLayerDataset.h" +#include "tests/datasets/ShapeDatasets.h" +#include "tests/framework/Macros.h" +#include "tests/framework/datasets/Datasets.h" +#include "tests/validation/Validation.h" +#include "tests/validation/fixtures/ROIAlignLayerFixture.h" +#include "utils/TypePrinter.h" + +namespace arm_compute +{ +namespace test +{ +namespace validation +{ +namespace +{ +RelativeTolerance relative_tolerance_f32(0.01f); +RelativeTolerance absolute_tolerance_f32(0.001f); +} // namespace + +TEST_SUITE(CL) +TEST_SUITE(RoiAlign) + +// *INDENT-OFF* +// clang-format off +DATA_TEST_CASE(Validate, framework::DatasetMode::ALL, zip(zip(zip(zip( + framework::dataset::make("InputInfo", { TensorInfo(TensorShape(250U, 128U, 3U), 1, DataType::F32), + TensorInfo(TensorShape(250U, 128U, 3U), 1, DataType::F32), // Mismatching data type input/output + TensorInfo(TensorShape(250U, 128U, 2U), 1, DataType::F32), // Mismatching depth size input/output + TensorInfo(TensorShape(250U, 128U, 2U), 1, DataType::F32), // Mismatching number of rois and output batch size + TensorInfo(TensorShape(250U, 128U, 2U), 1, DataType::F32), // Mismatching height and width input/output + + }), + framework::dataset::make("NumRois", { 3U, 3U, 4U, 10U, 4U})), + framework::dataset::make("OutputInfo",{ TensorInfo(TensorShape(7U, 7U, 3U, 3U), 1, DataType::F32), + TensorInfo(TensorShape(7U, 7U, 3U, 3U), 1, DataType::F16), + TensorInfo(TensorShape(7U, 7U, 4U, 3U), 1, DataType::F32), + TensorInfo(TensorShape(7U, 7U, 2U, 3U), 1, DataType::F32), + TensorInfo(TensorShape(5U, 5U, 2U, 4U), 1, DataType::F32), + })), + framework::dataset::make("PoolInfo", { ROIPoolingLayerInfo(7U, 7U, 1./8), + ROIPoolingLayerInfo(7U, 7U, 1./8), + ROIPoolingLayerInfo(7U, 7U, 1./8), + ROIPoolingLayerInfo(7U, 7U, 1./8), + ROIPoolingLayerInfo(7U, 7U, 1./8), + })), + framework::dataset::make("Expected", { true, false, false, false, false })), + input_info, num_rois, output_info, pool_info, expected) +{ + ARM_COMPUTE_EXPECT(bool(CLROIAlignLayer::validate(&input_info.clone()->set_is_resizable(true), num_rois, &output_info.clone()->set_is_resizable(true), pool_info)) == expected, framework::LogLevel::ERRORS); +} +// clang-format on +// *INDENT-ON* + +template +using CLROIAlignLayerFixture = ROIAlignLayerFixture, CLArrayAccessor, T>; + +TEST_SUITE(Float) +TEST_SUITE(FP32) +FIXTURE_DATA_TEST_CASE(SmallROIAlignLayer, CLROIAlignLayerFixture, framework::DatasetMode::ALL, + framework::dataset::combine(framework::dataset::combine(datasets::SmallROIPoolingLayerDataset(), + framework::dataset::make("DataType", { DataType::F32 })), + framework::dataset::make("Batches", { 1, 4, 8 }))) +{ + // Validate output + validate(CLAccessor(_target), _reference, relative_tolerance_f32, 0.f, absolute_tolerance_f32); +} +TEST_SUITE_END() // FP32 + +TEST_SUITE_END() // Float + +TEST_SUITE_END() // RoiAlign +TEST_SUITE_END() // CL +} // namespace validation +} // namespace test +} // namespace arm_compute diff --git a/tests/validation/fixtures/ROIAlignLayerFixture.h b/tests/validation/fixtures/ROIAlignLayerFixture.h new file mode 100644 index 0000000000..d327b0914e --- /dev/null +++ b/tests/validation/fixtures/ROIAlignLayerFixture.h @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2018 ARM Limited. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef ARM_COMPUTE_TEST_ROIALIGNLAYER_FIXTURE +#define ARM_COMPUTE_TEST_ROIALIGNLAYER_FIXTURE + +#include "arm_compute/core/TensorShape.h" +#include "arm_compute/core/Types.h" +#include "arm_compute/runtime/CL/functions/CLROIAlignLayer.h" +#include "tests/AssetsLibrary.h" +#include "tests/Globals.h" +#include "tests/IAccessor.h" +#include "tests/framework/Asserts.h" +#include "tests/framework/Fixture.h" +#include "tests/validation/Helpers.h" +#include "tests/validation/reference/ROIAlignLayer.h" + +namespace arm_compute +{ +namespace test +{ +namespace validation +{ +template +class ROIAlignLayerFixture : public framework::Fixture +{ +public: + template + void setup(TensorShape input_shape, const ROIPoolingLayerInfo pool_info, unsigned int num_rois, DataType data_type, int batches) + { + input_shape.set(2, batches); + std::vector rois = generate_random_rois(input_shape, pool_info, num_rois, 0U); + + _target = compute_target(input_shape, data_type, rois, pool_info); + _reference = compute_reference(input_shape, data_type, rois, pool_info); + } + +protected: + template + void fill(U &&tensor) + { + library->fill_tensor_uniform(tensor, 0); + } + + TensorType compute_target(const TensorShape &input_shape, + DataType data_type, + std::vector const &rois, + const ROIPoolingLayerInfo &pool_info) + { + // Create tensors + TensorType src = create_tensor(input_shape, data_type); + TensorType dst; + + size_t num_rois = rois.size(); + + // Create roi arrays + std::unique_ptr rois_array = arm_compute::support::cpp14::make_unique(num_rois); + fill_array(ArrayAccessor(*rois_array), rois); + + // Create and configure function + FunctionType roi_align_layer; + roi_align_layer.configure(&src, rois_array.get(), &dst, pool_info); + + ARM_COMPUTE_EXPECT(src.info()->is_resizable(), framework::LogLevel::ERRORS); + ARM_COMPUTE_EXPECT(dst.info()->is_resizable(), framework::LogLevel::ERRORS); + + // Allocate tensors + src.allocator()->allocate(); + dst.allocator()->allocate(); + + ARM_COMPUTE_EXPECT(!src.info()->is_resizable(), framework::LogLevel::ERRORS); + ARM_COMPUTE_EXPECT(!dst.info()->is_resizable(), framework::LogLevel::ERRORS); + + // Fill tensors + fill(AccessorType(src)); + + // Compute function + roi_align_layer.run(); + + return dst; + } + + SimpleTensor compute_reference(const TensorShape &input_shape, + DataType data_type, + std::vector const &rois, + const ROIPoolingLayerInfo &pool_info) + { + // Create reference tensor + SimpleTensor src{ input_shape, data_type }; + + // Fill reference tensor + fill(src); + + return reference::roi_align_layer(src, rois, pool_info); + } + + TensorType _target{}; + SimpleTensor _reference{}; +}; + +} // namespace validation +} // namespace test +} // namespace arm_compute +#endif /* ARM_COMPUTE_TEST_ROIALIGNLAYER_FIXTURE */ diff --git a/tests/validation/reference/ROIAlignLayer.cpp b/tests/validation/reference/ROIAlignLayer.cpp new file mode 100644 index 0000000000..68a465d18f --- /dev/null +++ b/tests/validation/reference/ROIAlignLayer.cpp @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2018 ARM Limited. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#include "ROIAlignLayer.h" + +#include "arm_compute/core/Types.h" +#include "arm_compute/core/utils/misc/ShapeCalculator.h" +#include "tests/validation/Helpers.h" + +#include + +namespace arm_compute +{ +namespace test +{ +namespace validation +{ +namespace reference +{ +namespace +{ +/** Average pooling over an aligned window */ +template +inline T roi_align_1x1(const T *input, TensorShape input_shape, + float region_start_x, + float bin_size_x, + int grid_size_x, + float region_end_x, + float region_start_y, + float bin_size_y, + int grid_size_y, + float region_end_y, + int pz) +{ + if((region_end_x <= region_start_x) || (region_end_y <= region_start_y)) + { + return T(0); + } + else + { + float avg = 0; + // Iterate through the aligned pooling region + for(int iy = 0; iy < grid_size_y; ++iy) + { + for(int ix = 0; ix < grid_size_x; ++ix) + { + // Align the window in the middle of every bin + float y = region_start_y + (iy + 0.5) * bin_size_y / float(grid_size_y); + float x = region_start_x + (ix + 0.5) * bin_size_x / float(grid_size_x); + + // Interpolation in the [0,0] [0,1] [1,0] [1,1] square + const int y_low = y; + const int x_low = x; + const int y_high = y_low + 1; + const int x_high = x_low + 1; + + const float ly = y - y_low; + const float lx = x - x_low; + const float hy = 1. - ly; + const float hx = 1. - lx; + + const float w1 = hy * hx; + const float w2 = hy * lx; + const float w3 = ly * hx; + const float w4 = ly * lx; + + const size_t idx1 = coord2index(input_shape, Coordinates(x_low, y_low, pz)); + T data1 = input[idx1]; + + const size_t idx2 = coord2index(input_shape, Coordinates(x_high, y_low, pz)); + T data2 = input[idx2]; + + const size_t idx3 = coord2index(input_shape, Coordinates(x_low, y_high, pz)); + T data3 = input[idx3]; + + const size_t idx4 = coord2index(input_shape, Coordinates(x_high, y_high, pz)); + T data4 = input[idx4]; + + avg += w1 * data1 + w2 * data2 + w3 * data3 + w4 * data4; + } + } + + avg /= grid_size_x * grid_size_y; + + return T(avg); + } +} + +/** Clamp the value between lower and upper */ +template +T clamp(T value, T lower, T upper) +{ + return std::max(lower, std::min(value, upper)); +} +} // namespace +template +SimpleTensor roi_align_layer(const SimpleTensor &src, const std::vector &rois, const ROIPoolingLayerInfo &pool_info) +{ + const size_t num_rois = rois.size(); + DataType dst_data_type = src.data_type(); + + TensorShape input_shape = src.shape(); + TensorShape output_shape(pool_info.pooled_width(), pool_info.pooled_height(), src.shape()[2], num_rois); + SimpleTensor dst(output_shape, dst_data_type); + + // Iterate over every pixel of the input image + for(size_t px = 0; px < pool_info.pooled_width(); px++) + { + for(size_t py = 0; py < pool_info.pooled_height(); py++) + { + for(size_t pw = 0; pw < num_rois; pw++) + { + ROI roi = rois[pw]; + const int roi_batch = roi.batch_idx; + + const float roi_anchor_x = roi.rect.x * pool_info.spatial_scale(); + const float roi_anchor_y = roi.rect.y * pool_info.spatial_scale(); + const float roi_dims_x = std::max(roi.rect.width * pool_info.spatial_scale(), 1.0f); + const float roi_dims_y = std::max(roi.rect.height * pool_info.spatial_scale(), 1.0f); + ; + + float bin_size_x = roi_dims_x / pool_info.pooled_width(); + float bin_size_y = roi_dims_y / pool_info.pooled_height(); + float region_start_x = px * bin_size_x + roi_anchor_x; + float region_start_y = py * bin_size_y + roi_anchor_y; + float region_end_x = (px + 1) * bin_size_x + roi_anchor_x; + float region_end_y = (py + 1) * bin_size_y + roi_anchor_y; + + region_start_x = clamp(region_start_x, 0.0f, float(input_shape[0])); + region_start_y = clamp(region_start_y, 0.0f, float(input_shape[1])); + region_end_x = clamp(region_end_x, 0.0f, float(input_shape[0])); + region_end_y = clamp(region_end_y, 0.0f, float(input_shape[1])); + + const int roi_bin_grid_x = (pool_info.sampling_ratio() > 0) ? pool_info.sampling_ratio() : int(ceil(bin_size_x)); + const int roi_bin_grid_y = (pool_info.sampling_ratio() > 0) ? pool_info.sampling_ratio() : int(ceil(bin_size_y)); + + // Move input and output pointer across the fourth dimension + const size_t input_stride_w = input_shape[0] * input_shape[1] * input_shape[2]; + const size_t output_stride_w = output_shape[0] * output_shape[1] * output_shape[2]; + const T *input_ptr = src.data() + roi_batch * input_stride_w; + T *output_ptr = dst.data() + px + py * output_shape[0] + pw * output_stride_w; + + for(int pz = 0; pz < int(input_shape[2]); ++pz) + { + // For every pixel pool over an aligned region + *(output_ptr + pz * output_shape[0] * output_shape[1]) = roi_align_1x1(input_ptr, input_shape, + region_start_x, + bin_size_x, + roi_bin_grid_x, + region_end_x, + region_start_y, + bin_size_y, + roi_bin_grid_y, + region_end_y, pz); + } + } + } + } + return dst; +} +template SimpleTensor roi_align_layer(const SimpleTensor &src, const std::vector &rois, const ROIPoolingLayerInfo &pool_info); +template SimpleTensor roi_align_layer(const SimpleTensor &src, const std::vector &rois, const ROIPoolingLayerInfo &pool_info); +} // namespace reference +} // namespace validation +} // namespace test +} // namespace arm_compute diff --git a/tests/validation/reference/ROIAlignLayer.h b/tests/validation/reference/ROIAlignLayer.h new file mode 100644 index 0000000000..818f9b147c --- /dev/null +++ b/tests/validation/reference/ROIAlignLayer.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2018 ARM Limited. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef __ARM_COMPUTE_TEST_ROIALIGNLAYER_H__ +#define __ARM_COMPUTE_TEST_ROIALIGNLAYER_H__ + +#include "arm_compute/core/Types.h" +#include "tests/SimpleTensor.h" +#include "tests/validation/Helpers.h" + +namespace arm_compute +{ +namespace test +{ +namespace validation +{ +namespace reference +{ +template +SimpleTensor roi_align_layer(const SimpleTensor &src, const std::vector &rois, const ROIPoolingLayerInfo &pool_info); +} // namespace reference +} // namespace validation +} // namespace test +} // namespace arm_compute +#endif /* __ARM_COMPUTE_TEST_ROIALIGNLAYER_H__ */ diff --git a/utils/TypePrinter.h b/utils/TypePrinter.h index d31c16c32b..10e407ddfa 100644 --- a/utils/TypePrinter.h +++ b/utils/TypePrinter.h @@ -220,6 +220,19 @@ inline ::std::ostream &operator<<(::std::ostream &os, const ROIPoolingLayerInfo return os; } +/** Formatted output of the ROIPoolingInfo type. + * + * @param[in] pool_info Type to output. + * + * @return Formatted string. + */ +inline std::string to_string(const ROIPoolingLayerInfo &pool_info) +{ + std::stringstream str; + str << pool_info; + return str.str(); +} + /** Formatted output of the QuantizationInfo type. * * @param[out] os Output stream. -- cgit v1.2.1