Compute Library
 21.08
ClScaleKernel.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2016-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 
29 #include "src/core/CL/CLValidate.h"
32 #include "support/Cast.h"
33 
34 namespace arm_compute
35 {
36 namespace opencl
37 {
38 namespace kernels
39 {
40 namespace
41 {
42 inline std::pair<float, float> calculate_scale_factors(const ITensorInfo *src, const ITensorInfo *dst, DataLayout data_layout, bool align_corners)
43 {
46 
47  // Compute the ratio between source width/height and destination width/height
48  const unsigned int src_width = src->dimension(idx_width);
49  const unsigned int src_height = src->dimension(idx_height);
50  const unsigned int dst_width = dst->dimension(idx_width);
51  const unsigned int dst_height = dst->dimension(idx_height);
52 
53  float wr = arm_compute::scale_utils::calculate_resize_ratio(src_width, dst_width, align_corners);
54  float hr = arm_compute::scale_utils::calculate_resize_ratio(src_height, dst_height, align_corners);
55 
56  return std::make_pair(wr, hr);
57 }
58 
59 Status validate_arguments(const ITensorInfo *src, const ITensorInfo *dst, const ScaleKernelInfo &info)
60 {
66  ARM_COMPUTE_RETURN_ERROR_ON(dst == src);
68 
69  float wr = 0.f;
70  float hr = 0.f;
71  const DataLayout data_layout = info.data_layout == DataLayout::UNKNOWN ? src->data_layout() : info.data_layout;
72  std::tie(wr, hr) = calculate_scale_factors(src, dst, data_layout, info.align_corners);
73 
74  ARM_COMPUTE_RETURN_ERROR_ON(info.interpolation_policy == InterpolationPolicy::AREA && (wr > 1.f || hr > 1.f));
75 
76  return Status{};
77 }
78 
79 std::pair<Status, Window> validate_and_configure_window(ITensorInfo *src, ITensorInfo *dst, const ScaleKernelInfo &info, BorderSize &border)
80 {
81  Window win{};
82  bool window_changed{};
83  unsigned int num_elems_processed_per_iteration = 0;
84  const DataLayout data_layout = info.data_layout == DataLayout::UNKNOWN ? src->data_layout() : info.data_layout;
85 
86  switch(data_layout)
87  {
88  case DataLayout::NCHW:
89  {
90  if(info.border_mode == BorderMode::UNDEFINED)
91  {
92  border = BorderSize(0);
93  }
94 
95  num_elems_processed_per_iteration = 4;
96  // Configure kernel window
97  win = calculate_max_window(*dst, Steps(num_elems_processed_per_iteration));
98  AccessWindowStatic input_access(src,
99  -border.left, -border.top,
100  src->dimension(0) + border.right,
101  src->dimension(1) + border.bottom);
102  AccessWindowHorizontal output_access(dst, 0, num_elems_processed_per_iteration);
103 
104  output_access.set_valid_region(win, calculate_valid_region_scale(*src,
105  dst->tensor_shape(),
106  info.interpolation_policy,
107  info.sampling_policy,
108  info.border_mode == BorderMode::UNDEFINED));
109 
110  window_changed = update_window_and_padding(win, input_access, output_access);
111  }
112  break;
113  case DataLayout::NHWC:
114  {
115  // Configure kernel window
116  win = calculate_max_window(*dst, Steps());
117  }
118  break;
119  default:
120  ARM_COMPUTE_ERROR("Data layout not supported");
121  }
122 
123  Status err = (window_changed) ? ARM_COMPUTE_CREATE_ERROR(ErrorCode::RUNTIME_ERROR, "Insufficient Padding!") : Status{};
124  return std::make_pair(err, win);
125 }
126 } // namespace
127 
129 {
130  return BorderSize(static_cast<size_t>(_data_layout == DataLayout::NCHW));
131 }
132 
134 {
135  ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(src, dst, info));
136  const DataLayout data_layout = info.data_layout == DataLayout::UNKNOWN ? src->data_layout() : info.data_layout;
137  BorderSize border = BorderSize(static_cast<size_t>(data_layout == DataLayout::NCHW));
138  ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window(src->clone().get(), dst->clone().get(), info, border).first);
139 
140  return Status{};
141 }
142 
144 {
146 }
147 
148 void ClScaleKernel::configure(const CLCompileContext &compile_context, ITensorInfo *src, ITensorInfo *dst, const ScaleKernelInfo &info)
149 {
150  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(src, dst, info));
151  auto padding_info = get_padding_info({ src, dst });
152 
153  // Info required for the static tuning
154  _data_layout = info.data_layout == DataLayout::UNKNOWN ? src->data_layout() : info.data_layout;
155 
156  float wr = 0.f;
157  float hr = 0.f;
158  std::tie(wr, hr) = calculate_scale_factors(src, dst, _data_layout, info.align_corners);
159  const bool call_quantized_kernel = is_data_type_quantized_asymmetric(src->data_type()) && info.interpolation_policy == InterpolationPolicy::BILINEAR;
160 
161  // Compute actual border size
162  BorderSize border = border_size();
163  const bool is_nhwc = _data_layout == DataLayout::NHWC;
164 
165  // Area interpolation behaves as Nearest Neighbour in case of up-sampling
166  auto interpolation_policy_to_use = info.interpolation_policy;
167  if(info.interpolation_policy == InterpolationPolicy::AREA && wr <= 1.f && hr <= 1.f)
168  {
169  interpolation_policy_to_use = InterpolationPolicy::NEAREST_NEIGHBOR;
170  }
171 
172  // Configure kernel window
173  auto win_config = validate_and_configure_window(src, dst, info, border);
174  ARM_COMPUTE_ERROR_THROW_ON(win_config.first);
175  ICLKernel::configure_internal(win_config.second);
176 
177  // Create kernel
178  CLBuildOptions build_opts;
179  build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(src->data_type()));
180  build_opts.add_option("-DCONSTANT_VALUE=" + string_from_pixel_value(info.constant_border_value, src->data_type()));
181  build_opts.add_option("-DBORDER_SIZE=" + support::cpp11::to_string(border.right));
182  build_opts.add_option_if(info.border_mode == BorderMode::REPLICATE, "-DBORDER_MODE_REPLICATE");
183  build_opts.add_option_if(is_nhwc, "-DDEPTH_OUT=" + support::cpp11::to_string(dst->dimension(2)));
184  build_opts.add_option_if_else(info.sampling_policy == SamplingPolicy::CENTER, "-DSAMPLING_POLICY_CENTER", "-DSAMPLING_POLICY_TOP_LEFT");
185  build_opts.add_option_if(info.align_corners, "-DALIGN_CORNERS");
186  if(call_quantized_kernel)
187  {
189  build_opts.add_option("-DSCALE=" + support::cpp11::to_string(qinfo.scale));
190  build_opts.add_option("-DOFFSET=" + support::cpp11::to_string(qinfo.offset));
191  }
192  std::string interpolation_name = string_from_interpolation_policy(interpolation_policy_to_use);
193  std::transform(interpolation_name.begin(), interpolation_name.end(), interpolation_name.begin(), ::tolower);
194  std::string kernel_name = "scale_" + interpolation_name;
195  kernel_name += call_quantized_kernel ? "_quantized_" : "_";
196  kernel_name += lower_string(string_from_data_layout(_data_layout));
197 
198  _kernel = create_kernel(compile_context, kernel_name, build_opts.options());
199  if(is_nhwc)
200  {
202  }
203 
204  const int idx_width = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::WIDTH);
205  const int idx_height = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::HEIGHT);
206  unsigned int idx = is_nhwc ? 2 * num_arguments_per_4D_tensor() : 2 * num_arguments_per_2D_tensor(); //Skip the input and output parameters
207  const unsigned int src_width = src->dimension(idx_width);
208  const unsigned int dst_height = src->dimension(idx_height);
209 
210  _kernel.setArg<float>(idx++, src_width);
211  _kernel.setArg<float>(idx++, dst_height);
212  _kernel.setArg<float>(idx++, wr);
213  _kernel.setArg<float>(idx++, hr);
214 
215  // Set config_id for enabling LWS tuning
216  _config_id = "scale_";
217  _config_id += (info.border_mode == BorderMode::REPLICATE ? "Bord_rep" : "");
218  _config_id += (info.sampling_policy == SamplingPolicy::CENTER ? "center" : "topleft");
219  _config_id += (is_nhwc ? "nhwc" : "nchw");
220  _config_id += "_";
221  _config_id += support::cpp11::to_string(dst->dimension(0));
222  _config_id += "_";
223  _config_id += support::cpp11::to_string(dst->dimension(1));
224  _config_id += "_";
225  _config_id += support::cpp11::to_string(dst->dimension(2));
226  _config_id += "_";
227  _config_id += support::cpp11::to_string(dst->dimension(3));
228 }
229 
230 void ClScaleKernel::run_op(ITensorPack &tensors, const Window &window, cl::CommandQueue &queue)
231 {
234 
235  auto src = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC));
236  auto dst = utils::cast::polymorphic_downcast<ICLTensor *>(tensors.get_tensor(TensorType::ACL_DST));
237 
238  switch(_data_layout)
239  {
240  case DataLayout::NCHW:
241  {
243 
244  do
245  {
246  unsigned int idx = 0;
247  add_2D_tensor_argument(idx, src, slice);
248  add_2D_tensor_argument(idx, dst, slice);
249  enqueue(queue, *this, slice, lws_hint());
250  }
251  while(window.slide_window_slice_2D(slice));
252  break;
253  }
254  case DataLayout::NHWC:
255  {
256  Window collapsed = window.collapse(ICLKernel::window(), Window::DimZ);
257  Window slice = collapsed.first_slice_window_4D();
258 
259  unsigned int idx = 0;
260  add_4D_tensor_argument(idx, src, slice);
261  add_4D_tensor_argument(idx, dst, slice);
262  enqueue(queue, *this, slice, lws_hint());
263  break;
264  }
265  default:
266  ARM_COMPUTE_ERROR("Data layout not supported");
267  }
268 }
269 } // namespace kernels
270 } // namespace opencl
271 } // namespace arm_compute
Window first_slice_window_2D() const
First 2D slice of the window.
Definition: Window.h:283
BorderMode border_mode
Border mode policy.
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
InterpolationPolicy interpolation_policy
Interpolation type to use.
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
Container for 2D border size.
Definition: Types.h:264
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.
#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:318
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.
1 channel, 1 F32 per channel
Output values are defined by bilinear interpolation between the pixels.
std::string string_from_pixel_value(const PixelValue &value, const DataType data_type)
Convert a PixelValue to a string, represented through the specific data type.
Definition: Utils.cpp:248
#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
const DataLayout data_layout
Definition: Im2Col.cpp:151
bool align_corners
Align corners of input and output.
Store the tensor&#39;s metadata.
Definition: ITensorInfo.h:40
#define ARM_COMPUTE_ERROR_THROW_ON(status)
Definition: Error.h:455
Quantization info when assuming per layer quantization.
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:326
#define ARM_COMPUTE_RETURN_ERROR_ON(cond)
If the condition is true, an error is returned.
Definition: Error.h:296
SimpleTensor< float > src
Definition: DFT.cpp:155
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
Samples are taken at pixel center.
bool is_align_corners_allowed_sampling_policy(SamplingPolicy sampling_policy)
Returns if aligned corners are allowed for the given sampling policy.
Definition: ScaleUtils.h:52
#define ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(...)
Definition: Validate.h:159
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
const ITensor * get_const_tensor(int id) const
Get constant tensor of a given id.
Definition: ITensorPack.cpp:54
std::string tolower(std::string string)
Convert string to lower case.
Definition: Utility.h:205
BorderSize border_size() const override
The size of the border for that kernel.
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
bool update_window_and_padding(Window &win, Ts &&... patterns)
Update window and padding size for each of the access patterns.
Definition: WindowHelpers.h:46
SamplingPolicy sampling_policy
Sampling policy used by the interpolation.
quantized, asymmetric fixed-point 8-bit number unsigned
const std::string & string_from_interpolation_policy(InterpolationPolicy policy)
Translates a given interpolation policy to a string.
Definition: Utils.cpp:187
unsigned int num_elems_processed_per_iteration
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:39
virtual std::unique_ptr< T > clone() const =0
Provide a clone of the current object of class T.
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:248
static Status validate(const ITensorInfo *src, const ITensorInfo *dst, const ScaleKernelInfo &info)
Static function to check if given info will lead to a valid configuration.
static constexpr unsigned int num_arguments_per_4D_tensor()
Returns the number of arguments enqueued per 4D tensor object.
Definition: ICLKernel.h:264
Elementeise CL kernel type.
Definition: CLTypes.h:84
virtual QuantizationInfo quantization_info() const =0
Get the quantization settings (scale and offset) of the tensor.
void run_op(ITensorPack &tensors, const Window &window, cl::CommandQueue &queue) override
Enqueue the OpenCL kernel to process the given window on the passed OpenCL command queue...
void configure(const CLCompileContext &compile_context, ITensorInfo *src, ITensorInfo *dst, const ScaleKernelInfo &info)
Initialise the kernel&#39;s inputs, output and interpolation policy.
#define ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(k)
Definition: Validate.h:915
1 channel, 1 S16 per channel
Output values are determined by averaging the source pixels whose areas fall under the area of the de...
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
Num samples, channels, height, width.
CLCompileContext class.
bool is_data_type_quantized_asymmetric(DataType dt)
Check if a given data type is of asymmetric quantized type.
Definition: Utils.h:1003
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:28
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:190
ScaleKernelInfo info(interpolation_policy, default_border_mode, PixelValue(), sampling_policy, false)
ITensor * get_tensor(int id)
Get tensor of a given id from the pac.
Definition: ITensorPack.cpp:64
const std::string & string_from_data_layout(DataLayout dl)
Convert a data layout identity into a string.
Definition: Utils.cpp:123
#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.
const QuantizationInfo qinfo
Definition: Im2Col.cpp:155
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(...)
Definition: Validate.h:541
Num samples, height, width, channels.
#define ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(t, c,...)
Definition: Validate.h:788
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
Window first_slice_window_4D() const
First 4D slice of the window.
Definition: Window.h:299
Tensor packing service.
Definition: ITensorPack.h:39
PixelValue constant_border_value
Constant value to use for constant border mode policy.
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: ScaleUtils.cpp:27
quantized, asymmetric fixed-point 8-bit number signed
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
DataLayout data_layout
Data layout to use.
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:111
Describe a multidimensional execution window.
Definition: Window.h:39
#define ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(f, s)
Definition: Validate.h:201
SimpleTensor< T > slice(const SimpleTensor< T > &src, Coordinates starts, Coordinates ends)
virtual DataLayout data_layout() const =0
Get the data layout of the tensor.
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.