Compute Library
 21.11
CLNormalizationLayerKernel.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2017-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"
34 #include "src/core/CL/CLValidate.h"
38 #include "support/StringSupport.h"
39 
40 namespace arm_compute
41 {
42 namespace
43 {
44 Status validate_arguments(const ITensorInfo *input, const ITensorInfo *output, NormalizationLayerInfo norm_info)
45 {
50 
51  ARM_COMPUTE_RETURN_ERROR_ON_MSG(!(norm_info.norm_size() % 2), "Normalization size should be odd");
52 
53  // Checks performed when output is configured
54  if(output->total_size() != 0)
55  {
59  }
60 
61  return Status{};
62 }
63 
64 std::pair<Status, Window> validate_and_configure_window(ITensorInfo *input, ITensorInfo *output, NormalizationLayerInfo norm_info)
65 {
66  // Output tensor auto initialization if not yet initialized
67  auto_init_if_empty(*output, *input->clone());
68 
69  bool window_changed = false;
70  Window win;
71  const DataLayout data_layout = input->data_layout();
72  if(data_layout == DataLayout::NCHW)
73  {
74  const unsigned int vec_size_x = adjust_vec_size(max_cl_vector_width / input->element_size(), input->dimension(0));
75  const unsigned int norm_idx = get_normalization_dimension_index(input->data_layout(), norm_info);
76  const bool is_norm_across_width = norm_idx == 0;
77 
78  const unsigned int norm_radius = norm_info.norm_size() / 2;
79  // Border / padding calculation:
80  // For NCHW no border handling is impelmeneted in the kernel in the x axis.
81  // This means the x axis is fully-padded depending on vec_size_x and norm_size
82  // E.G. for input x dimension = 3, norm_size = 3 (radius = 1), vec_size_x = 2 ('#' is element 'p' is padding):
83  // In : |p|#|#|#|p|p|
84  // Out: |#|#|#|p|
85  // The output has 1 right padding because of the vec_size_x.
86  // The input has 1 left padding because radius = 1.
87  // The input has 2 right padding because of radius = 1 AND because of the extra output padding
88  const unsigned int border_width_left = is_norm_across_width ? norm_radius : 0;
89  const unsigned int border_width_right = is_norm_across_width ? norm_radius + (vec_size_x - input->dimension(0) % vec_size_x) : 0;
90  const BorderSize border_size = BorderSize(0, border_width_right, 0, border_width_left);
91 
92  win = calculate_max_window(*input, Steps(vec_size_x));
93 
94  // We do not use a Rectangle window for IN_MAP_2D as we clamp the top and bottom accesses inside the kernel, avoiding padding
95  // Reads can occur within the valid region of the input
96  if(is_norm_across_width)
97  {
98  AccessWindowStatic input_access(input, -border_size.left, 0, input->dimension(0) + border_size.right, 0);
99  window_changed = window_changed || update_window_and_padding(win, input_access);
100  }
101  else
102  {
103  AccessWindowHorizontal input_access(input, -border_size.left, vec_size_x);
104  window_changed = window_changed || update_window_and_padding(win, input_access);
105  }
106 
107  AccessWindowHorizontal output_access(output, 0, vec_size_x);
108  window_changed = window_changed || update_window_and_padding(win, output_access);
109  }
110  else
111  {
112  unsigned int vec_size_x = adjust_vec_size(max_cl_vector_width / input->element_size(), input->dimension(0));
113  if(norm_info.is_cross_map())
114  {
115  vec_size_x = 1;
116  }
117  win = calculate_max_window(*input, Steps(vec_size_x));
118  }
119  Status err = (window_changed) ? ARM_COMPUTE_CREATE_ERROR(ErrorCode::RUNTIME_ERROR, "Insufficient Padding!") : Status{};
120  return std::make_pair(err, win);
121 }
122 } // namespace
123 
125  : _input(nullptr), _output(nullptr), _border_size(0), _is_norm_across_width(false)
126 {
128 }
129 
131 {
132  return _border_size;
133 }
134 
136 {
137  configure(CLKernelLibrary::get().get_compile_context(), input, output, norm_info);
138 }
139 
140 void CLNormalizationLayerKernel::configure(const CLCompileContext &compile_context, const ICLTensor *input, ICLTensor *output, NormalizationLayerInfo norm_info)
141 {
142  ARM_COMPUTE_ERROR_ON_NULLPTR(input, output);
143  auto padding_info = get_padding_info({ input, output });
144 
145  // Perform validation step
146  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input->info(), output->info(), norm_info));
147  auto win_config = validate_and_configure_window(input->info(), output->info(), norm_info);
148  ARM_COMPUTE_ERROR_THROW_ON(win_config.first);
149 
150  _input = input;
151  _output = output;
152 
153  const DataLayout data_layout = input->info()->data_layout();
154  unsigned int vec_size_x = adjust_vec_size(max_cl_vector_width / input->info()->element_size(), input->info()->dimension(0));
155  int vec_size_x_leftovers = input->info()->dimension(0) % vec_size_x;
156  if(norm_info.is_cross_map() && data_layout == DataLayout::NHWC)
157  {
158  vec_size_x = 1;
159  vec_size_x_leftovers = 0;
160  }
161 
162  if(data_layout == DataLayout::NCHW)
163  {
164  const unsigned int norm_idx = get_normalization_dimension_index(data_layout, norm_info);
165  _is_norm_across_width = norm_idx == 0;
166  const unsigned int norm_radius = norm_info.norm_size() / 2;
167  // Border / padding calculation:
168  // For NCHW no border handling is impelmeneted in the kernel in the x axis.
169  // This means the x axis is fully-padded depending on vec_size_x and norm_size
170  // E.G. for input x dimension = 3, norm_size = 3 (radius = 1), vec_size_x = 2 ('#' is element 'p' is padding):
171  // In : |p|#|#|#|p|p|
172  // Out: |#|#|#|p|
173  // The output has 1 right padding because of the vec_size_x.
174  // The input has 1 left padding because radius = 1.
175  // The input has 2 right padding because of radius = 1 AND the extra output padding
176  const unsigned int border_width_left = _is_norm_across_width ? norm_radius : 0;
177  const unsigned int border_width_right = _is_norm_across_width ? norm_radius + (vec_size_x - input->info()->dimension(0) % vec_size_x) : 0;
178  _border_size = BorderSize(0, border_width_right, 0, border_width_left);
179  }
180 
181  const bool is_in_map_2D = (norm_info.type() == NormType::IN_MAP_2D);
182 
183  // Set build options
184  CLBuildOptions build_opts;
185  build_opts.add_option(("-DDATA_TYPE=" + get_cl_type_from_data_type(input->info()->data_type())));
186  build_opts.add_option(("-DCOEFF=" + float_to_string_with_full_precision(norm_info.scale_coeff())));
187  build_opts.add_option(("-DBETA=" + float_to_string_with_full_precision(norm_info.beta())));
188  build_opts.add_option(("-DKAPPA=" + float_to_string_with_full_precision(norm_info.kappa())));
189  build_opts.add_option(("-DVEC_SIZE=" + support::cpp11::to_string(vec_size_x)));
190  build_opts.add_option(("-DVEC_SIZE_LEFTOVER=" + support::cpp11::to_string(vec_size_x_leftovers)));
191  build_opts.add_option(("-DRADIUS=" + support::cpp11::to_string(norm_info.norm_size() / 2)));
192  build_opts.add_option(("-DNUM_SLICES=" + support::cpp11::to_string(input->info()->dimension(2))));
193  build_opts.add_option_if(is_in_map_2D, "-DIN_MAP_2D");
194  build_opts.add_option_if(norm_info.is_in_map() || (data_layout == DataLayout::NHWC && norm_info.is_cross_map()), "-DWIDTH_SIZE=" + support::cpp11::to_string(input->info()->dimension(0)));
195  build_opts.add_option_if(norm_info.is_in_map() && data_layout == DataLayout::NHWC, "-DDIM1_SIZE=" + support::cpp11::to_string(input->info()->dimension(1)));
196 
197  // Create kernel
198  std::string kernel_name;
199  if(norm_info.is_in_map())
200  {
201  kernel_name = "normalization_layer_in_map_" + lower_string(string_from_data_layout(data_layout));
202  }
203  else
204  {
205  kernel_name = "normalization_layer_cross_map_" + lower_string(string_from_data_layout(data_layout));
206  }
207  _kernel = create_kernel(compile_context, kernel_name, build_opts.options());
208 
209  // Configure kernel window
210  ICLKernel::configure_internal(win_config.second);
211 
212  // Set config_id for enabling LWS tuning
213  _config_id = "normalization_layer_";
214  _config_id += lower_string(string_from_data_type(input->info()->data_type()));
215  _config_id += "_";
216  _config_id += support::cpp11::to_string(static_cast<std::underlying_type<NormType>::type>(norm_info.type()));
217  _config_id += "_";
218  _config_id += support::cpp11::to_string(norm_info.norm_size());
219  _config_id += "_";
220  _config_id += support::cpp11::to_string(input->info()->dimension(0));
221  _config_id += "_";
222  _config_id += support::cpp11::to_string(input->info()->dimension(1));
223  if(data_layout == DataLayout::NHWC)
224  {
226  }
227 }
228 
230 {
231  ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, norm_info));
232  ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window(input->clone().get(), output->clone().get(), norm_info).first);
233 
234  return Status{};
235 }
236 
237 void CLNormalizationLayerKernel::run(const Window &window, cl::CommandQueue &queue)
238 {
241 
242  const int collapsed_dimension = _is_norm_across_width ? Window::DimZ : 4;
243  Window window_collapsed = window.collapse_if_possible(ICLKernel::window(), collapsed_dimension);
244  Window slice = window_collapsed.first_slice_window_3D();
245 
246  do
247  {
248  unsigned int idx = 0;
249  add_3D_tensor_argument(idx, _input, slice);
250  add_3D_tensor_argument(idx, _output, slice);
251  enqueue(queue, *this, slice, lws_hint());
252  }
253  while(window_collapsed.slide_window_slice_3D(slice));
254 }
255 } // namespace arm_compute
float scale_coeff() const
Return the scaling factor of the normalization function.
Definition: Types.h:1674
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
void run(const Window &window, cl::CommandQueue &queue) override
Enqueue the OpenCL kernel to process the given window on the passed OpenCL command queue...
BorderSize border_size() const override
The size of the border for that kernel.
const Window & window() const
The maximum window the kernel can be executed on.
Definition: IKernel.cpp:28
float kappa() const
Get the kappa value.
Definition: Types.h:1648
#define ARM_COMPUTE_RETURN_ERROR_ON_DATA_LAYOUT_NOT_IN(t,...)
Definition: Validate.h:742
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_LAYOUT(...)
Definition: Validate.h:490
bool is_in_map() const
Check if normalization is not cross map.
Definition: Types.h:1663
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
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
uint32_t norm_size() const
Get the normalization size.
Definition: Types.h:1633
NormType type() const
Get the normalization type.
Definition: Types.h:1628
#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
Normalization Layer Information class.
Definition: Types.h:1610
bool is_cross_map() const
Check if normalization is cross map.
Definition: Types.h:1658
#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
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
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
decltype(strategy::transforms) typedef type
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
#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
bool update_window_and_padding(Window &win, Ts &&... patterns)
Update window and padding size for each of the access patterns.
Definition: WindowHelpers.h:46
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
std::string float_to_string_with_full_precision(float val)
Create a string with the float in full precision.
Definition: Utils.h:1075
void configure(const ICLTensor *input, ICLTensor *output, NormalizationLayerInfo norm_info)
Set the input and output tensors.
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.
float beta() const
Get the beta value.
Definition: Types.h:1643
void add_option_if(bool cond, std::string option)
Adds option if a given condition is true;.
virtual size_t element_size() const =0
Element size in bytes calculated as data_size() * num_channels()
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
#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
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(...)
Definition: Validate.h:541
static Status validate(const ITensorInfo *input, const ITensorInfo *output, NormalizationLayerInfo norm_info)
Static function to check if given info will lead to a valid configuration of CLNormalizationLayerKern...
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
Window first_slice_window_3D() const
First 3D slice of the window.
Definition: Window.h:291
std::string kernel_name
unsigned int get_normalization_dimension_index(DataLayout layout, const NormalizationLayerInfo &info)
Calculate the normalization dimension index for a given normalization type.
DataLayout
[DataLayout enum definition]
Definition: Types.h:113
Describe a multidimensional execution window.
Definition: Window.h:39
Normalization applied within the same map in 2D region.
#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.