2 * Copyright (c) 2017-2018 ARM Limited.
4 * SPDX-License-Identifier: MIT
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to
8 * deal in the Software without restriction, including without limitation the
9 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 * sell copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 #include "arm_compute/core/CL/kernels/CLIm2ColKernel.h"
26 #include "arm_compute/core/CL/CLHelpers.h"
27 #include "arm_compute/core/CL/CLKernelLibrary.h"
28 #include "arm_compute/core/CL/ICLTensor.h"
29 #include "arm_compute/core/CL/OpenCL.h"
30 #include "arm_compute/core/Error.h"
31 #include "arm_compute/core/Helpers.h"
32 #include "arm_compute/core/Size2D.h"
33 #include "arm_compute/core/Types.h"
34 #include "arm_compute/core/Validate.h"
35 #include "support/ToolchainSupport.h"
40 using namespace arm_compute;
44 Status validate_arguments(const ITensorInfo *input, const ITensorInfo *output, bool has_bias, const Size2D &dilation)
46 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input, 1, DataType::QS8, DataType::QASYMM8, DataType::QS16, DataType::F16, DataType::F32);
47 ARM_COMPUTE_RETURN_ERROR_ON(input->data_type() == DataType::QASYMM8 && has_bias);
48 ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(output);
49 ARM_COMPUTE_RETURN_ERROR_ON((dilation.x() < 1) || (dilation.y() < 1));
51 // Checks performed when output is configured
52 if(output->total_size() != 0)
54 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, output);
55 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_FIXED_POINT(input, output);
62 CLIm2ColKernel::CLIm2ColKernel()
63 : _input(nullptr), _output(nullptr), _convolved_dims(), _num_elems_processed_per_iteration(1), _run_func(nullptr), _kernel_dims()
67 void CLIm2ColKernel::configure(const ICLTensor *input, ICLTensor *output, const Size2D &kernel_dims, const PadStrideInfo &conv_info, bool has_bias, const Size2D &dilation)
69 ARM_COMPUTE_ERROR_ON_NULLPTR(input, output);
71 // Perform validation step
72 ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input->info(), output->info(), has_bias, dilation));
76 _kernel_dims = kernel_dims;
78 const DataType data_type = input->info()->data_type();
79 const GPUTarget gpu_target = get_target();
82 CLBuildOptions build_opts;
83 build_opts.add_option(("-DDATA_TYPE=" + get_cl_type_from_data_type(data_type)));
84 build_opts.add_option("-DELEMENT_SIZE=" + support::cpp11::to_string(input->info()->element_size()));
85 build_opts.add_option_if(has_bias, "-DHAS_BIAS");
86 build_opts.add_option_if(is_data_type_fixed_point(data_type), "-DFIXED_POINT_POSITION=" + support::cpp11::to_string(input->info()->fixed_point_position()));
91 std::tie(stride_x, stride_y) = conv_info.stride();
93 const bool run_img2col_reduced = (output->info()->dimension(0) == (input->info()->dimension(0) * input->info()->dimension(1) * input->info()->dimension(2))) && (TensorShape::num_max_dimensions >= 4)
94 && (std::equal(input->info()->tensor_shape().cbegin() + 3,
95 input->info()->tensor_shape().cend(),
96 output->info()->tensor_shape().cbegin() + 1))
97 && ((stride_x == 1) && (stride_y == 1) && !conv_info.has_padding());
99 bool is_optimized_path = false;
101 _num_elems_processed_per_iteration = 1;
103 std::string kernel_name;
104 if(!run_img2col_reduced)
106 // Default kernel name
107 kernel_name = "im2col_generic_dchw";
109 _convolved_dims = scaled_dimensions(input->info()->dimension(0), input->info()->dimension(1),
110 kernel_dims.width, kernel_dims.height,
111 conv_info, dilation);
113 build_opts.add_option("-DKERNEL_WIDTH=" + support::cpp11::to_string(kernel_dims.width));
114 build_opts.add_option("-DKERNEL_HEIGHT=" + support::cpp11::to_string(kernel_dims.height));
115 build_opts.add_option("-DKERNEL_DEPTH=" + support::cpp11::to_string(input->info()->dimension(2)));
116 build_opts.add_option("-DCONVOLVED_WIDTH=" + support::cpp11::to_string(_convolved_dims.first));
117 build_opts.add_option("-DCONVOLVED_HEIGHT=" + support::cpp11::to_string(_convolved_dims.second));
118 build_opts.add_option("-DSTRIDE_X=" + support::cpp11::to_string(conv_info.stride().first));
119 build_opts.add_option("-DSTRIDE_Y=" + support::cpp11::to_string(conv_info.stride().second));
120 build_opts.add_option("-DPAD_LEFT=" + support::cpp11::to_string(conv_info.pad_left()));
121 build_opts.add_option("-DPAD_TOP=" + support::cpp11::to_string(conv_info.pad_top()));
122 build_opts.add_option("-DPAD_RIGHT=" + support::cpp11::to_string(conv_info.pad_right()));
123 build_opts.add_option("-DPAD_BOTTOM=" + support::cpp11::to_string(conv_info.pad_bottom()));
124 build_opts.add_option("-DSRC_WIDTH=" + support::cpp11::to_string(input->info()->dimension(0)));
125 build_opts.add_option("-DSRC_HEIGHT=" + support::cpp11::to_string(input->info()->dimension(1)));
126 build_opts.add_option("-DDILATION_X=" + support::cpp11::to_string(dilation.x()));
127 build_opts.add_option("-DDILATION_Y=" + support::cpp11::to_string(dilation.y()));
128 build_opts.add_option_if_else(is_data_type_quantized(data_type), "-DPAD_VALUE=" + support::cpp11::to_string(input->info()->quantization_info().offset), "-DPAD_VALUE=0");
130 const bool squared_im2col = kernel_dims.width == kernel_dims.height;
132 if(dilation == Size2D(1U, 1U))
134 if(squared_im2col && !is_data_type_fixed_point(data_type))
136 // Check if we can run an optimized im2col
137 switch(kernel_dims.width)
140 // Optimized im2col1x1 if stride_x = 1 and conv_info.has_padding() = false
141 if(conv_info.stride().first == 1 && !conv_info.has_padding())
144 _lws_hint = cl::NDRange(1, 1, 8);
145 _num_elems_processed_per_iteration = 4;
146 is_optimized_path = true;
147 kernel_name = "im2col1x1_stridex1_dchw";
151 _lws_hint = cl::NDRange(1, 1, 8);
152 _num_elems_processed_per_iteration = 1;
153 is_optimized_path = true;
154 kernel_name = "im2col3x3_dchw";
157 _num_elems_processed_per_iteration = 1;
158 is_optimized_path = true;
159 kernel_name = "im2col5x5_dchw";
162 // Optimized im2col11x11 if pad_x = pad_y = 0
163 if(!conv_info.has_padding())
165 _num_elems_processed_per_iteration = 1;
166 is_optimized_path = true;
167 kernel_name = "im2col11x11_padx0_pady0_dchw";
171 is_optimized_path = false;
175 else if(kernel_dims.width > 1 && !conv_info.has_padding())
177 _num_elems_processed_per_iteration = 1;
178 kernel_name = "im2col_generic_padx0_pady0_dchw";
180 // Optimized im2col is performed using one or more vector operations with the specified vector size
181 // and a remainder. For example, for 5x5 convolutions, im2col is performed using vectors of size 4
182 // and scalars; for 7x7 convolutions, using vectors of size 4 and vectors of size 3.
183 // Using the vector size of 4 is always safe since OpenCL supports vectors of size 2 and 3.
184 // Using the vector size of 8, however, may be faster.
185 size_t vector_size = 4;
186 // For 2x2 convolutions, use vectors of size 2. (For 3x3 convolutions, im2col_kernel3x3_padx0_pady0
188 if(kernel_dims.width < vector_size)
190 vector_size = kernel_dims.width;
192 // Local work size and vector size optimized for the 11x11 AlexNet convolution on Bifrost.
193 if(gpu_target_is_in(gpu_target, GPUTarget::G71, GPUTarget::G72, GPUTarget::G51, GPUTarget::G51BIG, GPUTarget::G51LIT, GPUTarget::TNOX) && kernel_dims.width == 11)
195 _lws_hint = cl::NDRange(1, 1, 1);
198 const size_t width_mod_vector_size = kernel_dims.width % vector_size;
199 build_opts.add_option("-DVECTOR_SIZE=" + support::cpp11::to_string(vector_size));
200 build_opts.add_option("-DWIDTH_MOD_VECTOR_SIZE=" + support::cpp11::to_string(width_mod_vector_size));
203 _run_func = &CLIm2ColKernel::run_generic;
207 _num_elems_processed_per_iteration = 1;
208 kernel_name = "im2col_reduced_dchw";
209 _run_func = &CLIm2ColKernel::run_reduced;
213 _kernel = static_cast<cl::Kernel>(CLKernelLibrary::get().create_kernel(kernel_name, build_opts.options()));
215 // Configure kernel window
217 if(is_optimized_path)
219 win = calculate_max_window(*input->info(),
220 Steps(_num_elems_processed_per_iteration),
222 BorderSize(conv_info.pad_top(), conv_info.pad_right(), conv_info.pad_bottom(), conv_info.pad_left()));
224 const int x = -conv_info.pad_left();
225 const int y = -conv_info.pad_top();
226 const int w = kernel_dims.width * _num_elems_processed_per_iteration;
227 const int h = kernel_dims.height;
229 AccessWindowRectangle input_access(input->info(), x, y, w, h);
231 update_window_and_padding(win, input_access);
235 // For the generic case, CLIm2ColKernel doesn't need padding (we do not read out-of-bounds elements) so
236 // update_window_and_padding() can be skipped
237 win = calculate_max_window(*input->info(), Steps());
240 output->info()->set_valid_region(ValidRegion(Coordinates(), output->info()->tensor_shape()));
241 if(!run_img2col_reduced)
243 // set the Z dimension's step same size as the whole dimension so that one can't split across the Z dimension
244 win.set_dimension_step(Window::DimZ, win[Window::DimZ].end() - win[Window::DimZ].start());
247 ICLKernel::configure(win);
249 // Set config_id for enabling LWS tuning
250 _config_id = kernel_name;
252 _config_id += lower_string(string_from_data_type(input->info()->data_type()));
254 _config_id += support::cpp11::to_string(output->info()->dimension(0));
256 _config_id += support::cpp11::to_string(output->info()->dimension(1));
259 Status CLIm2ColKernel::validate(const ITensorInfo *input, const ITensorInfo *output, const Size2D &kernel_dims, const PadStrideInfo &conv_info, bool has_bias, const Size2D &dilation)
261 ARM_COMPUTE_UNUSED(kernel_dims);
262 ARM_COMPUTE_UNUSED(conv_info);
263 ARM_COMPUTE_UNUSED(has_bias);
264 ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, has_bias, dilation));
268 void CLIm2ColKernel::run(const Window &window, cl::CommandQueue &queue)
270 ARM_COMPUTE_ERROR_ON(_run_func == nullptr);
271 (this->*_run_func)(window, queue);
274 void CLIm2ColKernel::run_generic(const Window &window, cl::CommandQueue &queue)
276 ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
277 ARM_COMPUTE_ERROR_ON_MISMATCHING_WINDOWS(ICLKernel::window(), window);
279 // Get initial windows
280 Window window_collapsed = window.collapse_if_possible(ICLKernel::window(), Window::DimZ);
281 // Change the Z dimension's step back to 1
282 window_collapsed.set_dimension_step(Window::DimZ, 1);
284 Window slice = window_collapsed.first_slice_window_3D();
285 Window slice_in = window_collapsed.first_slice_window_3D();
286 Window slice_out = window_collapsed.first_slice_window_3D();
288 // Setup slice if stride_x != 0 or stride_y != 0
289 if(_convolved_dims.first != _input->info()->dimension(0) || _convolved_dims.second != _input->info()->dimension(1))
291 // If the stride_x or stride_y are not 1, the output tensor of matrix multiply (Convolved tensor) will not
292 // have the same shape of the im2col input tensor
293 // In this case we need to re-compute the window using the shape of the tensor after matrix multiply (convolved_dims)
294 slice.set(Window::DimX, Window::Dimension(0, static_cast<int>(_convolved_dims.first), 1));
295 slice.set(Window::DimY, Window::Dimension(0, static_cast<int>(_convolved_dims.second), 1));
299 // The first three dimensions of the input are increased by the inner loops
300 slice_in.set(Window::DimX, Window::Dimension(0, 0, 0));
301 slice_in.set(Window::DimY, Window::Dimension(0, 0, 0));
302 slice_in.set(Window::DimZ, Window::Dimension(0, 0, 0));
304 // Setup output slice
305 slice_out.set(Window::DimX, Window::Dimension(0, _output->info()->dimension(0), _kernel_dims.area()));
306 slice_out.set(Window::DimY, Window::Dimension(0, _output->info()->dimension(1), 1));
307 slice_out.set(Window::DimZ, Window::Dimension(0, 1, 1));
311 unsigned int idx = 0;
312 add_3D_tensor_argument(idx, _input, slice_in);
313 add_2D_tensor_argument(idx, _output, slice_out);
314 _kernel.setArg<cl_uint>(idx++, static_cast<unsigned int>(_input->info()->strides_in_bytes()[3]));
315 _kernel.setArg<cl_uint>(idx++, static_cast<unsigned int>(_output->info()->strides_in_bytes()[3]));
316 enqueue(queue, *this, slice, _lws_hint);
318 while(window_collapsed.slide_window_slice_3D(slice) && window_collapsed.slide_window_slice_3D(slice_out) && window_collapsed.slide_window_slice_3D(slice_in));
321 void CLIm2ColKernel::run_reduced(const Window &window, cl::CommandQueue &queue)
323 ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
324 ARM_COMPUTE_ERROR_ON_MISMATCHING_WINDOWS(ICLKernel::window(), window);
327 out_window.use_tensor_dimensions(_output->info()->tensor_shape());
329 Window out_slice = out_window.first_slice_window_1D();
330 Window in_slice = window.first_slice_window_3D();
336 unsigned int idx = 0;
337 add_3D_tensor_argument(idx, _input, in_slice);
338 add_1D_tensor_argument(idx, _output, out_slice);
340 _kernel.setArg<cl_uint>(idx++, _input->info()->dimension(0));
341 _kernel.setArg<cl_uint>(idx++, _input->info()->dimension(1));
342 enqueue(queue, *this, in_slice, _lws_hint);
344 while(window.slide_window_slice_3D(in_slice) && out_window.slide_window_slice_1D(out_slice));