Compute Library
 21.02
CLArgMinMaxLayerKernel.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2019-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"
33 #include "src/core/CL/CLValidate.h"
36 
37 #include "support/StringSupport.h"
38 
39 namespace arm_compute
40 {
41 namespace
42 {
43 Status validate_arguments(const ITensorInfo *input, const ITensorInfo *prev_output, const ITensorInfo *output, unsigned int axis, ReductionOperation op)
44 {
48  ARM_COMPUTE_RETURN_ERROR_ON_MSG(op != ReductionOperation::ARG_IDX_MAX && op != ReductionOperation::ARG_IDX_MIN, "Only ARG_IDX_MAX and ARG_IDX_MIN are supported");
49  ARM_COMPUTE_RETURN_ERROR_ON_MSG(axis >= TensorShape::num_max_dimensions, "Reduction axis greater than max number of dimensions");
50  ARM_COMPUTE_RETURN_ERROR_ON_MSG(axis > 3, "Unsupported reduction axis");
51 
52  if(output->total_size() != 0)
53  {
55  }
56  if(prev_output != nullptr && prev_output->total_size() != 0)
57  {
59  if(output->total_size() != 0)
60  {
62  }
63  }
64 
65  return Status{};
66 }
67 } // namespace
68 
70  : _input(nullptr), _prev_output(nullptr), _output(nullptr), _reduction_axis(0), _op(ReductionOperation::ARG_IDX_MAX)
71 {
72 }
73 
74 void CLArgMinMaxLayerKernel::configure(const ICLTensor *input, const ICLTensor *prev_output, ICLTensor *output, unsigned int axis, ReductionOperation op)
75 {
76  configure(CLKernelLibrary::get().get_compile_context(), input, prev_output, output, axis, op);
77 }
78 
79 void CLArgMinMaxLayerKernel::configure(const CLCompileContext &compile_context, const ICLTensor *input, const ICLTensor *prev_output, ICLTensor *output, unsigned int axis, ReductionOperation op)
80 {
81  ARM_COMPUTE_ERROR_ON_NULLPTR(input, output);
82 
84  output_shape.set(axis, 1);
85  auto_init_if_empty(*output->info(), input->info()->clone()->set_tensor_shape(output_shape).set_data_type(DataType::S32).reset_padding().set_is_resizable(true));
86 
87  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input->info(), (prev_output != nullptr) ? prev_output->info() : nullptr, output->info(), axis, op));
88 
89  auto padding_info = get_padding_info({ input, prev_output, output });
90 
91  _input = input;
92  _prev_output = prev_output;
93  _output = output;
94  _reduction_axis = axis;
95  _op = op;
96 
97  // Set build options
98  const auto vector_size = (axis == 0) ? 16U : adjust_vec_size(16U, input->info()->dimension(0));
99 
100  CLBuildOptions build_opts;
101  build_opts.add_option_if(_prev_output != nullptr, "-DPREV_OUTPUT");
102  build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(input->info()->data_type()));
103  build_opts.add_option("-DVEC_SIZE_LEFTOVER=" + support::cpp11::to_string(input->info()->dimension(0) % vector_size));
104  build_opts.add_option("-DVEC_SIZE=" + support::cpp11::to_string(vector_size));
105  build_opts.add_option_if(is_data_type_float(input->info()->data_type()), "-DFLOAT_DATA_TYPE");
106  build_opts.add_option_if_else(op == ReductionOperation::ARG_IDX_MAX, "-DARG_MAX", "-DARG_MIN");
107  build_opts.add_option("-DDATA_TYPE_OUTPUT=" + get_cl_type_from_data_type(output->info()->data_type()));
108 
109  // Create kernel
111  std::string kernel_axis_name;
112  switch(axis)
113  {
114  case 0:
115  {
116  const ICLTensor *input_for_width = prev_output != nullptr ? _prev_output : _input;
117  build_opts.add_option("-DWIDTH=" + support::cpp11::to_string(input_for_width->info()->dimension(0)));
118 
119  kernel_axis_name = "x";
120  lws_hint = create_lws_hint_parallel_implementations(input_for_width->info()->dimension(0), vector_size);
121  }
122  break;
123  case 1:
124  build_opts.add_option("-DHEIGHT=" + support::cpp11::to_string(input->info()->dimension(1)));
125  kernel_axis_name = "y";
126  break;
127  case 2:
128  build_opts.add_option("-DDEPTH=" + support::cpp11::to_string(input->info()->dimension(2)));
129  kernel_axis_name = "z";
130  break;
131  case 3:
132  build_opts.add_option("-DDEPTH=" + support::cpp11::to_string(input->info()->dimension(2)));
133  build_opts.add_option("-DBATCH=" + support::cpp11::to_string(input->info()->dimension(3)));
134  kernel_axis_name = "w";
135  break;
136  default:
137  ARM_COMPUTE_ERROR("Not supported");
138  }
139  _kernel = create_kernel(compile_context, "arg_min_max_" + kernel_axis_name, build_opts.options());
140 
141  // Configure kernel window
142  Window win = calculate_max_window((prev_output != nullptr) ? (*prev_output->info()) : (*input->info()), Steps(vector_size));
143  ICLKernel::configure_internal(win, lws_hint);
144 
146 }
147 
148 Status CLArgMinMaxLayerKernel::validate(const ITensorInfo *input, const ITensorInfo *prev_output, const ITensorInfo *output, unsigned int axis, ReductionOperation op)
149 {
150  ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, prev_output, output, axis, op));
151  return Status{};
152 }
153 
154 void CLArgMinMaxLayerKernel::run(const Window &window, cl::CommandQueue &queue)
155 {
158 
159  switch(_reduction_axis)
160  {
161  case 0:
162  {
163  // Set out window
164  Window out_window(window);
165  out_window.set(Window::DimX, Window::Dimension(0, 0, 0));
166 
167  // Get first input and output slices
168  Window in_slice = window.first_slice_window_2D();
169  Window out_slice = out_window.first_slice_window_2D();
170 
171  // Reshape window
172  const unsigned int num_tensors = _prev_output != nullptr ? 3 : 2;
173 
174  // Set local sums buffer
175  unsigned int local_res_size = lws_hint()[0] * _output->info()->element_size();
176  _kernel.setArg(num_arguments_per_2D_tensor() * num_tensors, local_res_size, nullptr);
177  do
178  {
179  unsigned int idx = 0;
180  add_2D_tensor_argument(idx, _input, in_slice);
181  if(_prev_output != nullptr)
182  {
183  add_2D_tensor_argument(idx, _prev_output, in_slice);
184  }
185  add_2D_tensor_argument(idx, _output, out_slice);
186  enqueue(queue, *this, in_slice, lws_hint());
187  }
188  while(window.slide_window_slice_2D(in_slice) && window.slide_window_slice_2D(out_slice));
189  }
190  break;
191  case 1:
192  {
193  // Get first input and output slices
194  Window window_in{ window };
195  window_in.set(Window::DimY, Window::Dimension(0, _input->info()->dimension(1), _input->info()->dimension(1)));
196  Window in_slice = window_in.first_slice_window_2D();
197  Window out_slice = window.first_slice_window_2D();
198 
199  do
200  {
201  unsigned int idx = 0;
202  add_2D_tensor_argument(idx, _input, in_slice);
203  add_2D_tensor_argument(idx, _output, out_slice);
204  enqueue(queue, *this, in_slice, lws_hint());
205  }
206  while(window_in.slide_window_slice_2D(in_slice) && window.slide_window_slice_2D(out_slice));
207  }
208  break;
209  case 2:
210  {
211  // Get first input and output slices
212  Window window_in{ window };
213  window_in.set(Window::DimZ, Window::Dimension(0, _input->info()->dimension(2), _input->info()->dimension(2)));
214  Window in_slice = window_in.first_slice_window_3D();
215  Window out_slice = window.first_slice_window_3D();
216 
217  do
218  {
219  unsigned int idx = 0;
220  add_3D_tensor_argument(idx, _input, in_slice);
221  add_3D_tensor_argument(idx, _output, out_slice);
222  enqueue(queue, *this, in_slice, lws_hint());
223  }
224  while(window_in.slide_window_slice_3D(in_slice) && window.slide_window_slice_3D(out_slice));
225  }
226  break;
227  case 3:
228  {
229  // Get first input and output slices
230  Window window_in{ window };
231  window_in.set(3, Window::Dimension(0, 1, 1));
232  Window in_slice = window_in.first_slice_window_4D();
233  Window out_slice = window.first_slice_window_4D();
234 
235  do
236  {
237  unsigned int idx = 0;
238  add_4D_tensor_argument(idx, _input, in_slice);
239  add_4D_tensor_argument(idx, _output, out_slice);
240  enqueue(queue, *this, in_slice, lws_hint());
241  }
242  while(window_in.slide_window_slice_4D(in_slice) && window.slide_window_slice_4D(out_slice));
243  }
244  break;
245  default:
246  ARM_COMPUTE_ERROR("Not supported");
247  }
248 }
249 } // namespace arm_compute
Window first_slice_window_2D() const
First 2D slice of the window.
Definition: Window.h:283
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
void enqueue(IGCKernel &kernel, const Window &window, const gles::NDRange &lws=gles::NDRange(1U, 1U, 1U))
Add the kernel to the command queue with the given window.
Definition: IGCKernel.cpp:41
virtual size_t dimension(size_t index) const =0
Return the size of the requested dimension.
ReductionOperation
Available reduction operations.
Definition: Types.h:521
const StringSet & options() const
Gets the current options list set.
#define ARM_COMPUTE_ERROR(msg)
Print the given message then throw an std::runtime_error.
Definition: Error.h:352
cl::NDRange lws_hint() const
Return the Local-Workgroup-Size hint.
Definition: ICLKernel.h:276
#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
void configure(const ICLTensor *input, const ICLTensor *prev_output, ICLTensor *output, unsigned int axis, ReductionOperation op)
Set the input and output tensors.
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
Status class.
Definition: Error.h:52
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:163
1 channel, 1 S32 per channel
void add_option(std::string option)
Adds option to the existing build option list.
cl::NDRange default_ndrange() const
Return the default NDRange for the device.
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
1 channel, 1 U32 per channel
virtual const TensorShape & tensor_shape() const =0
Size for each dimension of the tensor.
quantized, asymmetric fixed-point 8-bit number unsigned
Class to describe a number of elements in each dimension.
Definition: Steps.h:40
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 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.
static Status validate(const ITensorInfo *input, const ITensorInfo *prev_output, const ITensorInfo *output, unsigned int axis, ReductionOperation op)
Static function to check if given info will lead to a valid configuration of CLArgMinMaxLayerKernel.
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()
void set(size_t dimension, const Dimension &dim)
Set the values of a given dimension.
Definition: Window.inl:49
static constexpr unsigned int num_arguments_per_2D_tensor()
Returns the number of arguments enqueued per 2D tensor object.
Definition: ICLKernel.h:206
cl::NDRange create_lws_hint_parallel_implementations(unsigned int input_dimension, unsigned int vector_size)
Creates a suitable LWS hint object for parallel implementations.
Definition: CLHelpers.cpp:411
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:941
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:528
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&#39;s parameters to the object&#39;s kernel&#39;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:545
#define ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(t, c,...)
Definition: Validate.h:792
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:513
Status validate_arguments(const ITensorInfo *input, const ITensorInfo *bias, const ITensorInfo *output, const GEMMLowpOutputStageInfo *output_stage)
void run(const Window &window, cl::CommandQueue &queue) override
Enqueue the OpenCL kernel to process the given window on the passed OpenCL command queue...
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:161
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:1358
quantized, asymmetric fixed-point 8-bit number signed
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
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:182
Describe a multidimensional execution window.
Definition: Window.h:39
TensorShape & set(size_t dimension, size_t value, bool apply_dim_correction=true, bool increase_dim_unit=true)
Accessor to set the value of one of the dimensions.
Definition: TensorShape.h:79
bool is_data_type_float(DataType dt)
Check if a given data type is of floating point type.
Definition: Utils.h:1148
#define ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(f, s)
Definition: Validate.h:205
void add_option_if_else(bool cond, std::string option_true, std::string option_false)
Adds first option if condition is true else the second one.