Compute Library
 20.05
CLWinogradOutputTransformKernel.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2018-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 
34 #include "arm_compute/core/Types.h"
35 #include "arm_compute/core/Utils.h"
39 
40 #include "support/StringSupport.h"
41 
42 #include <cmath>
43 
44 namespace arm_compute
45 {
47 
48 namespace
49 {
50 Status validate_arguments(const ITensorInfo *input, const ITensorInfo *bias, const ITensorInfo *output, const WinogradInfo &winograd_info, const ActivationLayerInfo &act_info)
51 {
52  ARM_COMPUTE_UNUSED(act_info);
55 
56  ARM_COMPUTE_RETURN_ERROR_ON(output->data_layout() != winograd_info.output_data_layout);
57 
58  const PadStrideInfo conv_info = winograd_info.convolution_info;
59  const Size2D output_tile_size = winograd_info.output_tile_size;
60  const Size2D kernel_size = winograd_info.kernel_size;
61  const Size2D input_dimensions = winograd_info.input_dimensions;
62  const unsigned int num_channels = (winograd_info.kernel_size.width + winograd_info.output_tile_size.width - 1) * (winograd_info.kernel_size.height + winograd_info.output_tile_size.height - 1);
63 
64  ARM_COMPUTE_RETURN_ERROR_ON_MSG(!cl_winograd_convolution_layer_supported(output_tile_size, kernel_size, winograd_info.output_data_layout), "Winograd output transform not supported");
65  ARM_COMPUTE_RETURN_ERROR_ON_MSG(input->dimension(2) != num_channels, "Wrong number of channels");
66 
67  // Compute number of elements to process in the X and Y direction
68  // Compute the number of output tiles along the x and y direction of size "output_tile_size"
69  const Size2D num_tiles = compute_winograd_convolution_tiles(input_dimensions,
70  kernel_size,
71  output_tile_size,
72  conv_info);
73 
74  ARM_COMPUTE_RETURN_ERROR_ON(input->dimension(1) != static_cast<unsigned int>((num_tiles.area())));
75 
76  if(bias != nullptr)
77  {
79  ARM_COMPUTE_RETURN_ERROR_ON(input->dimension(0) != bias->dimension(0));
80  }
81 
82  // Checks performed when output is configured
83  if(output->total_size() != 0)
84  {
85  const TensorInfo tensor_info_output = input->clone()->set_tensor_shape(compute_winograd_output_transform_shape(*input, winograd_info));
86 
87  ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(output, &tensor_info_output);
89  }
90 
91  return Status{};
92 }
93 
94 std::pair<Status, Window> validate_and_configure_window(ITensorInfo *input, ITensorInfo *bias, ITensorInfo *output, const Size2D &output_tile_size)
95 {
97 
98  constexpr unsigned int num_elems_processed_per_iteration = 1;
99 
101  bool window_changed = false;
102 
103  int output_static_window_end_x = 0;
104  int output_static_window_end_y = 0;
105 
106  if(output->data_layout() == DataLayout::NCHW)
107  {
108  output_static_window_end_x = ceil_to_multiple(output->dimension(0), output_tile_size.width);
109  output_static_window_end_y = ceil_to_multiple(output->dimension(1), output_tile_size.height);
110  }
111  else
112  {
113  output_static_window_end_x = output->dimension(0);
114  output_static_window_end_y = std::max(ceil_to_multiple(output->dimension(1), output_tile_size.width), output->dimension(1) + 1 /* For out of bound reads towards the z axis */);
115  }
116 
117  AccessWindowRectangle input_access(input, 0, 0, num_elems_processed_per_iteration, num_elems_processed_per_iteration);
118  AccessWindowStatic output_access(output, 0, 0, output_static_window_end_x, output_static_window_end_y);
119  window_changed = update_window_and_padding(win, input_access, output_access);
120  output->set_valid_region(ValidRegion(Coordinates(), output->tensor_shape()));
121 
122  if(bias != nullptr)
123  {
124  AccessWindowStatic bias_access(bias, 0, 0, bias->dimension(0), bias->dimension(1));
125  window_changed = window_changed || update_window_and_padding(win, bias_access);
126  }
127 
128  Status err = (window_changed) ? ARM_COMPUTE_CREATE_ERROR(ErrorCode::RUNTIME_ERROR, "Insufficient Padding!") : Status{};
129  return std::make_pair(err, win);
130 }
131 } // namespace
132 
134  : _input(nullptr), _bias(nullptr), _output(nullptr), _is_nhwc(false)
135 {
136 }
137 
139 {
140  configure(CLKernelLibrary::get().get_compile_context(), input, bias, output, winograd_info, act_info);
141 }
142 
144  const ActivationLayerInfo &act_info)
145 {
147 
148  // Output tensor auto initialization if not yet initialized
149  auto_init_if_empty(*output->info(), input->info()->clone()->set_tensor_shape(compute_winograd_output_transform_shape(*input->info(), winograd_info)));
150 
151  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input->info(), (bias != nullptr ? bias->info() : nullptr), output->info(), winograd_info, act_info));
152 
153  _input = input;
154  _bias = bias;
155  _output = output;
156  _is_nhwc = winograd_info.output_data_layout == DataLayout::NHWC;
157 
158  // Compute num_tiles_x
159  const Size2D input_dimensions = winograd_info.input_dimensions;
160  const Size2D kernel_size = winograd_info.kernel_size;
161  const Size2D output_tile_size = winograd_info.output_tile_size;
162  const PadStrideInfo conv_info = winograd_info.convolution_info;
163 
164  // Compute the number of output tiles along the x and y direction of size "output_tile_size"
165  const Size2D num_tiles = compute_winograd_convolution_tiles(input_dimensions,
166  kernel_size,
167  output_tile_size,
168  conv_info);
169  const size_t total_batches = output->info()->tensor_shape().total_size_upper(3);
170 
171  // Set build options
172  CLBuildOptions build_opts;
173  build_opts.add_option("-DACTIVATION_TYPE=" + lower_string(string_from_activation_func(act_info.activation())));
174  build_opts.add_option_if(act_info.enabled(), "-DA_VAL=" + float_to_string_with_full_precision(act_info.a()));
175  build_opts.add_option_if(act_info.enabled(), "-DB_VAL=" + float_to_string_with_full_precision(act_info.b()));
176 
177  if((output_tile_size.x() == 2) || (output_tile_size.x() == 1 && output_tile_size.y() == 2))
178  {
179  build_opts.add_option("-DVEC_SIZE=2");
180  }
181  else if((output_tile_size.x() == 4) || (output_tile_size.x() == 1 && output_tile_size.y() == 4))
182  {
183  build_opts.add_option("-DVEC_SIZE=4");
184  }
185 
186  build_opts.add_option_if(_bias != nullptr, std::string("-DHAS_BIAS"));
187  build_opts.add_option("-DNUM_TILES_X=" + support::cpp11::to_string(num_tiles.width));
188  build_opts.add_option("-DOUTPUT_TILE_W=" + support::cpp11::to_string(output_tile_size.width));
189  build_opts.add_option("-DOUTPUT_TILE_H=" + support::cpp11::to_string(output_tile_size.height));
190  build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(input->info()->data_type()));
191  build_opts.add_option_if(total_batches > 1, "-DSRC_DEPTH=" + support::cpp11::to_string(_input->info()->dimension(2)));
192  build_opts.add_option_if(winograd_info.kernel_size.height == 1, "-DWINOGRAD_OUTPUT_TRANSFORM_HORIZONTAL");
193  build_opts.add_option_if(winograd_info.kernel_size.width == 1, "-DWINOGRAD_OUTPUT_TRANSFORM_VERTICAL");
194 
195  // Create kernel
196  std::string kernel_name = "winograd_output_transform_" + output_tile_size.to_string() + "_" + kernel_size.to_string() + "_" + lower_string(string_from_data_layout(winograd_info.output_data_layout));
197  _kernel = create_kernel(compile_context, kernel_name, build_opts.options());
198 
199  // Configure kernel window
200  auto win_config = validate_and_configure_window(input->info(), (bias != nullptr ? bias->info() : nullptr), output->info(), winograd_info.output_tile_size);
201  ARM_COMPUTE_ERROR_THROW_ON(win_config.first);
202  ICLKernel::configure_internal(win_config.second);
203 
204  // Set config_id for enabling LWS tuning
205  _config_id = kernel_name;
206  _config_id += "_";
207  _config_id += lower_string(string_from_data_type(input->info()->data_type()));
208  _config_id += "_";
209  _config_id += support::cpp11::to_string(input->info()->dimension(0));
210  _config_id += "_";
211  _config_id += support::cpp11::to_string(input->info()->dimension(1));
212  _config_id += "_";
213  _config_id += support::cpp11::to_string(output->info()->dimension(0));
214  _config_id += "_";
215  _config_id += support::cpp11::to_string(output->info()->dimension(1));
216  _config_id += "_";
217  _config_id += lower_string(string_from_data_layout(winograd_info.output_data_layout));
218 }
219 
221 {
222  ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, (bias != nullptr ? bias->clone().get() : nullptr), output, winograd_info, act_info));
223  ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window(input->clone().get(), (bias != nullptr ? bias->clone().get() : nullptr), output->clone().get(), winograd_info.output_tile_size).first);
224 
225  return Status{};
226 }
227 
228 void CLWinogradOutputTransformKernel::run(const Window &window, cl::CommandQueue &queue)
229 {
232 
233  // Collapse window
235 
236  // Get initial windows
237  Window slice = window_collapsed.first_slice_window_4D();
238  slice.set(Window::DimZ, Window::Dimension(0, 1, 1));
239 
240  // Setup output slice
241  Window slice_out(slice);
242  slice_out.set(Window::DimX, Window::Dimension(0, 0, 0));
243  slice_out.set(Window::DimY, Window::Dimension(0, 0, 0));
244 
245  if(_bias != nullptr)
246  {
247  unsigned int idx1 = 2 * num_arguments_per_4D_tensor();
248  Window slice_biases;
249  slice_biases.use_tensor_dimensions(_bias->info()->tensor_shape());
250  add_1D_tensor_argument(idx1, _bias, slice_biases);
251  }
252 
253  if(_is_nhwc)
254  {
255  unsigned int idx2 = 2 * num_arguments_per_4D_tensor() + ((_bias != nullptr) ? num_arguments_per_1D_tensor() : 0);
256  _kernel.setArg(idx2, static_cast<int>(_output->info()->total_size() - _output->info()->strides_in_bytes().y()));
257  }
258 
259  do
260  {
261  unsigned int idx = 0;
262  add_4D_tensor_argument(idx, _input, slice);
263  add_4D_tensor_argument(idx, _output, slice_out);
264  enqueue(queue, *this, slice, lws_hint());
265  }
267 }
268 } // namespace arm_compute
static constexpr unsigned int num_arguments_per_1D_tensor()
Returns the number of arguments enqueued per 1D tensor object.
Definition: ICLKernel.h:184
#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
static Status validate(const ITensorInfo *input, const ITensorInfo *bias, const ITensorInfo *output, const WinogradInfo &winograd_info, const ActivationLayerInfo &act_info=ActivationLayerInfo())
Static function to check if given info will lead to a valid configuration of CLWinogradOutputTransfor...
bool enabled() const
Check if initialised.
Definition: Types.h:1567
virtual size_t dimension(size_t index) const =0
Return the size of the requested dimension.
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
cl::NDRange lws_hint() const
Return the Local-Workgroup-Size hint.
Definition: ICLKernel.h:247
Winograd information.
Definition: Types.h:2110
float a() const
Get the alpha value.
Definition: Types.h:1557
#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.
#define ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(t, c,...)
Definition: Validate.h:792
1 channel, 1 F32 per channel
const std::string & string_from_activation_func(ActivationLayerInfo::ActivationFunction act)
Translates a given activation function to a string.
Definition: Utils.cpp:163
size_t total_size_upper(size_t dimension) const
Collapses given dimension and above.
Definition: TensorShape.h:181
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
Describe one of the image's dimensions with a start, end and step.
Definition: Window.h:75
Size2D compute_winograd_convolution_tiles(const Size2D &in_dims, const Size2D &kernel_size, const Size2D &output_tile_size, const PadStrideInfo &conv_info)
Calculate the number of output tiles required by Winograd Convolution layer.
Definition: Helpers.h:779
size_t x() const
Semantic accessor for width as x.
Definition: Size2D.h:74
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
Activation Layer Information class.
Definition: Types.h:1517
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
void use_tensor_dimensions(const TensorShape &shape, size_t first_dimension=Window::DimX)
Use the tensor's dimensions to fill the window dimensions.
Definition: Window.inl:276
Copyright (c) 2017-2020 ARM Limited.
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...
Definition: Helpers.inl:202
size_t height
Height of the image region or rectangle.
Definition: Size2D.h:90
1 channel, 1 F16 per channel
ITensorInfo * info() const override
Interface to be implemented by the child class to return the tensor's metadata.
Definition: Tensor.cpp:33
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:387
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: Helpers.h:437
#define ARM_COMPUTE_UNUSED(...)
To avoid unused variables warnings.
Definition: Error.h:152
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
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(...)
Definition: Validate.h:443
std::string float_to_string_with_full_precision(float val)
Create a string with the float in full precision.
Definition: Utils.h:1225
void configure(const ICLTensor *input, const ICLTensor *bias, ICLTensor *output, const WinogradInfo &winograd_info, const ActivationLayerInfo &act_info=ActivationLayerInfo())
Set the input and output tensor.
virtual const TensorShape & tensor_shape() const =0
Size for each dimension of the tensor.
auto ceil_to_multiple(S value, T divisor) -> decltype(((value+divisor - 1)/divisor) *divisor)
Computes the smallest number larger or equal to value that is a multiple of divisor.
Definition: Utils.h:67
std::string kernel_name
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 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's metadata.
void add_option_if(bool cond, std::string option)
Adds option if a given condition is true;.
Padding and stride information class.
Definition: Types.h:689
void set(size_t dimension, const Dimension &dim)
Set the values of a given dimension.
Definition: Window.inl:49
static constexpr unsigned int num_arguments_per_4D_tensor()
Returns the number of arguments enqueued per 4D tensor object.
Definition: ICLKernel.h:208
bool slide_window_slice_3D(Window &slice) const
Slide the passed 3D window slice.
Definition: Window.h:333
Num samples, channels, height, width.
CLCompileContext class.
size_t y() const
Semantic accessor for height as y.
Definition: Size2D.h:83
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 constexpr size_t DimY
Alias for dimension 1 also known as Y dimension.
Definition: Window.h:45
#define ARM_COMPUTE_ERROR_ON_NULLPTR(...)
Definition: Validate.h:161
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
TensorShape compute_winograd_output_transform_shape(const ITensorInfo &input, const WinogradInfo &winograd_info)
Calculate the winograd output transform shape.
virtual size_t total_size() const =0
Returns the total size of the tensor in bytes.
#define ARM_COMPUTE_CREATE_ERROR(error_code, msg)
Creates an error with a given message.
Definition: Error.h:159
size_t width
Width of the image region or rectangle.
Definition: Size2D.h:89
static constexpr size_t DimZ
Alias for dimension 2 also known as Z dimension.
Definition: Window.h:47
Class for specifying the size of an image or rectangle.
Definition: Size2D.h:34
Num samples, height, width, channels.
Status validate_arguments(const ITensorInfo *input, const ITensorInfo *bias, const ITensorInfo *output, const GEMMLowpOutputStageInfo *output_stage)
Window first_slice_window_4D() const
First 4D slice of the window.
Definition: Window.h:297
unsigned int num_elems_processed_per_iteration
#define ARM_COMPUTE_RETURN_ERROR_ON_MSG(cond, msg)
If the condition is true, an error is returned.
Definition: Error.h:244
T y() const
Alias to access the size of the second dimension.
Definition: Dimensions.h:86
ActivationFunction activation() const
Get the type of activation function.
Definition: Types.h:1552
float b() const
Get the beta value.
Definition: Types.h:1562
virtual const Strides & strides_in_bytes() const =0
The strides in bytes for accessing each dimension of the tensor.
void add_1D_tensor_argument(unsigned int &idx, const ICLTensor *tensor, const Window &window)
Add the passed 1D tensor's parameters to the object's kernel's arguments starting from the index idx.
Definition: ICLKernel.h:110
bool cl_winograd_convolution_layer_supported(const Size2D &output_tile, const Size2D &kernel_size, DataLayout data_layout)
This function checks if the Winograd configuration (defined through the output tile,...
Definition: CLHelpers.cpp:289
#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
Describe a multidimensional execution window.
Definition: Window.h:39
#define ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(k)
Definition: Validate.h:941
SimpleTensor< T > slice(const SimpleTensor< T > &src, Coordinates starts, Coordinates ends)
std::string to_string() const
Definition: Size2D.cpp:29