Compute Library
 21.08
CLNormalizePlanarYUVLayerKernel.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2018-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 *output, const ITensorInfo *mean, const ITensorInfo *std)
44 {
48 
51  ARM_COMPUTE_RETURN_ERROR_ON_MSG(mean->num_dimensions() > 1, "mean and std must be vectors");
52 
53  const unsigned int channel_idx = get_data_layout_dimension_index(input->data_layout(), DataLayoutDimension::CHANNEL);
54  ARM_COMPUTE_RETURN_ERROR_ON(input->dimension(channel_idx) != mean->dimension(0));
55 
56  // Checks performed when output is configured
57  if(output->total_size() != 0)
58  {
62  }
63 
64  return Status{};
65 }
66 
67 std::pair<Status, Window> validate_and_configure_window_nchw(ITensorInfo *input, ITensorInfo *output)
68 {
69  const unsigned int num_elems_processed_per_iteration = 16 / input->element_size();
70 
71  Window win = calculate_max_window(*input, Steps(num_elems_processed_per_iteration));
72 
73  AccessWindowHorizontal input_access(input, 0, num_elems_processed_per_iteration);
74  AccessWindowHorizontal output_access(output, 0, num_elems_processed_per_iteration);
75 
76  bool window_changed = update_window_and_padding(win, input_access, output_access);
77 
78  Status err = (window_changed) ? ARM_COMPUTE_CREATE_ERROR(ErrorCode::RUNTIME_ERROR, "Insufficient Padding!") : Status{};
79  return std::make_pair(err, win);
80 }
81 } // namespace
82 
84  : _input(nullptr), _output(nullptr), _mean(nullptr), _std(nullptr)
85 {
87 }
88 
89 void CLNormalizePlanarYUVLayerKernel::configure(const ICLTensor *input, ICLTensor *output, const ICLTensor *mean, const ICLTensor *std)
90 {
91  configure(CLKernelLibrary::get().get_compile_context(), input, output, mean, std);
92 }
93 
94 void CLNormalizePlanarYUVLayerKernel::configure(const CLCompileContext &compile_context, const ICLTensor *input, ICLTensor *output, const ICLTensor *mean, const ICLTensor *std)
95 {
96  // Perform validation step
97  ARM_COMPUTE_ERROR_ON_NULLPTR(input, output, mean, std);
98  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input->info(), output->info(), mean->info(), std->info()));
99 
100  // Output tensor auto initialization if not yet initialized
101  auto_init_if_empty(*output->info(), *input->info()->clone());
102 
103  auto padding_info = get_padding_info({ input, output });
104 
105  _input = input;
106  _output = output;
107  _mean = mean;
108  _std = std;
109 
110  const DataLayout data_layout = input->info()->data_layout();
111 
112  // Get number of elements to process per iterations
113  const unsigned int num_elems_processed_per_iteration = (data_layout == DataLayout::NHWC) ? adjust_vec_size(16 / input->info()->element_size(),
114  input->info()->dimension(0)) :
115  (16 / input->info()->element_size());
116  const unsigned int channel_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::CHANNEL);
117  const DataType dt = input->info()->data_type();
118 
119  // Set build options
120  CLBuildOptions build_opts;
121  build_opts.add_option(("-DDATA_TYPE=" + get_cl_type_from_data_type(dt)));
122  build_opts.add_option(("-DVEC_SIZE=" + support::cpp11::to_string(num_elems_processed_per_iteration)));
123  build_opts.add_option(("-DVEC_SIZE_LEFTOVER=" + support::cpp11::to_string(input->info()->dimension(0) % num_elems_processed_per_iteration)));
124  build_opts.add_option(("-DNUM_CHANNELS=" + support::cpp11::to_string(input->info()->dimension(channel_idx))));
125 
126  std::string kernel_name = "normalize_planar_yuv_layer_";
127  if(is_data_type_quantized(dt))
128  {
130  build_opts.add_option(("-DOFFSET=" + support::cpp11::to_string(qinfo.offset)));
131  build_opts.add_option(("-DSCALE=" + support::cpp11::to_string(qinfo.scale)));
132  kernel_name += "q8_";
133  }
134 
135  // Create kernel
136  kernel_name += lower_string(string_from_data_layout(data_layout));
137  _kernel = create_kernel(compile_context, kernel_name, build_opts.options());
138 
139  // Configure kernel window
140  if(data_layout == DataLayout::NHWC)
141  {
142  Window win = calculate_max_window(*input->info(), Steps(num_elems_processed_per_iteration));
143  ICLKernel::configure_internal(win);
145  }
146  else
147  {
148  auto win_config = validate_and_configure_window_nchw(input->info(), output->info());
149  ARM_COMPUTE_ERROR_THROW_ON(win_config.first);
150  ICLKernel::configure_internal(win_config.second);
151  }
152 
153  // Set config_id for enabling LWS tuning
154  _config_id = "normalize_planar_yuv_layer_";
155  _config_id += lower_string(string_from_data_layout(input->info()->data_layout()));
156  _config_id += "_";
157  _config_id += lower_string(string_from_data_type(dt));
158  _config_id += "_";
159  _config_id += support::cpp11::to_string(input->info()->dimension(0));
160  _config_id += "_";
161  _config_id += support::cpp11::to_string(input->info()->dimension(1));
162  _config_id += "_";
163  _config_id += support::cpp11::to_string(input->info()->dimension(2));
164 }
165 
167 {
168  ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, mean, std));
169  if(input->data_layout() == DataLayout::NCHW)
170  {
171  ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window_nchw(input->clone().get(), output->clone().get()).first);
172  }
173  return Status{};
174 }
175 
176 void CLNormalizePlanarYUVLayerKernel::run(const Window &window, cl::CommandQueue &queue)
177 {
180 
182  Window slice = collapsed.first_slice_window_3D();
183 
184  Window slice_in = collapsed.first_slice_window_1D();
185  slice_in.set(Window::DimX, Window::Dimension(0, 0, 0));
186 
187  unsigned int idx = 2 * num_arguments_per_3D_tensor();
188  add_1D_tensor_argument(idx, _mean, slice_in);
189  add_1D_tensor_argument(idx, _std, slice_in);
190 
191  do
192  {
193  idx = 0;
194  add_3D_tensor_argument(idx, _input, slice);
195  add_3D_tensor_argument(idx, _output, slice);
196  enqueue(queue, *this, slice, lws_hint());
197  }
198  while(collapsed.slide_window_slice_3D(slice));
199 }
200 } // namespace arm_compute
bool is_data_type_quantized(DataType dt)
Check if a given data type is of quantized type.
Definition: Utils.h:981
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
void run(const Window &window, cl::CommandQueue &queue) override
Enqueue the OpenCL kernel to process the given window on the passed OpenCL command queue...
static Status validate(const ITensorInfo *input, const ITensorInfo *output, const ITensorInfo *mean, const ITensorInfo *std)
Static function to check if given info will lead to a valid configuration of CLNormalizePlanarYUVLaye...
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.
cl::NDRange lws_hint() const
Return the Local-Workgroup-Size hint.
Definition: ICLKernel.h:318
#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
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
Quantization info when assuming per layer quantization.
Describe one of the image&#39;s dimensions with a start, end and step.
Definition: Window.h:77
Manages all the OpenCL kernels compilation and caching, provides accessors for the OpenCL Context...
Status class.
Definition: Error.h:52
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
void add_3D_tensor_argument(unsigned int &idx, const ICLTensor *tensor, const Window &window)
Add the passed 3D tensor&#39;s parameters to the object&#39;s kernel&#39;s arguments starting from the index idx...
Definition: ICLKernel.h:214
Copyright (c) 2017-2021 Arm Limited.
1 channel, 1 F16 per channel
DataType dt
#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.
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
const std::string & string_from_data_type(DataType dt)
Convert a data type identity into a string.
Definition: Utils.cpp:135
static constexpr size_t DimX
Alias for dimension 0 also known as X dimension.
Definition: Window.h:43
bool update_window_and_padding(Window &win, Ts &&... patterns)
Update window and padding size for each of the access patterns.
Definition: WindowHelpers.h:46
static constexpr unsigned int num_arguments_per_3D_tensor()
Returns the number of arguments enqueued per 3D tensor object.
Definition: ICLKernel.h:256
Window collapse_if_possible(const Window &full_window, size_t first, size_t last, bool *has_collapsed=nullptr) const
Collapse the dimensions between first and last if possible.
Definition: Window.inl:68
quantized, asymmetric fixed-point 8-bit number unsigned
Class to describe a number of elements in each dimension.
Definition: Steps.h:40
void configure(const ICLTensor *input, ICLTensor *output, const ICLTensor *mean, const ICLTensor *std)
Set the input and output tensors.
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
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.
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
Elementeise CL kernel type.
Definition: CLTypes.h:84
bool slide_window_slice_3D(Window &slice) const
Slide the passed 3D window slice.
Definition: Window.h:335
virtual QuantizationInfo quantization_info() const =0
Get the quantization settings (scale and offset) of the tensor.
#define ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(k)
Definition: Validate.h:915
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.
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:123
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(...)
Definition: Validate.h:439
#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
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
#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:157
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:1171
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
void add_1D_tensor_argument(unsigned int &idx, const ICLTensor *tensor, const Window &window)
Add the passed 1D tensor&#39;s parameters to the object&#39;s kernel&#39;s arguments starting from the index idx...
Definition: ICLKernel.h:166
Window first_slice_window_3D() const
First 3D slice of the window.
Definition: Window.h:291
std::string kernel_name
DataType
Available data types.
Definition: Types.h:77
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
Window first_slice_window_1D() const
First 1D slice of the window.
Definition: Window.h:275
SimpleTensor< T > slice(const SimpleTensor< T > &src, Coordinates starts, Coordinates ends)
virtual DataLayout data_layout() const =0
Get the data layout of the tensor.