Compute Library
 21.11
CLChannelShuffleLayerKernel.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2018-2021 Arm Limited.
3  *
4  * SPDX-License-Identifier: MIT
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
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
22  * SOFTWARE.
23  */
25 
31 #include "src/core/CL/CLValidate.h"
34 #include "support/StringSupport.h"
35 
36 namespace arm_compute
37 {
38 namespace
39 {
40 Status validate_arguments(const ITensorInfo *input, const ITensorInfo *output, unsigned int num_groups)
41 {
43  ARM_COMPUTE_RETURN_ERROR_ON(input->data_type() == DataType::UNKNOWN);
44  ARM_COMPUTE_RETURN_ERROR_ON_MSG(num_groups < 2, "Channel shuffling with less than 2 groups would be inefficient");
45 
46  const unsigned int channels = input->dimension(get_data_layout_dimension_index(input->data_layout(), DataLayoutDimension::CHANNEL));
47 
48  ARM_COMPUTE_RETURN_ERROR_ON_MSG(num_groups == channels, "Channel shuffling with same number of groups as number of channels would be inefficient");
49  // There cannot be more groups than channels
50  ARM_COMPUTE_RETURN_ERROR_ON(num_groups > channels);
51  ARM_COMPUTE_RETURN_ERROR_ON_MSG((channels % num_groups) != 0, "The number of channels must be a multiple of the number of groups");
52 
53  // Checks performed when output is configured
54  if(output->total_size() != 0)
55  {
59  }
60 
61  return Status{};
62 }
63 
64 std::pair<Status, Window> validate_and_configure_window(ITensorInfo *input, ITensorInfo *output)
65 {
66  // Output tensor auto initialization if not yet initialized
67  auto_init_if_empty(*output, *input->clone());
68 
69  const bool is_nhwc = input->data_layout() == DataLayout::NHWC;
70  if(is_nhwc)
71  {
72  unsigned int num_elems_processed_per_iteration_x = adjust_vec_size(max_cl_vector_width / input->element_size(), input->dimension(0));
73  Window win = calculate_max_window(*input, Steps(num_elems_processed_per_iteration_x));
74  Window win_collapsed = win.collapse(win, Window::DimZ);
75  return std::make_pair(Status{}, win_collapsed);
76  }
77  else
78  {
79  const unsigned int num_elems_processed_per_iteration_x = max_cl_vector_width / input->element_size();
80  constexpr unsigned int num_elems_processed_per_iteration_y = 2;
81 
82  // Configure kernel window
83  Window win = calculate_max_window(*input, Steps(num_elems_processed_per_iteration_x, num_elems_processed_per_iteration_y));
84  AccessWindowRectangle input_access(input, 0, 0, num_elems_processed_per_iteration_x, num_elems_processed_per_iteration_y);
85  AccessWindowRectangle output_access(output, 0, 0, num_elems_processed_per_iteration_x, num_elems_processed_per_iteration_y);
86 
87  const bool window_changed = update_window_and_padding(win, input_access, output_access);
88 
89  Window win_collapsed = win.collapse(win, Window::DimZ);
90 
91  Status err = (window_changed) ? ARM_COMPUTE_CREATE_ERROR(ErrorCode::RUNTIME_ERROR, "Insufficient Padding!") : Status{};
92  return std::make_pair(err, win_collapsed);
93  }
94 }
95 } // namespace
96 
98  : _input(nullptr), _output(nullptr)
99 {
101 }
102 
103 void CLChannelShuffleLayerKernel::configure(const ICLTensor *input, ICLTensor *output, unsigned int num_groups)
104 {
105  configure(CLKernelLibrary::get().get_compile_context(), input, output, num_groups);
106 }
107 
108 void CLChannelShuffleLayerKernel::configure(const CLCompileContext &compile_context, const ICLTensor *input, ICLTensor *output, unsigned int num_groups)
109 {
110  ARM_COMPUTE_ERROR_ON_NULLPTR(input, output);
111  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input->info(), output->info(), num_groups));
112  auto padding_info = get_padding_info({ input, output });
113 
114  _input = input;
115  _output = output;
116 
117  const DataLayout data_layout = input->info()->data_layout();
118  const bool is_nhwc = data_layout == DataLayout::NHWC;
119  const unsigned int channels = input->info()->dimension(get_data_layout_dimension_index(data_layout, DataLayoutDimension::CHANNEL));
120  unsigned int vec_size_x = 0;
121  unsigned int vec_size_x_leftovers = 0;
122  if(is_nhwc)
123  {
124  vec_size_x = adjust_vec_size(max_cl_vector_width / input->info()->element_size(), input->info()->dimension(0));
125  vec_size_x_leftovers = input->info()->dimension(0) % vec_size_x;
126  }
127  else
128  {
129  vec_size_x = max_cl_vector_width / input->info()->element_size();
130  }
131 
132  // Set kernel build options
133  CLBuildOptions build_opts;
134  build_opts.add_option("-DNUM_GROUPS=" + support::cpp11::to_string(num_groups));
135  build_opts.add_option("-DK=" + support::cpp11::to_string(channels / num_groups));
136  build_opts.add_option("-DVEC_SIZE=" + support::cpp11::to_string(vec_size_x));
137  build_opts.add_option_if(is_nhwc, "-DVEC_SIZE_LEFTOVER=" + support::cpp11::to_string(vec_size_x_leftovers));
138  build_opts.add_option_if(is_nhwc, "-DSRC_DIM_X=" + support::cpp11::to_string(input->info()->dimension(0)));
139  build_opts.add_option("-DSRC_DIM_Z=" + support::cpp11::to_string(input->info()->dimension(2)));
140  build_opts.add_option("-DDATA_TYPE=" + get_cl_unsigned_type_from_element_size(input->info()->element_size()));
141 
142  // Create kernel
143  std::string kernel_name = "channel_shuffle_" + lower_string(string_from_data_layout(data_layout));
144 
145  _kernel = create_kernel(compile_context, kernel_name, build_opts.options());
146 
147  // Configure kernel window
148  auto win_config = validate_and_configure_window(input->info(), output->info());
149  ARM_COMPUTE_ERROR_THROW_ON(win_config.first);
150  ICLKernel::configure_internal(win_config.second);
151 
152  // Set config_id for enabling LWS tuning
153  _config_id = kernel_name;
154  _config_id += "_";
155  _config_id += lower_string(string_from_data_type(input->info()->data_type()));
156  _config_id += "_";
157  _config_id += support::cpp11::to_string(num_groups);
158  _config_id += "_";
159  _config_id += support::cpp11::to_string(input->info()->dimension(0));
160  _config_id += "_";
161  _config_id += support::cpp11::to_string(input->info()->dimension(1));
162  _config_id += "_";
163  _config_id += support::cpp11::to_string(input->info()->dimension(2));
164  _config_id += "_";
165  _config_id += support::cpp11::to_string(output->info()->dimension(0));
166  _config_id += "_";
167  _config_id += support::cpp11::to_string(output->info()->dimension(1));
168  _config_id += "_";
169  _config_id += support::cpp11::to_string(output->info()->dimension(2));
170  if(data_layout == DataLayout::NHWC)
171  {
173  }
174 }
175 
176 Status CLChannelShuffleLayerKernel::validate(const ITensorInfo *input, const ITensorInfo *output, unsigned int num_groups)
177 {
178  ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, num_groups));
179  ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window(input->clone().get(), output->clone().get()).first);
180 
181  return Status{};
182 }
183 
184 void CLChannelShuffleLayerKernel::run(const Window &window, cl::CommandQueue &queue)
185 {
188 
189  unsigned int idx = 0;
190  add_4D_tensor_argument(idx, _input, window);
191  add_4D_tensor_argument(idx, _output, window);
192  enqueue(queue, *this, window, lws_hint());
193 }
194 } // namespace arm_compute
Window calculate_max_window(const ValidRegion &valid_region, const Steps &steps, bool skip_border, BorderSize border_size)
void run(const Window &window, cl::CommandQueue &queue) override
Enqueue the OpenCL kernel to process the given window on the passed OpenCL command queue...
#define ARM_COMPUTE_RETURN_ERROR_ON_F16_UNSUPPORTED(tensor)
Definition: CLValidate.h:35
const Window & window() const
The maximum window the kernel can be executed on.
Definition: IKernel.cpp:28
static Status validate(const ITensorInfo *input, const ITensorInfo *output, unsigned int num_groups)
Static function to check if given info will lead to a valid configuration of CLChannelShuffleLayerKer...
virtual size_t dimension(size_t index) const =0
Return the size of the requested dimension.
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_QUANTIZATION_INFO(...)
Definition: Validate.h:606
void enqueue(cl::CommandQueue &queue, ICLKernel &kernel, const Window &window, const cl::NDRange &lws_hint=CLKernelLibrary::get().default_ndrange(), bool use_dummy_work_items=false)
Add the kernel to the command queue with the given window.
Definition: ICLKernel.cpp:32
const StringSet & options() const
Gets the current options list set.
cl::NDRange lws_hint() const
Return the Local-Workgroup-Size hint.
Definition: ICLKernel.h:318
#define ARM_COMPUTE_RETURN_ON_ERROR(status)
Checks if a status contains an error and returns it.
Definition: Error.h:204
std::string to_string(T &&value)
Convert integer and float values to string.
virtual DataType data_type() const =0
Data type used for each element of the tensor.
#define ARM_COMPUTE_ERROR_ON(cond)
If the condition is true then an error message is printed and an exception thrown.
Definition: Error.h:466
static CLKernelLibrary & get()
Access the KernelLibrary singleton.
Store the tensor&#39;s metadata.
Definition: ITensorInfo.h:40
#define ARM_COMPUTE_ERROR_THROW_ON(status)
Definition: Error.h:455
Manages all the OpenCL kernels compilation and caching, provides accessors for the OpenCL Context...
Status class.
Definition: Error.h:52
std::string lower_string(const std::string &val)
Lower a given string.
Definition: Utils.cpp:326
#define ARM_COMPUTE_RETURN_ERROR_ON(cond)
If the condition is true, an error is returned.
Definition: Error.h:296
Copyright (c) 2017-2021 Arm Limited.
void add_option(std::string option)
Adds option to the existing build option list.
cl::Kernel create_kernel(const CLCompileContext &ctx, const std::string &kernel_name, const std::set< std::string > &build_opts=std::set< std::string >())
Creates an opencl kernel using a compile context.
Definition: CLHelpers.cpp:391
const std::string & string_from_data_type(DataType dt)
Convert a data type identity into a string.
Definition: Utils.cpp:135
bool update_window_and_padding(Window &win, Ts &&... patterns)
Update window and padding size for each of the access patterns.
Definition: WindowHelpers.h:46
void configure(const ICLTensor *input, ICLTensor *output, unsigned int num_groups)
Configure function&#39;s inputs and outputs.
const unsigned int num_groups
Definition: Im2Col.cpp:153
bool auto_init_if_empty(ITensorInfo &info, const TensorShape &shape, int num_channels, DataType data_type, QuantizationInfo quantization_info=QuantizationInfo())
Auto initialize the tensor info (shape, number of channels and data type) if the current assignment i...
virtual std::unique_ptr< T > clone() const =0
Provide a clone of the current object of class T.
virtual ITensorInfo * info() const =0
Interface to be implemented by the child class to return the tensor&#39;s metadata.
void add_option_if(bool cond, std::string option)
Adds option if a given condition is true;.
virtual size_t element_size() const =0
Element size in bytes calculated as data_size() * num_channels()
Elementeise CL kernel type.
Definition: CLTypes.h:84
#define ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(k)
Definition: Validate.h:915
bool has_padding_changed(const std::unordered_map< const ITensorInfo *, PaddingSize > &padding_map)
Check if the previously stored padding info has changed after configuring a kernel.
Definition: Utils.cpp:533
CLCompileContext class.
Interface for OpenCL tensor.
Definition: ICLTensor.h:42
const std::string & string_from_data_layout(DataLayout dl)
Convert a data layout identity into a string.
Definition: Utils.cpp:123
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(...)
Definition: Validate.h:439
#define ARM_COMPUTE_CREATE_ERROR(error_code, msg)
Creates an error with a given message.
Definition: Error.h:159
static constexpr size_t DimZ
Alias for dimension 2 also known as Z dimension.
Definition: Window.h:47
size_t get_data_layout_dimension_index(const DataLayout &data_layout, const DataLayoutDimension &data_layout_dimension)
Get the index of the given dimension.
Definition: Helpers.inl:193
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(...)
Definition: Validate.h:541
Num samples, height, width, channels.
std::string get_cl_unsigned_type_from_element_size(size_t element_size)
Translates the element size to an unsigned integer data type.
Definition: CLHelpers.cpp:105
std::unordered_map< const ITensorInfo *, PaddingSize > get_padding_info(std::initializer_list< const ITensorInfo *> infos)
Stores padding information before configuring a kernel.
Definition: Utils.cpp:518
#define ARM_COMPUTE_RETURN_ERROR_ON_MSG(cond, msg)
If the condition is true, an error is returned.
Definition: Error.h:244
#define ARM_COMPUTE_ERROR_ON_NULLPTR(...)
Definition: Validate.h:157
unsigned int adjust_vec_size(unsigned int vec_size, size_t dim0)
Returns the adjusted vector size in case it is less than the input&#39;s first dimension, getting rounded down to its closest valid vector size.
Definition: Utils.h:1171
std::string kernel_name
void add_4D_tensor_argument(unsigned int &idx, const ICLTensor *tensor, const Window &window)
Add the passed 4D tensor&#39;s parameters to the object&#39;s kernel&#39;s arguments starting from the index idx...
Definition: ICLKernel.h:224
DataLayout
[DataLayout enum definition]
Definition: Types.h:113
Describe a multidimensional execution window.
Definition: Window.h:39
#define ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(f, s)
Definition: Validate.h:201
virtual DataLayout data_layout() const =0
Get the data layout of the tensor.