From 5209be567a0a7df4d205d3dc2b971b8f03964593 Mon Sep 17 00:00:00 2001 From: Manuel Bottini Date: Wed, 13 Feb 2019 16:34:56 +0000 Subject: COMPMID-1999: Add support for GenerateProposals operator in CL Change-Id: Ie08a6874347085f96b00f25bdb605eee7d683c25 Signed-off-by: giuros01 Reviewed-on: https://review.mlplatform.org/719 Tested-by: Arm Jenkins Reviewed-by: Georgios Pinitas Reviewed-by: Michalis Spyrou --- src/core/CL/CLKernelLibrary.cpp | 5 + src/core/CL/cl_kernels/bounding_box_transform.cl | 4 +- src/core/CL/cl_kernels/generate_proposals.cl | 88 +++++++ .../CL/kernels/CLGenerateProposalsLayerKernel.cpp | 128 ++++++++++ .../CPPBoxWithNonMaximaSuppressionLimitKernel.cpp | 35 +-- src/graph/GraphBuilder.cpp | 16 ++ src/graph/backends/CL/CLFunctionsFactory.cpp | 2 + src/graph/backends/CL/CLNodeValidator.cpp | 2 + src/graph/backends/GLES/GCNodeValidator.cpp | 2 + src/graph/backends/NEON/NENodeValidator.cpp | 2 + src/graph/nodes/GenerateProposalsLayerNode.cpp | 102 ++++++++ src/runtime/CL/functions/CLComputeAllAnchors.cpp | 42 +++ .../CL/functions/CLGenerateProposalsLayer.cpp | 284 +++++++++++++++++++++ 13 files changed, 695 insertions(+), 17 deletions(-) create mode 100644 src/core/CL/cl_kernels/generate_proposals.cl create mode 100644 src/core/CL/kernels/CLGenerateProposalsLayerKernel.cpp create mode 100644 src/graph/nodes/GenerateProposalsLayerNode.cpp create mode 100644 src/runtime/CL/functions/CLComputeAllAnchors.cpp create mode 100644 src/runtime/CL/functions/CLGenerateProposalsLayer.cpp (limited to 'src') diff --git a/src/core/CL/CLKernelLibrary.cpp b/src/core/CL/CLKernelLibrary.cpp index a7d371dabc..4ecb885440 100644 --- a/src/core/CL/CLKernelLibrary.cpp +++ b/src/core/CL/CLKernelLibrary.cpp @@ -307,6 +307,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" }, @@ -704,6 +705,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 77db5d9311..e6f470a962 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) 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..a947dad523 --- /dev/null +++ b/src/core/CL/cl_kernels/generate_proposals.cl @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2019 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..f16422f815 --- /dev/null +++ b/src/core/CL/kernels/CLGenerateProposalsLayerKernel.cpp @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2019 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 5e4b80aa5a..02150ff275 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/graph/GraphBuilder.cpp b/src/graph/GraphBuilder.cpp index cac1a37099..a944d2c25d 100644 --- a/src/graph/GraphBuilder.cpp +++ b/src/graph/GraphBuilder.cpp @@ -448,6 +448,22 @@ NodeID GraphBuilder::add_fully_connected_layer(Graph &g, NodeParams params, Node return fc_nid; } +NodeID GraphBuilder::add_generate_proposals_node(Graph &g, NodeParams params, NodeIdxPair scores, NodeIdxPair deltas, NodeIdxPair anchors, GenerateProposalsInfo info) +{ + CHECK_NODEIDX_PAIR(scores, g); + CHECK_NODEIDX_PAIR(deltas, g); + CHECK_NODEIDX_PAIR(anchors, g); + + NodeID nid = g.add_node(info); + + g.add_connection(scores.node_id, scores.index, nid, 0); + g.add_connection(deltas.node_id, deltas.index, nid, 1); + g.add_connection(anchors.node_id, anchors.index, nid, 2); + + set_node_params(g, nid, params); + return nid; +} + NodeID GraphBuilder::add_normalization_node(Graph &g, NodeParams params, NodeIdxPair input, NormalizationLayerInfo norm_info) { return create_simple_single_input_output_node(g, params, input, norm_info); diff --git a/src/graph/backends/CL/CLFunctionsFactory.cpp b/src/graph/backends/CL/CLFunctionsFactory.cpp index 88d8e3c6c5..b9e3ddc0a3 100644 --- a/src/graph/backends/CL/CLFunctionsFactory.cpp +++ b/src/graph/backends/CL/CLFunctionsFactory.cpp @@ -192,6 +192,8 @@ std::unique_ptr CLFunctionFactory::create(INode *node, GraphContext & return detail::create_flatten_layer(*polymorphic_downcast(node)); case NodeType::FullyConnectedLayer: return detail::create_fully_connected_layer(*polymorphic_downcast(node), ctx); + case NodeType::GenerateProposalsLayer: + return detail::create_generate_proposals_layer(*polymorphic_downcast(node), ctx); case NodeType::NormalizationLayer: return detail::create_normalization_layer(*polymorphic_downcast(node), ctx); case NodeType::NormalizePlanarYUVLayer: diff --git a/src/graph/backends/CL/CLNodeValidator.cpp b/src/graph/backends/CL/CLNodeValidator.cpp index ca327c9771..4b71837a49 100644 --- a/src/graph/backends/CL/CLNodeValidator.cpp +++ b/src/graph/backends/CL/CLNodeValidator.cpp @@ -62,6 +62,8 @@ Status CLNodeValidator::validate(INode *node) CLDepthwiseConvolutionLayer3x3>(*polymorphic_downcast(node)); case NodeType::DetectionOutputLayer: return detail::validate_detection_output_layer(*polymorphic_downcast(node)); + case NodeType::GenerateProposalsLayer: + return detail::validate_generate_proposals_layer(*polymorphic_downcast(node)); case NodeType::NormalizePlanarYUVLayer: return detail::validate_normalize_planar_yuv_layer(*polymorphic_downcast(node)); case NodeType::PadLayer: diff --git a/src/graph/backends/GLES/GCNodeValidator.cpp b/src/graph/backends/GLES/GCNodeValidator.cpp index aaa031dbb9..f15ede6e2c 100644 --- a/src/graph/backends/GLES/GCNodeValidator.cpp +++ b/src/graph/backends/GLES/GCNodeValidator.cpp @@ -115,6 +115,8 @@ Status GCNodeValidator::validate(INode *node) return ARM_COMPUTE_CREATE_ERROR(arm_compute::ErrorCode::RUNTIME_ERROR, "Unsupported operation : DetectionOutputLayer"); case NodeType::FlattenLayer: return ARM_COMPUTE_CREATE_ERROR(arm_compute::ErrorCode::RUNTIME_ERROR, "Unsupported operation : FlattenLayer"); + case NodeType::GenerateProposalsLayer: + return ARM_COMPUTE_CREATE_ERROR(arm_compute::ErrorCode::RUNTIME_ERROR, "Unsupported operation : GenerateProposalsLayer"); case NodeType::NormalizePlanarYUVLayer: return detail::validate_normalize_planar_yuv_layer(*polymorphic_downcast(node)); case NodeType::PadLayer: diff --git a/src/graph/backends/NEON/NENodeValidator.cpp b/src/graph/backends/NEON/NENodeValidator.cpp index 96236b66c3..b0feec563b 100644 --- a/src/graph/backends/NEON/NENodeValidator.cpp +++ b/src/graph/backends/NEON/NENodeValidator.cpp @@ -62,6 +62,8 @@ Status NENodeValidator::validate(INode *node) NEDepthwiseConvolutionLayer3x3>(*polymorphic_downcast(node)); case NodeType::DetectionOutputLayer: return detail::validate_detection_output_layer(*polymorphic_downcast(node)); + case NodeType::GenerateProposalsLayer: + return ARM_COMPUTE_CREATE_ERROR(arm_compute::ErrorCode::RUNTIME_ERROR, "Unsupported operation : GenerateProposalsLayer"); case NodeType::NormalizePlanarYUVLayer: return ARM_COMPUTE_CREATE_ERROR(arm_compute::ErrorCode::RUNTIME_ERROR, "Unsupported operation : NormalizePlanarYUVLayer"); case NodeType::PadLayer: diff --git a/src/graph/nodes/GenerateProposalsLayerNode.cpp b/src/graph/nodes/GenerateProposalsLayerNode.cpp new file mode 100644 index 0000000000..dabfc5aa10 --- /dev/null +++ b/src/graph/nodes/GenerateProposalsLayerNode.cpp @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2019 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/graph/nodes/GenerateProposalsLayerNode.h" + +#include "arm_compute/graph/Graph.h" +#include "arm_compute/graph/INodeVisitor.h" + +#include "arm_compute/core/Helpers.h" + +namespace arm_compute +{ +namespace graph +{ +GenerateProposalsLayerNode::GenerateProposalsLayerNode(GenerateProposalsInfo &info) + : _info(info) +{ + _input_edges.resize(3, EmptyEdgeID); + _outputs.resize(3, NullTensorID); +} + +const GenerateProposalsInfo &GenerateProposalsLayerNode::info() const +{ + return _info; +} + +bool GenerateProposalsLayerNode::forward_descriptors() +{ + if((input_id(0) != NullTensorID) && (input_id(1) != NullTensorID) && (input_id(2) != NullTensorID) && (output_id(0) != NullTensorID) && (output_id(1) != NullTensorID) + && (output_id(2) != NullTensorID)) + { + for(unsigned int i = 0; i < 3; ++i) + { + Tensor *dst = output(i); + ARM_COMPUTE_ERROR_ON(dst == nullptr); + dst->desc() = configure_output(i); + } + return true; + } + return false; +} + +TensorDescriptor GenerateProposalsLayerNode::configure_output(size_t idx) const +{ + ARM_COMPUTE_ERROR_ON(idx > 3); + + const Tensor *src = input(0); + ARM_COMPUTE_ERROR_ON(src == nullptr); + TensorDescriptor output_desc = src->desc(); + + switch(idx) + { + case 0: + // Configure proposals output + output_desc.shape = TensorShape(5, src->desc().shape.total_size()); + break; + case 1: + // Configure scores_out output + output_desc.shape = TensorShape(src->desc().shape.total_size()); + break; + case 2: + // Configure num_valid_proposals + output_desc.shape = TensorShape(1); + output_desc.data_type = DataType::U32; + break; + default: + ARM_COMPUTE_ERROR("Unsupported output index"); + } + return output_desc; +} + +NodeType GenerateProposalsLayerNode::type() const +{ + return NodeType::GenerateProposalsLayer; +} + +void GenerateProposalsLayerNode::accept(INodeVisitor &v) +{ + v.visit(*this); +} +} // namespace graph +} // namespace arm_compute diff --git a/src/runtime/CL/functions/CLComputeAllAnchors.cpp b/src/runtime/CL/functions/CLComputeAllAnchors.cpp new file mode 100644 index 0000000000..24c152f4d6 --- /dev/null +++ b/src/runtime/CL/functions/CLComputeAllAnchors.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2019 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..c50132ea04 --- /dev/null +++ b/src/runtime/CL/functions/CLGenerateProposalsLayer.cpp @@ -0,0 +1,284 @@ +/* + * Copyright (c) 2019 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(), + _is_nhwc(false), + _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) +{ + ARM_COMPUTE_ERROR_ON_NULLPTR(scores, deltas, anchors, proposals, scores_out, num_valid_proposals); + ARM_COMPUTE_ERROR_THROW_ON(CLGenerateProposalsLayer::validate(scores->info(), deltas->info(), anchors->info(), proposals->info(), scores_out->info(), num_valid_proposals->info(), info)); + + _is_nhwc = scores->info()->data_layout() == DataLayout::NHWC; + const DataType data_type = deltas->info()->data_type(); + const int num_anchors = scores->info()->dimension(get_data_layout_dimension_index(scores->info()->data_layout(), DataLayoutDimension::CHANNEL)); + const int feat_width = scores->info()->dimension(get_data_layout_dimension_index(scores->info()->data_layout(), DataLayoutDimension::WIDTH)); + const int feat_height = scores->info()->dimension(get_data_layout_dimension_index(scores->info()->data_layout(), DataLayoutDimension::HEIGHT)); + 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 + if(!_is_nhwc) + { + _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(); + } + else + { + _memory_group.manage(&_deltas_flattened); + _flatten_deltas_kernel.configure(deltas, &_deltas_flattened); + } + + const TensorShape flatten_shape_scores(1, total_num_anchors); + _scores_flattened.allocator()->init(TensorInfo(flatten_shape_scores, 1, data_type)); + + // Permute and reshape scores + if(!_is_nhwc) + { + _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(); + } + else + { + _memory_group.manage(&_scores_flattened); + _flatten_scores_kernel.configure(scores, &_scores_flattened); + } + + // 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(1), 1, DataType::U32); + + // 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(scores, deltas, anchors, proposals, scores_out, num_valid_proposals); + ARM_COMPUTE_RETURN_ERROR_ON_DATA_LAYOUT_NOT_IN(scores, DataLayout::NCHW, DataLayout::NHWC); + ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_LAYOUT(scores, deltas); + + const int num_anchors = scores->dimension(get_data_layout_dimension_index(scores->data_layout(), DataLayoutDimension::CHANNEL)); + const int feat_width = scores->dimension(get_data_layout_dimension_index(scores->data_layout(), DataLayoutDimension::WIDTH)); + const int feat_height = scores->dimension(get_data_layout_dimension_index(scores->data_layout(), DataLayoutDimension::HEIGHT)); + 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); + TensorInfo scores_permuted_info = scores->clone()->set_tensor_shape(TensorShape(num_anchors, feat_width, feat_height)).set_is_resizable(true); + if(scores->data_layout() == DataLayout::NHWC) + { + ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(deltas, &deltas_permuted_info); + ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(scores, &scores_permuted_info); + } + else + { + ARM_COMPUTE_RETURN_ON_ERROR(CLPermuteKernel::validate(deltas, &deltas_permuted_info, PermutationVector{ 2, 0, 1 })); + ARM_COMPUTE_RETURN_ON_ERROR(CLPermuteKernel::validate(scores, &scores_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_flattened_info(deltas->clone()->set_tensor_shape(TensorShape(1, total_num_anchors)).set_is_resizable(true)); + TensorInfo proposals_4_roi_values(deltas->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_CHANNEL_NOT_IN(num_valid_proposals, 1, 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 + if(!_is_nhwc) + { + CLScheduler::get().enqueue(_permute_deltas_kernel, false); + CLScheduler::get().enqueue(_permute_scores_kernel, false); + } + CLScheduler::get().enqueue(_flatten_deltas_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 -- cgit v1.2.1