From cd96a26f67bfbb9b0efe6e0e2b229d0b46b4e3e6 Mon Sep 17 00:00:00 2001 From: giuros01 Date: Wed, 3 Oct 2018 12:44:35 +0100 Subject: COMPMID-1329: Add support for GenerateProposals operator in CL Change-Id: Ib0798cc17496b7817f5b5769b25d98913a33a69d --- arm_compute/core/CL/CLKernels.h | 1 + .../CL/kernels/CLGenerateProposalsLayerKernel.h | 76 +++++ arm_compute/core/Types.h | 163 +++++++++- arm_compute/runtime/CL/CLFunctions.h | 2 + .../runtime/CL/functions/CLComputeAllAnchors.h | 62 ++++ .../CL/functions/CLGenerateProposalsLayer.h | 146 +++++++++ src/core/CL/CLKernelLibrary.cpp | 5 + src/core/CL/cl_kernels/bounding_box_transform.cl | 6 +- src/core/CL/cl_kernels/generate_proposals.cl | 88 ++++++ .../CL/kernels/CLGenerateProposalsLayerKernel.cpp | 128 ++++++++ .../CPPBoxWithNonMaximaSuppressionLimitKernel.cpp | 35 ++- src/runtime/CL/functions/CLComputeAllAnchors.cpp | 42 +++ .../CL/functions/CLGenerateProposalsLayer.cpp | 251 ++++++++++++++++ tests/validation/CL/GenerateProposalsLayer.cpp | 334 +++++++++++++++++++++ .../validation/fixtures/ComputeAllAnchorsFixture.h | 107 +++++++ .../validation/reference/BoundingBoxTransform.cpp | 8 +- tests/validation/reference/ComputeAllAnchors.cpp | 79 +++++ tests/validation/reference/ComputeAllAnchors.h | 45 +++ utils/TypePrinter.h | 52 ++++ 19 files changed, 1606 insertions(+), 24 deletions(-) create mode 100644 arm_compute/core/CL/kernels/CLGenerateProposalsLayerKernel.h create mode 100644 arm_compute/runtime/CL/functions/CLComputeAllAnchors.h create mode 100644 arm_compute/runtime/CL/functions/CLGenerateProposalsLayer.h create mode 100644 src/core/CL/cl_kernels/generate_proposals.cl create mode 100644 src/core/CL/kernels/CLGenerateProposalsLayerKernel.cpp create mode 100644 src/runtime/CL/functions/CLComputeAllAnchors.cpp create mode 100644 src/runtime/CL/functions/CLGenerateProposalsLayer.cpp create mode 100644 tests/validation/CL/GenerateProposalsLayer.cpp create mode 100644 tests/validation/fixtures/ComputeAllAnchorsFixture.h create mode 100644 tests/validation/reference/ComputeAllAnchors.cpp create mode 100644 tests/validation/reference/ComputeAllAnchors.h diff --git a/arm_compute/core/CL/CLKernels.h b/arm_compute/core/CL/CLKernels.h index 12700192e6..cc76231345 100644 --- a/arm_compute/core/CL/CLKernels.h +++ b/arm_compute/core/CL/CLKernels.h @@ -83,6 +83,7 @@ #include "arm_compute/core/CL/kernels/CLGaussian3x3Kernel.h" #include "arm_compute/core/CL/kernels/CLGaussian5x5Kernel.h" #include "arm_compute/core/CL/kernels/CLGaussianPyramidKernel.h" +#include "arm_compute/core/CL/kernels/CLGenerateProposalsLayerKernel.h" #include "arm_compute/core/CL/kernels/CLHOGDescriptorKernel.h" #include "arm_compute/core/CL/kernels/CLHOGDetectorKernel.h" #include "arm_compute/core/CL/kernels/CLHarrisCornersKernel.h" diff --git a/arm_compute/core/CL/kernels/CLGenerateProposalsLayerKernel.h b/arm_compute/core/CL/kernels/CLGenerateProposalsLayerKernel.h new file mode 100644 index 0000000000..6c883348a5 --- /dev/null +++ b/arm_compute/core/CL/kernels/CLGenerateProposalsLayerKernel.h @@ -0,0 +1,76 @@ +/* + * 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_CLGENERATEPROPOSALSLAYERKERNEL_H__ +#define __ARM_COMPUTE_CLGENERATEPROPOSALSLAYERKERNEL_H__ + +#include "arm_compute/core/CL/ICLKernel.h" +namespace arm_compute +{ +class ICLTensor; + +/** Interface for Compute All Anchors kernel */ +class CLComputeAllAnchorsKernel : public ICLKernel +{ +public: + /** Default constructor */ + CLComputeAllAnchorsKernel(); + /** Prevent instances of this class from being copied (As this class contains pointers) */ + CLComputeAllAnchorsKernel(const CLComputeAllAnchorsKernel &) = delete; + /** Prevent instances of this class from being copied (As this class contains pointers) */ + CLComputeAllAnchorsKernel &operator=(const CLComputeAllAnchorsKernel &) = delete; + /** Allow instances of this class to be moved */ + CLComputeAllAnchorsKernel(CLComputeAllAnchorsKernel &&) = default; + /** Allow instances of this class to be moved */ + CLComputeAllAnchorsKernel &operator=(CLComputeAllAnchorsKernel &&) = default; + /** Default destructor */ + ~CLComputeAllAnchorsKernel() = default; + + /** Set the input and output tensors. + * + * @param[in] anchors Source tensor. Original set of anchors of size (4, A), where A is the number of anchors. Data types supported: F16/F32 + * @param[out] all_anchors Destination tensor. Destination anchors of size (4, H*W*A) where H and W are the height and width of the feature map and A is the number of anchors. Data types supported: Same as @p input + * @param[in] info Contains Compute Anchors operation information described in @ref ComputeAnchorsInfo + * + */ + void configure(const ICLTensor *anchors, ICLTensor *all_anchors, const ComputeAnchorsInfo &info); + + /** Static function to check if given info will lead to a valid configuration of @ref CLComputeAllAnchorsKernel + * + * @param[in] anchors Source tensor info. Original set of anchors of size (4, A), where A is the number of anchors. Data types supported: F16/F32 + * @param[in] all_anchors Destination tensor info. Destination anchors of size (4, H*W*A) where H and W are the height and width of the feature map and A is the number of anchors. Data types supported: Same as @p input + * @param[in] info Contains Compute Anchors operation information described in @ref ComputeAnchorsInfo + * + * @return a Status + */ + static Status validate(const ITensorInfo *anchors, const ITensorInfo *all_anchors, const ComputeAnchorsInfo &info); + + // Inherited methods overridden: + void run(const Window &window, cl::CommandQueue &queue) override; + +private: + const ICLTensor *_anchors; + ICLTensor *_all_anchors; +}; +} // arm_compute +#endif // __ARM_COMPUTE_CLGENERATEPROSPOSALSLAYERKERNEL_H__ diff --git a/arm_compute/core/Types.h b/arm_compute/core/Types.h index 03f195f7da..1c9571463b 100644 --- a/arm_compute/core/Types.h +++ b/arm_compute/core/Types.h @@ -595,13 +595,17 @@ public: * @param[in] soft_nms_method (Optional) Soft NMS method * @param[in] soft_nms_sigma (Optional) Soft NMS sigma value * @param[in] soft_nms_min_score_thres (Optional) Soft NMS minimum score threshold + * @param[in] suppress_size (Optional) Filter out boxes based on their size. Defaults to false + * @param[in] min_size (Optional) Smaller boxes than min_size will be filtered out. Defaults to 1 + * @param[in] im_width (Optional) Boxes whose centers (on the x axis) is beyond im_width will be filtered. Defaults to 1 + * @param[in] im_height (Optional) Boxes whose centers (on the y axis) is beyond im_height will be filtered. Defaults to 1 */ BoxNMSLimitInfo(float score_thresh = 0.05f, float nms = 0.3f, int detections = 100, bool soft_nms_enabled = false, NMSType soft_nms_method = NMSType::LINEAR, - float soft_nms_sigma = 0.5f, float soft_nms_min_score_thres = 0.001f) + float soft_nms_sigma = 0.5f, float soft_nms_min_score_thres = 0.001f, bool suppress_size = false, float min_size = 1.0f, float im_width = 1.0f, float im_height = 1.0f) : _score_thresh(score_thresh), _nms(nms), _detections_per_im(detections), _soft_nms_enabled(soft_nms_enabled), _soft_nms_method(soft_nms_method), _soft_nms_sigma(soft_nms_sigma), - _soft_nms_min_score_thres(soft_nms_min_score_thres) + _soft_nms_min_score_thres(soft_nms_min_score_thres), _suppress_size(suppress_size), _min_size(min_size), _im_width(im_width), _im_height(im_height) { } /** Get the score threshold */ @@ -639,6 +643,26 @@ public: { return _soft_nms_min_score_thres; } + /** Get if NMS will suppress boxes based on their size/position */ + bool suppress_size() const + { + return _suppress_size; + } + /** Get size suppression threshold */ + float min_size() const + { + return _min_size; + } + /** Get image width (NMS may suppress boxes whose center sits beyond the image width) */ + float im_width() const + { + return _im_width; + } + /** Get image height (NMS may suppress boxes whose center sits beyond the image height) */ + float im_height() const + { + return _im_height; + } private: float _score_thresh; @@ -648,6 +672,10 @@ private: NMSType _soft_nms_method; float _soft_nms_sigma; float _soft_nms_min_score_thres; + bool _suppress_size; + float _min_size; + float _im_width; + float _im_height; }; /** Padding and stride information class */ @@ -1049,6 +1077,137 @@ private: unsigned int _sampling_ratio; }; +/** Generate Proposals Information class */ +class GenerateProposalsInfo +{ +public: + /** Constructor + * + * @param[in] im_width Width of the original image + * @param[in] im_height Height of the original image + * @param[in] im_scale Scale applied to the original image + * @param[in] spatial_scale (Optional)Scale applied to the feature map. Defaults to 1.0 + * @param[in] pre_nms_topN (Optional)Number of the best scores to be selected from the transformations. Defaults to 6000. + * @param[in] post_nms_topN (Optional)Number of the best scores to be selected from the NMS operation. Defaults to 300. + * @param[in] nms_thres (Optional)NMS overlap threshold. Defaults to 0.7. + * @param[in] min_size (Optional)Size used to validate the anchors produced. Defaults to 16. + * @param[in] values_per_roi (Optional)Values used to represent a ROI(Region of interest). Defaults to 4. + */ + GenerateProposalsInfo(float im_width, float im_height, float im_scale, float spatial_scale = 1.0, int pre_nms_topN = 6000, int post_nms_topN = 300, float nms_thres = 0.7, float min_size = 16.0, + size_t values_per_roi = 4) + : _im_height(im_height), _im_width(im_width), _im_scale(im_scale), _spatial_scale(spatial_scale), _pre_nms_topN(pre_nms_topN), _post_nms_topN(post_nms_topN), _nms_thres(nms_thres), + _min_size(min_size), _values_per_roi(values_per_roi) + { + } + + /* Get the original height */ + float im_height() const + { + return _im_height; + } + /* Get the original width */ + float im_width() const + { + return _im_width; + } + /* Get the image scale */ + float im_scale() const + { + return _im_scale; + } + /* Get the value of how many best scores to select (before NMS) */ + int pre_nms_topN() const + { + return _pre_nms_topN; + } + /* Get the value of how many best scores to select (after NMS) */ + int post_nms_topN() const + { + return _post_nms_topN; + } + /* Get the NMS overlap threshold */ + float nms_thres() const + { + return _nms_thres; + } + /* Get the minimal size */ + float min_size() const + { + return _min_size; + } + /* Get the spatial scale to be applied to the feature maps */ + float spatial_scale() const + { + return _spatial_scale; + } + /* Get the values used to represent a ROI(Region of interest)*/ + size_t values_per_roi() const + { + return _values_per_roi; + } + +private: + float _im_height; + float _im_width; + float _im_scale; + float _spatial_scale; + int _pre_nms_topN; + int _post_nms_topN; + float _nms_thres; + float _min_size; + size_t _values_per_roi; +}; + +/** ComputeAnchors information class */ +class ComputeAnchorsInfo +{ +public: + /** Constructor + * + * @param[in] feat_width Feature map width + * @param[in] feat_height Feature map height + * @param[in] spatial_scale Feature map scale + * @param[in] values_per_roi (Optional)Values used to represent a ROI(Region Of Interest). Defaults to 4 + */ + ComputeAnchorsInfo(float feat_width, float feat_height, float spatial_scale, size_t values_per_roi = 4) + : _feat_height(feat_height), + _feat_width(feat_width), + _spatial_scale(spatial_scale), + _values_per_roi(values_per_roi) + { + } + + /* Get the height of the feature map */ + float feat_height() const + { + return _feat_height; + } + + /* Get the width of the feature map */ + float feat_width() const + { + return _feat_width; + } + + /* Get the scale of the feature map */ + float spatial_scale() const + { + return _spatial_scale; + } + + /* Get the values used to represent a ROI(Region Of Interest)*/ + size_t values_per_roi() const + { + return _values_per_roi; + } + +private: + float _feat_height; + float _feat_width; + float _spatial_scale; + size_t _values_per_roi; +}; + /** Bounding Box Transform information class */ class BoundingBoxTransformInfo { diff --git a/arm_compute/runtime/CL/CLFunctions.h b/arm_compute/runtime/CL/CLFunctions.h index 694e818788..9d4aa5b6a2 100644 --- a/arm_compute/runtime/CL/CLFunctions.h +++ b/arm_compute/runtime/CL/CLFunctions.h @@ -44,6 +44,7 @@ #include "arm_compute/runtime/CL/functions/CLChannelExtract.h" #include "arm_compute/runtime/CL/functions/CLChannelShuffleLayer.h" #include "arm_compute/runtime/CL/functions/CLColorConvert.h" +#include "arm_compute/runtime/CL/functions/CLComputeAllAnchors.h" #include "arm_compute/runtime/CL/functions/CLConcatenateLayer.h" #include "arm_compute/runtime/CL/functions/CLConvertFullyConnectedWeights.h" #include "arm_compute/runtime/CL/functions/CLConvolution.h" @@ -76,6 +77,7 @@ #include "arm_compute/runtime/CL/functions/CLGaussian3x3.h" #include "arm_compute/runtime/CL/functions/CLGaussian5x5.h" #include "arm_compute/runtime/CL/functions/CLGaussianPyramid.h" +#include "arm_compute/runtime/CL/functions/CLGenerateProposalsLayer.h" #include "arm_compute/runtime/CL/functions/CLHOGDescriptor.h" #include "arm_compute/runtime/CL/functions/CLHOGDetector.h" #include "arm_compute/runtime/CL/functions/CLHOGGradient.h" diff --git a/arm_compute/runtime/CL/functions/CLComputeAllAnchors.h b/arm_compute/runtime/CL/functions/CLComputeAllAnchors.h new file mode 100644 index 0000000000..6c6da791a1 --- /dev/null +++ b/arm_compute/runtime/CL/functions/CLComputeAllAnchors.h @@ -0,0 +1,62 @@ +/* + * 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_CLCOMPUTEALLANCHORS_H__ +#define __ARM_COMPUTE_CLCOMPUTEALLANCHORS_H__ + +#include "arm_compute/core/CL/kernels/CLGenerateProposalsLayerKernel.h" +#include "arm_compute/runtime/CL/ICLSimpleFunction.h" + +namespace arm_compute +{ +class ICLTensor; + +/** Basic function to run @ref CLComputeAllAnchorsKernel. + * + * This function calls the following OpenCL kernels: + * -# @ref CLComputeAllAnchorsKernel + */ +class CLComputeAllAnchors : public ICLSimpleFunction +{ +public: + /** Set the input and output tensors. + * + * @param[in] anchors Source tensor. Original set of anchors of size (4, A) where A is the number of anchors. Data types supported: F16/F32 + * @param[out] all_anchors Destination tensor. Destination anchors of size (4, H*W*A) where H and W are the height and width of the feature map and A is the number of anchors. Data types supported: Same as @p input + * @param[in] info Contains Compute Anchors operation information described in @ref ComputeAnchorsInfo + * + */ + void configure(const ICLTensor *anchors, ICLTensor *all_anchors, const ComputeAnchorsInfo &info); + + /** Static function to check if given info will lead to a valid configuration of @ref CLComputeAllAnchorsKernel + * + * @param[in] anchors Source tensor info. Original set of anchors of size (4, A) where A is the number of anchors. Data types supported: F16/F32 + * @param[in] all_anchors Destination tensor info. Destination anchors of size (4, H*W*A) where H and W are the height and width of the feature map and A is the number of anchors. Data types supported: Same as @p input + * @param[in] info Contains Compute Anchors operation information described in @ref ComputeAnchorsInfo + * + * @return a Status + */ + static Status validate(const ITensorInfo *anchors, const ITensorInfo *all_anchors, const ComputeAnchorsInfo &info); +}; +} // namespace arm_compute +#endif /* __ARM_COMPUTE_CLCOMPUTEALLANCOHORS_H__ */ diff --git a/arm_compute/runtime/CL/functions/CLGenerateProposalsLayer.h b/arm_compute/runtime/CL/functions/CLGenerateProposalsLayer.h new file mode 100644 index 0000000000..343229fe10 --- /dev/null +++ b/arm_compute/runtime/CL/functions/CLGenerateProposalsLayer.h @@ -0,0 +1,146 @@ +/* + * 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_CLGENERATEPROPOSALSLAYER_H__ +#define __ARM_COMPUTE_CLGENERATEPROPOSALSLAYER_H__ +#include "arm_compute/core/CL/kernels/CLBoundingBoxTransformKernel.h" +#include "arm_compute/core/CL/kernels/CLCopyKernel.h" +#include "arm_compute/core/CL/kernels/CLGenerateProposalsLayerKernel.h" +#include "arm_compute/core/CL/kernels/CLMemsetKernel.h" +#include "arm_compute/core/CL/kernels/CLPermuteKernel.h" +#include "arm_compute/core/CL/kernels/CLReshapeLayerKernel.h" +#include "arm_compute/core/CL/kernels/CLStridedSliceKernel.h" +#include "arm_compute/core/CPP/kernels/CPPBoxWithNonMaximaSuppressionLimitKernel.h" +#include "arm_compute/core/Types.h" +#include "arm_compute/runtime/CL/CLMemoryGroup.h" +#include "arm_compute/runtime/CL/CLScheduler.h" +#include "arm_compute/runtime/CL/CLTensor.h" +#include "arm_compute/runtime/CPP/CPPScheduler.h" +#include "arm_compute/runtime/IFunction.h" + +namespace arm_compute +{ +class ICLTensor; + +/** Basic function to generate proposals for a RPN (Region Proposal Network) + * + * This function calls the following OpenCL kernels: + * -# @ref CLComputeAllAnchors + * -# @ref CLPermute x 2 + * -# @ref CLReshapeLayer x 2 + * -# @ref CLStridedSlice x 3 + * -# @ref CLBoundingBoxTransform + * -# @ref CLCopyKernel + * -# @ref CLMemsetKernel + * And the following CPP kernels: + * -# @ref CPPBoxWithNonMaximaSuppressionLimit + */ +class CLGenerateProposalsLayer : public IFunction +{ +public: + /** Default constructor + * + * @param[in] memory_manager (Optional) Memory manager. + */ + CLGenerateProposalsLayer(std::shared_ptr memory_manager = nullptr); + /** Prevent instances of this class from being copied (As this class contains pointers) */ + CLGenerateProposalsLayer(const CLGenerateProposalsLayer &) = delete; + /** Default move constructor */ + CLGenerateProposalsLayer(CLGenerateProposalsLayer &&) = default; + /** Prevent instances of this class from being copied (As this class contains pointers) */ + CLGenerateProposalsLayer &operator=(const CLGenerateProposalsLayer &) = delete; + /** Default move assignment operator */ + CLGenerateProposalsLayer &operator=(CLGenerateProposalsLayer &&) = default; + + /** Set the input and output tensors. + * + * @param[in] scores Scores from convolution layer of size (W, H, A), where H and W are the height and width of the feature map, and A is the number of anchors. Data types supported: F16/F32 + * @param[in] deltas Bounding box deltas from convolution layer of size (W, H, 4*A). Data types supported: Same as @p scores + * @param[in] anchors Anchors tensor of size (4, A). Data types supported: Same as @p input + * @param[out] proposals Box proposals output tensor of size (5, W*H*A). Data types supported: Same as @p input + * @param[out] scores_out Box scores output tensor of size (W*H*A). Data types supported: Same as @p input + * @param[out] num_valid_proposals Scalar output tensor which says which of the first proposals are valid. Data types supported: U32 + * @param[in] info Contains GenerateProposals operation information described in @ref GenerateProposalsInfo + * + * @note Only single image prediction is supported. Height and Width (and scale) of the image will be contained in the @ref GenerateProposalsInfo struct. + * @note Proposals contains all the proposals. Of those, only the first num_valid_proposals are valid. + */ + void configure(const ICLTensor *scores, const ICLTensor *deltas, const ICLTensor *anchors, ICLTensor *proposals, ICLTensor *scores_out, ICLTensor *num_valid_proposals, + const GenerateProposalsInfo &info); + + /** Static function to check if given info will lead to a valid configuration of @ref CLGenerateProposalsLayer + * + * @param[in] scores Scores info from convolution layer of size (W, H, A), where H and W are the height and width of the feature map, and A is the number of anchors. Data types supported: F16/F32 + * @param[in] deltas Bounding box deltas info from convolution layer of size (W, H, 4*A). Data types supported: Same as @p scores + * @param[in] anchors Anchors tensor info of size (4, A). Data types supported: Same as @p input + * @param[in] proposals Box proposals info output tensor of size (5, W*H*A). Data types supported: Data types supported: U32 + * @param[in] scores_out Box scores output tensor info of size (W*H*A). Data types supported: Same as @p input + * @param[in] num_valid_proposals Scalar output tensor info which says which of the first proposals are valid. Data types supported: Same as @p input + * @param[in] info Contains GenerateProposals operation information described in @ref GenerateProposalsInfo + * + * @return a Status + */ + static Status validate(const ITensorInfo *scores, const ITensorInfo *deltas, const ITensorInfo *anchors, const ITensorInfo *proposals, const ITensorInfo *scores_out, + const ITensorInfo *num_valid_proposals, + const GenerateProposalsInfo &info); + + // Inherited methods overridden: + void run() override; + +private: + // Memory group manager + CLMemoryGroup _memory_group; + + // OpenCL kernels + CLPermuteKernel _permute_deltas_kernel; + CLReshapeLayerKernel _flatten_deltas_kernel; + CLPermuteKernel _permute_scores_kernel; + CLReshapeLayerKernel _flatten_scores_kernel; + CLComputeAllAnchorsKernel _compute_anchors_kernel; + CLBoundingBoxTransformKernel _bounding_box_kernel; + CLMemsetKernel _memset_kernel; + CLCopyKernel _padded_copy_kernel; + + // CPP kernels + CPPBoxWithNonMaximaSuppressionLimitKernel _cpp_nms_kernel; + + // Temporary tensors + CLTensor _deltas_permuted; + CLTensor _deltas_flattened; + CLTensor _scores_permuted; + CLTensor _scores_flattened; + CLTensor _all_anchors; + CLTensor _all_proposals; + CLTensor _keeps_nms_unused; + CLTensor _classes_nms_unused; + CLTensor _proposals_4_roi_values; + + // Output tensor pointers + ICLTensor *_num_valid_proposals; + ICLTensor *_scores_out; + + /** Internal function to run the CPP BoxWithNMS kernel */ + void run_cpp_nms_kernel(); +}; +} // namespace arm_compute +#endif /* __ARM_COMPUTE_CLGENERATEPROPOSALSLAYER_H__ */ diff --git a/src/core/CL/CLKernelLibrary.cpp b/src/core/CL/CLKernelLibrary.cpp index ccc9aec0d8..fde9608949 100644 --- a/src/core/CL/CLKernelLibrary.cpp +++ b/src/core/CL/CLKernelLibrary.cpp @@ -275,6 +275,7 @@ const std::map CLKernelLibrary::_kernel_program_map = { "gemmlowp_output_stage_quantize_down", "gemmlowp.cl" }, { "gemmlowp_output_stage_quantize_down_fixedpoint", "gemmlowp.cl" }, { "gemmlowp_output_stage_quantize_down_float", "gemmlowp.cl" }, + { "generate_proposals_compute_all_anchors", "generate_proposals.cl" }, { "harris_score_3x3", "harris_corners.cl" }, { "harris_score_5x5", "harris_corners.cl" }, { "harris_score_7x7", "harris_corners.cl" }, @@ -653,6 +654,10 @@ const std::map CLKernelLibrary::_program_source_map = { "gemv.cl", #include "./cl_kernels/gemv.clembed" + }, + { + "generate_proposals.cl", +#include "./cl_kernels/generate_proposals.clembed" }, { "harris_corners.cl", diff --git a/src/core/CL/cl_kernels/bounding_box_transform.cl b/src/core/CL/cl_kernels/bounding_box_transform.cl index d33018847e..14a0fadc2f 100644 --- a/src/core/CL/cl_kernels/bounding_box_transform.cl +++ b/src/core/CL/cl_kernels/bounding_box_transform.cl @@ -28,11 +28,11 @@ /** Perform a padded copy of input tensor to the output tensor. Padding values are defined at compile time * * @attention The following variables must be passed at compile time: - * -# -DDATA_TYPE = Tensor data type. Supported data types: F16/F32 + * -# -DDATA_TYPE= Tensor data type. Supported data types: F16/F32 * -# -DWEIGHT{X,Y,W,H}= Weights [wx, wy, ww, wh] for the deltas * -# -DIMG_WIDTH= Original image width * -# -DIMG_HEIGHT= Original image height - * -# -DBOX_FIELDS=Number of fields that are used to represent a box in boxes + * -# -DBOX_FIELDS= Number of fields that are used to represent a box in boxes * * @param[in] boxes_ptr Pointer to the boxes tensor. Supported data types: F16/F32 * @param[in] boxes_stride_x Stride of the boxes tensor in X dimension (in bytes) @@ -97,7 +97,7 @@ __kernel void bounding_box_transform( // Useful vector constant definitions const VEC_DATA_TYPE(DATA_TYPE, 4) - max_values = (VEC_DATA_TYPE(DATA_TYPE, 4))(IMG_WIDTH, IMG_HEIGHT, IMG_WIDTH, IMG_HEIGHT); + max_values = (VEC_DATA_TYPE(DATA_TYPE, 4))(IMG_WIDTH - 1, IMG_HEIGHT - 1, IMG_WIDTH - 1, IMG_HEIGHT - 1); const VEC_DATA_TYPE(DATA_TYPE, 4) sign = (VEC_DATA_TYPE(DATA_TYPE, 4))(-1, -1, 1, 1); const VEC_DATA_TYPE(DATA_TYPE, 4) diff --git a/src/core/CL/cl_kernels/generate_proposals.cl b/src/core/CL/cl_kernels/generate_proposals.cl new file mode 100644 index 0000000000..bc6f4b5e17 --- /dev/null +++ b/src/core/CL/cl_kernels/generate_proposals.cl @@ -0,0 +1,88 @@ +/* + * 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" + +/** Generate all the region of interests based on the image size and the anchors passed in. For each element (x,y) of the + * grid, it will generate NUM_ANCHORS rois, given by shifting the grid position to match the anchor. + * + * @attention The following variables must be passed at compile time: + * -# -DDATA_TYPE= Tensor data type. Supported data types: F16/F32 + * -# -DHEIGHT= Height of the feature map on which this kernel is applied + * -# -DWIDTH= Width of the feature map on which this kernel is applied + * -# -DNUM_ANCHORS= Number of anchors to be used to generate the rois per each pixel + * -# -DSTRIDE= Stride to be applied at each different pixel position (i.e., x_range = (1:WIDTH)*STRIDE and y_range = (1:HEIGHT)*STRIDE + * -# -DNUM_ROI_FIELDS= Number of fields used to represent a roi + * + * @param[in] anchors_ptr Pointer to the anchors tensor. Supported data types: F16/F32 + * @param[in] anchors_stride_x Stride of the anchors tensor in X dimension (in bytes) + * @param[in] anchors_step_x anchors_stride_x * number of elements along X processed per workitem(in bytes) + * @param[in] anchors_stride_y Stride of the anchors tensor in Y dimension (in bytes) + * @param[in] anchors_step_y anchors_stride_y * number of elements along Y processed per workitem(in bytes) + * @param[in] anchors_stride_z Stride of the source tensor in Z dimension (in bytes) + * @param[in] anchors_step_z anchors_stride_z * number of elements along Z processed per workitem(in bytes) + * @param[in] anchors_offset_first_element_in_bytes The offset of the first element in the boxes tensor + * @param[out] rois_ptr Pointer to the rois. Supported data types: same as @p in_ptr + * @param[out] rois_stride_x Stride of the rois in X dimension (in bytes) + * @param[out] rois_step_x pred_boxes_stride_x * number of elements along X processed per workitem(in bytes) + * @param[out] rois_stride_y Stride of the rois in Y dimension (in bytes) + * @param[out] rois_step_y pred_boxes_stride_y * number of elements along Y processed per workitem(in bytes) + * @param[out] rois_stride_z Stride of the rois in Z dimension (in bytes) + * @param[out] rois_step_z pred_boxes_stride_z * number of elements along Z processed per workitem(in bytes) + * @param[out] rois_offset_first_element_in_bytes The offset of the first element in the rois + */ +#if defined(DATA_TYPE) && defined(WIDTH) && defined(HEIGHT) && defined(NUM_ANCHORS) && defined(STRIDE) && defined(NUM_ROI_FIELDS) +__kernel void generate_proposals_compute_all_anchors( + VECTOR_DECLARATION(anchors), + VECTOR_DECLARATION(rois)) +{ + Vector anchors = CONVERT_TO_VECTOR_STRUCT_NO_STEP(anchors); + Vector rois = CONVERT_TO_VECTOR_STRUCT(rois); + + const size_t idx = get_global_id(0); + // Find the index of the anchor + const size_t anchor_idx = idx % NUM_ANCHORS; + + // Find which shift is this thread using + const size_t shift_idx = idx / NUM_ANCHORS; + + // Compute the shift on the X and Y direction (the shift depends exclusively by the index thread id) + const DATA_TYPE + shift_x = (DATA_TYPE)(shift_idx % WIDTH) * STRIDE; + const DATA_TYPE + shift_y = (DATA_TYPE)(shift_idx / WIDTH) * STRIDE; + + const VEC_DATA_TYPE(DATA_TYPE, NUM_ROI_FIELDS) + shift = (VEC_DATA_TYPE(DATA_TYPE, NUM_ROI_FIELDS))(shift_x, shift_y, shift_x, shift_y); + + // Read the given anchor + const VEC_DATA_TYPE(DATA_TYPE, NUM_ROI_FIELDS) + anchor = vload4(0, (__global DATA_TYPE *)vector_offset(&anchors, anchor_idx * NUM_ROI_FIELDS)); + + // Apply the shift to the anchor + const VEC_DATA_TYPE(DATA_TYPE, NUM_ROI_FIELDS) + shifted_anchor = anchor + shift; + + vstore4(shifted_anchor, 0, (__global DATA_TYPE *)rois.ptr); +} +#endif //defined(DATA_TYPE) && defined(WIDTH) && defined(HEIGHT) && defined(NUM_ANCHORS) && defined(STRIDE) && defined(NUM_ROI_FIELDS) diff --git a/src/core/CL/kernels/CLGenerateProposalsLayerKernel.cpp b/src/core/CL/kernels/CLGenerateProposalsLayerKernel.cpp new file mode 100644 index 0000000000..5d100a4c1e --- /dev/null +++ b/src/core/CL/kernels/CLGenerateProposalsLayerKernel.cpp @@ -0,0 +1,128 @@ +/* + * 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/CLGenerateProposalsLayerKernel.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 *anchors, const ITensorInfo *all_anchors, const ComputeAnchorsInfo &info) +{ + ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(anchors, all_anchors); + ARM_COMPUTE_RETURN_ERROR_ON(anchors->dimension(0) != info.values_per_roi()); + ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_NOT_IN(anchors, DataType::F16, DataType::F32); + ARM_COMPUTE_RETURN_ERROR_ON(anchors->num_dimensions() > 2); + if(all_anchors->total_size() > 0) + { + size_t feature_height = info.feat_height(); + size_t feature_width = info.feat_width(); + size_t num_anchors = anchors->dimension(1); + ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(all_anchors, anchors); + ARM_COMPUTE_RETURN_ERROR_ON(all_anchors->num_dimensions() > 2); + ARM_COMPUTE_RETURN_ERROR_ON(all_anchors->dimension(0) != info.values_per_roi()); + ARM_COMPUTE_RETURN_ERROR_ON(all_anchors->dimension(1) != feature_height * feature_width * num_anchors); + } + return Status{}; +} +} // namespace + +CLComputeAllAnchorsKernel::CLComputeAllAnchorsKernel() + : _anchors(nullptr), _all_anchors(nullptr) +{ +} + +void CLComputeAllAnchorsKernel::configure(const ICLTensor *anchors, ICLTensor *all_anchors, const ComputeAnchorsInfo &info) +{ + ARM_COMPUTE_ERROR_ON_NULLPTR(anchors, all_anchors); + ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(anchors->info(), all_anchors->info(), info)); + + // Metadata + const size_t num_anchors = anchors->info()->dimension(1); + const DataType data_type = anchors->info()->data_type(); + const float width = info.feat_width(); + const float height = info.feat_height(); + + // Initialize the output if empty + const TensorShape output_shape(info.values_per_roi(), width * height * num_anchors); + auto_init_if_empty(*all_anchors->info(), output_shape, 1, data_type); + + // Set instance variables + _anchors = anchors; + _all_anchors = all_anchors; + + // Set build options + CLBuildOptions build_opts; + build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(data_type)); + build_opts.add_option("-DWIDTH=" + float_to_string_with_full_precision(width)); + build_opts.add_option("-DHEIGHT=" + float_to_string_with_full_precision(height)); + build_opts.add_option("-DSTRIDE=" + float_to_string_with_full_precision(1.f / info.spatial_scale())); + build_opts.add_option("-DNUM_ANCHORS=" + support::cpp11::to_string(num_anchors)); + build_opts.add_option("-DNUM_ROI_FIELDS=" + support::cpp11::to_string(info.values_per_roi())); + + // Create kernel + _kernel = static_cast(CLKernelLibrary::get().create_kernel("generate_proposals_compute_all_anchors", build_opts.options())); + + // The tensor all_anchors can be interpreted as an array of structs (each structs has values_per_roi fields). + // This means we don't need to pad on the X dimension, as we know in advance how many fields + // compose the struct. + Window win = calculate_max_window(*all_anchors->info(), Steps(info.values_per_roi())); + ICLKernel::configure_internal(win); +} + +Status CLComputeAllAnchorsKernel::validate(const ITensorInfo *anchors, const ITensorInfo *all_anchors, const ComputeAnchorsInfo &info) +{ + ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(anchors, all_anchors, info)); + return Status{}; +} + +void CLComputeAllAnchorsKernel::run(const Window &window, cl::CommandQueue &queue) +{ + ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this); + ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(IKernel::window(), window); + + // Collapse everything on the first dimension + Window collapsed = window.collapse(ICLKernel::window(), Window::DimX); + + // Set arguments + unsigned int idx = 0; + add_1D_tensor_argument(idx, _anchors, collapsed); + add_1D_tensor_argument(idx, _all_anchors, collapsed); + + // Note that we don't need to loop over the slices, as we are launching exactly + // as many threads as all the anchors generated + enqueue(queue, *this, collapsed); +} +} // namespace arm_compute diff --git a/src/core/CPP/kernels/CPPBoxWithNonMaximaSuppressionLimitKernel.cpp b/src/core/CPP/kernels/CPPBoxWithNonMaximaSuppressionLimitKernel.cpp index 89413fcca4..2b9934cfa8 100644 --- a/src/core/CPP/kernels/CPPBoxWithNonMaximaSuppressionLimitKernel.cpp +++ b/src/core/CPP/kernels/CPPBoxWithNonMaximaSuppressionLimitKernel.cpp @@ -54,7 +54,7 @@ std::vector SoftNMS(const ITensor *proposals, std::vector> & areas[i] = (x2[i] - x1[i] + 1.0) * (y2[i] - y1[i] + 1.0); } - // Note: Soft NMS scores have already been initialize with input scores + // Note: Soft NMS scores have already been initialized with input scores while(!inds.empty()) { @@ -150,17 +150,21 @@ std::vector NonMaximaSuppression(const ITensor *proposals, std::vector for(unsigned int j = 0; j < sorted_indices_temp.size(); ++j) { - const auto xx1 = std::max(x1[sorted_indices_temp.at(j)], x1[i]); - const auto yy1 = std::max(y1[sorted_indices_temp.at(j)], y1[i]); - const auto xx2 = std::min(x2[sorted_indices_temp.at(j)], x2[i]); - const auto yy2 = std::min(y2[sorted_indices_temp.at(j)], y2[i]); - - const auto w = std::max((xx2 - xx1 + 1.f), 0.f); - const auto h = std::max((yy2 - yy1 + 1.f), 0.f); - const auto inter = w * h; - const auto ovr = inter / (areas[i] + areas[sorted_indices_temp.at(j)] - inter); - - if(ovr <= info.nms()) + const float xx1 = std::max(x1[sorted_indices_temp.at(j)], x1[i]); + const float yy1 = std::max(y1[sorted_indices_temp.at(j)], y1[i]); + const float xx2 = std::min(x2[sorted_indices_temp.at(j)], x2[i]); + const float yy2 = std::min(y2[sorted_indices_temp.at(j)], y2[i]); + + const float w = std::max((xx2 - xx1 + 1.f), 0.f); + const float h = std::max((yy2 - yy1 + 1.f), 0.f); + const float inter = w * h; + const float ovr = inter / (areas[i] + areas[sorted_indices_temp.at(j)] - inter); + const float ctr_x = xx1 + (w / 2); + const float ctr_y = yy1 + (h / 2); + + // If suppress_size is specified, filter the boxes based on their size and position + const bool keep_size = !info.suppress_size() || (w >= info.min_size() && h >= info.min_size() && ctr_x < info.im_width() && ctr_y < info.im_height()); + if(ovr <= info.nms() && keep_size) { new_indices.push_back(j); } @@ -214,8 +218,9 @@ void CPPBoxWithNonMaximaSuppressionLimitKernel::run_nmslimit() for(int b = 0; b < batch_size; ++b) { const int num_boxes = _batch_splits_in == nullptr ? 1 : static_cast(*reinterpret_cast(_batch_splits_in->ptr_to_element(Coordinates(b)))); - // Skip first class - for(int j = 1; j < num_classes; ++j) + // Skip first class if there is more than 1 except if the number of classes is 1. + const int j_start = (num_classes == 1 ? 0 : 1); + for(int j = j_start; j < num_classes; ++j) { std::vector cur_scores(scores_count); std::vector inds; @@ -290,7 +295,7 @@ void CPPBoxWithNonMaximaSuppressionLimitKernel::run_nmslimit() // Write results int cur_out_idx = 0; - for(int j = 1; j < num_classes; ++j) + for(int j = j_start; j < num_classes; ++j) { auto &cur_keep = keeps[j]; auto cur_out_scores = reinterpret_cast(_scores_out->ptr_to_element(Coordinates(cur_start_idx + cur_out_idx))); diff --git a/src/runtime/CL/functions/CLComputeAllAnchors.cpp b/src/runtime/CL/functions/CLComputeAllAnchors.cpp new file mode 100644 index 0000000000..409d3c9e91 --- /dev/null +++ b/src/runtime/CL/functions/CLComputeAllAnchors.cpp @@ -0,0 +1,42 @@ +/* + * 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/CLComputeAllAnchors.h" + +#include "support/ToolchainSupport.h" + +namespace arm_compute +{ +void CLComputeAllAnchors::configure(const ICLTensor *anchors, ICLTensor *all_anchors, const ComputeAnchorsInfo &info) +{ + // Configure ComputeAllAnchors kernel + auto k = arm_compute::support::cpp14::make_unique(); + k->configure(anchors, all_anchors, info); + _kernel = std::move(k); +} + +Status CLComputeAllAnchors::validate(const ITensorInfo *anchors, const ITensorInfo *all_anchors, const ComputeAnchorsInfo &info) +{ + return CLComputeAllAnchorsKernel::validate(anchors, all_anchors, info); +} +} // namespace arm_compute diff --git a/src/runtime/CL/functions/CLGenerateProposalsLayer.cpp b/src/runtime/CL/functions/CLGenerateProposalsLayer.cpp new file mode 100644 index 0000000000..80ed0e55a4 --- /dev/null +++ b/src/runtime/CL/functions/CLGenerateProposalsLayer.cpp @@ -0,0 +1,251 @@ +/* + * 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/CLGenerateProposalsLayer.h" + +#include "arm_compute/core/CL/ICLTensor.h" +#include "arm_compute/core/Types.h" +#include "support/ToolchainSupport.h" + +namespace arm_compute +{ +CLGenerateProposalsLayer::CLGenerateProposalsLayer(std::shared_ptr memory_manager) + : _memory_group(std::move(memory_manager)), + _permute_deltas_kernel(), + _flatten_deltas_kernel(), + _permute_scores_kernel(), + _flatten_scores_kernel(), + _compute_anchors_kernel(), + _bounding_box_kernel(), + _memset_kernel(), + _padded_copy_kernel(), + _cpp_nms_kernel(), + _deltas_permuted(), + _deltas_flattened(), + _scores_permuted(), + _scores_flattened(), + _all_anchors(), + _all_proposals(), + _keeps_nms_unused(), + _classes_nms_unused(), + _proposals_4_roi_values(), + _num_valid_proposals(nullptr), + _scores_out(nullptr) +{ +} + +void CLGenerateProposalsLayer::configure(const ICLTensor *scores, const ICLTensor *deltas, const ICLTensor *anchors, ICLTensor *proposals, ICLTensor *scores_out, ICLTensor *num_valid_proposals, + const GenerateProposalsInfo &info) +{ + const DataType data_type = deltas->info()->data_type(); + const int num_anchors = scores->info()->dimension(2); + const int feat_width = scores->info()->dimension(0); + const int feat_height = scores->info()->dimension(1); + const int total_num_anchors = num_anchors * feat_width * feat_height; + const int pre_nms_topN = info.pre_nms_topN(); + const int post_nms_topN = info.post_nms_topN(); + const size_t values_per_roi = info.values_per_roi(); + + // Compute all the anchors + _memory_group.manage(&_all_anchors); + _compute_anchors_kernel.configure(anchors, &_all_anchors, ComputeAnchorsInfo(feat_width, feat_height, info.spatial_scale())); + + const TensorShape flatten_shape_deltas(values_per_roi, total_num_anchors); + _deltas_flattened.allocator()->init(TensorInfo(flatten_shape_deltas, 1, data_type)); + + // Permute and reshape deltas + _memory_group.manage(&_deltas_permuted); + _memory_group.manage(&_deltas_flattened); + _permute_deltas_kernel.configure(deltas, &_deltas_permuted, PermutationVector{ 2, 0, 1 }); + _flatten_deltas_kernel.configure(&_deltas_permuted, &_deltas_flattened); + _deltas_permuted.allocator()->allocate(); + + const TensorShape flatten_shape_scores(1, total_num_anchors); + _scores_flattened.allocator()->init(TensorInfo(flatten_shape_scores, 1, data_type)); + + // Permute and reshape scores + _memory_group.manage(&_scores_permuted); + _memory_group.manage(&_scores_flattened); + _permute_scores_kernel.configure(scores, &_scores_permuted, PermutationVector{ 2, 0, 1 }); + _flatten_scores_kernel.configure(&_scores_permuted, &_scores_flattened); + _scores_permuted.allocator()->allocate(); + + // Bounding box transform + _memory_group.manage(&_all_proposals); + BoundingBoxTransformInfo bbox_info(info.im_width(), info.im_height(), 1.f); + _bounding_box_kernel.configure(&_all_anchors, &_all_proposals, &_deltas_flattened, bbox_info); + _deltas_flattened.allocator()->allocate(); + _all_anchors.allocator()->allocate(); + + // The original layer implementation first selects the best pre_nms_topN anchors (thus having a lightweight sort) + // that are then transformed by bbox_transform. The boxes generated are then fed into a non-sorting NMS operation. + // Since we are reusing the NMS layer and we don't implement any CL/sort, we let NMS do the sorting (of all the input) + // and the filtering + const int scores_nms_size = std::min(std::min(post_nms_topN, pre_nms_topN), total_num_anchors); + const float min_size_scaled = info.min_size() * info.im_scale(); + _memory_group.manage(&_classes_nms_unused); + _memory_group.manage(&_keeps_nms_unused); + + // Note that NMS needs outputs preinitialized. + auto_init_if_empty(*scores_out->info(), TensorShape(scores_nms_size), 1, data_type); + auto_init_if_empty(*_proposals_4_roi_values.info(), TensorShape(values_per_roi, scores_nms_size), 1, data_type); + auto_init_if_empty(*num_valid_proposals->info(), TensorShape(values_per_roi, scores_nms_size), 1, data_type); + + // Initialize temporaries (unused) outputs + _classes_nms_unused.allocator()->init(TensorInfo(TensorShape(1, 1), 1, data_type)); + _keeps_nms_unused.allocator()->init(*scores_out->info()); + + // Save the output (to map and unmap them at run) + _scores_out = scores_out; + _num_valid_proposals = num_valid_proposals; + + _memory_group.manage(&_proposals_4_roi_values); + _cpp_nms_kernel.configure(&_scores_flattened, &_all_proposals, nullptr, scores_out, &_proposals_4_roi_values, &_classes_nms_unused, nullptr, &_keeps_nms_unused, num_valid_proposals, + BoxNMSLimitInfo(0.0f, info.nms_thres(), scores_nms_size, false, NMSType::LINEAR, 0.5f, 0.001f, true, min_size_scaled, info.im_width(), info.im_height())); + _keeps_nms_unused.allocator()->allocate(); + _classes_nms_unused.allocator()->allocate(); + _all_proposals.allocator()->allocate(); + _scores_flattened.allocator()->allocate(); + + // Add the first column that represents the batch id. This will be all zeros, as we don't support multiple images + _padded_copy_kernel.configure(&_proposals_4_roi_values, proposals, PaddingList{ { 1, 0 } }); + _proposals_4_roi_values.allocator()->allocate(); + + _memset_kernel.configure(proposals, PixelValue()); +} + +Status CLGenerateProposalsLayer::validate(const ITensorInfo *scores, const ITensorInfo *deltas, const ITensorInfo *anchors, const ITensorInfo *proposals, const ITensorInfo *scores_out, + const ITensorInfo *num_valid_proposals, const GenerateProposalsInfo &info) +{ + ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(proposals, scores_out, num_valid_proposals); + + const int num_anchors = scores->dimension(2); + const int feat_width = scores->dimension(0); + const int feat_height = scores->dimension(1); + const int num_images = scores->dimension(3); + const int total_num_anchors = num_anchors * feat_width * feat_height; + const int values_per_roi = info.values_per_roi(); + + ARM_COMPUTE_RETURN_ERROR_ON(num_images > 1); + + TensorInfo all_anchors_info(anchors->clone()->set_tensor_shape(TensorShape(values_per_roi, total_num_anchors)).set_is_resizable(true)); + ARM_COMPUTE_RETURN_ON_ERROR(CLComputeAllAnchorsKernel::validate(anchors, &all_anchors_info, ComputeAnchorsInfo(feat_width, feat_height, info.spatial_scale()))); + + TensorInfo deltas_permuted_info = deltas->clone()->set_tensor_shape(TensorShape(values_per_roi * num_anchors, feat_width, feat_height)).set_is_resizable(true); + ARM_COMPUTE_RETURN_ON_ERROR(CLPermuteKernel::validate(deltas, &deltas_permuted_info, PermutationVector{ 2, 0, 1 })); + + TensorInfo deltas_flattened_info(deltas->clone()->set_tensor_shape(TensorShape(values_per_roi, total_num_anchors)).set_is_resizable(true)); + ARM_COMPUTE_RETURN_ON_ERROR(CLReshapeLayerKernel::validate(&deltas_permuted_info, &deltas_flattened_info)); + + TensorInfo scores_permuted_info = scores->clone()->set_tensor_shape(TensorShape(num_anchors, feat_width, feat_height)).set_is_resizable(true); + ARM_COMPUTE_RETURN_ON_ERROR(CLPermuteKernel::validate(scores, &scores_permuted_info, PermutationVector{ 2, 0, 1 })); + + TensorInfo scores_flattened_info(deltas->clone()->set_tensor_shape(TensorShape(1, total_num_anchors)).set_is_resizable(true)); + TensorInfo proposals_4_roi_values(proposals->clone()->set_tensor_shape(TensorShape(values_per_roi, total_num_anchors)).set_is_resizable(true)); + + ARM_COMPUTE_RETURN_ON_ERROR(CLReshapeLayerKernel::validate(&scores_permuted_info, &scores_flattened_info)); + ARM_COMPUTE_RETURN_ON_ERROR(CLBoundingBoxTransformKernel::validate(&all_anchors_info, &proposals_4_roi_values, &deltas_flattened_info, BoundingBoxTransformInfo(info.im_width(), info.im_height(), + 1.f))); + + ARM_COMPUTE_RETURN_ON_ERROR(CLCopyKernel::validate(&proposals_4_roi_values, proposals, PaddingList{ { 0, 1 } })); + ARM_COMPUTE_RETURN_ON_ERROR(CLMemsetKernel::validate(proposals, PixelValue())); + + if(num_valid_proposals->total_size() > 0) + { + ARM_COMPUTE_RETURN_ERROR_ON(num_valid_proposals->num_dimensions() > 1); + ARM_COMPUTE_RETURN_ERROR_ON(num_valid_proposals->dimension(0) > 1); + ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_NOT_IN(num_valid_proposals, DataType::U32); + } + + if(proposals->total_size() > 0) + { + ARM_COMPUTE_RETURN_ERROR_ON(proposals->num_dimensions() > 2); + ARM_COMPUTE_RETURN_ERROR_ON(proposals->dimension(0) != size_t(values_per_roi) + 1); + ARM_COMPUTE_RETURN_ERROR_ON(proposals->dimension(1) != size_t(total_num_anchors)); + ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(proposals, deltas); + } + + if(scores_out->total_size() > 0) + { + ARM_COMPUTE_RETURN_ERROR_ON(scores_out->num_dimensions() > 1); + ARM_COMPUTE_RETURN_ERROR_ON(scores_out->dimension(0) != size_t(total_num_anchors)); + ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(scores_out, scores); + } + + return Status{}; +} + +void CLGenerateProposalsLayer::run_cpp_nms_kernel() +{ + // Map inputs + _scores_flattened.map(true); + _all_proposals.map(true); + + // Map outputs + _scores_out->map(CLScheduler::get().queue(), true); + _proposals_4_roi_values.map(CLScheduler::get().queue(), true); + _num_valid_proposals->map(CLScheduler::get().queue(), true); + _keeps_nms_unused.map(true); + _classes_nms_unused.map(true); + + // Run nms + CPPScheduler::get().schedule(&_cpp_nms_kernel, Window::DimX); + + // Unmap outputs + _keeps_nms_unused.unmap(); + _classes_nms_unused.unmap(); + _scores_out->unmap(CLScheduler::get().queue()); + _proposals_4_roi_values.unmap(CLScheduler::get().queue()); + _num_valid_proposals->unmap(CLScheduler::get().queue()); + + // Unmap inputs + _scores_flattened.unmap(); + _all_proposals.unmap(); +} + +void CLGenerateProposalsLayer::run() +{ + // Acquire all the temporaries + _memory_group.acquire(); + + // Compute all the anchors + CLScheduler::get().enqueue(_compute_anchors_kernel, false); + + // Transpose and reshape the inputs + CLScheduler::get().enqueue(_permute_deltas_kernel, false); + CLScheduler::get().enqueue(_flatten_deltas_kernel, false); + CLScheduler::get().enqueue(_permute_scores_kernel, false); + CLScheduler::get().enqueue(_flatten_scores_kernel, false); + + // Build the boxes + CLScheduler::get().enqueue(_bounding_box_kernel, false); + // Non maxima suppression + run_cpp_nms_kernel(); + // Add dummy batch indexes + CLScheduler::get().enqueue(_memset_kernel, true); + CLScheduler::get().enqueue(_padded_copy_kernel, true); + + // Release all the temporaries + _memory_group.release(); +} +} // namespace arm_compute diff --git a/tests/validation/CL/GenerateProposalsLayer.cpp b/tests/validation/CL/GenerateProposalsLayer.cpp new file mode 100644 index 0000000000..28cdc71ae6 --- /dev/null +++ b/tests/validation/CL/GenerateProposalsLayer.cpp @@ -0,0 +1,334 @@ +/* + * 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/CLComputeAllAnchors.h" +#include "arm_compute/runtime/CL/functions/CLGenerateProposalsLayer.h" +#include "arm_compute/runtime/CL/functions/CLSlice.h" +#include "tests/CL/CLAccessor.h" +#include "tests/CL/CLArrayAccessor.h" +#include "tests/Globals.h" +#include "tests/framework/Macros.h" +#include "tests/framework/datasets/Datasets.h" +#include "tests/validation/Validation.h" +#include "tests/validation/fixtures/ComputeAllAnchorsFixture.h" +#include "utils/TypePrinter.h" + +namespace arm_compute +{ +namespace test +{ +namespace validation +{ +namespace +{ +template +inline void fill_tensor(U &&tensor, const std::vector &v) +{ + std::memcpy(tensor.data(), v.data(), sizeof(T) * v.size()); +} + +const auto ComputeAllInfoDataset = framework::dataset::make("ComputeAllInfo", +{ + ComputeAnchorsInfo(10U, 10U, 1. / 16.f), + ComputeAnchorsInfo(100U, 1U, 1. / 2.f), + ComputeAnchorsInfo(100U, 1U, 1. / 4.f), + ComputeAnchorsInfo(100U, 100U, 1. / 4.f), + +}); +} // namespace + +TEST_SUITE(CL) +TEST_SUITE(GenerateProposals) + +// *INDENT-OFF* +// clang-format off +DATA_TEST_CASE(Validate, framework::DatasetMode::ALL, zip(zip(zip(zip(zip(zip(zip( + framework::dataset::make("scores", { TensorInfo(TensorShape(100U, 100U, 9U), 1, DataType::F32), + TensorInfo(TensorShape(100U, 100U, 9U), 1, DataType::F16), // Mismatching types + TensorInfo(TensorShape(100U, 100U, 9U), 1, DataType::F16), // Wrong deltas (number of transformation non multiple of 4) + TensorInfo(TensorShape(100U, 100U, 9U), 1, DataType::F16), // Wrong anchors (number of values per roi != 5) + TensorInfo(TensorShape(100U, 100U, 9U), 1, DataType::F16)}), // Output tensor num_valid_proposals not scalar + framework::dataset::make("deltas",{ TensorInfo(TensorShape(100U, 100U, 36U), 1, DataType::F32), + TensorInfo(TensorShape(100U, 100U, 36U), 1, DataType::F32), + TensorInfo(TensorShape(100U, 100U, 38U), 1, DataType::F32), + TensorInfo(TensorShape(100U, 100U, 38U), 1, DataType::F32), + TensorInfo(TensorShape(100U, 100U, 38U), 1, DataType::F32)})), + framework::dataset::make("anchors", { TensorInfo(TensorShape(4U, 9U), 1, DataType::F32), + TensorInfo(TensorShape(4U, 9U), 1, DataType::F32), + TensorInfo(TensorShape(4U, 9U), 1, DataType::F32), + TensorInfo(TensorShape(5U, 9U), 1, DataType::F32), + TensorInfo(TensorShape(4U, 9U), 1, DataType::F32)})), + framework::dataset::make("proposals", { TensorInfo(TensorShape(5U, 100U*100U*9U), 1, DataType::F32), + TensorInfo(TensorShape(5U, 100U*100U*9U), 1, DataType::F32), + TensorInfo(TensorShape(5U, 100U*100U*9U), 1, DataType::F32), + TensorInfo(TensorShape(5U, 100U*100U*9U), 1, DataType::F32), + TensorInfo(TensorShape(5U, 100U*100U*9U), 1, DataType::F32)})), + framework::dataset::make("scores_out", { TensorInfo(TensorShape(100U*100U*9U), 1, DataType::F32), + TensorInfo(TensorShape(100U*100U*9U), 1, DataType::F32), + TensorInfo(TensorShape(100U*100U*9U), 1, DataType::F32), + TensorInfo(TensorShape(100U*100U*9U), 1, DataType::F32), + TensorInfo(TensorShape(100U*100U*9U), 1, DataType::F32)})), + framework::dataset::make("num_valid_proposals", { TensorInfo(TensorShape(1U, 1U), 1, DataType::U32), + TensorInfo(TensorShape(1U, 1U), 1, DataType::U32), + TensorInfo(TensorShape(1U, 1U), 1, DataType::U32), + TensorInfo(TensorShape(1U, 1U), 1, DataType::U32), + TensorInfo(TensorShape(1U, 10U), 1, DataType::U32)})), + framework::dataset::make("generate_proposals_info", { GenerateProposalsInfo(10.f, 10.f, 1.f), + GenerateProposalsInfo(10.f, 10.f, 1.f), + GenerateProposalsInfo(10.f, 10.f, 1.f), + GenerateProposalsInfo(10.f, 10.f, 1.f), + GenerateProposalsInfo(10.f, 10.f, 1.f)})), + framework::dataset::make("Expected", { true, false, false, false, false })), + scores, deltas, anchors, proposals, scores_out, num_valid_proposals, generate_proposals_info, expected) +{ + ARM_COMPUTE_EXPECT(bool(CLGenerateProposalsLayer::validate(&scores.clone()->set_is_resizable(true), + &deltas.clone()->set_is_resizable(true), + &anchors.clone()->set_is_resizable(true), + &proposals.clone()->set_is_resizable(true), + &scores_out.clone()->set_is_resizable(true), + &num_valid_proposals.clone()->set_is_resizable(true), + generate_proposals_info)) == expected, framework::LogLevel::ERRORS); +} +// clang-format on +// *INDENT-ON* + +template +using CLComputeAllAnchorsFixture = ComputeAllAnchorsFixture; + +TEST_SUITE(Float) +TEST_SUITE(FP32) +DATA_TEST_CASE(IntegrationTestCaseAllAnchors, framework::DatasetMode::ALL, framework::dataset::make("DataType", { DataType::F32 }), + data_type) +{ + const int values_per_roi = 4; + const int num_anchors = 3; + const int feature_height = 4; + const int feature_width = 3; + + SimpleTensor anchors_expected(TensorShape(values_per_roi, feature_width * feature_height * num_anchors), DataType::F32); + fill_tensor(anchors_expected, std::vector { -38, -16, 53, 31, -84, -40, 99, 55, -176, -88, 191, 103, + -22, -16, 69, 31, -68, -40, 115, 55, -160, -88, 207, 103, + -6, -16, 85, 31, -52, -40, 131, 55, -144, -88, 223, 103, -38, + 0, 53, 47, -84, -24, 99, 71, + -176, -72, 191, 119, -22, 0, 69, 47, -68, -24, 115, 71, -160, -72, 207, + 119, -6, 0, 85, 47, -52, -24, 131, 71, -144, -72, 223, 119, -38, 16, 53, + 63, -84, -8, 99, 87, -176, -56, 191, 135, -22, 16, 69, 63, -68, -8, 115, + 87, -160, -56, 207, 135, -6, 16, 85, 63, -52, -8, 131, 87, -144, -56, 223, + 135, -38, 32, 53, 79, -84, 8, 99, 103, -176, -40, 191, 151, -22, 32, 69, + 79, -68, 8, 115, 103, -160, -40, 207, 151, -6, 32, 85, 79, -52, 8, 131, + 103, -144, -40, 223, 151 + }); + + CLTensor all_anchors; + CLTensor anchors = create_tensor(TensorShape(4, num_anchors), data_type); + + // Create and configure function + CLComputeAllAnchors compute_anchors; + compute_anchors.configure(&anchors, &all_anchors, ComputeAnchorsInfo(feature_width, feature_height, 1. / 16.0)); + anchors.allocator()->allocate(); + all_anchors.allocator()->allocate(); + + fill_tensor(CLAccessor(anchors), std::vector { -38, -16, 53, 31, + -84, -40, 99, 55, + -176, -88, 191, 103 + }); + // Compute function + compute_anchors.run(); + validate(CLAccessor(all_anchors), anchors_expected); +} + +DATA_TEST_CASE(IntegrationTestCaseGenerateProposals, framework::DatasetMode::ALL, framework::dataset::make("DataType", { DataType::F32 }), + data_type) +{ + const int values_per_roi = 4; + const int num_anchors = 2; + const int feature_height = 4; + const int feature_width = 5; + + std::vector scores_vector + { + 5.44218998e-03f, 1.19207997e-03f, 1.12379994e-03f, 1.17181998e-03f, + 1.20544003e-03f, 6.17993006e-04f, 1.05261997e-05f, 8.91025957e-06f, + 9.29536981e-09f, 6.09605013e-05f, 4.72735002e-04f, 1.13482002e-10f, + 1.50015003e-05f, 4.45032993e-06f, 3.21612994e-08f, 8.02662980e-04f, + 1.40488002e-04f, 3.12508007e-07f, 3.02616991e-06f, 1.97759000e-08f, + 2.66913995e-02f, 5.26766013e-03f, 5.05053019e-03f, 5.62100019e-03f, + 5.37420018e-03f, 5.26280981e-03f, 2.48894998e-04f, 1.06842002e-04f, + 3.92931997e-06f, 1.79388002e-03f, 4.79440019e-03f, 3.41609990e-07f, + 5.20430971e-04f, 3.34090000e-05f, 2.19159006e-07f, 2.28786003e-03f, + 5.16703985e-05f, 4.04523007e-06f, 1.79227004e-06f, 5.32449000e-08f + }; + + std::vector bbx_vector + { + -1.65040009e-02f, -1.84051003e-02f, -1.85930002e-02f, -2.08263006e-02f, + -1.83814000e-02f, -2.89172009e-02f, -3.89706008e-02f, -7.52277970e-02f, + -1.54091999e-01f, -2.55433004e-02f, -1.77490003e-02f, -1.10340998e-01f, + -4.20190990e-02f, -2.71421000e-02f, 6.89801015e-03f, 5.71171008e-02f, + -1.75665006e-01f, 2.30021998e-02f, 3.08554992e-02f, -1.39333997e-02f, + 3.40579003e-01f, 3.91070992e-01f, 3.91624004e-01f, 3.92527014e-01f, + 3.91445011e-01f, 3.79328012e-01f, 4.26631987e-01f, 3.64892989e-01f, + 2.76894987e-01f, 5.13985991e-01f, 3.79999995e-01f, 1.80457994e-01f, + 4.37402993e-01f, 4.18545991e-01f, 2.51549989e-01f, 4.48318988e-01f, + 1.68564007e-01f, 4.65440989e-01f, 4.21891987e-01f, 4.45928007e-01f, + 3.27155995e-03f, 3.71480011e-03f, 3.60032008e-03f, 4.27092984e-03f, + 3.74579988e-03f, 5.95752988e-03f, -3.14473989e-03f, 3.52022005e-03f, + -1.88564006e-02f, 1.65188999e-03f, 1.73791999e-03f, -3.56074013e-02f, + -1.66615995e-04f, 3.14146001e-03f, -1.11830998e-02f, -5.35363983e-03f, + 6.49790000e-03f, -9.27671045e-03f, -2.83346009e-02f, -1.61233004e-02f, + -2.15505004e-01f, -2.19910994e-01f, -2.20872998e-01f, -2.12831005e-01f, + -2.19145000e-01f, -2.27687001e-01f, -3.43973994e-01f, -2.75869995e-01f, + -3.19516987e-01f, -2.50418007e-01f, -2.48537004e-01f, -5.08224010e-01f, + -2.28724003e-01f, -2.82402009e-01f, -3.75815988e-01f, -2.86352992e-01f, + -5.28333001e-02f, -4.43836004e-01f, -4.55134988e-01f, -4.34897989e-01f, + -5.65053988e-03f, -9.25739005e-04f, -1.06790999e-03f, -2.37016007e-03f, + -9.71166010e-04f, -8.90910998e-03f, -1.17592998e-02f, -2.08992008e-02f, + -4.94231991e-02f, 6.63906988e-03f, 3.20469006e-03f, -6.44695014e-02f, + -3.11607006e-03f, 2.02738005e-03f, 1.48096997e-02f, 4.39785011e-02f, + -8.28424022e-02f, 3.62076014e-02f, 2.71668993e-02f, 1.38250999e-02f, + 6.76669031e-02f, 1.03252999e-01f, 1.03255004e-01f, 9.89722982e-02f, + 1.03646003e-01f, 4.79663983e-02f, 1.11014001e-01f, 9.31736007e-02f, + 1.15768999e-01f, 1.04014002e-01f, -8.90677981e-03f, 1.13103002e-01f, + 1.33085996e-01f, 1.25405997e-01f, 1.50051996e-01f, -1.13038003e-01f, + 7.01059997e-02f, 1.79651007e-01f, 1.41055003e-01f, 1.62841007e-01f, + -1.00247003e-02f, -8.17587040e-03f, -8.32176022e-03f, -8.90108012e-03f, + -8.13035015e-03f, -1.77263003e-02f, -3.69572006e-02f, -3.51580009e-02f, + -5.92143014e-02f, -1.80795006e-02f, -5.46086021e-03f, -4.10550982e-02f, + -1.83081999e-02f, -2.15411000e-02f, -1.17953997e-02f, 3.33894007e-02f, + -5.29635996e-02f, -6.97528012e-03f, -3.15250992e-03f, -3.27355005e-02f, + 1.29676998e-01f, 1.16080999e-01f, 1.15947001e-01f, 1.21797003e-01f, + 1.16089001e-01f, 1.44875005e-01f, 1.15617000e-01f, 1.31586999e-01f, + 1.74735002e-02f, 1.21973999e-01f, 1.31596997e-01f, 2.48907991e-02f, + 6.18605018e-02f, 1.12855002e-01f, -6.99798986e-02f, 9.58312973e-02f, + 1.53593004e-01f, -8.75087008e-02f, -4.92327996e-02f, -3.32239009e-02f + }; + + std::vector anchors_vector{ -38, -16, 53, 31, + -120, -120, 135, 135 }; + + SimpleTensor proposals_expected(TensorShape(5, 9), DataType::F32); + fill_tensor(proposals_expected, std::vector { 0, 0, 0, 79, 59, + 0, 0, 5.0005703f, 52.63237f, 43.69501495f, + 0, 24.13628387f, 7.51243401f, 79, 46.06628418f, + 0, 0, 7.50924301f, 68.47792816f, 46.03357315f, + 0, 0, 23.09477997f, 51.61448669f, 59, + 0, 0, 39.52141571f, 52.44710541f, 59, + 0, 23.57396317f, 29.98791885f, 79, 59, + 0, 0, 41.90219116f, 79, 59, + 0, 0, 23.30098343f, 79, 59 + }); + + SimpleTensor scores_expected(TensorShape(9), DataType::F32); + fill_tensor(scores_expected, std::vector + { + 2.66913995e-02f, + 5.44218998e-03f, + 1.20544003e-03f, + 1.19207997e-03f, + 6.17993006e-04f, + 4.72735002e-04f, + 6.09605013e-05f, + 1.50015003e-05f, + 8.91025957e-06f + }); + + // Inputs + CLTensor scores = create_tensor(TensorShape(feature_width, feature_height, num_anchors), data_type); + CLTensor bbox_deltas = create_tensor(TensorShape(feature_width, feature_height, values_per_roi * num_anchors), data_type); + CLTensor anchors = create_tensor(TensorShape(values_per_roi, num_anchors), data_type); + + // Outputs + CLTensor proposals; + CLTensor num_valid_proposals; + CLTensor scores_out; + num_valid_proposals.allocator()->init(TensorInfo(TensorShape(1), 1, DataType::F32)); + + CLGenerateProposalsLayer generate_proposals; + generate_proposals.configure(&scores, &bbox_deltas, &anchors, &proposals, &scores_out, &num_valid_proposals, + GenerateProposalsInfo(80, 60, 0.166667f, 1 / 16.0, 6000, 300, 0.7f, 16.0f)); + + // Allocate memory for input/output tensors + scores.allocator()->allocate(); + bbox_deltas.allocator()->allocate(); + anchors.allocator()->allocate(); + proposals.allocator()->allocate(); + num_valid_proposals.allocator()->allocate(); + scores_out.allocator()->allocate(); + + // Fill inputs + fill_tensor(CLAccessor(scores), scores_vector); + fill_tensor(CLAccessor(bbox_deltas), bbx_vector); + fill_tensor(CLAccessor(anchors), anchors_vector); + + // Run operator + generate_proposals.run(); + + // Gather num_valid_proposals + num_valid_proposals.map(); + const float N = *reinterpret_cast(num_valid_proposals.ptr_to_element(Coordinates(0, 0))); + num_valid_proposals.unmap(); + + // Select the first N entries of the proposals + CLTensor proposals_final; + CLSlice select_proposals; + select_proposals.configure(&proposals, &proposals_final, Coordinates(0, 0), Coordinates(values_per_roi + 1, size_t(N))); + proposals_final.allocator()->allocate(); + select_proposals.run(); + + // Select the first N entries of the proposals + CLTensor scores_final; + CLSlice select_scores; + select_scores.configure(&scores_out, &scores_final, Coordinates(0), Coordinates(size_t(N))); + scores_final.allocator()->allocate(); + select_scores.run(); + + // Validate the output + validate(CLAccessor(proposals_final), proposals_expected); + validate(CLAccessor(scores_final), scores_expected); +} + +FIXTURE_DATA_TEST_CASE(ComputeAllAnchors, CLComputeAllAnchorsFixture, framework::DatasetMode::ALL, + combine(combine(framework::dataset::make("NumAnchors", { 2, 4, 8 }), ComputeAllInfoDataset), framework::dataset::make("DataType", { DataType::F32 }))) +{ + // Validate output + validate(CLAccessor(_target), _reference); +} +TEST_SUITE_END() // FP32 + +TEST_SUITE(FP16) +FIXTURE_DATA_TEST_CASE(ComputeAllAnchors, CLComputeAllAnchorsFixture, framework::DatasetMode::ALL, + combine(combine(framework::dataset::make("NumAnchors", { 2, 4, 8 }), ComputeAllInfoDataset), framework::dataset::make("DataType", { DataType::F16 }))) +{ + // Validate output + validate(CLAccessor(_target), _reference); +} +TEST_SUITE_END() // FP16 +TEST_SUITE_END() // Float + +TEST_SUITE_END() // GenerateProposals +TEST_SUITE_END() // CL + +} // namespace validation +} // namespace test +} // namespace arm_compute diff --git a/tests/validation/fixtures/ComputeAllAnchorsFixture.h b/tests/validation/fixtures/ComputeAllAnchorsFixture.h new file mode 100644 index 0000000000..f82cac4fe6 --- /dev/null +++ b/tests/validation/fixtures/ComputeAllAnchorsFixture.h @@ -0,0 +1,107 @@ +/* + * 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_COMPUTEALLANCHORS_FIXTURE +#define ARM_COMPUTE_TEST_COMPUTEALLANCHORS_FIXTURE + +#include "arm_compute/core/TensorShape.h" +#include "arm_compute/core/Types.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/ComputeAllAnchors.h" + +namespace arm_compute +{ +namespace test +{ +namespace validation +{ +template +class ComputeAllAnchorsFixture : public framework::Fixture +{ +public: + template + void setup(size_t num_anchors, const ComputeAnchorsInfo &info, DataType data_type) + { + _target = compute_target(num_anchors, data_type, info); + _reference = compute_reference(num_anchors, data_type, info); + } + +protected: + template + void fill(U &&tensor) + { + library->fill_tensor_uniform(tensor, 0, T(0), T(100)); + } + + TensorType compute_target(size_t num_anchors, DataType data_type, const ComputeAnchorsInfo &info) + { + // Create tensors + TensorShape anchors_shape(4, num_anchors); + TensorType anchors = create_tensor(anchors_shape, data_type); + TensorType all_anchors; + + // Create and configure function + FunctionType compute_all_anchors; + compute_all_anchors.configure(&anchors, &all_anchors, info); + + ARM_COMPUTE_EXPECT(all_anchors.info()->is_resizable(), framework::LogLevel::ERRORS); + + // Allocate tensors + all_anchors.allocator()->allocate(); + anchors.allocator()->allocate(); + + ARM_COMPUTE_EXPECT(!all_anchors.info()->is_resizable(), framework::LogLevel::ERRORS); + + // Fill tensors + fill(CLAccessor(anchors)); + + // Compute function + compute_all_anchors.run(); + + return all_anchors; + } + + SimpleTensor compute_reference(size_t num_anchors, + DataType data_type, + const ComputeAnchorsInfo &info) + { + // Create reference tensor + SimpleTensor anchors(TensorShape(4, num_anchors), data_type); + + // Fill reference tensor + fill(anchors); + return reference::compute_all_anchors(anchors, info); + } + + TensorType _target{}; + SimpleTensor _reference{}; +}; +} // namespace validation +} // namespace test +} // namespace arm_compute +#endif /* ARM_COMPUTE_TEST_COMPUTEALLANCHORS_FIXTURE */ diff --git a/tests/validation/reference/BoundingBoxTransform.cpp b/tests/validation/reference/BoundingBoxTransform.cpp index 6ac512e749..9918ff68c5 100644 --- a/tests/validation/reference/BoundingBoxTransform.cpp +++ b/tests/validation/reference/BoundingBoxTransform.cpp @@ -84,10 +84,10 @@ SimpleTensor bounding_box_transform(const SimpleTensor &boxes, const Simpl const T pred_h = T(std::exp(dh)) * height; // Store the prediction into the output tensor - pred_boxes_ptr[start_delta] = scale * utility::clamp(pred_ctr_x - T(0.5) * pred_w, T(0), T(img_w)); - pred_boxes_ptr[start_delta + 1] = scale * utility::clamp(pred_ctr_y - T(0.5) * pred_h, T(0), T(img_h)); - pred_boxes_ptr[start_delta + 2] = scale * utility::clamp(pred_ctr_x + T(0.5) * pred_w, T(0), T(img_w)); - pred_boxes_ptr[start_delta + 3] = scale * utility::clamp(pred_ctr_y + T(0.5) * pred_h, T(0), T(img_h)); + pred_boxes_ptr[start_delta] = scale * utility::clamp(pred_ctr_x - T(0.5) * pred_w, T(0), T(img_w - 1)); + pred_boxes_ptr[start_delta + 1] = scale * utility::clamp(pred_ctr_y - T(0.5) * pred_h, T(0), T(img_h - 1)); + pred_boxes_ptr[start_delta + 2] = scale * utility::clamp(pred_ctr_x + T(0.5) * pred_w, T(0), T(img_w - 1)); + pred_boxes_ptr[start_delta + 3] = scale * utility::clamp(pred_ctr_y + T(0.5) * pred_h, T(0), T(img_h - 1)); } } return pred_boxes; diff --git a/tests/validation/reference/ComputeAllAnchors.cpp b/tests/validation/reference/ComputeAllAnchors.cpp new file mode 100644 index 0000000000..48f4767fae --- /dev/null +++ b/tests/validation/reference/ComputeAllAnchors.cpp @@ -0,0 +1,79 @@ +/* + * 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 "ComputeAllAnchors.h" + +#include "arm_compute/core/Types.h" +#include "arm_compute/core/utils/misc/ShapeCalculator.h" +#include "arm_compute/core/utils/misc/Utility.h" +#include "tests/validation/Helpers.h" + +namespace arm_compute +{ +namespace test +{ +namespace validation +{ +namespace reference +{ +template +SimpleTensor compute_all_anchors(const SimpleTensor &anchors, const ComputeAnchorsInfo &info) +{ + const int num_anchors = anchors.shape()[1]; + const auto width = int(info.feat_width()); + const auto height = int(info.feat_height()); + const float stride = 1. / info.spatial_scale(); + + SimpleTensor all_anchors(TensorShape(4, width * height * num_anchors), anchors.data_type()); + const T *anchors_ptr = anchors.data(); + T *all_anchors_ptr = all_anchors.data(); + + // Iterate over the input grid and anchors + for(int y = 0; y < height; y++) + { + for(int x = 0; x < width; x++) + { + for(int a = 0; a < num_anchors; a++) + { + const T shift_x = T(x) * T(stride); + const T shift_y = T(y) * T(stride); + const size_t anchor_id = a + x * num_anchors + y * width * num_anchors; + // x1 + all_anchors_ptr[anchor_id * 4] = anchors_ptr[4 * a] + shift_x; + // y1 + all_anchors_ptr[anchor_id * 4 + 1] = anchors_ptr[4 * a + 1] + shift_y; + // x2 + all_anchors_ptr[anchor_id * 4 + 2] = anchors_ptr[4 * a + 2] + shift_x; + // y2 + all_anchors_ptr[anchor_id * 4 + 3] = anchors_ptr[4 * a + 3] + shift_y; + } + } + } + return all_anchors; +} +template SimpleTensor compute_all_anchors(const SimpleTensor &anchors, const ComputeAnchorsInfo &info); +template SimpleTensor compute_all_anchors(const SimpleTensor &anchors, const ComputeAnchorsInfo &info); +} // namespace reference +} // namespace validation +} // namespace test +} // namespace arm_compute diff --git a/tests/validation/reference/ComputeAllAnchors.h b/tests/validation/reference/ComputeAllAnchors.h new file mode 100644 index 0000000000..b21bf3cc7e --- /dev/null +++ b/tests/validation/reference/ComputeAllAnchors.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_COMPUTEALLANCHORS_H__ +#define __ARM_COMPUTE_TEST_COMPUTEALLANCHORS_H__ + +#include "arm_compute/core/Types.h" +#include "arm_compute/core/utils/misc/ShapeCalculator.h" +#include "tests/validation/Helpers.h" + +namespace arm_compute +{ +namespace test +{ +namespace validation +{ +namespace reference +{ +template +SimpleTensor compute_all_anchors(const SimpleTensor &anchors, const ComputeAnchorsInfo &info); +} // namespace reference +} // namespace validation +} // namespace test +} // namespace arm_compute +#endif /* __ARM_COMPUTE_TEST_COMPUTEALLANCHORS_H__ */ diff --git a/utils/TypePrinter.h b/utils/TypePrinter.h index df16cba9b5..58162000a6 100644 --- a/utils/TypePrinter.h +++ b/utils/TypePrinter.h @@ -261,6 +261,58 @@ inline std::string to_string(const BoundingBoxTransformInfo &bbox_info) return str.str(); } +/** Formatted output of the ComputeAnchorsInfo type. + * + * @param[out] os Output stream. + * @param[in] anchors_info Type to output. + * + * @return Modified output stream. + */ +inline ::std::ostream &operator<<(::std::ostream &os, const ComputeAnchorsInfo &anchors_info) +{ + os << "(" << anchors_info.feat_width() << "x" << anchors_info.feat_height() << ")~" << anchors_info.spatial_scale(); + return os; +} + +/** Formatted output of the ComputeAnchorsInfo type. + * + * @param[in] anchors_info Type to output. + * + * @return Formatted string. + */ +inline std::string to_string(const ComputeAnchorsInfo &anchors_info) +{ + std::stringstream str; + str << anchors_info; + return str.str(); +} + +/** Formatted output of the GenerateProposalsInfo type. + * + * @param[out] os Output stream. + * @param[in] proposals_info Type to output. + * + * @return Modified output stream. + */ +inline ::std::ostream &operator<<(::std::ostream &os, const GenerateProposalsInfo &proposals_info) +{ + os << "(" << proposals_info.im_width() << "x" << proposals_info.im_height() << ")~" << proposals_info.im_scale(); + return os; +} + +/** Formatted output of the GenerateProposalsInfo type. + * + * @param[in] proposals_info Type to output. + * + * @return Formatted string. + */ +inline std::string to_string(const GenerateProposalsInfo &proposals_info) +{ + std::stringstream str; + str << proposals_info; + return str.str(); +} + /** Formatted output of the QuantizationInfo type. * * @param[out] os Output stream. -- cgit v1.2.1