Compute Library
 21.05
CLReductionOperationKernel.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2017-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 "arm_compute/core/Utils.h"
35 #include "src/core/CL/CLValidate.h"
38 
39 #include "support/StringSupport.h"
40 
41 namespace arm_compute
42 {
43 namespace
44 {
45 Status validate_arguments(const ITensorInfo *input, const ITensorInfo *output, unsigned int axis, ReductionOperation op)
46 {
49  if(input->num_channels() == 1)
50  {
52  }
53  else
54  {
56  ARM_COMPUTE_RETURN_ERROR_ON(axis == 0);
57  }
58  ARM_COMPUTE_RETURN_ERROR_ON_MSG(op == ReductionOperation::SUM_SQUARE && input->data_type() == DataType::QASYMM8, "Not supported reduction operation for QASYMM8");
59  ARM_COMPUTE_RETURN_ERROR_ON_MSG(axis >= TensorShape::num_max_dimensions, "Reduction axis greater than max number of dimensions");
60  ARM_COMPUTE_RETURN_ERROR_ON_MSG(axis > 3, "Unsupported reduction axis");
61  ARM_COMPUTE_RETURN_ERROR_ON((op == ReductionOperation::MEAN_SUM) && (axis == 0) && (input->dimension(0) == 0) && (input->data_type() != DataType::QASYMM8)
62  && (input->data_type() != DataType::QASYMM8_SIGNED));
63  ARM_COMPUTE_RETURN_ERROR_ON_MSG((op == ReductionOperation::ARG_IDX_MAX) || (op == ReductionOperation::ARG_IDX_MIN), "Not supported reduction operation, use CLArgMinMaxLayer");
64 
65  if(output->total_size() != 0)
66  {
69  }
70 
71  return Status{};
72 }
73 } // namespace
74 
76  : _input(nullptr), _output(nullptr), _reduction_axis(0), _op(ReductionOperation::SUM_SQUARE)
77 {
78 }
79 
81 {
82  configure(CLKernelLibrary::get().get_compile_context(), input, output, axis, op);
83 }
84 
85 void CLReductionOperationKernel::configure(const CLCompileContext &compile_context, const ICLTensor *input, ICLTensor *output, unsigned int axis, ReductionOperation op)
86 {
88 
89  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input->info(), output->info(), axis, op));
90 
91  auto padding_info = get_padding_info({ input, output });
92 
93  _input = input;
94  _output = output;
95  _reduction_axis = axis;
96  _op = op;
97 
99  auto_init_if_empty(*output->info(), input->info()->clone()->set_tensor_shape(output_shape).reset_padding().set_is_resizable(true));
100 
101  // Set build options
102  CLBuildOptions build_opts;
103  DataType data_type = input->info()->data_type();
104  std::string data_type_promoted{};
105 
107  {
108  data_type_promoted = "int";
109  }
110  else
111  {
112  data_type_promoted = get_cl_type_from_data_type(data_type);
113  }
114 
115  const unsigned int width = input->info()->dimension(0) * input->info()->num_channels();
116  unsigned int vec_size = (is_data_type_quantized(input->info()->data_type()) && (axis == 0)) ? 1 : 16;
117  vec_size = adjust_vec_size(vec_size, width);
118  const unsigned int vec_size_leftover = width % vec_size;
119 
120  build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(data_type));
121  build_opts.add_option("-DDATA_TYPE_PROMOTED=" + data_type_promoted);
122  build_opts.add_option("-DVEC_SIZE=" + support::cpp11::to_string(vec_size));
123  build_opts.add_option("-DVEC_SIZE_LEFTOVER=" + support::cpp11::to_string(vec_size_leftover));
124  build_opts.add_option_if(is_data_type_float(data_type), "-DFLOAT_DATA_TYPE");
125  build_opts.add_option_if(op == ReductionOperation::SUM_SQUARE, "-DSUM_SQUARE");
126  build_opts.add_option_if(op == ReductionOperation::MEAN_SUM, "-DMEAN");
127  build_opts.add_option_if(op == ReductionOperation::SUM, "-DSUM");
128  build_opts.add_option_if(op == ReductionOperation::PROD, "-DPROD");
129  build_opts.add_option_if(op == ReductionOperation::MIN, "-DMIN");
130  build_opts.add_option_if(op == ReductionOperation::MAX, "-DMAX");
131  build_opts.add_option_if(is_data_type_quantized(data_type), "-DOFFSET=" + support::cpp11::to_string(input->info()->quantization_info().uniform().offset));
132  build_opts.add_option_if(is_data_type_quantized(data_type), "-DSCALE=" + float_to_string_with_full_precision(input->info()->quantization_info().uniform().scale));
133 
134  switch(op)
135  {
137  build_opts.add_option(("-DOPERATION=square_sum"));
138  break;
141  build_opts.add_option(("-DOPERATION=sum"));
142  break;
145  break;
147  build_opts.add_option(("-DOPERATION=product"));
148  break;
149  default:
150  ARM_COMPUTE_ERROR("Unsupported reduction operation");
151  }
152 
153  // Create kernel
154  std::string kernel_axis_name;
155  const bool is_serial_op = needs_serialized_reduction(_op, _input->info()->data_type(), _reduction_axis);
156 
157  switch(axis)
158  {
159  case 0:
160  {
161  build_opts.add_option("-DWIDTH=" + support::cpp11::to_string(width));
162  kernel_axis_name = ((is_serial_op) ? "non_parallel_x" : "x");
163  }
164  break;
165  case 1:
166  build_opts.add_option("-DHEIGHT=" + support::cpp11::to_string(input->info()->dimension(1)));
167  kernel_axis_name = "y";
168  break;
169  case 2:
170  build_opts.add_option("-DDEPTH=" + support::cpp11::to_string(input->info()->dimension(2)));
171  kernel_axis_name = "z";
172  break;
173  case 3:
174  build_opts.add_option("-DDEPTH=" + support::cpp11::to_string(input->info()->dimension(2)));
175  build_opts.add_option("-DBATCH=" + support::cpp11::to_string(input->info()->dimension(3)));
176  kernel_axis_name = "w";
177  break;
178  default:
179  ARM_COMPUTE_ERROR("Not supported");
180  }
181  _kernel = create_kernel(compile_context, "reduction_operation_" + kernel_axis_name, build_opts.options());
182 
183  // Configure kernel window
184  Window win = calculate_max_window(*input->info(), Steps(vec_size));
185  win.set(Window::DimX, Window::Dimension(win.x().start(), win.x().end() * _input->info()->num_channels(), win.x().step()));
186  ICLKernel::configure_internal(win);
187 
189 }
190 
192 {
194  return Status{};
195 }
196 
197 void CLReductionOperationKernel::run(const Window &window, cl::CommandQueue &queue)
198 {
201 
202  const bool is_serial_op = needs_serialized_reduction(_op, _input->info()->data_type(), _reduction_axis);
203  switch(_reduction_axis)
204  {
205  case 0:
206  {
207  // We use parallel reduction only in non quantized types
208  if(is_serial_op)
209  {
210  // Get first input and output slices
211  Window window_in{ window };
212  window_in.set(Window::DimX, Window::Dimension(0, _input->info()->dimension(0), _input->info()->dimension(0)));
213 
214  Window out_window{ window };
215  out_window.set(Window::DimX, Window::Dimension(0, 0, 0));
216 
217  Window in_slice = window_in.first_slice_window_1D();
218  Window out_slice = out_window.first_slice_window_1D();
219 
220  do
221  {
222  unsigned int idx = 0;
223  add_1D_tensor_argument(idx, _input, in_slice);
224  add_1D_tensor_argument(idx, _output, out_slice);
225  enqueue(queue, *this, in_slice);
226  }
227  while(window_in.slide_window_slice_1D(in_slice) && out_window.slide_window_slice_1D(out_slice));
228  }
229  else
230  {
231  // Set out window
232  bool has_collapsed = true;
233  Window window_in = window.collapse_if_possible(window, 2, &has_collapsed);
234  ARM_COMPUTE_ERROR_ON(!has_collapsed);
235 
236  Window window_out = window_in;
237  window_out.set(0, Window::Dimension());
238 
239  unsigned int idx = 0;
240  add_3D_tensor_argument(idx, _input, window_in);
241  add_3D_tensor_argument(idx, _output, window_out);
242  enqueue(queue, *this, window_in);
243  }
244  }
245  break;
246  case 1:
247  {
248  // Get first input and output slices
249  Window window_in{ window };
250  window_in.set(Window::DimY, Window::Dimension(0, _input->info()->dimension(1), _input->info()->dimension(1)));
251  Window in_slice = window_in.first_slice_window_2D();
252  Window out_slice = window.first_slice_window_2D();
253 
254  do
255  {
256  unsigned int idx = 0;
257  add_2D_tensor_argument(idx, _input, in_slice);
258  add_2D_tensor_argument(idx, _output, out_slice);
259  enqueue(queue, *this, in_slice);
260  }
261  while(window_in.slide_window_slice_2D(in_slice) && window.slide_window_slice_2D(out_slice));
262  }
263  break;
264  case 2:
265  {
266  // Get first input and output slices
267  Window window_in{ window };
268  window_in.set(Window::DimZ, Window::Dimension(0, _input->info()->dimension(2), _input->info()->dimension(2)));
269  Window in_slice = window_in.first_slice_window_3D();
270  Window out_slice = window.first_slice_window_3D();
271 
272  do
273  {
274  unsigned int idx = 0;
275  add_3D_tensor_argument(idx, _input, in_slice);
276  add_3D_tensor_argument(idx, _output, out_slice);
277  enqueue(queue, *this, in_slice);
278  }
279  while(window_in.slide_window_slice_3D(in_slice) && window.slide_window_slice_3D(out_slice));
280  }
281  break;
282  case 3:
283  {
284  // Get first input and output slices
285  Window window_in{ window };
286  window_in.set(3, Window::Dimension(0, 1, 1));
287  Window in_slice = window_in.first_slice_window_4D();
288  Window out_slice = window.first_slice_window_4D();
289 
290  do
291  {
292  unsigned int idx = 0;
293  add_4D_tensor_argument(idx, _input, in_slice);
294  add_4D_tensor_argument(idx, _output, out_slice);
295  enqueue(queue, *this, in_slice);
296  }
297  while(window_in.slide_window_slice_4D(in_slice) && window.slide_window_slice_4D(out_slice));
298  }
299  break;
300  default:
301  ARM_COMPUTE_ERROR("Not supported");
302  }
303 }
304 } // namespace arm_compute
bool is_data_type_quantized(DataType dt)
Check if a given data type is of quantized type.
Definition: Utils.h:967
Window first_slice_window_2D() const
First 2D slice of the window.
Definition: Window.h:283
bool needs_serialized_reduction(ReductionOperation op, DataType dt, unsigned int axis)
Check if the given reduction operation should be handled in a serial way.
Definition: Utils.cpp:429
Window calculate_max_window(const ValidRegion &valid_region, const Steps &steps, bool skip_border, BorderSize border_size)
#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
Shape of a tensor.
Definition: TensorShape.h:39
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:489
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
ReductionOperation
Available reduction operations.
Definition: Types.h:457
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
#define ARM_COMPUTE_ERROR(msg)
Print the given message then throw an std::runtime_error.
Definition: Error.h:352
#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.
1 channel, 1 F32 per channel
#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's metadata.
Definition: ITensorInfo.h:40
#define ARM_COMPUTE_ERROR_THROW_ON(status)
Definition: Error.h:455
Describe one of the image's dimensions with a start, end and step.
Definition: Window.h:77
void configure(const ICLTensor *input, ICLTensor *output, unsigned int axis, ReductionOperation op)
Set the input and output tensors.
Status class.
Definition: Error.h:52
#define ARM_COMPUTE_RETURN_ERROR_ON(cond)
If the condition is true, an error is returned.
Definition: Error.h:296
void run(const Window &window, cl::CommandQueue &queue) override
Enqueue the OpenCL kernel to process the given window on the passed OpenCL command queue.
void add_3D_tensor_argument(unsigned int &idx, const ICLTensor *tensor, const Window &window)
Add the passed 3D tensor's parameters to the object's kernel's arguments starting from the index idx.
Definition: ICLKernel.h:172
bool slide_window_slice_2D(Window &slice) const
Slide the passed 2D window slice.
Definition: Window.h:323
Copyright (c) 2017-2021 Arm Limited.
1 channel, 1 F16 per channel
#define ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(...)
Definition: Validate.h:159
1 channel, 1 S32 per channel
const DataType data_type
Definition: Im2Col.cpp:150
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:403
static constexpr size_t DimX
Alias for dimension 0 also known as X dimension.
Definition: Window.h:43
Window collapse_if_possible(const Window &full_window, size_t first, size_t last, bool *has_collapsed=nullptr) const
Collapse the dimensions between first and last if possible.
Definition: Window.inl:68
std::string float_to_string_with_full_precision(float val)
Create a string with the float in full precision.
Definition: Utils.h:1061
quantized, asymmetric fixed-point 8-bit number unsigned
Class to describe a number of elements in each dimension.
Definition: Steps.h:40
TensorShape compute_reduced_shape(const TensorShape &input, unsigned int axis, bool keep_dims=true)
Calculate the reduced shape of a tensor given an axis.
std::string get_cl_type_from_data_type(const DataType &dt)
Translates a tensor data type to the appropriate OpenCL type.
Definition: CLHelpers.cpp:37
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 ITensorInfo * info() const =0
Interface to be implemented by the child class to return the tensor's metadata.
void set(size_t dimension, const Dimension &dim)
Set the values of a given dimension.
Definition: Window.inl:49
bool slide_window_slice_3D(Window &slice) const
Slide the passed 3D window slice.
Definition: Window.h:335
#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:504
CLCompileContext class.
static constexpr size_t DimY
Alias for dimension 1 also known as Y dimension.
Definition: Window.h:45
void add_2D_tensor_argument(unsigned int &idx, const ICLTensor *tensor, const Window &window)
Add the passed 2D tensor's parameters to the object's kernel's arguments starting from the index idx.
Definition: ICLKernel.h:148
Interface for OpenCL tensor.
Definition: ICLTensor.h:42
static constexpr size_t DimZ
Alias for dimension 2 also known as Z dimension.
Definition: Window.h:47
Manages all the OpenCL kernels compilation and caching, provides accessors for the OpenCL Context.
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(...)
Definition: Validate.h:541
#define ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(t, c,...)
Definition: Validate.h:788
Status validate_arguments(const ITensorInfo *input, const ITensorInfo *bias, const ITensorInfo *output, const GEMMLowpOutputStageInfo *output_stage)
Window first_slice_window_4D() const
First 4D slice of the window.
Definition: Window.h:299
bool slide_window_slice_4D(Window &slice) const
Slide the passed 4D window slice.
Definition: Window.h:347
#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's first dimension,...
Definition: Utils.h:1157
static Status validate(const ITensorInfo *input, const ITensorInfo *output, unsigned int axis, ReductionOperation op)
Static function to check if given info will lead to a valid configuration of CLReductionOperationKern...
quantized, asymmetric fixed-point 8-bit number signed
void add_1D_tensor_argument(unsigned int &idx, const ICLTensor *tensor, const Window &window)
Add the passed 1D tensor's parameters to the object's kernel's arguments starting from the index idx.
Definition: ICLKernel.h:124
static constexpr size_t num_max_dimensions
Number of dimensions the tensor has.
Definition: Dimensions.h:46
Window first_slice_window_3D() const
First 3D slice of the window.
Definition: Window.h:291
DataType
Available data types.
Definition: Types.h:77
void add_4D_tensor_argument(unsigned int &idx, const ICLTensor *tensor, const Window &window)
Add the passed 4D tensor's parameters to the object's kernel's arguments starting from the index idx.
Definition: ICLKernel.h:182
Describe a multidimensional execution window.
Definition: Window.h:39
bool is_data_type_float(DataType dt)
Check if a given data type is of floating point type.
Definition: Utils.h:947
#define ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(f, s)
Definition: Validate.h:201
Window first_slice_window_1D() const
First 1D slice of the window.
Definition: Window.h:275