Compute Library
 22.11
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 scale_x = arm_compute::scale_utils::calculate_resize_ratio(src_width, dst_width, align_corners);
54  float scale_y = arm_compute::scale_utils::calculate_resize_ratio(src_height, dst_height, align_corners);
55 
56  return std::make_pair(scale_x, scale_y);
57 }
58 
59 Status validate_arguments(const ITensorInfo *src, const ITensorInfo *dst, const ScaleKernelInfo &info)
60 {
66  ARM_COMPUTE_RETURN_ERROR_ON(dst == src);
69 
70  float scale_x = 0.f;
71  float scale_y = 0.f;
72  const DataLayout data_layout = info.data_layout == DataLayout::UNKNOWN ? src->data_layout() : info.data_layout;
73  std::tie(scale_x, scale_y) = calculate_scale_factors(src, dst, data_layout, info.align_corners);
74 
75  ARM_COMPUTE_RETURN_ERROR_ON(info.interpolation_policy == InterpolationPolicy::AREA && (scale_x > 1.f || scale_y > 1.f));
76 
77  return Status{};
78 }
79 } // namespace
80 
82 {
84  return Status{};
85 }
86 
88 {
90 }
91 
92 void ClScaleKernel::configure(const CLCompileContext &compile_context, ITensorInfo *src, ITensorInfo *dst, const ScaleKernelInfo &info)
93 {
95  auto padding_info = get_padding_info({ src, dst });
96 
97  // Info required for the static tuning
98  _data_layout = info.data_layout == DataLayout::UNKNOWN ? src->data_layout() : info.data_layout;
99 
100  const bool is_nhwc = _data_layout == DataLayout::NHWC;
101 
102  float scale_x = 0.f;
103  float scale_y = 0.f;
104  std::tie(scale_x, scale_y) = calculate_scale_factors(src, dst, _data_layout, info.align_corners);
105  const bool is_qasymm_bilinear = is_data_type_quantized_asymmetric(src->data_type()) && info.interpolation_policy == InterpolationPolicy::BILINEAR;
106 
107  // Area interpolation behaves as Nearest Neighbour in case of up-sampling
108  auto interpolation_policy_to_use = info.interpolation_policy;
109  if(info.interpolation_policy == InterpolationPolicy::AREA && scale_x <= 1.f && scale_y <= 1.f)
110  {
111  interpolation_policy_to_use = InterpolationPolicy::NEAREST_NEIGHBOR;
112  }
113 
114  // Create kernel
115  const int idx_width = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::WIDTH);
116  const int idx_height = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::HEIGHT);
117  const int idx_channel = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::CHANNEL);
118  const unsigned int src_width = src->dimension(idx_width);
119  const unsigned int src_height = src->dimension(idx_height);
120  const unsigned int dst_width = dst->dimension(idx_width);
121  const unsigned int dst_channels = dst->dimension(idx_channel);
122  unsigned int vec_size = 0;
123  unsigned int vec_size_leftover = 0;
124 
125  CLBuildOptions build_opts;
126  if(_data_layout == DataLayout::NHWC)
127  {
128  vec_size = adjust_vec_size(src->data_type() == DataType::F32 ? 4 : 8, dst_channels);
129  vec_size_leftover = dst_channels % vec_size;
130  build_opts.add_option("-DSRC_TENSOR_TYPE=BUFFER");
131  build_opts.add_option("-DSRC_DATA_TYPE=" + get_cl_type_from_data_type(src->data_type()));
132  build_opts.add_option("-DDST_TENSOR_TYPE=BUFFER");
133  build_opts.add_option("-DDST_DATA_TYPE=" + get_cl_type_from_data_type(dst->data_type()));
134  build_opts.add_option("-DCONSTANT_VALUE=" + string_from_pixel_value(info.constant_border_value, src->data_type()));
135  build_opts.add_option("-DN0=" + support::cpp11::to_string(vec_size));
136  build_opts.add_option("-DPARTIAL_N0=" + support::cpp11::to_string(vec_size_leftover));
137  build_opts.add_option("-DSCALE_" + string_from_interpolation_policy(interpolation_policy_to_use));
138  build_opts.add_option_if(src->num_dimensions() > 3, "-DBATCHED_EXECUTION");
139  build_opts.add_option_if(info.border_mode == BorderMode::REPLICATE, "-DBORDER_MODE_REPLICATE");
140  build_opts.add_option_if(info.border_mode == BorderMode::CONSTANT, "-DBORDER_MODE_CONSTANT");
141  build_opts.add_option_if(info.align_corners, "-DALIGN_CORNERS");
142  build_opts.add_option_if(is_data_type_float(src->data_type()), "-DIS_FLOATING_POINT");
143  build_opts.add_option_if_else(info.sampling_policy == SamplingPolicy::CENTER, "-DSAMPLING_POLICY_CENTER", "-DSAMPLING_POLICY_TOP_LEFT");
144  if(is_qasymm_bilinear)
145  {
147  build_opts.add_option("-DSCALE=" + support::cpp11::to_string(qinfo.scale));
148  build_opts.add_option("-DOFFSET=" + support::cpp11::to_string(qinfo.offset));
149  }
150  else
151  {
152  build_opts.add_option("-DSCALE=" + support::cpp11::to_string(1));
153  build_opts.add_option("-DOFFSET=" + support::cpp11::to_string(0));
154  }
155  }
156  else if(_data_layout == DataLayout::NCHW)
157  {
158  vec_size = adjust_vec_size(4, dst_width);
159  vec_size_leftover = dst_width % vec_size;
160  build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(src->data_type()));
161  build_opts.add_option("-DCONSTANT_VALUE=" + string_from_pixel_value(info.constant_border_value, src->data_type()));
162  build_opts.add_option("-DSRC_WIDTH=" + support::cpp11::to_string(src_width));
163  build_opts.add_option("-DSRC_HEIGHT=" + support::cpp11::to_string(src_height));
164  build_opts.add_option("-DSCALE_X=" + float_to_string_with_full_precision(scale_x));
165  build_opts.add_option("-DSCALE_Y=" + float_to_string_with_full_precision(scale_y));
166  build_opts.add_option("-DVEC_SIZE=" + support::cpp11::to_string(vec_size));
167  build_opts.add_option("-DVEC_SIZE_LEFTOVER=" + ((vec_size_leftover == 0) ? support::cpp11::to_string(vec_size) : support::cpp11::to_string(vec_size_leftover)));
168  build_opts.add_option_if(info.border_mode == BorderMode::REPLICATE, "-DBORDER_MODE_REPLICATE");
169  build_opts.add_option_if(info.border_mode == BorderMode::CONSTANT, "-DBORDER_MODE_CONSTANT");
170  build_opts.add_option_if(info.align_corners, "-DALIGN_CORNERS");
171  build_opts.add_option_if_else(info.sampling_policy == SamplingPolicy::CENTER, "-DSAMPLING_POLICY_CENTER", "-DSAMPLING_POLICY_TOP_LEFT");
172  if(is_qasymm_bilinear)
173  {
175  build_opts.add_option("-DSCALE=" + support::cpp11::to_string(qinfo.scale));
176  build_opts.add_option("-DOFFSET=" + support::cpp11::to_string(qinfo.offset));
177  }
178  }
179  else
180  {
181  ARM_COMPUTE_ERROR_ON("Unsupported data layout");
182  }
183 
184  std::string interpolation_name = string_from_interpolation_policy(interpolation_policy_to_use);
185  std::transform(interpolation_name.begin(), interpolation_name.end(), interpolation_name.begin(), ::tolower);
186  std::string kernel_name = "scale_" + interpolation_name + "_";
187  kernel_name += lower_string(string_from_data_layout(_data_layout));
188 
189  _kernel = create_kernel(compile_context, kernel_name, build_opts.options());
190 
191  // Configure kernel window
192  Window win = calculate_max_window(*dst, Steps(vec_size));
193  ICLKernel::configure_internal(win);
194 
196 
197  // Pass scale kernel arguments
198  if(is_nhwc)
199  {
200  unsigned int idx = 2 * num_arguments_per_4d_tensor_nhwc();
201  _kernel.setArg<cl_float>(idx++, scale_x);
202  _kernel.setArg<cl_float>(idx++, scale_y);
203  }
204  // Set config_id for enabling LWS tuning
205  _config_id = "scale_";
206  _config_id += (info.border_mode == BorderMode::REPLICATE ? "Bord_rep" : "");
207  _config_id += (info.sampling_policy == SamplingPolicy::CENTER ? "center" : "topleft");
208  _config_id += (is_nhwc ? "nhwc" : "nchw");
209  _config_id += "_";
210  _config_id += support::cpp11::to_string(dst->dimension(0));
211  _config_id += "_";
212  _config_id += support::cpp11::to_string(dst->dimension(1));
213  _config_id += "_";
214  _config_id += support::cpp11::to_string(dst->dimension(2));
215  _config_id += "_";
216  _config_id += support::cpp11::to_string(dst->dimension(3));
217 }
218 
219 void ClScaleKernel::run_op(ITensorPack &tensors, const Window &window, cl::CommandQueue &queue)
220 {
223 
224  auto src = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC));
225  auto dst = utils::cast::polymorphic_downcast<ICLTensor *>(tensors.get_tensor(TensorType::ACL_DST));
226 
227  switch(_data_layout)
228  {
229  case DataLayout::NCHW:
230  {
232 
233  do
234  {
235  unsigned int idx = 0;
236  add_2D_tensor_argument(idx, src, slice);
237  add_2D_tensor_argument(idx, dst, slice);
238  enqueue(queue, *this, slice, lws_hint());
239  }
240  while(window.slide_window_slice_2D(slice));
241  break;
242  }
243  case DataLayout::NHWC:
244  {
245  Window collapsed = window.collapse(ICLKernel::window(), Window::DimZ);
246  Window slice = collapsed.first_slice_window_4D();
247 
248  unsigned int idx = 0;
249  add_4d_tensor_nhwc_argument(idx, src);
250  add_4d_tensor_nhwc_argument(idx, dst);
251  enqueue(queue, *this, slice, lws_hint());
252  break;
253  }
254  default:
255  ARM_COMPUTE_ERROR("Data layout not supported");
256  }
257 }
258 } // namespace kernels
259 } // namespace opencl
260 } // namespace arm_compute
void add_4d_tensor_nhwc_argument(unsigned int &idx, const ICLTensor *tensor)
Add the passed NHWC 4D tensor&#39;s parameters to the object&#39;s kernel&#39;s arguments by passing strides...
Definition: ICLKernel.cpp:144
bool is_data_type_quantized(DataType dt)
Check if a given data type is of quantized type.
Definition: Utils.h:1030
Window first_slice_window_2D() const
First 2D slice of the window.
Definition: Window.h:297
BorderMode border_mode
Border mode policy.
virtual size_t num_dimensions() const =0
The number of dimensions of the tensor (rank)
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
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:383
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:275
#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
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:353
Status validate_arguments(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *dst, const PadStrideInfo &conv_info)
#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:337
Copyright (c) 2017-2022 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:49
#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
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:404
SamplingPolicy sampling_policy
Sampling policy used by the interpolation.
std::string float_to_string_with_full_precision(float val)
Create a string with the float in full precision.
Definition: Utils.h:1124
quantized, asymmetric fixed-point 8-bit number unsigned
Class to describe a number of elements in each dimension.
Definition: Steps.h:40
const std::string & string_from_interpolation_policy(InterpolationPolicy policy)
Translates a given interpolation policy to a string.
Definition: Utils.cpp:189
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
void add_option_if(bool cond, std::string option)
Adds option if a given condition is true;.
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.
Elementwise CL kernel type.
Definition: CLTypes.h:85
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:603
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:1052
static constexpr unsigned int num_arguments_per_4d_tensor_nhwc()
Returns the number of arguments enqueued per NHWC 4D Tensor object.
Definition: ICLKernel.h:279
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:202
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
static constexpr size_t DimZ
Alias for dimension 2 also known as Z dimension.
Definition: Window.h:47
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
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:588
Window first_slice_window_4D() const
First 4D slice of the window.
Definition: Window.h:313
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:31
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:1222
quantized, asymmetric fixed-point 8-bit number signed
DataLayout data_layout
Data layout to use.
std::string kernel_name
DataLayout
[DataLayout enum definition]
Definition: Types.h:113
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:1010
#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.