From d844c08861706803ea7bebe64450e5feaa9b8179 Mon Sep 17 00:00:00 2001 From: Manuel Bottini Date: Wed, 14 Jul 2021 12:58:54 +0100 Subject: Port CLIm2ColKernel to ClIm2ColKernel Resolves: COMPMID-4516 Change-Id: I6a6db66797fa801dfe1238fceca413277241d2ec Signed-off-by: Manuel Bottini Reviewed-on: https://review.mlplatform.org/c/ml/ComputeLibrary/+/5946 Comments-Addressed: Arm Jenkins Reviewed-by: Michele Di Giorgio Tested-by: Arm Jenkins --- Android.bp | 2 +- .../runtime/CL/functions/CLFullyConnectedLayer.h | 2 +- .../runtime/CL/functions/CLGEMMConvolutionLayer.h | 11 +- docs/user_guide/release_version_and_change_log.dox | 6 +- filelist.json | 2 +- src/core/CL/CLKernels.h | 1 - src/core/CL/kernels/CLIm2ColKernel.cpp | 428 -------------------- src/core/CL/kernels/CLIm2ColKernel.h | 136 ------- src/core/CL/kernels/CLWeightsReshapeKernel.h | 4 +- src/core/gpu/cl/kernels/ClCol2ImKernel.h | 2 +- src/core/gpu/cl/kernels/ClIm2ColKernel.cpp | 431 +++++++++++++++++++++ src/core/gpu/cl/kernels/ClIm2ColKernel.h | 106 +++++ .../CL/functions/CLGEMMConvolutionLayer.cpp | 25 +- .../CL/functions/CLGEMMDeconvolutionLayer.cpp | 1 - tests/validation/CL/Im2Col.cpp | 42 +- tests/validation/CL/UNIT/DynamicTensor.cpp | 1 - tests/validation/fixtures/Im2ColFixture.h | 86 ---- 17 files changed, 589 insertions(+), 697 deletions(-) delete mode 100644 src/core/CL/kernels/CLIm2ColKernel.cpp delete mode 100644 src/core/CL/kernels/CLIm2ColKernel.h create mode 100644 src/core/gpu/cl/kernels/ClIm2ColKernel.cpp create mode 100644 src/core/gpu/cl/kernels/ClIm2ColKernel.h diff --git a/Android.bp b/Android.bp index f2934cb37d..1d9ec1c9c1 100644 --- a/Android.bp +++ b/Android.bp @@ -98,7 +98,6 @@ cc_library_static { "src/core/CL/kernels/CLFuseBatchNormalizationKernel.cpp", "src/core/CL/kernels/CLGatherKernel.cpp", "src/core/CL/kernels/CLGenerateProposalsLayerKernel.cpp", - "src/core/CL/kernels/CLIm2ColKernel.cpp", "src/core/CL/kernels/CLInstanceNormalizationLayerKernel.cpp", "src/core/CL/kernels/CLL2NormalizeLayerKernel.cpp", "src/core/CL/kernels/CLMaxUnpoolingLayerKernel.cpp", @@ -356,6 +355,7 @@ cc_library_static { "src/core/gpu/cl/kernels/ClGemmReshapeLhsMatrixKernel.cpp", "src/core/gpu/cl/kernels/ClGemmReshapeRhsMatrixKernel.cpp", "src/core/gpu/cl/kernels/ClHeightConcatenateKernel.cpp", + "src/core/gpu/cl/kernels/ClIm2ColKernel.cpp", "src/core/gpu/cl/kernels/ClMulKernel.cpp", "src/core/gpu/cl/kernels/ClPermuteKernel.cpp", "src/core/gpu/cl/kernels/ClPool2dKernel.cpp", diff --git a/arm_compute/runtime/CL/functions/CLFullyConnectedLayer.h b/arm_compute/runtime/CL/functions/CLFullyConnectedLayer.h index 075c5d1f45..82d1621341 100644 --- a/arm_compute/runtime/CL/functions/CLFullyConnectedLayer.h +++ b/arm_compute/runtime/CL/functions/CLFullyConnectedLayer.h @@ -96,7 +96,7 @@ private: /** Basic function to compute a Fully Connected layer on OpenCL. This function calls the following OpenCL kernels: * - * -# @ref CLIm2ColKernel (called when the input comes from a convolutional layer) + * -# @ref opencl::kernels::ClIm2ColKernel (called when the input comes from a convolutional layer) * -# @ref CLTranspose (if @p are_weights_reshaped is set to false and transpose_weights is set to true ) (called once) * -# @ref opencl::kernels::ClGemmMatrixMultiplyKernel or @ref CLGEMMLowpMatrixMultiplyCore (if quantized asymmetric) * diff --git a/arm_compute/runtime/CL/functions/CLGEMMConvolutionLayer.h b/arm_compute/runtime/CL/functions/CLGEMMConvolutionLayer.h index 564fb1ecde..e262409ee7 100644 --- a/arm_compute/runtime/CL/functions/CLGEMMConvolutionLayer.h +++ b/arm_compute/runtime/CL/functions/CLGEMMConvolutionLayer.h @@ -41,16 +41,16 @@ namespace arm_compute { +class CLWeightsReshapeKernel; +class ICLTensor; namespace opencl { namespace kernels { +class ClIm2ColKernel; class ClCol2ImKernel; } // namespace kernels } // namespace opencl -class CLIm2ColKernel; -class CLWeightsReshapeKernel; -class ICLTensor; /** Function to reshape and transpose the weights. This function calls the following kernels: * -# @ref CLWeightsReshapeKernel @@ -173,7 +173,7 @@ private: /** Basic function to compute the convolution layer. This function calls the following OpenCL kernels/functions: * - * -# @ref CLIm2ColKernel + * -# @ref opencl::kernels::ClIm2ColKernel * -# @ref CLGEMM (if the data type is FP32 or FP16) * -# @ref CLGEMMLowpMatrixMultiplyCore (if the data type is QASYMM8/QASYMM8_SIGNED) * -# @ref CLGEMMLowpOutputStage with QUANTIZE_DOWN_FIXEDPOINT type of quantization (if the data type is QASYMM8/QASYMM8_SIGNED) @@ -321,13 +321,14 @@ private: IWeightsManager *_weights_manager; CLConvolutionLayerReshapeWeights _reshape_weights; weights_transformations::CLConvolutionLayerReshapeWeightsTransform _reshape_weights_managed; - std::unique_ptr _im2col_kernel; + std::unique_ptr _im2col_kernel; CLGEMM _mm_gemm; CLGEMMLowpMatrixMultiplyCore _mm_gemmlowp; std::unique_ptr _col2im_kernel; CLActivationLayer _activationlayer_function; const ICLTensor *_original_weights; + const ICLTensor *_input; const ICLTensor *_gemm_output_to_use; ICLTensor *_output; diff --git a/docs/user_guide/release_version_and_change_log.dox b/docs/user_guide/release_version_and_change_log.dox index 8b15a384cc..45303e5d87 100644 --- a/docs/user_guide/release_version_and_change_log.dox +++ b/docs/user_guide/release_version_and_change_log.dox @@ -567,7 +567,7 @@ v20.08 Public major release The default "axis" value for @ref NESoftmaxLayer, @ref NELogSoftmaxLayer is changed from 1 to 0. Only axis 0 is supported. - The support for quantized data types has been removed from @ref CLLogSoftmaxLayer due to implementation complexity. - - Removed padding requirement for the input (e.g. LHS of GEMM) and output in CLGEMMMatrixMultiplyNativeKernel, CLGEMMMatrixMultiplyReshapedKernel, CLGEMMMatrixMultiplyReshapedOnlyRHSKernel and @ref CLIm2ColKernel (NHWC only) + - Removed padding requirement for the input (e.g. LHS of GEMM) and output in CLGEMMMatrixMultiplyNativeKernel, CLGEMMMatrixMultiplyReshapedKernel, CLGEMMMatrixMultiplyReshapedOnlyRHSKernel and CLIm2ColKernel (NHWC only) - This change allows to use @ref CLGEMMConvolutionLayer without extra padding for the input and output. - Only the weights/bias of @ref CLGEMMConvolutionLayer could require padding for the computation. - Only on Arm® Mali™ Midgard GPUs, @ref CLGEMMConvolutionLayer could require padding since CLGEMMMatrixMultiplyKernel is called and currently requires padding. @@ -1064,7 +1064,7 @@ v18.08 Public major release - @ref CLDirectConvolutionLayer - @ref CLConvolutionLayer - @ref CLScale - - @ref CLIm2ColKernel + - CLIm2ColKernel - New Arm® Neon™ kernels / functions: - @ref NERNNLayer - New OpenCL kernels / functions: @@ -1384,7 +1384,7 @@ v17.02.1 Sources preview - New OpenCL kernels / functions: - CLLogits1DMaxKernel, CLLogits1DShiftExpSumKernel, CLLogits1DNormKernel / @ref CLSoftmaxLayer - CLPoolingLayerKernel / @ref CLPoolingLayer - - @ref CLIm2ColKernel, CLCol2ImKernel, CLConvolutionLayerWeightsReshapeKernel / CLConvolutionLayer + - CLIm2ColKernel, CLCol2ImKernel, CLConvolutionLayerWeightsReshapeKernel / CLConvolutionLayer - @ref CLRemapKernel / @ref CLRemap - CLGaussianPyramidHorKernel, CLGaussianPyramidVertKernel / CLGaussianPyramid, CLGaussianPyramidHalf, CLGaussianPyramidOrb - CLMinMaxKernel, CLMinMaxLocationKernel / CLMinMaxLocation diff --git a/filelist.json b/filelist.json index c311af459d..68e6aebf4f 100644 --- a/filelist.json +++ b/filelist.json @@ -400,7 +400,7 @@ "files": { "kernel": [ "src/core/gpu/cl/kernels/ClCol2ImKernel.cpp", - "src/core/CL/kernels/CLIm2ColKernel.cpp" + "src/core/gpu/cl/kernels/ClIm2ColKernel.cpp" ] } }, diff --git a/src/core/CL/CLKernels.h b/src/core/CL/CLKernels.h index d2d5b928bc..6f6a8642e8 100644 --- a/src/core/CL/CLKernels.h +++ b/src/core/CL/CLKernels.h @@ -43,7 +43,6 @@ #include "src/core/CL/kernels/CLFuseBatchNormalizationKernel.h" #include "src/core/CL/kernels/CLGatherKernel.h" #include "src/core/CL/kernels/CLGenerateProposalsLayerKernel.h" -#include "src/core/CL/kernels/CLIm2ColKernel.h" #include "src/core/CL/kernels/CLInstanceNormalizationLayerKernel.h" #include "src/core/CL/kernels/CLL2NormalizeLayerKernel.h" #include "src/core/CL/kernels/CLMaxUnpoolingLayerKernel.h" diff --git a/src/core/CL/kernels/CLIm2ColKernel.cpp b/src/core/CL/kernels/CLIm2ColKernel.cpp deleted file mode 100644 index 97740e3c34..0000000000 --- a/src/core/CL/kernels/CLIm2ColKernel.cpp +++ /dev/null @@ -1,428 +0,0 @@ -/* - * Copyright (c) 2017-2021 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 "src/core/CL/kernels/CLIm2ColKernel.h" - -#include "arm_compute/core/CL/CLHelpers.h" -#include "arm_compute/core/CL/CLKernelLibrary.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/Validate.h" -#include "arm_compute/core/utils/misc/ShapeCalculator.h" -#include "src/core/AccessWindowStatic.h" -#include "src/core/CL/CLValidate.h" -#include "src/core/helpers/AutoConfiguration.h" -#include "src/core/helpers/WindowHelpers.h" -#include "support/StringSupport.h" - -#include -#include -#include - -namespace arm_compute -{ -using namespace misc::shape_calculator; - -namespace -{ -struct Im2ColConfiguration -{ - std::string kernel_name{}; - std::set build_options{}; - unsigned int num_elems_processed_per_iteration{}; - bool is_padding_required_nchw{}; -}; - -Status validate_arguments(const ITensorInfo *input, const ITensorInfo *output, const Size2D &kernel_dims, const PadStrideInfo &conv_info, bool has_bias, const Size2D &dilation, - unsigned int num_groups) -{ - const unsigned int channel_idx = get_data_layout_dimension_index(input->data_layout(), DataLayoutDimension::CHANNEL); - - ARM_COMPUTE_RETURN_ERROR_ON_F16_UNSUPPORTED(input); - ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input, 1, DataType::QASYMM8, DataType::QASYMM8_SIGNED, DataType::F16, DataType::F32); - ARM_COMPUTE_RETURN_ERROR_ON(is_data_type_quantized(input->data_type()) && has_bias); - ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(output); - ARM_COMPUTE_RETURN_ERROR_ON((dilation.x() < 1) || (dilation.y() < 1)); - ARM_COMPUTE_RETURN_ERROR_ON(input->data_layout() == DataLayout::UNKNOWN); - ARM_COMPUTE_RETURN_ERROR_ON(num_groups == 0); - ARM_COMPUTE_RETURN_ERROR_ON(input->data_layout() == DataLayout::NHWC && num_groups > 1); - ARM_COMPUTE_RETURN_ERROR_ON((input->dimension(channel_idx) % num_groups) != 0); - - // Since there's no implicit padding added, check the total input spatial dimensions (with conv paddings) are big enough for the kernel dimensions - const unsigned int width_idx = get_data_layout_dimension_index(input->data_layout(), DataLayoutDimension::WIDTH); - const unsigned int height_idx = get_data_layout_dimension_index(input->data_layout(), DataLayoutDimension::HEIGHT); - const unsigned total_width = input->dimension(width_idx) + conv_info.pad_left() + conv_info.pad_right(); - const unsigned total_height = input->dimension(height_idx) + conv_info.pad_top() + conv_info.pad_bottom(); - ARM_COMPUTE_RETURN_ERROR_ON((total_width < kernel_dims.width) || (total_height < kernel_dims.height)); - - if(output->total_size() > 0) - { - const TensorInfo tensor_info_output = output->clone()->set_tensor_shape(compute_im2col_conv_shape(input, kernel_dims, conv_info, has_bias, dilation, num_groups == 1, num_groups)); - ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(output, &tensor_info_output); - ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, output); - ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_QUANTIZATION_INFO(input, output); - } - - return Status{}; -} - -std::pair validate_and_configure_window(ITensorInfo *input, ITensorInfo *output, const Size2D &kernel_dims, const PadStrideInfo &conv_info, bool has_bias, const Size2D &dilation, - unsigned int num_elems_processed_per_iteration, bool is_padding_required_nchw, unsigned int num_groups) -{ - ARM_COMPUTE_ERROR_ON_NULLPTR(input, output); - - // Output tensor auto initialization if not yet initialized - TensorShape expected_output_shape = compute_im2col_conv_shape(input, kernel_dims, conv_info, has_bias, dilation, num_groups == 1, num_groups); - - auto_init_if_empty(*output, input->clone()->set_tensor_shape(expected_output_shape)); - - const DataLayout data_layout = input->data_layout(); - const unsigned int width_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::WIDTH); - const unsigned int height_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::HEIGHT); - const unsigned int input_width = input->dimension(width_idx); - const unsigned int input_height = input->dimension(height_idx); - - // Configure the execute window based on the selected optimal OpenCL kernel - bool window_changed = false; - Window win; - - if(data_layout == DataLayout::NHWC) - { - win = calculate_max_window(*input, Steps(num_elems_processed_per_iteration)); - } - else - { - if(is_padding_required_nchw) - { - const BorderSize border(conv_info.pad_top(), conv_info.pad_right(), conv_info.pad_bottom(), conv_info.pad_left()); - win = calculate_max_window(*input, - Steps(num_elems_processed_per_iteration * conv_info.stride().first, conv_info.stride().second)); - AccessWindowStatic input_access(input, - -border.left, - -border.top, - ceil_to_multiple(input_width + border.right, kernel_dims.width * num_elems_processed_per_iteration), - input_height + border.bottom); - window_changed = window_changed || update_window_and_padding(win, input_access); - } - else - { - // For the generic case, CLIm2ColKernel doesn't need padding (we do not read out-of-bounds elements) so - // update_window_and_padding() can be skipped - win = calculate_max_window(*input, Steps()); - } - } - - // set the Z dimension's step same size as the whole dimension so that one can't split across the Z dimension - win.set_dimension_step(Window::DimZ, win[Window::DimZ].end() - win[Window::DimZ].start()); - - Status err = (window_changed) ? ARM_COMPUTE_CREATE_ERROR(ErrorCode::RUNTIME_ERROR, "Insufficient Padding!") : Status{}; - return std::make_pair(err, win); -} - -Im2ColConfiguration configure_opencl_kernel(const ITensorInfo *input, const Size2D &kernel_dims, const PadStrideInfo &conv_info, bool has_bias, const Size2D &dilation, unsigned int num_groups) -{ - const DataLayout data_layout = input->data_layout(); - const DataType data_type = input->data_type(); - const unsigned int width_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::WIDTH); - const unsigned int height_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::HEIGHT); - const unsigned int channel_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::CHANNEL); - const unsigned int input_width = input->dimension(width_idx); - const unsigned int input_height = input->dimension(height_idx); - const unsigned int input_channel = input->dimension(channel_idx); - - const std::pair convolved_dims = scaled_dimensions(input_width, input_height, kernel_dims.width, kernel_dims.height, conv_info, dilation); - - // Im2Col configuration - std::string kernel_name = "im2col_generic_"; - CLBuildOptions build_opts; - unsigned int num_elems_processed_per_iteration = 1; - bool is_padding_required_nchw = false; - const UniformQuantizationInfo qinfo = input->quantization_info().uniform(); - - build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(data_type)); - build_opts.add_option("-DELEMENT_SIZE=" + support::cpp11::to_string(input->element_size())); - build_opts.add_option("-DKERNEL_WIDTH=" + support::cpp11::to_string(kernel_dims.width)); - build_opts.add_option("-DKERNEL_HEIGHT=" + support::cpp11::to_string(kernel_dims.height)); - build_opts.add_option("-DCONVOLVED_WIDTH=" + support::cpp11::to_string(convolved_dims.first)); - build_opts.add_option("-DCONVOLVED_HEIGHT=" + support::cpp11::to_string(convolved_dims.second)); - build_opts.add_option("-DSTRIDE_X=" + support::cpp11::to_string(conv_info.stride().first)); - build_opts.add_option("-DSTRIDE_Y=" + support::cpp11::to_string(conv_info.stride().second)); - build_opts.add_option("-DPAD_LEFT=" + support::cpp11::to_string(conv_info.pad_left())); - build_opts.add_option("-DPAD_TOP=" + support::cpp11::to_string(conv_info.pad_top())); - build_opts.add_option("-DPAD_RIGHT=" + support::cpp11::to_string(conv_info.pad_right())); - build_opts.add_option("-DPAD_BOTTOM=" + support::cpp11::to_string(conv_info.pad_bottom())); - build_opts.add_option("-DSRC_WIDTH=" + support::cpp11::to_string(input_width)); - build_opts.add_option("-DSRC_HEIGHT=" + support::cpp11::to_string(input_height)); - build_opts.add_option("-DSRC_DEPTH=" + support::cpp11::to_string(input_channel)); - build_opts.add_option("-DDILATION_X=" + support::cpp11::to_string(dilation.x())); - build_opts.add_option("-DDILATION_Y=" + support::cpp11::to_string(dilation.y())); - build_opts.add_option_if(num_groups > 1, "-DNUM_GROUPS=" + support::cpp11::to_string(num_groups)); - build_opts.add_option_if_else(is_data_type_quantized(data_type), "-DPAD_VALUE=" + support::cpp11::to_string(qinfo.offset), "-DPAD_VALUE=0"); - build_opts.add_option_if(has_bias, "-DHAS_BIAS"); - - if(data_layout == DataLayout::NHWC) - { - num_elems_processed_per_iteration = std::min(2U, input_channel); - is_padding_required_nchw = false; - - // Only the 3x3 and 9x9 cases are optimized for NHWC - if(kernel_dims == Size2D(3U, 3U)) - { - kernel_name = "im2col3x3_"; - } - else if(kernel_dims == Size2D(9U, 9U)) - { - kernel_name = "im2col9x9_"; - } - - // Get boundary vector (the first/last vector with potentially a partial vector size) size - // If input_channel is a multiple of num_elems_processed_per_iteration, the boundary vec size is the (full) vector size - // otherwise, the boundary vec size is the (partial) remainder vector size - const unsigned int vec_size = num_elems_processed_per_iteration; - const unsigned int partial_vec_size = input_channel % vec_size; - const unsigned int boundary_vec_size = vec_size - ((vec_size - partial_vec_size) % vec_size); - build_opts.add_option("-DVECTOR_SIZE=" + support::cpp11::to_string(vec_size)); - build_opts.add_option("-DBOUNDARY_VECTOR_SIZE=" + support::cpp11::to_string(boundary_vec_size)); - } - else - { - if(dilation == Size2D(1U, 1U)) - { - const bool squared_im2col = kernel_dims.width == kernel_dims.height; - if(squared_im2col) - { - // Check if we can run an optimized im2col for NCHW - switch(kernel_dims.width) - { - case 1: - // Optimized im2col1x1 if stride_x = 1 and conv_info.has_padding() = false - if(conv_info.stride().first == 1 && !conv_info.has_padding()) - { - kernel_name = "im2col1x1_stridex1_"; - num_elems_processed_per_iteration = 4; - is_padding_required_nchw = true; - } - break; - case 3: - kernel_name = "im2col3x3_"; - num_elems_processed_per_iteration = 1; - is_padding_required_nchw = true; - break; - case 5: - kernel_name = "im2col5x5_"; - num_elems_processed_per_iteration = 1; - is_padding_required_nchw = true; - break; - case 11: - // Optimized im2col11x11 if pad_x = pad_y = 0 - if(!conv_info.has_padding()) - { - kernel_name = "im2col11x11_padx0_pady0_"; - num_elems_processed_per_iteration = 1; - is_padding_required_nchw = true; - } - break; - default: - kernel_name = "im2col_generic_"; - num_elems_processed_per_iteration = 1; - is_padding_required_nchw = false; - break; - } - } - else if(kernel_dims.width > 1 && !conv_info.has_padding()) - { - kernel_name = "im2col_generic_padx0_pady0_"; - num_elems_processed_per_iteration = 1; - is_padding_required_nchw = false; - - // Optimized im2col is performed using one or more vector operations with the specified vector size - // and a remainder. For example, for 5x5 convolutions, im2col is performed using vectors of size 4 - // and scalars; for 7x7 convolutions, using vectors of size 4 and vectors of size 3. - // Using the vector size of 4 is always safe since OpenCL supports vectors of size 2 and 3. - // Using the vector size of 8, however, may be faster. - // For 2x2 convolutions, use vectors of size 2. (For 3x3 convolutions, im2col_kernel3x3_padx0_pady0 - // is used instead.) - const size_t vector_size = std::min(static_cast(4), kernel_dims.width); - const size_t width_mod_vector_size = kernel_dims.width % vector_size; - build_opts.add_option("-DVECTOR_SIZE=" + support::cpp11::to_string(vector_size)); - build_opts.add_option("-DWIDTH_MOD_VECTOR_SIZE=" + support::cpp11::to_string(width_mod_vector_size)); - } - } - } - - // Append the data layout to the kernel_name - kernel_name += lower_string(string_from_data_layout(data_layout)); - - Im2ColConfiguration im2col_config; - im2col_config.kernel_name = kernel_name; - im2col_config.build_options = build_opts.options(); - im2col_config.num_elems_processed_per_iteration = num_elems_processed_per_iteration; - im2col_config.is_padding_required_nchw = is_padding_required_nchw; - - return im2col_config; -} -} // namespace - -CLIm2ColKernel::CLIm2ColKernel() - : _input(nullptr), _output(nullptr), _data_layout(DataLayout::UNKNOWN), _convolved_dims(), _num_elems_processed_per_iteration(1), _kernel_dims(), _conv_info(), _num_groups() -{ - _type = CLKernelType::ELEMENTWISE; -} - -void CLIm2ColKernel::configure(const ICLTensor *input, ICLTensor *output, const Size2D &kernel_dims, const PadStrideInfo &conv_info, bool has_bias, const Size2D &dilation, - unsigned int num_groups) -{ - configure(CLKernelLibrary::get().get_compile_context(), input, output, kernel_dims, conv_info, has_bias, dilation, num_groups); -} - -void CLIm2ColKernel::configure(const CLCompileContext &compile_context, const ICLTensor *input, ICLTensor *output, const Size2D &kernel_dims, const PadStrideInfo &conv_info, bool has_bias, - const Size2D &dilation, - unsigned int num_groups) -{ - ARM_COMPUTE_ERROR_ON_NULLPTR(input, output); - ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input->info(), output->info(), kernel_dims, conv_info, has_bias, dilation, num_groups)); - - auto padding_info = get_padding_info({ input, output }); - _data_layout = input->info()->data_layout(); - - const unsigned int width_idx = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::WIDTH); - const unsigned int height_idx = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::HEIGHT); - const unsigned int input_width = input->info()->dimension(width_idx); - const unsigned int input_height = input->info()->dimension(height_idx); - - // Select and configure the optimal OpenCL kernel to run. - // This function returns the OpenCL kernel's name, the arguments to pass at compile time, the number of elements processed per iteration - // and the padding requirement flag - Im2ColConfiguration im2col_config = configure_opencl_kernel(input->info(), kernel_dims, conv_info, has_bias, dilation, num_groups); - - // Create kernel - _kernel = create_kernel(compile_context, im2col_config.kernel_name, im2col_config.build_options); - - _input = input; - _output = output; - _convolved_dims = scaled_dimensions(input_width, input_height, kernel_dims.width, kernel_dims.height, conv_info, dilation); - _num_elems_processed_per_iteration = im2col_config.num_elems_processed_per_iteration; - _kernel_dims = kernel_dims; // Only needed by the Tuner - _conv_info = conv_info; // Only needed by the Tuner - _num_groups = num_groups; - - // Configure kernel window - auto win_config = validate_and_configure_window(input->info(), output->info(), kernel_dims, conv_info, has_bias, dilation, im2col_config.num_elems_processed_per_iteration, - im2col_config.is_padding_required_nchw, num_groups); - ARM_COMPUTE_ERROR_THROW_ON(win_config.first); - ICLKernel::configure_internal(win_config.second); - - // Set config_id for enabling LWS tuning - _config_id = im2col_config.kernel_name; - _config_id += "_"; - _config_id += lower_string(string_from_data_type(input->info()->data_type())); - _config_id += "_"; - _config_id += support::cpp11::to_string(num_groups); - _config_id += "_"; - _config_id += support::cpp11::to_string(output->info()->dimension(0)); - _config_id += "_"; - _config_id += support::cpp11::to_string(output->info()->dimension(1)); - _config_id += "_"; - _config_id += lower_string(string_from_data_layout(_data_layout)); - - ARM_COMPUTE_ERROR_ON(input->info()->data_layout() == DataLayout::NHWC && has_padding_changed(padding_info)); -} - -Status CLIm2ColKernel::validate(const ITensorInfo *input, const ITensorInfo *output, const Size2D &kernel_dims, const PadStrideInfo &conv_info, bool has_bias, const Size2D &dilation, - unsigned int num_groups) -{ - ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, kernel_dims, conv_info, has_bias, dilation, num_groups)); - Im2ColConfiguration im2col_config = configure_opencl_kernel(input, kernel_dims, conv_info, has_bias, dilation, num_groups); - ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window(input->clone().get(), output->clone().get(), kernel_dims, conv_info, has_bias, dilation, im2col_config.num_elems_processed_per_iteration, - im2col_config.is_padding_required_nchw, num_groups) - .first); - return Status{}; -} - -void CLIm2ColKernel::run(const Window &window, cl::CommandQueue &queue) -{ - ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this); - ARM_COMPUTE_ERROR_ON_MISMATCHING_WINDOWS(ICLKernel::window(), window); - - // Get initial windows - // Collapse in order to have (SRC_DEPTH * BATCH_SIZE) on the 3rd dimension - Window window_collapsed = window.collapse_if_possible(ICLKernel::window(), Window::DimZ); - window_collapsed.set_dimension_step(Window::DimZ, 1); - - Window window_output; - window_output.use_tensor_dimensions(_output->info()->tensor_shape()); - - const Window first_slice_3d = window_collapsed.first_slice_window_3D(); - - Window slice = first_slice_3d; - Window slice_in = first_slice_3d; - Window slice_out = window_output.first_slice_window_2D(); - - if(_data_layout == DataLayout::NHWC) - { - const Window tmp_win = window.collapse_if_possible(ICLKernel::window(), 3); - const int num_batches = tmp_win[3].end(); - - slice.set(1, Window::Dimension(0, static_cast(_output->info()->tensor_shape()[1]), 1)); - slice.set(2, Window::Dimension(0, static_cast(num_batches), 1)); - } - else - { - slice.set(0, Window::Dimension(0, static_cast(ceil_to_multiple(_convolved_dims.first, _num_elems_processed_per_iteration)), _num_elems_processed_per_iteration)); - slice.set(1, Window::Dimension(0, static_cast(_convolved_dims.second), 1)); - // Note: In case of NCHW the 3rd dimension is already set collapsing the input window - } - - // Setup input slice - // The dimensions of the input are increased within the OpenCL kernel - slice_in.set(Window::DimX, Window::Dimension(0, 0, 0)); - slice_in.set(Window::DimY, Window::Dimension(0, 0, 0)); - slice_in.set(Window::DimZ, Window::Dimension(0, 0, 0)); - - // Setup output slice - // The dimensions of the output are increased within the OpenCL kernel - slice_out.set(Window::DimX, Window::Dimension(0, 0, 0)); - slice_out.set(Window::DimY, Window::Dimension(0, 0, 0)); - - unsigned int idx = num_arguments_per_3D_tensor() + (_num_groups == 1 ? num_arguments_per_2D_tensor() : num_arguments_per_3D_tensor()); - _kernel.setArg(idx++, static_cast(_input->info()->strides_in_bytes()[3])); - _kernel.setArg(idx++, static_cast(_output->info()->strides_in_bytes()[((_num_groups == 1) ? 2 : 3)])); - do - { - unsigned int idx = 0; - add_3D_tensor_argument(idx, _input, slice_in); - if(_num_groups == 1) - { - add_2D_tensor_argument(idx, _output, slice_out); - } - else - { - add_3D_tensor_argument(idx, _output, slice_out); - } - enqueue(queue, *this, slice, lws_hint()); - } - while(window_collapsed.slide_window_slice_3D(slice) && window_output.slide_window_slice_2D(slice_out) && window_collapsed.slide_window_slice_3D(slice_in)); -} -} // namespace arm_compute diff --git a/src/core/CL/kernels/CLIm2ColKernel.h b/src/core/CL/kernels/CLIm2ColKernel.h deleted file mode 100644 index 2920c7d138..0000000000 --- a/src/core/CL/kernels/CLIm2ColKernel.h +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (c) 2017-2020 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_CLIM2COLKERNEL_H -#define ARM_COMPUTE_CLIM2COLKERNEL_H - -#include "arm_compute/core/Size2D.h" -#include "src/core/CL/ICLKernel.h" - -namespace arm_compute -{ -class ICLTensor; - -/** Interface for the im2col reshape kernel. - * - * Rearranges image blocks into columns. It is used to strip out each convolution block to a single column. - * It is used to transform a convolution to a plain matrix multiplication. - * - * For example taking into account the image below and assuming 3x3 image blocks with stride of 1 we have: - * @f[ - * \left( \begin{array}{cccc} - * a00 & a01 & a02 & a03 \\ - * a10 & a11 & a12 & a13 \\ - * a20 & a21 & a22 & a23 \\ - * a30 & a31 & a32 & a33 \\ - * \end{array} \right) - * = - * \left( \begin{array}{ccccccccc} - * a00 & a01 & a02 & a10 & a11 & a12 & a20 & a21 & a22 \\ - * a01 & a02 & a03 & a11 & a12 & a13 & a21 & a22 & a23 \\ - * a10 & a11 & a12 & a20 & a21 & a22 & a30 & a31 & a32 \\ - * a11 & a12 & a13 & a21 & a22 & a23 & a31 & a32 & a33 \\ - * \end{array} \right) - * @f] - */ -class CLIm2ColKernel : public ICLKernel -{ -public: - /** Default constructor */ - CLIm2ColKernel(); - /** Prevent instances of this class from being copied (As this class contains pointers) */ - CLIm2ColKernel(const CLIm2ColKernel &) = delete; - /** Prevent instances of this class from being copied (As this class contains pointers) */ - CLIm2ColKernel &operator=(const CLIm2ColKernel &) = delete; - /** Allow instances of this class to be moved */ - CLIm2ColKernel(CLIm2ColKernel &&) = default; - /** Allow instances of this class to be moved */ - CLIm2ColKernel &operator=(CLIm2ColKernel &&) = default; - /** Set the input and output of the kernel. - * - * @param[in] input The input tensor to convert. 3 lower dimensions represent a single input [width, height, IFM], - * while every optional dimension from 4 and above represent a batch of inputs. Data types supported: QASYMM8/QASYMM8_SIGNED/F16/F32 - * @param[out] output The output tensor. First 2 lower dimensions represent a transform of each 3D input, - * while every dimension above represents a batch. Data types supported: Same as @p input - * @param[in] kernel_dims The kernel dimensions (width and height). - * @param[in] conv_info Contains padding and stride information described in @ref PadStrideInfo. - * @param[in] has_bias In case biases are provided expands the matrix with 1. - * This is valid only for non-quantized inputs. - * @param[in] dilation (Optional) Dilation, in elements, across x and y. Defaults to (1, 1). - * @param[in] num_groups (Optional) Number of groups when performing a grouped convolution. - * Number of groups other than 1 is only supported for NCHW data layout. - * Number of groups should be multiple to the number of channels. - */ - void configure(const ICLTensor *input, ICLTensor *output, const Size2D &kernel_dims, const PadStrideInfo &conv_info, bool has_bias, const Size2D &dilation = Size2D(1U, 1U), - unsigned int num_groups = 1); - /** Set the input and output of the kernel. - * - * @param[in] compile_context The compile context to be used. - * @param[in] input The input tensor to convert. 3 lower dimensions represent a single input [width, height, IFM], - * while every optional dimension from 4 and above represent a batch of inputs. Data types supported: QASYMM8/QASYMM8_SIGNED/F16/F32 - * @param[out] output The output tensor. First 2 lower dimensions represent a transform of each 3D input, - * while every dimension above represents a batch. Data types supported: Same as @p input - * @param[in] kernel_dims The kernel dimensions (width and height). - * @param[in] conv_info Contains padding and stride information described in @ref PadStrideInfo. - * @param[in] has_bias In case biases are provided expands the matrix with 1. - * @param[in] dilation (Optional) Dilation, in elements, across x and y. Defaults to (1, 1). - * @param[in] num_groups (Optional) Number of groups when performing a grouped convolution. num_groups != 1 is only supported for NCHW data layout - */ - void configure(const CLCompileContext &compile_context, const ICLTensor *input, ICLTensor *output, const Size2D &kernel_dims, const PadStrideInfo &conv_info, bool has_bias, - const Size2D &dilation = Size2D(1U, 1U), - unsigned int num_groups = 1); - /** Static function to check if given info will lead to a valid configuration of @ref CLIm2ColKernel - * - * @param[in] input The input tensor to convert. 3 lower dimensions represent a single input [width, height, IFM], - * while every optional dimension from 4 and above represent a batch of inputs. Data types supported: QASYMM8/QASYMM8_SIGNED/F16/F32 - * @param[in] output The output tensor. First 2 lower dimensions represent a transform of each 3D input, - * while every dimension above represents a batch. Data types supported: Same as @p input - * @param[in] kernel_dims The kernel dimensions (width and height). - * @param[in] conv_info Contains padding and stride information described in @ref PadStrideInfo. - * @param[in] has_bias In case biases are provided expands the matrix with 1. - * This is valid only for non-quantized inputs. - * @param[in] dilation (Optional) Dilation, in elements, across x and y. Defaults to (1, 1). - * @param[in] num_groups (Optional) Number of groups when performing a grouped convolution. - * Number of groups other than 1 is only supported for NCHW data layout. - * Number of groups should be multiple to the number of channels. - * - * @return a status - */ - static Status validate(const ITensorInfo *input, const ITensorInfo *output, const Size2D &kernel_dims, const PadStrideInfo &conv_info, bool has_bias, const Size2D &dilation = Size2D(1U, 1U), - unsigned int num_groups = 1); - - // Inherited methods overridden: - void run(const Window &window, cl::CommandQueue &queue) override; - -public: - const ICLTensor *_input; - ICLTensor *_output; - DataLayout _data_layout; - std::pair _convolved_dims; - unsigned int _num_elems_processed_per_iteration; - Size2D _kernel_dims; - PadStrideInfo _conv_info; - unsigned int _num_groups; -}; -} // namespace arm_compute -#endif /*ARM_COMPUTE_CLIM2COLKERNEL_H */ diff --git a/src/core/CL/kernels/CLWeightsReshapeKernel.h b/src/core/CL/kernels/CLWeightsReshapeKernel.h index 402a60472b..9ac60a7a1a 100644 --- a/src/core/CL/kernels/CLWeightsReshapeKernel.h +++ b/src/core/CL/kernels/CLWeightsReshapeKernel.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2020 Arm Limited. + * Copyright (c) 2017-2021 Arm Limited. * * SPDX-License-Identifier: MIT * @@ -31,7 +31,7 @@ namespace arm_compute /** OpenCL kernel to perform reshaping on the weights used by convolution and locally connected layer * * Rearranges each 3-dimensional kernel to a single row leading to a matrix with linearized kernels. - * In combination with the @ref CLIm2ColKernel can transform a convolution to a matrix multiplication. + * In combination with the @ref opencl::kernels::ClIm2ColKernel can transform a convolution to a matrix multiplication. * * For example assuming a 3D weight kernel of 3x3 dimensions and depth of 2 we have: * @f[ diff --git a/src/core/gpu/cl/kernels/ClCol2ImKernel.h b/src/core/gpu/cl/kernels/ClCol2ImKernel.h index 42d0a96075..74a9027628 100644 --- a/src/core/gpu/cl/kernels/ClCol2ImKernel.h +++ b/src/core/gpu/cl/kernels/ClCol2ImKernel.h @@ -37,7 +37,7 @@ namespace kernels { /** Interface for the col2im reshaping kernel. * - * Rearranges each matrix column into image blocks. It's the inverse operation of @ref CLIm2ColKernel. + * Rearranges each matrix column into image blocks. It's the inverse operation of @ref opencl::kernels::ClIm2ColKernel. * * For example, a vector of 9 elements can be reshaped to a block(image) of 3x3: * diff --git a/src/core/gpu/cl/kernels/ClIm2ColKernel.cpp b/src/core/gpu/cl/kernels/ClIm2ColKernel.cpp new file mode 100644 index 0000000000..61ee443aa5 --- /dev/null +++ b/src/core/gpu/cl/kernels/ClIm2ColKernel.cpp @@ -0,0 +1,431 @@ +/* + * Copyright (c) 2017-2021 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 "src/core/gpu/cl/kernels/ClIm2ColKernel.h" + +#include "arm_compute/core/CL/CLHelpers.h" +#include "arm_compute/core/CL/CLKernelLibrary.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/Validate.h" +#include "arm_compute/core/utils/misc/ShapeCalculator.h" +#include "src/core/AccessWindowStatic.h" +#include "src/core/CL/CLValidate.h" +#include "src/core/helpers/AutoConfiguration.h" +#include "src/core/helpers/WindowHelpers.h" +#include "support/Cast.h" +#include "support/StringSupport.h" + +#include +#include +#include + +namespace arm_compute +{ +using namespace misc::shape_calculator; +namespace opencl +{ +namespace kernels +{ +namespace +{ +struct Im2ColConfiguration +{ + std::string kernel_name{}; + std::set build_options{}; + unsigned int num_elems_processed_per_iteration{}; + bool is_padding_required_nchw{}; +}; + +Status validate_arguments(const ITensorInfo *src, const ITensorInfo *dst, const Size2D &kernel_dims, const PadStrideInfo &conv_info, bool has_bias, const Size2D &dilation, + unsigned int num_groups) +{ + const unsigned int channel_idx = get_data_layout_dimension_index(src->data_layout(), DataLayoutDimension::CHANNEL); + + ARM_COMPUTE_RETURN_ERROR_ON_F16_UNSUPPORTED(src); + ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(src, 1, DataType::QASYMM8, DataType::QASYMM8_SIGNED, DataType::F16, DataType::F32); + ARM_COMPUTE_RETURN_ERROR_ON(is_data_type_quantized(src->data_type()) && has_bias); + ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(dst); + ARM_COMPUTE_RETURN_ERROR_ON((dilation.x() < 1) || (dilation.y() < 1)); + ARM_COMPUTE_RETURN_ERROR_ON(src->data_layout() == DataLayout::UNKNOWN); + ARM_COMPUTE_RETURN_ERROR_ON(num_groups == 0); + ARM_COMPUTE_RETURN_ERROR_ON(src->data_layout() == DataLayout::NHWC && num_groups > 1); + ARM_COMPUTE_RETURN_ERROR_ON((src->dimension(channel_idx) % num_groups) != 0); + + // Since there's no implicit padding added, check the total input spatial dimensions (with conv paddings) are big enough for the kernel dimensions + const unsigned int width_idx = get_data_layout_dimension_index(src->data_layout(), DataLayoutDimension::WIDTH); + const unsigned int height_idx = get_data_layout_dimension_index(src->data_layout(), DataLayoutDimension::HEIGHT); + const unsigned total_width = src->dimension(width_idx) + conv_info.pad_left() + conv_info.pad_right(); + const unsigned total_height = src->dimension(height_idx) + conv_info.pad_top() + conv_info.pad_bottom(); + ARM_COMPUTE_RETURN_ERROR_ON((total_width < kernel_dims.width) || (total_height < kernel_dims.height)); + + if(dst->total_size() > 0) + { + const TensorInfo tensor_info_output = dst->clone()->set_tensor_shape(compute_im2col_conv_shape(src, kernel_dims, conv_info, has_bias, dilation, num_groups == 1, num_groups)); + ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(dst, &tensor_info_output); + ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src, dst); + ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_QUANTIZATION_INFO(src, dst); + } + + return Status{}; +} + +std::pair validate_and_configure_window(ITensorInfo *src, ITensorInfo *dst, const Size2D &kernel_dims, const PadStrideInfo &conv_info, bool has_bias, const Size2D &dilation, + unsigned int num_elems_processed_per_iteration, bool is_padding_required_nchw, unsigned int num_groups) +{ + ARM_COMPUTE_ERROR_ON_NULLPTR(src, dst); + + // Output tensor auto initialization if not yet initialized + TensorShape expected_output_shape = compute_im2col_conv_shape(src, kernel_dims, conv_info, has_bias, dilation, num_groups == 1, num_groups); + + auto_init_if_empty(*dst, src->clone()->set_tensor_shape(expected_output_shape)); + + const DataLayout data_layout = src->data_layout(); + const unsigned int width_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::WIDTH); + const unsigned int height_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::HEIGHT); + const unsigned int input_width = src->dimension(width_idx); + const unsigned int input_height = src->dimension(height_idx); + + // Configure the execute window based on the selected optimal OpenCL kernel + bool window_changed = false; + Window win; + + if(data_layout == DataLayout::NHWC) + { + win = calculate_max_window(*src, Steps(num_elems_processed_per_iteration)); + } + else + { + if(is_padding_required_nchw) + { + const BorderSize border(conv_info.pad_top(), conv_info.pad_right(), conv_info.pad_bottom(), conv_info.pad_left()); + win = calculate_max_window(*src, + Steps(num_elems_processed_per_iteration * conv_info.stride().first, conv_info.stride().second)); + AccessWindowStatic input_access(src, + -border.left, + -border.top, + ceil_to_multiple(input_width + border.right, kernel_dims.width * num_elems_processed_per_iteration), + input_height + border.bottom); + window_changed = window_changed || update_window_and_padding(win, input_access); + } + else + { + // For the generic case, CLIm2ColKernel doesn't need padding (we do not read out-of-bounds elements) so + // update_window_and_padding() can be skipped + win = calculate_max_window(*src, Steps()); + } + } + + // set the Z dimension's step same size as the whole dimension so that one can't split across the Z dimension + win.set_dimension_step(Window::DimZ, win[Window::DimZ].end() - win[Window::DimZ].start()); + + Status err = (window_changed) ? ARM_COMPUTE_CREATE_ERROR(ErrorCode::RUNTIME_ERROR, "Insufficient Padding!") : Status{}; + return std::make_pair(err, win); +} + +Im2ColConfiguration configure_opencl_kernel(const ITensorInfo *src, const Size2D &kernel_dims, const PadStrideInfo &conv_info, bool has_bias, const Size2D &dilation, unsigned int num_groups) +{ + const DataLayout data_layout = src->data_layout(); + const DataType data_type = src->data_type(); + const unsigned int width_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::WIDTH); + const unsigned int height_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::HEIGHT); + const unsigned int channel_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::CHANNEL); + const unsigned int input_width = src->dimension(width_idx); + const unsigned int input_height = src->dimension(height_idx); + const unsigned int input_channel = src->dimension(channel_idx); + + const std::pair convolved_dims = scaled_dimensions(input_width, input_height, kernel_dims.width, kernel_dims.height, conv_info, dilation); + + // Im2Col configuration + std::string kernel_name = "im2col_generic_"; + CLBuildOptions build_opts; + unsigned int num_elems_processed_per_iteration = 1; + bool is_padding_required_nchw = false; + const UniformQuantizationInfo qinfo = src->quantization_info().uniform(); + + build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(data_type)); + build_opts.add_option("-DELEMENT_SIZE=" + support::cpp11::to_string(src->element_size())); + build_opts.add_option("-DKERNEL_WIDTH=" + support::cpp11::to_string(kernel_dims.width)); + build_opts.add_option("-DKERNEL_HEIGHT=" + support::cpp11::to_string(kernel_dims.height)); + build_opts.add_option("-DCONVOLVED_WIDTH=" + support::cpp11::to_string(convolved_dims.first)); + build_opts.add_option("-DCONVOLVED_HEIGHT=" + support::cpp11::to_string(convolved_dims.second)); + build_opts.add_option("-DSTRIDE_X=" + support::cpp11::to_string(conv_info.stride().first)); + build_opts.add_option("-DSTRIDE_Y=" + support::cpp11::to_string(conv_info.stride().second)); + build_opts.add_option("-DPAD_LEFT=" + support::cpp11::to_string(conv_info.pad_left())); + build_opts.add_option("-DPAD_TOP=" + support::cpp11::to_string(conv_info.pad_top())); + build_opts.add_option("-DPAD_RIGHT=" + support::cpp11::to_string(conv_info.pad_right())); + build_opts.add_option("-DPAD_BOTTOM=" + support::cpp11::to_string(conv_info.pad_bottom())); + build_opts.add_option("-DSRC_WIDTH=" + support::cpp11::to_string(input_width)); + build_opts.add_option("-DSRC_HEIGHT=" + support::cpp11::to_string(input_height)); + build_opts.add_option("-DSRC_DEPTH=" + support::cpp11::to_string(input_channel)); + build_opts.add_option("-DDILATION_X=" + support::cpp11::to_string(dilation.x())); + build_opts.add_option("-DDILATION_Y=" + support::cpp11::to_string(dilation.y())); + build_opts.add_option_if(num_groups > 1, "-DNUM_GROUPS=" + support::cpp11::to_string(num_groups)); + build_opts.add_option_if_else(is_data_type_quantized(data_type), "-DPAD_VALUE=" + support::cpp11::to_string(qinfo.offset), "-DPAD_VALUE=0"); + build_opts.add_option_if(has_bias, "-DHAS_BIAS"); + + if(data_layout == DataLayout::NHWC) + { + num_elems_processed_per_iteration = std::min(2U, input_channel); + is_padding_required_nchw = false; + + // Only the 3x3 and 9x9 cases are optimized for NHWC + if(kernel_dims == Size2D(3U, 3U)) + { + kernel_name = "im2col3x3_"; + } + else if(kernel_dims == Size2D(9U, 9U)) + { + kernel_name = "im2col9x9_"; + } + + // Get boundary vector (the first/last vector with potentially a partial vector size) size + // If input_channel is a multiple of num_elems_processed_per_iteration, the boundary vec size is the (full) vector size + // otherwise, the boundary vec size is the (partial) remainder vector size + const unsigned int vec_size = num_elems_processed_per_iteration; + const unsigned int partial_vec_size = input_channel % vec_size; + const unsigned int boundary_vec_size = vec_size - ((vec_size - partial_vec_size) % vec_size); + build_opts.add_option("-DVECTOR_SIZE=" + support::cpp11::to_string(vec_size)); + build_opts.add_option("-DBOUNDARY_VECTOR_SIZE=" + support::cpp11::to_string(boundary_vec_size)); + } + else + { + if(dilation == Size2D(1U, 1U)) + { + const bool squared_im2col = kernel_dims.width == kernel_dims.height; + if(squared_im2col) + { + // Check if we can run an optimized im2col for NCHW + switch(kernel_dims.width) + { + case 1: + // Optimized im2col1x1 if stride_x = 1 and conv_info.has_padding() = false + if(conv_info.stride().first == 1 && !conv_info.has_padding()) + { + kernel_name = "im2col1x1_stridex1_"; + num_elems_processed_per_iteration = 4; + is_padding_required_nchw = true; + } + break; + case 3: + kernel_name = "im2col3x3_"; + num_elems_processed_per_iteration = 1; + is_padding_required_nchw = true; + break; + case 5: + kernel_name = "im2col5x5_"; + num_elems_processed_per_iteration = 1; + is_padding_required_nchw = true; + break; + case 11: + // Optimized im2col11x11 if pad_x = pad_y = 0 + if(!conv_info.has_padding()) + { + kernel_name = "im2col11x11_padx0_pady0_"; + num_elems_processed_per_iteration = 1; + is_padding_required_nchw = true; + } + break; + default: + kernel_name = "im2col_generic_"; + num_elems_processed_per_iteration = 1; + is_padding_required_nchw = false; + break; + } + } + else if(kernel_dims.width > 1 && !conv_info.has_padding()) + { + kernel_name = "im2col_generic_padx0_pady0_"; + num_elems_processed_per_iteration = 1; + is_padding_required_nchw = false; + + // Optimized im2col is performed using one or more vector operations with the specified vector size + // and a remainder. For example, for 5x5 convolutions, im2col is performed using vectors of size 4 + // and scalars; for 7x7 convolutions, using vectors of size 4 and vectors of size 3. + // Using the vector size of 4 is always safe since OpenCL supports vectors of size 2 and 3. + // Using the vector size of 8, however, may be faster. + // For 2x2 convolutions, use vectors of size 2. (For 3x3 convolutions, im2col_kernel3x3_padx0_pady0 + // is used instead.) + const size_t vector_size = std::min(static_cast(4), kernel_dims.width); + const size_t width_mod_vector_size = kernel_dims.width % vector_size; + build_opts.add_option("-DVECTOR_SIZE=" + support::cpp11::to_string(vector_size)); + build_opts.add_option("-DWIDTH_MOD_VECTOR_SIZE=" + support::cpp11::to_string(width_mod_vector_size)); + } + } + } + + // Append the data layout to the kernel_name + kernel_name += lower_string(string_from_data_layout(data_layout)); + + Im2ColConfiguration im2col_config; + im2col_config.kernel_name = kernel_name; + im2col_config.build_options = build_opts.options(); + im2col_config.num_elems_processed_per_iteration = num_elems_processed_per_iteration; + im2col_config.is_padding_required_nchw = is_padding_required_nchw; + + return im2col_config; +} +} // namespace + +ClIm2ColKernel::ClIm2ColKernel() + : _data_layout(DataLayout::UNKNOWN), _convolved_dims(), _num_elems_processed_per_iteration(1), _kernel_dims(), _conv_info(), _num_groups() +{ + _type = CLKernelType::ELEMENTWISE; +} + +void ClIm2ColKernel::configure(const ClCompileContext &compile_context, ITensorInfo *src, ITensorInfo *dst, const Size2D &kernel_dims, const PadStrideInfo &conv_info, bool has_bias, + const Size2D &dilation, + unsigned int num_groups) +{ + ARM_COMPUTE_ERROR_ON_NULLPTR(src, dst); + ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(src, dst, kernel_dims, conv_info, has_bias, dilation, num_groups)); + + auto padding_info = get_padding_info({ src, dst }); + _data_layout = src->data_layout(); + + const unsigned int width_idx = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::WIDTH); + const unsigned int height_idx = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::HEIGHT); + const unsigned int input_width = src->dimension(width_idx); + const unsigned int input_height = src->dimension(height_idx); + + // Select and configure the optimal OpenCL kernel to run. + // This function returns the OpenCL kernel's name, the arguments to pass at compile time, the number of elements processed per iteration + // and the padding requirement flag + Im2ColConfiguration im2col_config = configure_opencl_kernel(src, kernel_dims, conv_info, has_bias, dilation, num_groups); + + // Create kernel + _kernel = create_kernel(compile_context, im2col_config.kernel_name, im2col_config.build_options); + + _convolved_dims = scaled_dimensions(input_width, input_height, kernel_dims.width, kernel_dims.height, conv_info, dilation); + _num_elems_processed_per_iteration = im2col_config.num_elems_processed_per_iteration; + _kernel_dims = kernel_dims; // Only needed by the Tuner + _conv_info = conv_info; // Only needed by the Tuner + _num_groups = num_groups; + + // Configure kernel window + auto win_config = validate_and_configure_window(src, dst, kernel_dims, conv_info, has_bias, dilation, im2col_config.num_elems_processed_per_iteration, + im2col_config.is_padding_required_nchw, num_groups); + ARM_COMPUTE_ERROR_THROW_ON(win_config.first); + IClKernel::configure_internal(win_config.second); + + // Set config_id for enabling LWS tuning + _config_id = im2col_config.kernel_name; + _config_id += "_"; + _config_id += lower_string(string_from_data_type(src->data_type())); + _config_id += "_"; + _config_id += support::cpp11::to_string(num_groups); + _config_id += "_"; + _config_id += support::cpp11::to_string(dst->dimension(0)); + _config_id += "_"; + _config_id += support::cpp11::to_string(dst->dimension(1)); + _config_id += "_"; + _config_id += lower_string(string_from_data_layout(_data_layout)); + + ARM_COMPUTE_ERROR_ON(src->data_layout() == DataLayout::NHWC && has_padding_changed(padding_info)); +} + +Status ClIm2ColKernel::validate(const ITensorInfo *src, const ITensorInfo *dst, const Size2D &kernel_dims, const PadStrideInfo &conv_info, bool has_bias, const Size2D &dilation, + unsigned int num_groups) +{ + ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(src, dst, kernel_dims, conv_info, has_bias, dilation, num_groups)); + Im2ColConfiguration im2col_config = configure_opencl_kernel(src, kernel_dims, conv_info, has_bias, dilation, num_groups); + ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window(src->clone().get(), dst->clone().get(), kernel_dims, conv_info, has_bias, dilation, im2col_config.num_elems_processed_per_iteration, + im2col_config.is_padding_required_nchw, num_groups) + .first); + return Status{}; +} + +void ClIm2ColKernel::run_op(ITensorPack &tensors, const Window &window, cl::CommandQueue &queue) +{ + ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this); + ARM_COMPUTE_ERROR_ON_MISMATCHING_WINDOWS(IClKernel::window(), window); + ARM_COMPUTE_ERROR_ON(tensors.empty()); + + // Get initial windows + // Collapse in order to have (SRC_DEPTH * BATCH_SIZE) on the 3rd dimension + Window window_collapsed = window.collapse_if_possible(ICLKernel::window(), Window::DimZ); + window_collapsed.set_dimension_step(Window::DimZ, 1); + + auto src = utils::cast::polymorphic_downcast(tensors.get_const_tensor(TensorType::ACL_SRC)); + auto dst = utils::cast::polymorphic_downcast(tensors.get_tensor(TensorType::ACL_DST)); + ARM_COMPUTE_ERROR_ON_NULLPTR(src, dst); + + Window window_output; + window_output.use_tensor_dimensions(dst->info()->tensor_shape()); + + const Window first_slice_3d = window_collapsed.first_slice_window_3D(); + + Window slice = first_slice_3d; + Window slice_in = first_slice_3d; + Window slice_out = window_output.first_slice_window_2D(); + + if(_data_layout == DataLayout::NHWC) + { + const Window tmp_win = window.collapse_if_possible(ICLKernel::window(), 3); + const int num_batches = tmp_win[3].end(); + + slice.set(1, Window::Dimension(0, static_cast(dst->info()->tensor_shape()[1]), 1)); + slice.set(2, Window::Dimension(0, static_cast(num_batches), 1)); + } + else + { + slice.set(0, Window::Dimension(0, static_cast(ceil_to_multiple(_convolved_dims.first, _num_elems_processed_per_iteration)), _num_elems_processed_per_iteration)); + slice.set(1, Window::Dimension(0, static_cast(_convolved_dims.second), 1)); + // Note: In case of NCHW the 3rd dimension is already set collapsing the input window + } + + // Setup input slice + // The dimensions of the input are increased within the OpenCL kernel + slice_in.set(Window::DimX, Window::Dimension(0, 0, 0)); + slice_in.set(Window::DimY, Window::Dimension(0, 0, 0)); + slice_in.set(Window::DimZ, Window::Dimension(0, 0, 0)); + + // Setup output slice + // The dimensions of the output are increased within the OpenCL kernel + slice_out.set(Window::DimX, Window::Dimension(0, 0, 0)); + slice_out.set(Window::DimY, Window::Dimension(0, 0, 0)); + + unsigned int idx = num_arguments_per_3D_tensor() + (_num_groups == 1 ? num_arguments_per_2D_tensor() : num_arguments_per_3D_tensor()); + _kernel.setArg(idx++, static_cast(src->info()->strides_in_bytes()[3])); + _kernel.setArg(idx++, static_cast(dst->info()->strides_in_bytes()[((_num_groups == 1) ? 2 : 3)])); + do + { + unsigned int idx = 0; + add_3D_tensor_argument(idx, src, slice_in); + if(_num_groups == 1) + { + add_2D_tensor_argument(idx, dst, slice_out); + } + else + { + add_3D_tensor_argument(idx, dst, slice_out); + } + enqueue(queue, *this, slice, lws_hint()); + } + while(window_collapsed.slide_window_slice_3D(slice) && window_output.slide_window_slice_2D(slice_out) && window_collapsed.slide_window_slice_3D(slice_in)); +} +} // namespace kernels +} // namespace opencl +} // namespace arm_compute diff --git a/src/core/gpu/cl/kernels/ClIm2ColKernel.h b/src/core/gpu/cl/kernels/ClIm2ColKernel.h new file mode 100644 index 0000000000..d1443f0434 --- /dev/null +++ b/src/core/gpu/cl/kernels/ClIm2ColKernel.h @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2017-2021 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_CL_IM2COL_KERNEL_H +#define ARM_COMPUTE_CL_IM2COL_KERNEL_H + +#include "arm_compute/core/KernelDescriptors.h" +#include "arm_compute/core/Size2D.h" +#include "src/core/common/Macros.h" +#include "src/core/gpu/cl/ClCompileContext.h" +#include "src/core/gpu/cl/IClKernel.h" + +namespace arm_compute +{ +namespace opencl +{ +namespace kernels +{ +/** Interface for the im2col reshape kernel. + * + * Rearranges image blocks into columns. It is used to strip out each convolution block to a single column. + * It is used to transform a convolution to a plain matrix multiplication. + * + * For example taking into account the image below and assuming 3x3 image blocks with stride of 1 we have: + * @f[ + * \left( \begin{array}{cccc} + * a00 & a01 & a02 & a03 \\ + * a10 & a11 & a12 & a13 \\ + * a20 & a21 & a22 & a23 \\ + * a30 & a31 & a32 & a33 \\ + * \end{array} \right) + * = + * \left( \begin{array}{ccccccccc} + * a00 & a01 & a02 & a10 & a11 & a12 & a20 & a21 & a22 \\ + * a01 & a02 & a03 & a11 & a12 & a13 & a21 & a22 & a23 \\ + * a10 & a11 & a12 & a20 & a21 & a22 & a30 & a31 & a32 \\ + * a11 & a12 & a13 & a21 & a22 & a23 & a31 & a32 & a33 \\ + * \end{array} \right) + * @f] + */ +class ClIm2ColKernel : public IClKernel +{ +public: + /** Default constructor */ + ClIm2ColKernel(); + ARM_COMPUTE_DISALLOW_COPY_ALLOW_MOVE(ClIm2ColKernel); + /** Set the input and output of the kernel. + * + * @param[in] compile_context The compile context to be used. + * @param[in] src The input tensor info to convert. 3 lower dimensions represent a single input [width, height, IFM], + * while every optional dimension from 4 and above represent a batch of inputs. Data types supported: QASYMM8/QASYMM8_SIGNED/F16/F32 + * @param[out] dst The output tensor info. First 2 lower dimensions represent a transform of each 3D input, + * while every dimension above represents a batch. Data types supported: Same as @p input + * @param[in] kernel_dims The kernel dimensions (width and height). + * @param[in] conv_info Contains padding and stride information described in @ref PadStrideInfo. + * @param[in] has_bias In case biases are provided expands the matrix with 1. + * @param[in] dilation (Optional) Dilation, in elements, across x and y. Defaults to (1, 1). + * @param[in] num_groups (Optional) Number of groups when performing a grouped convolution. num_groups != 1 is only supported for NCHW data layout + */ + void configure(const ClCompileContext &compile_context, ITensorInfo *src, ITensorInfo *dst, const Size2D &kernel_dims, const PadStrideInfo &conv_info, bool has_bias, + const Size2D &dilation = Size2D(1U, 1U), + unsigned int num_groups = 1); + /** Static function to check if given info will lead to a valid configuration + * + * Similar to ClIm2ColKernel::configure() + * + * @return a status + */ + static Status validate(const ITensorInfo *input, const ITensorInfo *output, const Size2D &kernel_dims, const PadStrideInfo &conv_info, bool has_bias, const Size2D &dilation = Size2D(1U, 1U), + unsigned int num_groups = 1); + + // Inherited methods overridden: + void run_op(ITensorPack &tensors, const Window &window, cl::CommandQueue &queue) override; + +public: + DataLayout _data_layout; + std::pair _convolved_dims; + unsigned int _num_elems_processed_per_iteration; + Size2D _kernel_dims; + PadStrideInfo _conv_info; + unsigned int _num_groups; +}; +} // namespace kernels +} // namespace opencl +} // namespace arm_compute +#endif /* ARM_COMPUTE_CL_IM2COL_KERNEL_H */ diff --git a/src/runtime/CL/functions/CLGEMMConvolutionLayer.cpp b/src/runtime/CL/functions/CLGEMMConvolutionLayer.cpp index f0f45a8659..f926b1d0a6 100644 --- a/src/runtime/CL/functions/CLGEMMConvolutionLayer.cpp +++ b/src/runtime/CL/functions/CLGEMMConvolutionLayer.cpp @@ -30,9 +30,9 @@ #include "arm_compute/core/utils/misc/ShapeCalculator.h" #include "arm_compute/core/utils/quantization/AsymmHelpers.h" #include "arm_compute/runtime/CL/CLScheduler.h" -#include "src/core/CL/kernels/CLIm2ColKernel.h" #include "src/core/CL/kernels/CLWeightsReshapeKernel.h" #include "src/core/gpu/cl/kernels/ClCol2ImKernel.h" +#include "src/core/gpu/cl/kernels/ClIm2ColKernel.h" #include "src/core/helpers/AutoConfiguration.h" #include "support/Cast.h" @@ -105,8 +105,8 @@ void CLConvolutionLayerReshapeWeights::run() } CLGEMMConvolutionLayer::CLGEMMConvolutionLayer(std::shared_ptr memory_manager, IWeightsManager *weights_manager) - : _memory_group(memory_manager), _weights_manager(weights_manager), _reshape_weights(), _reshape_weights_managed(), _im2col_kernel(std::make_unique()), _mm_gemm(memory_manager, - weights_manager), _mm_gemmlowp(memory_manager), _col2im_kernel(nullptr), _activationlayer_function(), _original_weights(nullptr), _gemm_output_to_use(nullptr), _output(nullptr), _im2col_output(), + : _memory_group(memory_manager), _weights_manager(weights_manager), _reshape_weights(), _reshape_weights_managed(), _im2col_kernel(nullptr), _mm_gemm(memory_manager, weights_manager), + _mm_gemmlowp(memory_manager), _col2im_kernel(nullptr), _activationlayer_function(), _original_weights(nullptr), _input(nullptr), _gemm_output_to_use(nullptr), _output(nullptr), _im2col_output(), _weights_reshaped(), _gemm_output(), _skip_im2col(false), _skip_col2im(false), _is_quantized(false), _fuse_activation(true), _is_prepared(false) { } @@ -229,6 +229,7 @@ void CLGEMMConvolutionLayer::configure(const CLCompileContext &compile_context, _is_prepared = weights_info.retain_internal_weights(); _original_weights = weights; + _input = input; _is_quantized = is_data_type_quantized_asymmetric(input->info()->data_type()); _skip_im2col = (data_layout == DataLayout::NHWC && kernel_width == 1 && kernel_height == 1 && conv_info.stride().first == 1 && conv_info.stride().second == 1); _skip_col2im = data_layout == DataLayout::NHWC; @@ -236,9 +237,6 @@ void CLGEMMConvolutionLayer::configure(const CLCompileContext &compile_context, // Only for quantize there are few cases where we cannot fuse the activation function in GEMM _fuse_activation = true; - // Set the GPU target for im2col and col2im - _im2col_kernel->set_target(CLScheduler::get().target()); - const ICLTensor *gemm_input_to_use = input; ICLTensor *gemm_output_to_use = output; @@ -299,7 +297,11 @@ void CLGEMMConvolutionLayer::configure(const CLCompileContext &compile_context, _memory_group.manage(&_im2col_output); // Configure and tune im2col. im2col output shape is auto-initialized - _im2col_kernel->configure(compile_context, input, &_im2col_output, Size2D(kernel_width, kernel_height), conv_info, append_bias, dilation, num_groups); + _im2col_kernel = std::make_unique(); + + // Set the GPU target for im2col + _im2col_kernel->set_target(CLScheduler::get().target()); + _im2col_kernel->configure(compile_context, input->info(), _im2col_output.info(), Size2D(kernel_width, kernel_height), conv_info, append_bias, dilation, num_groups); // Set quantization info _im2col_output.info()->set_quantization_info(input->info()->quantization_info()); @@ -525,7 +527,7 @@ Status CLGEMMConvolutionLayer::validate(const ITensorInfo *input, const ITensorI auto_init_if_empty(im2col_reshaped_info, input->clone()->set_tensor_shape(expected_output_shape)); - ARM_COMPUTE_RETURN_ON_ERROR(CLIm2ColKernel::validate(input, &im2col_reshaped_info, kernel_dims, conv_info, append_bias, dilation, num_groups)); + ARM_COMPUTE_RETURN_ON_ERROR(opencl::kernels::ClIm2ColKernel::validate(input, &im2col_reshaped_info, kernel_dims, conv_info, append_bias, dilation, num_groups)); gemm_input_to_use = &im2col_reshaped_info; } @@ -620,7 +622,12 @@ void CLGEMMConvolutionLayer::run() // Run im2col if(!_skip_im2col) { - CLScheduler::get().enqueue(*_im2col_kernel); + ITensorPack pack = + { + { TensorType::ACL_SRC, _input }, + { TensorType::ACL_DST, &_im2col_output } + }; + CLScheduler::get().enqueue_op(*_im2col_kernel, pack, false); } // Runs CLGEMM or CLGEMMLowpMatrixMultiplyCore functions diff --git a/src/runtime/CL/functions/CLGEMMDeconvolutionLayer.cpp b/src/runtime/CL/functions/CLGEMMDeconvolutionLayer.cpp index bab29a5095..7b98b524c1 100644 --- a/src/runtime/CL/functions/CLGEMMDeconvolutionLayer.cpp +++ b/src/runtime/CL/functions/CLGEMMDeconvolutionLayer.cpp @@ -30,7 +30,6 @@ #include "arm_compute/runtime/CL/CLScheduler.h" #include "src/core/CL/kernels/CLDeconvolutionReshapeOutputKernel.h" #include "src/core/CL/kernels/CLFillBorderKernel.h" -#include "src/core/CL/kernels/CLIm2ColKernel.h" #include "src/core/CL/kernels/CLWeightsReshapeKernel.h" #include diff --git a/tests/validation/CL/Im2Col.cpp b/tests/validation/CL/Im2Col.cpp index c6006efcba..041f549777 100644 --- a/tests/validation/CL/Im2Col.cpp +++ b/tests/validation/CL/Im2Col.cpp @@ -22,7 +22,7 @@ * SOFTWARE. */ #include "arm_compute/core/Types.h" -#include "src/core/CL/kernels/CLIm2ColKernel.h" +#include "src/core/gpu/cl/kernels/ClIm2ColKernel.h" #include "tests/CL/CLAccessor.h" #include "tests/CL/Helper.h" #include "tests/framework/Asserts.h" @@ -40,7 +40,7 @@ namespace validation TEST_SUITE(CL) TEST_SUITE(Im2Col) -using CLIm2Col = CLSynthetizeFunction; +using ClIm2Col = ClSynthetizeOperatorWithBorder; /** Negative tests * @@ -63,7 +63,7 @@ TEST_CASE(Negative, framework::DatasetMode::ALL) const auto output = TensorInfo(TensorShape(9U, 10U, 12U, 2U), 1, DataType::F32); const auto conv_size = Size2D(3, 3); const bool has_bias = false; - const auto status = CLIm2ColKernel::validate(&input, &output, conv_size, PadStrideInfo(), has_bias); + const auto status = opencl::kernels::ClIm2ColKernel::validate(&input, &output, conv_size, PadStrideInfo(), has_bias); ARM_COMPUTE_EXPECT(bool(status) == false, framework::LogLevel::ERRORS); } @@ -73,7 +73,7 @@ TEST_CASE(Negative, framework::DatasetMode::ALL) const auto output = TensorInfo(TensorShape(9U, 80U, 2U), 1, DataType::QASYMM8); const auto conv_size = Size2D(3, 3); const bool has_bias = true; - const auto status = CLIm2ColKernel::validate(&input, &output, conv_size, PadStrideInfo(), has_bias); + const auto status = opencl::kernels::ClIm2ColKernel::validate(&input, &output, conv_size, PadStrideInfo(), has_bias); ARM_COMPUTE_EXPECT(bool(status) == false, framework::LogLevel::ERRORS); } @@ -84,7 +84,7 @@ TEST_CASE(Negative, framework::DatasetMode::ALL) const auto conv_size = Size2D(3, 3); const auto dilation = Size2D(0, 1); const bool has_bias = false; - const auto status = CLIm2ColKernel::validate(&input, &output, conv_size, PadStrideInfo(), has_bias, dilation); + const auto status = opencl::kernels::ClIm2ColKernel::validate(&input, &output, conv_size, PadStrideInfo(), has_bias, dilation); ARM_COMPUTE_EXPECT(bool(status) == false, framework::LogLevel::ERRORS); } @@ -96,7 +96,7 @@ TEST_CASE(Negative, framework::DatasetMode::ALL) const auto dilation = Size2D(1, 1); const bool has_bias = false; const unsigned int num_groups = 2; - const auto status = CLIm2ColKernel::validate(&input, &output, conv_size, PadStrideInfo(), has_bias, dilation, num_groups); + const auto status = opencl::kernels::ClIm2ColKernel::validate(&input, &output, conv_size, PadStrideInfo(), has_bias, dilation, num_groups); ARM_COMPUTE_EXPECT(bool(status) == false, framework::LogLevel::ERRORS); } @@ -108,7 +108,7 @@ TEST_CASE(Negative, framework::DatasetMode::ALL) const auto dilation = Size2D(1, 1); const bool has_bias = false; const unsigned int num_groups = 2; - const auto status = CLIm2ColKernel::validate(&input, &output, conv_size, PadStrideInfo(), has_bias, dilation, num_groups); + const auto status = opencl::kernels::ClIm2ColKernel::validate(&input, &output, conv_size, PadStrideInfo(), has_bias, dilation, num_groups); ARM_COMPUTE_EXPECT(bool(status) == false, framework::LogLevel::ERRORS); } @@ -118,7 +118,7 @@ TEST_CASE(Negative, framework::DatasetMode::ALL) const auto output = TensorInfo(TensorShape(9U, 81U, 2U), 1, DataType::F32); const auto conv_size = Size2D(3, 3); const bool has_bias = false; - const auto status = CLIm2ColKernel::validate(&input, &output, conv_size, PadStrideInfo(), has_bias); + const auto status = opencl::kernels::ClIm2ColKernel::validate(&input, &output, conv_size, PadStrideInfo(), has_bias); ARM_COMPUTE_EXPECT(bool(status) == false, framework::LogLevel::ERRORS); } @@ -128,13 +128,13 @@ TEST_CASE(Negative, framework::DatasetMode::ALL) const auto output = TensorInfo(TensorShape(1U, 1U, 1U, 2U), 1, DataType::F32, DataLayout::NHWC); const auto conv_size = Size2D(9, 9); const bool has_bias = false; - const auto status = CLIm2ColKernel::validate(&input, &output, conv_size, PadStrideInfo(), has_bias); + const auto status = opencl::kernels::ClIm2ColKernel::validate(&input, &output, conv_size, PadStrideInfo(), has_bias); ARM_COMPUTE_EXPECT(bool(status) == false, framework::LogLevel::ERRORS); } } template -using CLIm2ColFixture = Im2ColValidationFixture; +using ClIm2ColFixture = Im2ColOpValidationFixture; TEST_SUITE(NHWC) @@ -150,7 +150,7 @@ TEST_SUITE(NHWC) * Kernel tested im2col3x3_nhwc */ FIXTURE_DATA_TEST_CASE(W3x3, - CLIm2ColFixture, + ClIm2ColFixture, framework::DatasetMode::ALL, combine(combine(combine(combine(combine(combine( framework::dataset::make("InputShape", @@ -180,7 +180,7 @@ framework::dataset::make("Groups", 1))) * Kernel tested im2col9x9_nhwc */ FIXTURE_DATA_TEST_CASE(W9x9, - CLIm2ColFixture, + ClIm2ColFixture, framework::DatasetMode::ALL, combine(combine(combine(combine(combine(combine( framework::dataset::make("InputShape", @@ -210,7 +210,7 @@ framework::dataset::make("Groups", 1))) * Kernel tested im2col_generic_nhwc */ FIXTURE_DATA_TEST_CASE(Generic, - CLIm2ColFixture, + ClIm2ColFixture, framework::DatasetMode::ALL, combine(combine(combine(combine(combine(combine( framework::dataset::make("InputShape", @@ -243,7 +243,7 @@ TEST_SUITE(NCHW) * Kernel tested im2col1x1_stridex1_nchw */ FIXTURE_DATA_TEST_CASE(W1x1_Stride1_NoPad, - CLIm2ColFixture, + ClIm2ColFixture, framework::DatasetMode::ALL, combine(combine(combine(combine(combine(combine( framework::dataset::make("InputShape", { TensorShape(4U, 4U, 3U, 2U), TensorShape(5U, 4U, 3U, 2U), TensorShape(3U, 4U, 3U, 2U) }), @@ -267,7 +267,7 @@ FIXTURE_DATA_TEST_CASE(W1x1_Stride1_NoPad, * Kernel tested im2col3x3_nchw */ FIXTURE_DATA_TEST_CASE(W3x3, - CLIm2ColFixture, + ClIm2ColFixture, framework::DatasetMode::ALL, combine(combine(combine(combine(combine(combine( framework::dataset::make("InputShape", TensorShape(4U, 4U, 3U, 2U)), @@ -291,7 +291,7 @@ FIXTURE_DATA_TEST_CASE(W3x3, * Kernel tested im2col5x5_nchw */ FIXTURE_DATA_TEST_CASE(W5x5, - CLIm2ColFixture, + ClIm2ColFixture, framework::DatasetMode::ALL, combine(combine(combine(combine(combine(combine( framework::dataset::make("InputShape", TensorShape(7U, 4U, 3U, 2U)), @@ -317,7 +317,7 @@ FIXTURE_DATA_TEST_CASE(W5x5, * Kernel tested im2col11x11_padx0_pady0_nchw */ FIXTURE_DATA_TEST_CASE(W11x11_NoPad, - CLIm2ColFixture, + ClIm2ColFixture, framework::DatasetMode::ALL, combine(combine(combine(combine(combine(combine( framework::dataset::make("InputShape", { TensorShape(11U, 11U, 2U, 2U), TensorShape(14U, 13U, 1U, 2U) }), @@ -341,7 +341,7 @@ FIXTURE_DATA_TEST_CASE(W11x11_NoPad, * Kernel tested im2col_generic_padx0_pady0_nchw */ FIXTURE_DATA_TEST_CASE(GenericZeroPad, - CLIm2ColFixture, + ClIm2ColFixture, framework::DatasetMode::ALL, combine(combine(combine(combine(combine(combine( framework::dataset::make("InputShape", TensorShape(13U, 11U, 2U, 2U)), @@ -367,7 +367,7 @@ TEST_SUITE_END() // NCHW * Kernel tested im2col_generic_(nchw|nhwc) */ FIXTURE_DATA_TEST_CASE(Generic, - CLIm2ColFixture, + ClIm2ColFixture, framework::DatasetMode::ALL, combine(combine(combine(combine(combine(combine( framework::dataset::make("InputShape", TensorShape(13U, 11U, 5U, 2U)), @@ -393,7 +393,7 @@ FIXTURE_DATA_TEST_CASE(Generic, * - im2col9x9_nhwc */ FIXTURE_DATA_TEST_CASE(Quantized, - CLIm2ColFixture, + ClIm2ColFixture, framework::DatasetMode::ALL, combine(combine(combine(combine(combine(combine( framework::dataset::make("InputShape", TensorShape(13U, 11U, 11U, 2U)), @@ -419,7 +419,7 @@ FIXTURE_DATA_TEST_CASE(Quantized, * - im2col9x9_nhwc */ FIXTURE_DATA_TEST_CASE(FP16, - CLIm2ColFixture, + ClIm2ColFixture, framework::DatasetMode::ALL, combine(combine(combine(combine(combine(combine( framework::dataset::make("InputShape", TensorShape(13U, 11U, 11U, 2U)), diff --git a/tests/validation/CL/UNIT/DynamicTensor.cpp b/tests/validation/CL/UNIT/DynamicTensor.cpp index ad2d4892ba..f83a92ec2f 100644 --- a/tests/validation/CL/UNIT/DynamicTensor.cpp +++ b/tests/validation/CL/UNIT/DynamicTensor.cpp @@ -29,7 +29,6 @@ #include "arm_compute/runtime/MemoryManagerOnDemand.h" #include "arm_compute/runtime/PoolManager.h" #include "src/core/CL/kernels/CLFillBorderKernel.h" -#include "src/core/CL/kernels/CLIm2ColKernel.h" #include "src/core/CL/kernels/CLL2NormalizeLayerKernel.h" #include "src/core/CL/kernels/CLReductionOperationKernel.h" #include "src/core/CL/kernels/CLWeightsReshapeKernel.h" diff --git a/tests/validation/fixtures/Im2ColFixture.h b/tests/validation/fixtures/Im2ColFixture.h index 38970116f6..a0732c3eb3 100644 --- a/tests/validation/fixtures/Im2ColFixture.h +++ b/tests/validation/fixtures/Im2ColFixture.h @@ -134,92 +134,6 @@ protected: bool _has_bias{}; unsigned int _num_groups{}; }; - -template -class Im2ColValidationFixture : public framework::Fixture -{ -public: - template - void setup(TensorShape input_shape, DataType data_type, const Size2D &kernel_dims, const PadStrideInfo &conv_info, const QuantizationInfo &quant_info, const DataLayout &data_layout, - unsigned int num_groups) - { - _kernel_dims = kernel_dims; - _conv_info = conv_info; - _quant_info = quant_info; - _data_layout = data_layout; - _has_bias = data_type != DataType::QASYMM8; - _num_groups = num_groups; - - if(_data_layout == DataLayout::NHWC) - { - permute(input_shape, PermutationVector(2U, 0U, 1U)); - } - - TensorInfo input_info(input_shape, 1, data_type); - input_info.set_data_layout(_data_layout); - - const TensorShape output_shape = compute_im2col_conv_shape(&input_info, _kernel_dims, _conv_info, _has_bias, Size2D(1U, 1U), batch_size_on_z && _num_groups == 1, _num_groups); - _target = compute_target(input_shape, output_shape, data_type); - - compute_reference(input_shape, output_shape, data_type); - } - -protected: - template - void fill(U &&tensor) - { - library->fill_tensor_uniform(tensor, 0); - } - - TensorType compute_target(const TensorShape &input_shape, const TensorShape &output_shape, DataType data_type) - { - // Create tensors - TensorType src = create_tensor(input_shape, data_type, 1, _quant_info, _data_layout); - TensorType dst = create_tensor(output_shape, data_type, 1, _quant_info); - - // Create and configure function - FunctionType im2col_func; - im2col_func.configure(&src, &dst, _kernel_dims, _conv_info, _has_bias, Size2D(1U, 1U), _num_groups); - - ARM_COMPUTE_ASSERT(src.info()->is_resizable()); - ARM_COMPUTE_ASSERT(dst.info()->is_resizable()); - - // Allocate tensors - src.allocator()->allocate(); - dst.allocator()->allocate(); - - ARM_COMPUTE_ASSERT(!src.info()->is_resizable()); - ARM_COMPUTE_ASSERT(!dst.info()->is_resizable()); - - // Fill tensors - fill(AccessorType(src)); - - // Compute function - im2col_func.run(); - - return dst; - } - - void compute_reference(const TensorShape &input_shape, const TensorShape &output_shape, DataType data_type) - { - // Create reference - SimpleTensor src{ input_shape, data_type, 1, _quant_info, _data_layout }; - _reference = SimpleTensor(output_shape, data_type, 1, _quant_info, DataLayout::NCHW); - - // Fill reference - fill(src); - - reference::im2col(src, _reference, _kernel_dims, _conv_info, _has_bias, _num_groups); - } - TensorType _target{}; - SimpleTensor _reference{}; - Size2D _kernel_dims{}; - PadStrideInfo _conv_info{}; - DataLayout _data_layout{}; - QuantizationInfo _quant_info{}; - bool _has_bias{}; - unsigned int _num_groups{}; -}; } // namespace validation } // namespace test } // namespace arm_compute -- cgit v1.2.1