Compute Library
 21.02
CLPriorBoxLayerKernel.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2018-2020 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 
40 
41 namespace arm_compute
42 {
43 namespace
44 {
45 Status validate_arguments(const ITensorInfo *input1, const ITensorInfo *input2, const ITensorInfo *output, const PriorBoxLayerInfo &info)
46 {
47  ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(input1, input2, output);
51 
52  // Check variances
53  const int var_size = info.variances().size();
54  if(var_size > 1)
55  {
56  ARM_COMPUTE_RETURN_ERROR_ON_MSG(var_size != 4, "Must provide 4 variance values");
57  for(int i = 0; i < var_size; ++i)
58  {
59  ARM_COMPUTE_RETURN_ERROR_ON_MSG(var_size <= 0, "Must be greater than 0");
60  }
61  }
62  ARM_COMPUTE_RETURN_ERROR_ON_MSG(info.steps()[0] < 0.f, "Step x should be greater or equal to 0");
63  ARM_COMPUTE_RETURN_ERROR_ON_MSG(info.steps()[1] < 0.f, "Step y should be greater or equal to 0");
64 
65  if(!info.max_sizes().empty())
66  {
67  ARM_COMPUTE_RETURN_ERROR_ON_MSG(info.max_sizes().size() != info.min_sizes().size(), "Max and min sizes dimensions should match");
68  }
69 
70  for(unsigned int i = 0; i < info.max_sizes().size(); ++i)
71  {
72  ARM_COMPUTE_RETURN_ERROR_ON_MSG(info.max_sizes()[i] < info.min_sizes()[i], "Max size should be greater than min size");
73  }
74 
75  if(output != nullptr && output->total_size() != 0)
76  {
77  ARM_COMPUTE_RETURN_ERROR_ON(output->dimension(1) != 2);
78  }
79 
80  return Status{};
81 }
82 
83 std::pair<Status, Window> validate_and_configure_window(const ITensorInfo *input1, const ITensorInfo *input2, ITensorInfo *output, const PriorBoxLayerInfo &info, int num_priors)
84 {
85  ARM_COMPUTE_UNUSED(input2);
86  // Output tensor auto initialization if not yet initialized
87  TensorShape output_shape = compute_prior_box_shape(*input1, info);
88  auto_init_if_empty(*output, output_shape, 1, input1->data_type());
89 
90  const unsigned int num_elems_processed_per_iteration = 4 * num_priors;
91  Window win = calculate_max_window(*output, Steps(num_elems_processed_per_iteration));
92  AccessWindowHorizontal output_access(output, 0, num_elems_processed_per_iteration);
93  bool window_changed = update_window_and_padding(win, output_access);
94  Status err = (window_changed) ? ARM_COMPUTE_CREATE_ERROR(ErrorCode::RUNTIME_ERROR, "Insufficient Padding!") : Status{};
95  return std::make_pair(err, win);
96 }
97 } // namespace
98 
100  : _input1(nullptr), _input2(nullptr), _output(nullptr), _info(), _num_priors(), _min(), _max(), _aspect_ratios()
101 {
102 }
103 
104 void CLPriorBoxLayerKernel::configure(const ICLTensor *input1, const ICLTensor *input2, ICLTensor *output, const PriorBoxLayerInfo &info, cl::Buffer *min, cl::Buffer *max, cl::Buffer *aspect_ratios)
105 {
106  configure(CLKernelLibrary::get().get_compile_context(), input1, input2, output, info, min, max, aspect_ratios);
107 }
108 
109 void CLPriorBoxLayerKernel::configure(const CLCompileContext &compile_context, const ICLTensor *input1, const ICLTensor *input2, ICLTensor *output, const PriorBoxLayerInfo &info, cl::Buffer *min,
110  cl::Buffer *max, cl::Buffer *aspect_ratios)
111 {
112  ARM_COMPUTE_ERROR_ON_NULLPTR(input1, input2, output);
113 
114  _input1 = input1;
115  _input2 = input2;
116  _output = output;
117  _info = info;
118  _min = min;
119  _max = max;
120  _aspect_ratios = aspect_ratios;
121 
122  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input1->info(), input2->info(), output->info(), info));
123 
124  // Calculate number of aspect ratios
125  _num_priors = info.aspect_ratios().size() * info.min_sizes().size() + info.max_sizes().size();
126 
127  const DataLayout data_layout = input1->info()->data_layout();
128 
129  const int width_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::WIDTH);
130  const int height_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::HEIGHT);
131 
132  const int layer_width = input1->info()->dimension(width_idx);
133  const int layer_height = input1->info()->dimension(height_idx);
134 
135  int img_width = info.img_size().x;
136  int img_height = info.img_size().y;
137  if(img_width == 0 || img_height == 0)
138  {
139  img_width = input2->info()->dimension(width_idx);
140  img_height = input2->info()->dimension(height_idx);
141  }
142 
143  float step_x = info.steps()[0];
144  float step_y = info.steps()[0];
145  if(step_x == 0.f || step_y == 0.f)
146  {
147  step_x = static_cast<float>(img_width) / layer_width;
148  step_y = static_cast<float>(img_height) / layer_height;
149  }
150 
151  // Set build options
152  CLBuildOptions build_opts;
153  build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(input1->info()->data_type()));
154  build_opts.add_option("-DWIDTH=" + support::cpp11::to_string(img_width));
155  build_opts.add_option("-DHEIGHT=" + support::cpp11::to_string(img_height));
156  build_opts.add_option("-DLAYER_WIDTH=" + support::cpp11::to_string(layer_width));
157  build_opts.add_option("-DLAYER_HEIGHT=" + support::cpp11::to_string(layer_height));
158  build_opts.add_option("-DSTEP_X=" + support::cpp11::to_string(step_x));
159  build_opts.add_option("-DSTEP_Y=" + support::cpp11::to_string(step_y));
160  build_opts.add_option("-DNUM_PRIORS=" + support::cpp11::to_string(_num_priors));
161  build_opts.add_option("-DOFFSET=" + support::cpp11::to_string(info.offset()));
162  build_opts.add_option_if(info.clip(), "-DIN_PLACE");
163 
164  if(info.variances().size() > 1)
165  {
166  for(unsigned int i = 0; i < info.variances().size(); ++i)
167  {
168  build_opts.add_option("-DVARIANCE_" + support::cpp11::to_string(i) + "=" + support::cpp11::to_string(info.variances().at(i)));
169  }
170  }
171  else
172  {
173  for(unsigned int i = 0; i < 4; ++i)
174  {
175  build_opts.add_option("-DVARIANCE_" + support::cpp11::to_string(i) + "=" + support::cpp11::to_string(info.variances().at(0)));
176  }
177  }
178 
179  unsigned int idx = num_arguments_per_2D_tensor();
180  _kernel = create_kernel(compile_context, "prior_box_layer_nchw", build_opts.options());
181 
182  _kernel.setArg(idx++, *_min);
183  _kernel.setArg(idx++, *_max);
184  _kernel.setArg(idx++, *_aspect_ratios);
185  _kernel.setArg<unsigned int>(idx++, info.min_sizes().size());
186  _kernel.setArg<unsigned int>(idx++, info.max_sizes().size());
187  _kernel.setArg<unsigned int>(idx++, info.aspect_ratios().size());
188 
189  // Configure kernel window
190  auto win_config = validate_and_configure_window(input1->info(), input2->info(), output->info(), info, _num_priors);
191 
192  ARM_COMPUTE_ERROR_THROW_ON(win_config.first);
193  ICLKernel::configure_internal(win_config.second);
194 }
195 
196 Status CLPriorBoxLayerKernel::validate(const ITensorInfo *input1, const ITensorInfo *input2, const ITensorInfo *output, const PriorBoxLayerInfo &info)
197 {
198  ARM_COMPUTE_ERROR_ON_NULLPTR(input1, input2, output);
199  ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input1, input2, output, info));
200  const int num_priors = info.aspect_ratios().size() * info.min_sizes().size() + info.max_sizes().size();
201  ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window(input1->clone().get(), input2->clone().get(), output->clone().get(), info, num_priors)
202  .first);
203 
204  return Status{};
205 }
206 
207 void CLPriorBoxLayerKernel::run(const Window &window, cl::CommandQueue &queue)
208 {
211 
212  queue.enqueueWriteBuffer(*_min, CL_TRUE, 0, _info.min_sizes().size() * sizeof(float), _info.min_sizes().data());
213  queue.enqueueWriteBuffer(*_aspect_ratios, CL_TRUE, 0, _info.aspect_ratios().size() * sizeof(float), _info.aspect_ratios().data());
214  if(!_info.max_sizes().empty())
215  {
216  queue.enqueueWriteBuffer(*_max, CL_TRUE, 0, _info.max_sizes().size() * sizeof(float), _info.max_sizes().data());
217  }
218 
220  slice.set(Window::DimY, Window::Dimension(0, _output->info()->dimension(1), 2));
221 
222  unsigned int idx = 0;
223  add_2D_tensor_argument(idx, _output, slice);
224  enqueue(queue, *this, slice, lws_hint());
225 }
226 } // 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)
const Window & window() const
The maximum window the kernel can be executed on.
Definition: IKernel.cpp:28
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
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_LAYOUT(...)
Definition: Validate.h:494
virtual size_t dimension(size_t index) const =0
Return the size of the requested dimension.
const StringSet & options() const
Gets the current options list set.
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.
std::vector< float > aspect_ratios() const
Get aspect ratios.
Definition: Types.h:944
virtual DataType data_type() const =0
Data type used for each element of the tensor.
1 channel, 1 F32 per channel
void configure(const ICLTensor *input1, const ICLTensor *input2, ICLTensor *output, const PriorBoxLayerInfo &info, cl::Buffer *min, cl::Buffer *max, cl::Buffer *aspect_ratios)
Set the input and output tensors.
const DataLayout data_layout
Definition: Im2Col.cpp:151
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
Describe one of the image&#39;s dimensions with a start, end and step.
Definition: Window.h:77
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
static Status validate(const ITensorInfo *input1, const ITensorInfo *input2, const ITensorInfo *output, const PriorBoxLayerInfo &info)
Static function to check if given info will lead to a valid configuration of CLPriorBoxLayerKernel.
Copyright (c) 2017-2021 Arm Limited.
int32_t x
X coordinates.
Definition: Types.h:465
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_NULLPTR(...)
Definition: Validate.h:163
void add_option(std::string option)
Adds option to the existing build option list.
TensorShape compute_prior_box_shape(const ITensorInfo &input, const PriorBoxLayerInfo &info)
Calculate the prior box output shape of a tensor.
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
int32_t y
Y coordinates.
Definition: Types.h:466
bool update_window_and_padding(Window &win, Ts &&... patterns)
Update window and padding size for each of the access patterns.
Definition: WindowHelpers.h:46
#define ARM_COMPUTE_UNUSED(...)
To avoid unused variables warnings.
Definition: Error.h:152
std::array< float, 2 > steps() const
Get the step coordinates.
Definition: Types.h:914
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.
PriorBox layer info.
Definition: Types.h:839
float offset() const
Get the offset.
Definition: Types.h:924
void add_option_if(bool cond, std::string option)
Adds option if a given condition is true;.
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
Coordinates2D img_size() const
Get the image size coordinates.
Definition: Types.h:919
#define ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(k)
Definition: Validate.h:941
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
ScaleKernelInfo info(interpolation_policy, default_border_mode, PixelValue(), sampling_policy, false)
Interface for OpenCL tensor.
Definition: ICLTensor.h:42
#define ARM_COMPUTE_CREATE_ERROR(error_code, msg)
Creates an error with a given message.
Definition: Error.h:159
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
std::vector< float > max_sizes() const
Get max sizes.
Definition: Types.h:939
#define ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(t, c,...)
Definition: Validate.h:792
Status validate_arguments(const ITensorInfo *input, const ITensorInfo *bias, const ITensorInfo *output, const GEMMLowpOutputStageInfo *output_stage)
std::vector< float > variances() const
Get min variances.
Definition: Types.h:909
unsigned int num_elems_processed_per_iteration
#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
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
bool clip() const
Get the clip value.
Definition: Types.h:934
DataLayout
[DataLayout enum definition]
Definition: Types.h:120
Describe a multidimensional execution window.
Definition: Window.h:39
#define ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(f, s)
Definition: Validate.h:205
SimpleTensor< T > slice(const SimpleTensor< T > &src, Coordinates starts, Coordinates ends)
virtual DataLayout data_layout() const =0
Get the data layout of the tensor.
std::vector< float > min_sizes() const
Get min sizes.
Definition: Types.h:904