Compute Library
 22.05
ClWinogradConv2d.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 
27 #include "arm_compute/core/Utils.h"
39 
40 #include "src/common/utils/Log.h"
41 #include "support/Cast.h"
42 
43 using namespace arm_compute::experimental;
44 
45 namespace arm_compute
46 {
47 namespace opencl
48 {
49 namespace
50 {
51 Size2D winograd_output_tile(const Size2D &input_dims, const Size2D &kernel_dims, DataLayout data_layout)
52 {
53  Size2D output_tile = Size2D{};
54 
55  const unsigned int kernel_max_dim = std::max(kernel_dims.width, kernel_dims.height);
56 
57  // Check if the input spatial dimensions are smaller than 4
58  const bool is_input_lt4_nchw = (input_dims.width <= 4 && input_dims.height <= 4) && (data_layout == DataLayout::NCHW);
59 
60  if(kernel_max_dim == 3U)
61  {
62  if(kernel_dims == Size2D(3U, 3U))
63  {
64  output_tile = is_input_lt4_nchw ? Size2D(2U, 2U) : Size2D(4U, 4U);
65  }
66  else if(kernel_dims == Size2D(3U, 1U))
67  {
68  output_tile = is_input_lt4_nchw ? Size2D(2U, 1U) : Size2D(4U, 1U);
69  }
70  else
71  {
72  output_tile = is_input_lt4_nchw ? Size2D(1U, 2U) : Size2D(1U, 4U);
73  }
74  }
75  else if(kernel_max_dim == 5U)
76  {
77  output_tile = Size2D(kernel_dims.width == 1 ? 1U : 4U,
78  kernel_dims.height == 1 ? 1U : 4U);
79  }
80  else if(kernel_max_dim == 7U)
81  {
82  output_tile = Size2D(kernel_dims.width == 1 ? 1U : 2U,
83  kernel_dims.height == 1 ? 1U : 2U);
84  }
85 
86  return output_tile;
87 }
88 
89 bool check_support_fast_math(const Size2D &output_tile, const Size2D &kernel_size)
90 {
91  // Check if we want to configure a Winograd configuration which requires fast math
92  using WinogradConfiguration = std::pair<std::pair<int, int>, std::pair<int, int>>;
93 
94  std::vector<WinogradConfiguration> fast_math_winograd =
95  {
96  WinogradConfiguration(std::pair<int, int>(4, 4), std::pair<int, int>(5, 5)),
97  WinogradConfiguration(std::pair<int, int>(2, 2), std::pair<int, int>(7, 7))
98  };
99 
100  auto p = std::make_pair(std::pair<int, int>(output_tile.width, output_tile.height),
101  std::pair<int, int>(kernel_size.width, kernel_size.height));
102 
103  return std::find(fast_math_winograd.begin(), fast_math_winograd.end(), p) != fast_math_winograd.end();
104 }
105 
106 Status validate_arguments(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst, const PadStrideInfo &conv_info,
107  const ActivationLayerInfo &act_info, bool enable_fast_math)
108 {
109  // Get indeces for the width and height
110  const size_t idx_width = get_data_layout_dimension_index(src->data_layout(), DataLayoutDimension::WIDTH);
111  const size_t idx_height = get_data_layout_dimension_index(src->data_layout(), DataLayoutDimension::HEIGHT);
112 
113  // Input shape, kernel size and output tile
114  const Size2D input_dims = Size2D(src->tensor_shape()[idx_width], src->tensor_shape()[idx_height]);
115  const Size2D kernel_size = Size2D(weights->tensor_shape()[idx_width], weights->tensor_shape()[idx_height]);
116  const Size2D output_tile = winograd_output_tile(input_dims, kernel_size, src->data_layout());
117 
118  ARM_COMPUTE_RETURN_ERROR_ON_MSG(((conv_info.pad_left() > (kernel_size.x() / 2u)) || (conv_info.pad_right() > (kernel_size.x() / 2u))), "Winograd only supports padding up to half kernel size");
119  ARM_COMPUTE_RETURN_ERROR_ON_MSG(((conv_info.pad_top() > (kernel_size.y() / 2u)) || (conv_info.pad_bottom() > (kernel_size.y() / 2u))), "Winograd only supports padding up to half kernel size");
120 
121  // Check if the Winograd configuration requires fast math
122  if(!enable_fast_math)
123  {
124  ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(src, 1, DataType::F32); //disable winograd for fp16 if fast math is false.
125  ARM_COMPUTE_RETURN_ERROR_ON_MSG(check_support_fast_math(output_tile, kernel_size), "This Winograd configuration requires enable_fast_math=true");
126  }
127 
128  const WinogradInfo winograd_info = WinogradInfo(output_tile,
129  kernel_size,
130  input_dims,
131  conv_info,
132  src->data_layout());
133 
134  // Validate input transform
135  const TensorShape input0_shape = misc::shape_calculator::compute_winograd_input_transform_shape(*src, winograd_info);
136  const TensorInfo input0 = src->clone()->set_tensor_shape(input0_shape);
138 
139  // Validate filter transform
140  const TensorShape input1_shape = misc::shape_calculator::compute_winograd_filter_transform_shape(*weights, winograd_info);
141  const TensorInfo input1 = weights->clone()->set_tensor_shape(input1_shape);
143 
144  // Validate batched matrix multiply
145  TensorShape batched_mm_output_shape = input0.tensor_shape();
146  batched_mm_output_shape[0] = input1.tensor_shape()[0];
147  const TensorInfo batched_mm_output = input0.clone()->set_tensor_shape(batched_mm_output_shape);
148  ARM_COMPUTE_RETURN_ON_ERROR(ClGemm::validate(&input0, &input1, nullptr, &batched_mm_output, 1.0f, 0.0f, GEMMInfo(false, false, true /* Reshape weights only for the first run*/, 0, false, false,
149  GEMMLowpOutputStageInfo(), (src->data_type() == DataType::F16))));
150 
151  // Configure output transform
152  ARM_COMPUTE_RETURN_ON_ERROR(kernels::ClWinogradOutputTransformKernel::validate(&batched_mm_output, biases, dst, winograd_info, act_info));
153  return Status{};
154 }
155 
156 } // namespace
157 
158 ClWinogradConv2d::ClWinogradConv2d()
159  : _batched_mm(),
160  _input_transform(std::make_unique<kernels::ClWinogradInputTransformKernel>()),
161  _filter_transform(std::make_unique<kernels::ClWinogradFilterTransformKernel>()),
162  _output_transform(std::make_unique<kernels::ClWinogradOutputTransformKernel>()),
163  _border_handler(),
164  _input0(),
165  _input1(),
166  _batched_mm_output(),
167  _is_prepared(false),
168  _aux_mem()
169 {
170 }
171 
173 
174 void ClWinogradConv2d::configure(const ClCompileContext &compile_context, ITensorInfo *src, ITensorInfo *weights, ITensorInfo *biases, ITensorInfo *dst,
175  const PadStrideInfo &conv_info, const ActivationLayerInfo &act_info, bool enable_fast_math)
176 {
177  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(src, weights, biases, dst, conv_info, act_info, enable_fast_math));
178  ARM_COMPUTE_LOG_PARAMS(src, weights, biases, dst, conv_info, act_info, enable_fast_math);
179 
180  // Get indices for the width and height
183 
184  // Input shape, kernel size and output tile
185  const Size2D input_dims = Size2D(src->tensor_shape()[idx_width], src->tensor_shape()[idx_height]);
186  const Size2D kernel_size = Size2D(weights->tensor_shape()[idx_width], weights->tensor_shape()[idx_height]);
187  const Size2D output_tile = winograd_output_tile(input_dims, kernel_size, src->data_layout());
188 
189  // Check if the Winograd configuration requires fast math
190  if(!enable_fast_math)
191  {
192  ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(src, 1, DataType::F32); //disable winograd for fp16 if fast math is false.
193  ARM_COMPUTE_ERROR_ON_MSG(check_support_fast_math(output_tile, kernel_size), "This Winograd configuration requires enable_fast_math=true");
194  }
195  const WinogradInfo winograd_info = WinogradInfo(output_tile,
196  kernel_size,
197  input_dims,
198  conv_info,
199  src->data_layout());
200 
201  _is_prepared = false;
202 
203  // Configure input transform
204  _input_transform->configure(compile_context, src, &_input0, winograd_info);
205  _border_handler.configure(compile_context, src, _input_transform->border_size(), BorderMode::CONSTANT, PixelValue());
206 
207  // Configure filter transform
208  _filter_transform->configure(compile_context, weights, &_input1, winograd_info);
209 
210  // Configure batched matrix multiply
211  _batched_mm.configure(compile_context, &_input0, &_input1, nullptr, &_batched_mm_output, 1.0f, 0.0f, GEMMInfo(false, false, true /* Reshape weights only for the first run*/, 0,
212  false, false,
214  (src->data_type() == DataType::F16)));
215 
216  // Configure output transform
217  _output_transform->configure(compile_context, &_batched_mm_output, biases, dst, winograd_info, act_info);
218 
219  _aux_mem = _batched_mm.workspace();
220  const MemoryLifetime wino_wei_lifetm = std::any_of(std::begin(_aux_mem), std::end(_aux_mem), [](const auto & r)
221  {
222  return (r.lifetime == MemoryLifetime::Persistent) && (r.size > 0);
223  }) ?
225  MemoryLifetime::Persistent;
226  _aux_mem.push_back(MemoryInfo(offset_int_vec(2), MemoryLifetime::Temporary, _input0.total_size()));
227  _aux_mem.push_back(MemoryInfo(offset_int_vec(3), wino_wei_lifetm, _input1.total_size()));
228  _aux_mem.push_back(MemoryInfo(offset_int_vec(4), MemoryLifetime::Temporary, _batched_mm_output.total_size()));
229 }
230 
231 Status ClWinogradConv2d::validate(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst, const PadStrideInfo &conv_info,
232  const ActivationLayerInfo &act_info, bool enable_fast_math)
233 {
234  ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(src, weights, biases, dst, conv_info, act_info, enable_fast_math));
235  return Status{};
236 }
237 
239 {
240  const bool is_gemm_reshaped = _aux_mem[3].lifetime == MemoryLifetime::Prepare;
241 
242  auto src = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC_0));
243  auto biases = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC_2));
244  auto dst = utils::cast::polymorphic_downcast<ICLTensor *>(tensors.get_tensor(TensorType::ACL_DST));
245 
246  CLAuxTensorHandler input0(offset_int_vec(2), _input0, tensors, true);
247  CLAuxTensorHandler input1(offset_int_vec(3), _input1, tensors, true, is_gemm_reshaped);
248  CLAuxTensorHandler batched_mm_output(offset_int_vec(4), _batched_mm_output, tensors, true);
249 
250  prepare(tensors);
251 
252  // Run input transform
253  ITensorPack pack_it
254  {
255  { TensorType::ACL_SRC, src },
256  { TensorType::ACL_DST, input0.get() },
257  };
258  CLScheduler::get().enqueue_op(_border_handler, pack_it, false);
259  CLScheduler::get().enqueue_op(*_input_transform, pack_it, false);
260 
261  // Run batched matrix multiplication
262  ITensorPack pack_mm = tensors;
263  pack_mm.add_const_tensor(TensorType::ACL_SRC_0, input0.get());
264  pack_mm.add_tensor(TensorType::ACL_DST, batched_mm_output.get());
265  is_gemm_reshaped ? pack_mm.remove_tensor(TensorType::ACL_SRC_1) : pack_mm.add_const_tensor(TensorType::ACL_SRC_1, input1.get());
266  _batched_mm.run(pack_mm);
267 
268  // Run output transform
269  ITensorPack pack_ot
270  {
271  { TensorType::ACL_SRC_0, batched_mm_output.get() },
272  { TensorType::ACL_SRC_1, biases },
273  { TensorType::ACL_DST, dst },
274  };
275  CLScheduler::get().enqueue_op(*_output_transform, pack_ot);
276 }
277 
279 {
280  if(!_is_prepared)
281  {
282  auto weights = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC_1));
283  ICLTensor *in1_aux = utils::cast::polymorphic_downcast<ICLTensor *>(tensors.get_tensor(offset_int_vec(3)));
284 
285  CLAuxTensorHandler input1(_input1, *in1_aux);
286  ITensorPack pack_ft
287  {
288  { TensorType::ACL_SRC, weights },
289  { TensorType::ACL_DST, input1.get() },
290  };
291  // Run filter transform and mark original weights as unused
292  CLScheduler::get().enqueue_op(*_filter_transform, pack_ft, false);
293  weights->mark_as_unused();
294 
295  // Prepare GEMM and release reshaped weights if marked unused by ClGemm
296  ITensorPack mm_prepare_pack = tensors;
297  mm_prepare_pack.add_tensor(ACL_SRC_1, input1.get());
298  _batched_mm.prepare(mm_prepare_pack);
299 
300  CLScheduler::get().queue().finish();
301  _is_prepared = true;
302  }
303 }
304 
306 {
307  return _aux_mem;
308 }
309 } // namespace opencl
310 } // namespace arm_compute
Class describing the value of a pixel for any image format.
Definition: PixelValue.h:34
Status validate(const OperatorGraph &op_graph)
Return the validity of op_graph, usually after performing an operation (e.g.
void configure(const CLCompileContext &compile_context, ICLTensor *tensor, BorderSize border_size, BorderMode border_mode, const PixelValue &constant_border_value=PixelValue())
Initialise the kernel&#39;s input, output and border mode.
TensorShape compute_winograd_input_transform_shape(const ITensorInfo &input, const WinogradInfo &winograd_info)
Calculate the winograd input transform shape.
void add_const_tensor(int id, const ITensor *tensor)
Add const tensor to the pack.
Definition: ITensorPack.cpp:49
static CLScheduler & get()
Access the scheduler singleton.
~ClWinogradConv2d()
Default destructor.
Winograd information.
Definition: Types.h:2328
#define ARM_COMPUTE_RETURN_ON_ERROR(status)
Checks if a status contains an error and returns it.
Definition: Error.h:204
virtual DataType data_type() const =0
Data type used for each element of the tensor.
void configure(const CLCompileContext &compile_context, ITensorInfo *a, ITensorInfo *b, ITensorInfo *c, ITensorInfo *output, float alpha, float beta, const GEMMInfo &gemm_info)
Initialise the kernel&#39;s inputs and output.
Definition: ClGemm.cpp:461
1 channel, 1 F32 per channel
void prepare(ITensorPack &tensors) override
Prepare the function for executing.
Store the tensor&#39;s metadata.
Definition: ITensorInfo.h:40
#define ARM_COMPUTE_ERROR_THROW_ON(status)
Definition: Error.h:455
Status class.
Definition: Error.h:52
Status validate_arguments(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *dst, const PadStrideInfo &conv_info)
Activation Layer Information class.
Definition: Types.h:1625
SimpleTensor< float > src
Definition: DFT.cpp:155
Copyright (c) 2017-2022 Arm Limited.
std::vector< MemoryInfo > MemoryRequirements
Definition: Types.h:134
1 channel, 1 F16 per channel
static Status validate(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst, const PadStrideInfo &conv_info, const ActivationLayerInfo &act_info=ActivationLayerInfo(), bool enable_fast_math=false)
Static function to check if given info will lead to a valid configuration.
Interface to enqueue OpenCL kernels and get/set the OpenCL CommandQueue and ICLTuner.
const ITensor * get_const_tensor(int id) const
Get constant tensor of a given id.
Definition: ITensorPack.cpp:54
void remove_tensor(int id)
Remove the tensor stored with the given id.
Definition: ITensorPack.cpp:70
virtual const TensorShape & tensor_shape() const =0
Size for each dimension of the tensor.
#define ARM_COMPUTE_ERROR_ON_MSG(cond, msg)
Definition: Error.h:456
size_t total_size() const override
Returns the total size of the tensor in bytes.
Definition: TensorInfo.h:250
void enqueue_op(ICLKernel &kernel, ITensorPack &tensors, bool flush=true)
Schedule the execution of the passed kernel if possible.
GEMMLowp output stage info.
Definition: Types.h:2038
Padding and stride information class.
Definition: Types.h:669
void end(TokenStream &in, bool &valid)
Definition: MLGOParser.cpp:290
void configure(const ClCompileContext &compile_context, ITensorInfo *src, ITensorInfo *weights, ITensorInfo *biases, ITensorInfo *dst, const PadStrideInfo &conv_info, const ActivationLayerInfo &act_info=ActivationLayerInfo(), bool enable_fast_math=false)
Set the input and output tensors.
TensorShape compute_winograd_filter_transform_shape(const ITensorInfo &input, const WinogradInfo &winograd_info)
Calculate the winograd filter transform shape.
cl::CommandQueue & queue()
Accessor for the associated CL command queue.
Definition: CLScheduler.cpp:43
void run(ITensorPack &tensors) override
Run the kernels contained in the function.
Num samples, channels, height, width.
#define ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(t, c,...)
Definition: Validate.h:786
CLCompileContext class.
ITensor * get_tensor(int id)
Get tensor of a given id from the pac.
Definition: ITensorPack.cpp:64
Interface for OpenCL tensor.
Definition: ICLTensor.h:42
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
Class for specifying the size of an image or rectangle.
Definition: Size2D.h:34
#define ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(t, c,...)
Definition: Validate.h:788
void run(ITensorPack &tensors) override
Run the kernels contained in the function.
Definition: ClGemm.cpp:557
#define ARM_COMPUTE_RETURN_ERROR_ON_MSG(cond, msg)
If the condition is true, an error is returned.
Definition: Error.h:244
Tensor packing service.
Definition: ITensorPack.h:39
#define ARM_COMPUTE_LOG_PARAMS(...)
void prepare(ITensorPack &constants) override
Prepare the function for executing.
Definition: ClGemm.cpp:637
int offset_int_vec(int offset)
Definition: MemoryHelpers.h:38
GEMM information class.
Definition: Types.h:2090
DataLayout
[DataLayout enum definition]
Definition: Types.h:113
experimental::MemoryRequirements workspace() const override
Return the memory requirements required by the workspace.
void add_tensor(int id, ITensor *tensor)
Add tensor to the pack.
Definition: ITensorPack.cpp:39
virtual DataLayout data_layout() const =0
Get the data layout of the tensor.
experimental::MemoryRequirements workspace() const override
Return the memory requirements required by the workspace.
Definition: ClGemm.cpp:659