Compute Library
 20.02.1
CLScaleKernel.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2016-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 
33 #include "arm_compute/core/Error.h"
36 
37 #include <set>
38 #include <string>
39 
40 using namespace arm_compute;
41 
42 namespace
43 {
44 inline std::pair<float, float> calculate_scale_factors(const ITensorInfo &input, const ITensorInfo &output, bool align_corners)
45 {
46  DataLayout data_layout = input.data_layout();
49 
50  // Compute the ratio between source width/height and destination width/height
51  const unsigned int input_width = input.dimension(idx_width);
52  const unsigned int input_height = input.dimension(idx_height);
53  const unsigned int output_width = output.dimension(idx_width);
54  const unsigned int output_height = output.dimension(idx_height);
55 
56  float wr = arm_compute::calculate_resize_ratio(input_width, output_width, align_corners);
57  float hr = arm_compute::calculate_resize_ratio(input_height, output_height, align_corners);
58 
59  return std::make_pair(wr, hr);
60 }
61 
62 Status validate_arguments(const ITensorInfo *input, const ITensorInfo *output, InterpolationPolicy policy, bool align_corners)
63 {
70 
71  if(align_corners)
72  {
73  // For bilinear method with aligned corners, the resize ratio will
74  // be calculated by (input_size - 1)/(output_size - 1). Belows are
75  // checking possible overflows.
76  const auto data_layout = input->data_layout();
79 
80  const auto input_width = input->dimension(width_index);
81  const auto input_height = input->dimension(height_index);
82  const auto output_width = output->dimension(width_index);
83  const auto output_height = output->dimension(height_index);
84 
85  ARM_COMPUTE_RETURN_ERROR_ON(input_width == 0 || input_height == 0 || output_width == 0 || output_height == 0);
86  ARM_COMPUTE_RETURN_ERROR_ON((output_width - 1 == 0) || (output_height - 1 == 0));
87  }
88 
89  float wr = 0.f;
90  float hr = 0.f;
91  std::tie(wr, hr) = calculate_scale_factors(*input, *output, align_corners);
92 
93  ARM_COMPUTE_RETURN_ERROR_ON(policy == InterpolationPolicy::AREA && (wr > 1.f || hr > 1.f));
94 
95  return Status{};
96 }
97 
98 std::pair<Status, Window> validate_and_configure_window(ITensorInfo *input, ITensorInfo *output, InterpolationPolicy policy, BorderMode border_mode, SamplingPolicy sampling_policy, BorderSize &border)
99 {
100  Window win{};
101  bool window_changed{};
102  unsigned int num_elems_processed_per_iteration = 0;
103  DataLayout data_layout = input->data_layout();
104 
105  switch(data_layout)
106  {
107  case DataLayout::NCHW:
108  {
110  {
111  border = BorderSize(0);
112  }
113 
115  // Configure kernel window
117  AccessWindowStatic input_access(input,
118  -border.left, -border.top,
119  input->dimension(0) + border.right,
120  input->dimension(1) + border.bottom);
122 
123  output_access.set_valid_region(win, calculate_valid_region_scale(*(input),
124  output->tensor_shape(),
125  policy,
126  sampling_policy,
128 
129  window_changed = update_window_and_padding(win, input_access, output_access);
130  }
131  break;
132  case DataLayout::NHWC:
133  {
135  // Configure kernel window
137  AccessWindowStatic input_access(input, -border.left, -border.top,
138  input->dimension(0) + border.right,
139  input->dimension(1) + border.bottom);
141  window_changed = update_window_and_padding(win, input_access, output_access);
142  output_access.set_valid_region(win, ValidRegion(Coordinates(), output->tensor_shape()));
143  }
144  break;
145  default:
146  ARM_COMPUTE_ERROR("Data layout not supported");
147  }
148 
149  Status err = (window_changed) ? ARM_COMPUTE_CREATE_ERROR(ErrorCode::RUNTIME_ERROR, "Insufficient Padding!") : Status{};
150  return std::make_pair(err, win);
151 }
152 } // namespace
153 
155 {
156  return BorderSize(1);
157 }
158 
160  BorderMode border_mode, SamplingPolicy sampling_policy, bool align_corners)
161 {
162  BorderSize border = BorderSize(1);
163  const bool is_align_corners = policy == InterpolationPolicy::BILINEAR
164  && sampling_policy == SamplingPolicy::TOP_LEFT
165  && align_corners;
166  ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, policy, is_align_corners));
167  ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window(input->clone().get(), output->clone().get(), policy, border_mode, sampling_policy, border).first);
168 
169  return Status{};
170 }
171 
173 {
174  return _input;
175 }
176 
178 {
179  return _output;
180 }
181 
183 {
185  && sampling_policy == SamplingPolicy::TOP_LEFT
186  && align_corners;
187 
188  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input->info(), output->info(), policy, _align_corners));
189 
190  _input = input;
191  _output = output;
194 
195  float wr = 0.f;
196  float hr = 0.f;
197  std::tie(wr, hr) = calculate_scale_factors(*input->info(), *output->info(), _align_corners);
198 
199  const bool call_quantized_kernel = is_data_type_quantized_asymmetric(input->info()->data_type()) && policy == InterpolationPolicy::BILINEAR;
200 
203  const bool is_nhwc = _data_layout == DataLayout::NHWC;
204 
205  // Compute actual border size
206  BorderSize border = border_size();
207 
208  // Area interpolation behaves as Nearest Neighbour in case of up-sampling
209  if(policy == InterpolationPolicy::AREA && wr <= 1.f && hr <= 1.f)
210  {
212  }
213 
214  // Configure kernel window
215  auto win_config = validate_and_configure_window(input->info(), output->info(), policy, border_mode, sampling_policy, border);
216  ARM_COMPUTE_ERROR_THROW_ON(win_config.first);
217  ICLKernel::configure_internal(win_config.second);
218 
219  // Create kernel
220  CLBuildOptions build_opts;
221  build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(input->info()->data_type()));
222  build_opts.add_option("-DBORDER_SIZE=" + support::cpp11::to_string(border.right));
223  build_opts.add_option_if(border_mode == BorderMode::REPLICATE, "-DBORDER_MODE_REPLICATE");
224  build_opts.add_option_if(is_nhwc, "-DDEPTH_OUT=" + support::cpp11::to_string(output->info()->dimension(2)));
225  build_opts.add_option_if_else(sampling_policy == SamplingPolicy::CENTER, "-DSAMPLING_POLICY_CENTER", "-DSAMPLING_POLICY_TOP_LEFT");
226  if(call_quantized_kernel)
227  {
229  build_opts.add_option("-DSCALE=" + support::cpp11::to_string(qinfo.scale));
230  build_opts.add_option("-DOFFSET=" + support::cpp11::to_string(qinfo.offset));
231  }
232 
233  std::string interpolation_name = string_from_interpolation_policy(policy);
234  std::transform(interpolation_name.begin(), interpolation_name.end(), interpolation_name.begin(), ::tolower);
235  std::string kernel_name = "scale_" + interpolation_name;
236  kernel_name += call_quantized_kernel ? "_quantized_" : "_";
238  _kernel = static_cast<cl::Kernel>(CLKernelLibrary::get().create_kernel(kernel_name, build_opts.options()));
239 
240  unsigned int idx = is_nhwc ? 2 * num_arguments_per_4D_tensor() : 2 * num_arguments_per_2D_tensor(); //Skip the input and output parameters
241 
242  const unsigned int input_width = input->info()->dimension(idx_width);
243  const unsigned int input_height = input->info()->dimension(idx_height);
244 
245  _kernel.setArg<float>(idx++, input_width);
246  _kernel.setArg<float>(idx++, input_height);
247  _kernel.setArg<float>(idx++, wr);
248  _kernel.setArg<float>(idx++, hr);
249 
250  // Set config_id for enabling LWS tuning
251  _config_id = "scale_";
252  _config_id += (border_mode == BorderMode::REPLICATE ? "Bord_rep" : "");
253  _config_id += (sampling_policy == SamplingPolicy::CENTER ? "center" : "topleft");
254  _config_id += (is_nhwc ? "nhwc" : "nchw");
255  _config_id += "_";
256  _config_id += support::cpp11::to_string(output->info()->dimension(0));
257  _config_id += "_";
258  _config_id += support::cpp11::to_string(output->info()->dimension(1));
259  _config_id += "_";
260  _config_id += support::cpp11::to_string(output->info()->dimension(2));
261  _config_id += "_";
262  _config_id += support::cpp11::to_string(output->info()->dimension(3));
263 }
264 
265 void CLScaleKernel::run(const Window &window, cl::CommandQueue &queue)
266 {
269 
270  switch(_data_layout)
271  {
272  case DataLayout::NCHW:
273  {
275 
276  do
277  {
278  unsigned int idx = 0;
279  add_2D_tensor_argument(idx, _input, slice);
280  add_2D_tensor_argument(idx, _output, slice);
281  enqueue(queue, *this, slice, lws_hint());
282  }
284  break;
285  }
286  case DataLayout::NHWC:
287  {
289  Window slice = collapsed.first_slice_window_4D();
290 
291  unsigned int idx = 0;
292  add_4D_tensor_argument(idx, _input, slice);
293  add_4D_tensor_argument(idx, _output, slice);
294  enqueue(queue, *this, slice, lws_hint());
295  break;
296  }
297  default:
298  ARM_COMPUTE_ERROR("Data layout not supported");
299  }
300 }
BorderMode
Methods available to handle borders.
Definition: Types.h:261
Window first_slice_window_2D() const
First 2D slice of the window.
Definition: Window.h:281
const std::vector< int32_t > & offset() const
Offset vector accessor.
unsigned int top
top of the border
Definition: Types.h:349
InterpolationPolicy
Interpolation method.
Definition: Types.h:366
#define ARM_COMPUTE_RETURN_ERROR_ON_F16_UNSUPPORTED(tensor)
Definition: CLValidate.h:34
const Window & window() const
The maximum window the kernel can be executed on.
Definition: IKernel.cpp:28
const DataLayout data_layout
Definition: Im2Col.cpp:146
virtual size_t dimension(size_t index) const =0
Return the size of the requested dimension.
Container for 2D border size.
Definition: Types.h:269
BorderSize border_size() const override
The size of the border for that kernel.
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:39
const StringSet & options() const
Gets the current options list set.
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(...)
Definition: Validate.h:545
#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:247
1 channel, 1 U8 per channel
#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_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(t, c,...)
Definition: Validate.h:792
1 channel, 1 F32 per channel
Output values are defined by bilinear interpolation between the pixels.
float calculate_resize_ratio(size_t input_size, size_t output_size, bool align_corners=false)
Returns resize ratio between input and output with consideration of aligned corners.
Definition: Utils.cpp: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
Quantization info when assuming per layer quantization.
unsigned int bottom
bottom of the border
Definition: Types.h:351
Status class.
Definition: Error.h:52
Output values are defined to match the source pixel whose center is nearest to the sample position.
std::string lower_string(const std::string &val)
Lower a given string.
Definition: Utils.cpp:333
#define ARM_COMPUTE_RETURN_ERROR_ON(cond)
If the condition is true, an error is returned.
Definition: Error.h:296
Window calculate_max_window(const ValidRegion &valid_region, const Steps &steps=Steps(), bool skip_border=false, BorderSize border_size=BorderSize())
Calculate the maximum window for a given tensor shape and border setting.
Definition: Helpers.cpp:28
bool slide_window_slice_2D(Window &slice) const
Slide the passed 2D window slice.
Definition: Window.h:321
Copyright (c) 2017-2020 ARM Limited.
1 channel, 1 F16 per channel
Samples are taken at pixel center.
Implementation of a static rectangular access pattern.
void add_option(std::string option)
Adds option to the existing build option list.
Window collapse(const Window &full_window, size_t first, size_t last=Coordinates::num_max_dimensions) const
Collapse the dimensions between first and last.
Definition: Window.inl:111
std::string tolower(std::string string)
Convert string to lower case.
Definition: Utility.h:203
bool update_window_and_padding(Window &win, Ts &&... patterns)
Update window and padding size for each of the access patterns.
Definition: Helpers.h:402
virtual const TensorShape & tensor_shape() const =0
Size for each dimension of the tensor.
static Status validate(const ITensorInfo *input, const ITensorInfo *output, InterpolationPolicy policy, BorderMode border_mode, SamplingPolicy sampling_policy=SamplingPolicy::CENTER, bool align_corners=false)
Static function to check if given info will lead to a valid configuration of CLScaleKernel.
quantized, asymmetric fixed-point 8-bit number unsigned
Class to describe a number of elements in each dimension.
Definition: Steps.h:40
Coordinates of an item.
Definition: Coordinates.h:37
Implementation of a row access pattern.
std::string kernel_name
const std::string & string_from_interpolation_policy(InterpolationPolicy policy)
Translates a given interpolation policy to a string.
Definition: Utils.cpp:219
UniformQuantizationInfo uniform() const
Return per layer quantization info.
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
virtual ITensorInfo * info() const =0
Interface to be implemented by the child class to return the tensor's metadata.
Samples are taken at pixel top left corner.
const std::vector< float > & scale() const
Scale vector accessor.
void add_option_if(bool cond, std::string option)
Adds option if a given condition is true;.
static constexpr unsigned int num_arguments_per_2D_tensor()
Returns the number of arguments enqueued per 2D tensor object.
Definition: ICLKernel.h:192
std::unique_ptr< Kernel > create_kernel()
Helper function to create and return a unique_ptr pointed to a CL/GLES kernel object.
Definition: Helpers.h:86
static constexpr unsigned int num_arguments_per_4D_tensor()
Returns the number of arguments enqueued per 4D tensor object.
Definition: ICLKernel.h:208
unsigned int left
left of the border
Definition: Types.h:352
const ICLTensor * output() const
Output tensor accessor.
virtual QuantizationInfo quantization_info() const =0
Get the quantization settings (scale and offset) of the tensor.
unsigned int right
right of the border
Definition: Types.h:350
1 channel, 1 S16 per channel
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_QUANTIZATION_INFO(...)
Definition: Validate.h:610
Output values are determined by averaging the source pixels whose areas fall under the area of the de...
Num samples, channels, height, width.
bool is_data_type_quantized_asymmetric(DataType dt)
Check if a given data type is of asymmetric quantized type.
Definition: Utils.h:1139
ValidRegion calculate_valid_region_scale(const ITensorInfo &src_info, const TensorShape &dst_shape, InterpolationPolicy interpolate_policy, SamplingPolicy sampling_policy, bool border_undefined)
Helper function to calculate the Valid Region for Scale.
Definition: Helpers.cpp:184
#define ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(...)
Definition: Validate.h:163
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:134
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:132
#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
Borders are left undefined.
Pixels outside the image are assumed to have the same value as the closest image pixel.
void configure(const ICLTensor *input, ICLTensor *output, InterpolationPolicy policy, BorderMode border_mode, SamplingPolicy sampling_policy=SamplingPolicy::CENTER, bool align_corners=false)
Initialise the kernel's inputs, output and interpolation policy.
const QuantizationInfo qinfo
Definition: Im2Col.cpp:150
Num samples, height, width, channels.
Window first_slice_window_4D() const
First 4D slice of the window.
Definition: Window.h:297
unsigned int num_elems_processed_per_iteration
void run(const Window &window, cl::CommandQueue &queue) override
Enqueue the OpenCL kernel to process the given window on the passed OpenCL command queue.
quantized, asymmetric fixed-point 8-bit number signed
Container for valid region of a window.
Definition: Types.h:184
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:327
const ICLTensor * input() const
Input tensor accessor.
#define ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(f, s)
Definition: Validate.h:205
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:168
DataLayout
[DataLayout enum definition]
Definition: Types.h:117
Describe a multidimensional execution window.
Definition: Window.h:39
#define ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(k)
Definition: Validate.h:941
SamplingPolicy
Available Sampling Policies.
Definition: Types.h:99
SimpleTensor< T > slice(const SimpleTensor< T > &src, Coordinates starts, Coordinates ends)
virtual DataLayout data_layout() const =0
Get the data layout of the tensor.
InterpolationPolicy _interpolationPolicy
Definition: CLScaleKernel.h:80
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.