Compute Library
 21.02
CLWinogradInputTransformKernel.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 
30 #include "arm_compute/core/Error.h"
32 #include "arm_compute/core/Types.h"
33 #include "arm_compute/core/Utils.h"
36 #include "src/core/CL/CLValidate.h"
39 #include "support/StringSupport.h"
40 
41 using namespace arm_compute;
42 
43 namespace
44 {
46 {
49 
50  const PadStrideInfo conv_info = winograd_info.convolution_info;
51  const Size2D output_tile_size = winograd_info.output_tile_size;
52  const Size2D kernel_size = winograd_info.kernel_size;
53  ARM_COMPUTE_RETURN_ERROR_ON_MSG(conv_info.stride().first != 1 || conv_info.stride().second != 1, "Winograd input transform only supports unit strides");
54  ARM_COMPUTE_RETURN_ERROR_ON_MSG(!cl_winograd_convolution_layer_supported(output_tile_size, kernel_size, input->data_layout()), "Winograd input transform not supported");
55 
56  ARM_COMPUTE_UNUSED(conv_info);
57  ARM_COMPUTE_UNUSED(output_tile_size);
58  ARM_COMPUTE_UNUSED(kernel_size);
59 
60  // Validate configured output
61  if(output->total_size() != 0)
62  {
64 
67  }
68 
69  return Status{};
70 }
71 
72 std::pair<Status, Window> validate_and_configure_window(ITensorInfo *input, ITensorInfo *output, const WinogradInfo &winograd_info)
73 {
74  ARM_COMPUTE_UNUSED(output);
75  ARM_COMPUTE_ERROR_ON_NULLPTR(input, output);
76 
77  bool window_changed = false;
78  Window win = calculate_max_window(*input, Steps(1, 1));
79 
80  if(input->data_layout() == DataLayout::NCHW)
81  {
82  const PadStrideInfo conv_info = winograd_info.convolution_info;
83  const Size2D output_tile_size = winograd_info.output_tile_size;
84  const Size2D kernel_size = winograd_info.kernel_size;
85 
86  unsigned int num_elems_read_per_iteration_x = output_tile_size.width + kernel_size.width - 1;
87  unsigned int num_elems_read_per_iteration_y = output_tile_size.height + kernel_size.height - 1;
88 
89  AccessWindowRectangle input_access(input, -conv_info.pad_left(), -conv_info.pad_top(), num_elems_read_per_iteration_x, num_elems_read_per_iteration_y);
90  window_changed = update_window_and_padding(win, input_access);
91  }
92 
93  Status err = (window_changed) ? ARM_COMPUTE_CREATE_ERROR(ErrorCode::RUNTIME_ERROR, "Insufficient Padding!") : Status{};
94  return std::make_pair(err, win);
95 }
96 } // namespace
97 
99  : _border_size(0), _input(nullptr), _output(nullptr), _data_layout(DataLayout::UNKNOWN), _num_tiles_x(0), _num_tiles_y(0), _step_z(1)
100 {
101 }
102 
104 {
105  return _border_size;
106 }
107 
108 void CLWinogradInputTransformKernel::configure(const ICLTensor *input, ICLTensor *output, const WinogradInfo &winograd_info)
109 {
110  configure(CLKernelLibrary::get().get_compile_context(), input, output, winograd_info);
111 }
112 
113 void CLWinogradInputTransformKernel::configure(const CLCompileContext &compile_context, const ICLTensor *input, ICLTensor *output, const WinogradInfo &winograd_info)
114 {
115  ARM_COMPUTE_ERROR_ON_NULLPTR(input, output);
117 
118  auto padding_info = get_padding_info({ input, output });
119 
120  const PadStrideInfo conv_info = winograd_info.convolution_info;
121  const Size2D output_tile_size = winograd_info.output_tile_size;
122  const Size2D kernel_size = winograd_info.kernel_size;
123 
124  _data_layout = input->info()->data_layout();
125 
126  const size_t idx_w = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::WIDTH);
127  const size_t idx_h = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::HEIGHT);
128 
129  // Compute the number of output tiles along the x and y direction of size "output_tile_size"
130  const Size2D num_tiles = compute_winograd_convolution_tiles(Size2D(input->info()->dimension(idx_w), input->info()->dimension(idx_h)),
131  kernel_size,
132  output_tile_size,
133  conv_info);
134 
135  _input = input;
136  _output = output;
137  _num_tiles_x = num_tiles.width;
138  _num_tiles_y = num_tiles.height;
139 
141 
142  // Output auto initialization if not yet initialized
143  auto_init_if_empty(*output->info(), input->info()->clone()->set_tensor_shape(output_shape));
144 
145  ARM_COMPUTE_ERROR_ON(_num_tiles_x * _num_tiles_y != static_cast<int>(output->info()->dimension(1)));
146  const size_t total_batches = input->info()->tensor_shape().total_size_upper(3);
147 
148  CLBuildOptions build_opts;
149  build_opts.add_option("-DNUM_TILES_X=" + support::cpp11::to_string(_num_tiles_x));
150  build_opts.add_option("-DPAD_LEFT=" + support::cpp11::to_string(conv_info.pad_left()));
151  build_opts.add_option("-DPAD_TOP=" + support::cpp11::to_string(conv_info.pad_top()));
152  build_opts.add_option("-DOUTPUT_TILE_W=" + support::cpp11::to_string(output_tile_size.width));
153  build_opts.add_option("-DOUTPUT_TILE_H=" + support::cpp11::to_string(output_tile_size.height));
154  build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(input->info()->data_type()));
155  build_opts.add_option_if(winograd_info.kernel_size.height == 1, "-DWINOGRAD_INPUT_TRANSFORM_HORIZONTAL");
156  build_opts.add_option_if(winograd_info.kernel_size.width == 1, "-DWINOGRAD_INPUT_TRANSFORM_VERTICAL");
157  if(_data_layout == DataLayout::NHWC)
158  {
159  build_opts.add_option_if(total_batches > 1, "-DNUM_TILES_Y=" + support::cpp11::to_string(_num_tiles_y));
160  build_opts.add_option("-DSRC_DIM_1=" + support::cpp11::to_string(_input->info()->dimension(1)));
161  build_opts.add_option("-DSRC_DIM_2=" + support::cpp11::to_string(_input->info()->dimension(2)));
162  }
163  else
164  {
165  build_opts.add_option_if(total_batches > 1, "-DSRC_DEPTH=" + support::cpp11::to_string(_input->info()->dimension(2)));
166  }
167 
168  // Create kernel
169  std::string kernel_name = "winograd_input_transform_" + output_tile_size.to_string() + "_" + kernel_size.to_string();
170 
171  // Get the maximum dimension from the tile size
172  const unsigned int tile_max_dim = std::max(output_tile_size.width, output_tile_size.height);
173 
174  // Check optimized kernel if output_dims == 2x2
175  if((tile_max_dim == 2) && (_data_layout == DataLayout::NCHW))
176  {
177  _step_z = (_input->info()->dimension(2) % 2) != 0 ? 1 : 2;
178  }
179 
180  // Append stepz and data layout
181  kernel_name += "_stepz";
182  kernel_name += support::cpp11::to_string(_step_z);
183  kernel_name += "_" + lower_string(string_from_data_layout(_data_layout));
184 
185  _kernel = create_kernel(compile_context, kernel_name, build_opts.options());
186 
187  // Create window and update padding
188  auto win_config = validate_and_configure_window(input->info(), output->info(), winograd_info);
189  ARM_COMPUTE_ERROR_THROW_ON(win_config.first);
190  ICLKernel::configure_internal(win_config.second, cl::NDRange(1, 1, 8));
191 
192  _border_size = BorderSize(_input->info()->padding());
193 
194  ARM_COMPUTE_ERROR_ON((input->info()->data_layout() == DataLayout::NHWC) && has_padding_changed(padding_info));
195 
196  _config_id = kernel_name;
197  _config_id += support::cpp11::to_string(input->info()->dimension(0));
198  _config_id += "_";
199  _config_id += support::cpp11::to_string(input->info()->dimension(1));
200  _config_id += "_";
201  _config_id += support::cpp11::to_string(input->info()->dimension(2));
202  _config_id += "_";
203  _config_id += support::cpp11::to_string(conv_info.pad_left());
204  _config_id += "_";
205  _config_id += support::cpp11::to_string(conv_info.pad_top());
206  _config_id += "_";
207  _config_id += lower_string(string_from_data_layout(_data_layout));
208 }
209 
210 Status CLWinogradInputTransformKernel::validate(const ITensorInfo *input, const ITensorInfo *output, const WinogradInfo &winograd_info)
211 {
213  ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, winograd_info));
214  ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window(input->clone().get(), output->clone().get(), winograd_info).first);
215 
216  return Status{};
217 }
218 
219 void CLWinogradInputTransformKernel::run(const Window &window, cl::CommandQueue &queue)
220 {
223 
224  const size_t idx_w = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::WIDTH);
225  const size_t idx_h = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::HEIGHT);
226  const size_t idx_c = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::CHANNEL);
227  const size_t total_batches = window.shape().total_size_upper(3);
228 
229  // Collapse window
230  Window window_collapsed = window.collapse_if_possible(ICLKernel::window(), Window::DimZ);
231 
232  Window slice = window_collapsed.first_slice_window_3D();
233  slice.set(idx_w, Window::Dimension(0, _num_tiles_x, 1));
234  slice.set(idx_h, Window::Dimension(0, _num_tiles_y, 1));
235  if(_data_layout == DataLayout::NHWC)
236  {
237  slice.set(idx_h, Window::Dimension(0, _num_tiles_y * total_batches, 1));
238  }
239 
240  ARM_COMPUTE_ERROR_ON(((slice[idx_c].end() - slice[idx_c].start()) % _step_z) != 0);
241  slice.set(idx_c, Window::Dimension(slice[idx_c].start(), slice[idx_c].end(), _step_z));
242 
243  unsigned int idx = 2 * num_arguments_per_3D_tensor();
244  _kernel.setArg<cl_uint>(idx++, static_cast<unsigned int>(_input->info()->strides_in_bytes()[3]));
245  _kernel.setArg<cl_uint>(idx++, static_cast<unsigned int>(_output->info()->strides_in_bytes()[3]));
246 
247  do
248  {
249  unsigned int idx = 0;
250  add_3D_tensor_argument(idx, _input, slice);
251  add_3D_tensor_argument(idx, _output, slice);
252 
253  enqueue(queue, *this, slice, lws_hint());
254  }
255  while(window_collapsed.slide_window_slice_3D(slice));
256 }
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
Shape of a tensor.
Definition: TensorShape.h:39
TensorShape compute_winograd_input_transform_shape(const ITensorInfo &input, const WinogradInfo &winograd_info)
Calculate the winograd input transform shape.
void enqueue(IGCKernel &kernel, const Window &window, const gles::NDRange &lws=gles::NDRange(1U, 1U, 1U))
Add the kernel to the command queue with the given window.
Definition: IGCKernel.cpp:41
virtual size_t dimension(size_t index) const =0
Return the size of the requested dimension.
BorderSize border_size() const override
The size of the border for that kernel.
Container for 2D border size.
Definition: Types.h:273
const StringSet & options() const
Gets the current options list set.
static Status validate(const ITensorInfo *input, const ITensorInfo *output, const WinogradInfo &winograd_info)
Static function to check if given info will lead to a valid configuration of CLWinogradInputTransform...
cl::NDRange lws_hint() const
Return the Local-Workgroup-Size hint.
Definition: ICLKernel.h:276
Winograd information.
Definition: Types.h:2182
PadStrideInfo convolution_info
Convolution info (Pads, strides,...)
Definition: Types.h:2200
#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
size_t total_size_upper(size_t dimension) const
Collapses given dimension and above.
Definition: TensorShape.h:182
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
Describe one of the image&#39;s dimensions with a start, end and step.
Definition: Window.h:77
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:211
unsigned int pad_top() const
Get the top padding.
Definition: Types.h:806
Status class.
Definition: Error.h:52
std::string lower_string(const std::string &val)
Lower a given string.
Definition: Utils.cpp:350
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DIMENSIONS(...)
Definition: Validate.h:288
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:172
Copyright (c) 2017-2021 Arm Limited.
size_t height
Height of the image region or rectangle.
Definition: Size2D.h:90
1 channel, 1 F16 per channel
#define ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(...)
Definition: Validate.h:163
void add_option(std::string option)
Adds option to the existing build option list.
Implementation of a rectangular access pattern.
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:403
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:214
#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
virtual const TensorShape & tensor_shape() const =0
Size for each dimension of the tensor.
Size2D output_tile_size
Width and height of the output tile.
Definition: Types.h:2197
Class to describe a number of elements in each dimension.
Definition: Steps.h:40
std::pair< unsigned int, unsigned int > stride() const
Get the stride.
Definition: Types.h:770
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
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...
void configure(const ICLTensor *input, ICLTensor *output, const WinogradInfo &winograd_info)
Set the input and output of the kernel.
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.
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:722
void end(TokenStream &in, bool &valid)
Definition: MLGOParser.cpp:290
void set(size_t dimension, const Dimension &dim)
Set the values of a given dimension.
Definition: Window.inl:49
virtual PaddingSize padding() const =0
Padding of tensor.
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:941
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:528
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
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
Manages all the OpenCL kernels compilation and caching, provides accessors for the OpenCL Context...
Class for specifying the size of an image or rectangle.
Definition: Size2D.h:34
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(...)
Definition: Validate.h:545
void run(const Window &window, cl::CommandQueue &queue) override
Enqueue the OpenCL kernel to process the given window on the passed OpenCL command queue...
Num samples, height, width, channels.
#define ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(t, c,...)
Definition: Validate.h:792
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:513
Status validate_arguments(const ITensorInfo *input, const ITensorInfo *bias, const ITensorInfo *output, const GEMMLowpOutputStageInfo *output_stage)
Wrapper to configure the Khronos OpenCL C++ header.
TensorShape shape() const
Return the shape of the window in number of steps.
Definition: Window.inl:284
#define ARM_COMPUTE_RETURN_ERROR_ON_MSG(cond, msg)
If the condition is true, an error is returned.
Definition: Error.h:244
Size2D kernel_size
Width and height of the kernel.
Definition: Types.h:2198
#define ARM_COMPUTE_ERROR_ON_NULLPTR(...)
Definition: Validate.h:161
virtual const Strides & strides_in_bytes() const =0
The strides in bytes for accessing each dimension of the tensor.
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
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, kernel size and the data layout) is supported on OpenCL.
Definition: CLHelpers.cpp:284
Window first_slice_window_3D() const
First 3D slice of the window.
Definition: Window.h:291
unsigned int pad_left() const
Get the left padding.
Definition: Types.h:796
DataLayout
[DataLayout enum definition]
Definition: Types.h:120
Describe a multidimensional execution window.
Definition: Window.h:39
#define ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(f, s)
Definition: Validate.h:205
SimpleTensor< T > slice(const SimpleTensor< T > &src, Coordinates starts, Coordinates ends)
virtual DataLayout data_layout() const =0
Get the data layout of the tensor.
std::string to_string() const
Definition: Size2D.cpp:29