Compute Library
 22.11
CpuGemmConv2d.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2021-2022 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 
28 #include "arm_compute/core/Utils.h"
33 
34 #include "src/common/utils/Log.h"
44 
45 #include <set>
46 #include <tuple>
47 
49 using namespace arm_compute::experimental;
50 
51 namespace arm_compute
52 {
53 namespace cpu
54 {
55 CpuGemmConv2d::SkipInfo CpuGemmConv2d::skip_im_col_info(const ITensorInfo *src, const ITensorInfo *weights, const PadStrideInfo &conv_info,
56  const Size2D &dilation, const ActivationLayerInfo &act_info)
57 {
58  const DataLayout data_layout = src->data_layout();
61  const unsigned int kernel_width = weights->dimension(idx_width);
62  const unsigned int kernel_height = weights->dimension(idx_height);
63  unsigned int conv_w = 0;
64  unsigned int conv_h = 0;
65  std::tie(conv_w, conv_h) = scaled_dimensions(src->dimension(idx_width),
66  src->dimension(idx_height),
67  kernel_width,
68  kernel_height,
69  conv_info,
70  dilation);
71  const bool skip_im2col = (data_layout == DataLayout::NHWC && kernel_width == 1 && kernel_height == 1 && conv_info.stride().first == 1 && conv_info.stride().second == 1);
72 
73  if(skip_im2col)
74  {
75  const bool skip_col2im = (data_layout == DataLayout::NHWC && (bool(CpuGemmConv2d::validate_gemm3d(src, weights, act_info, conv_h, /*skip_im2col*/ true))));
76  if(skip_col2im)
77  {
78  return { true, true };
79  }
80  }
81  else
82  {
83  const bool skip_col2im = (data_layout == DataLayout::NHWC && (bool(CpuGemmConv2d::validate_gemm3d(src, weights, act_info, conv_h, /*skip_im2col*/ false))));
84  if(skip_col2im)
85  {
86  return { false, true };
87  }
88  }
89 
90  // Default case when we cannot reinterpret the input and output as 3D.
91  return { false, false };
92 }
93 
94 CpuGemmConv2d::CpuGemmConv2d()
95  : _weights_reshape_kernel(nullptr), _im2col_kernel(), _mm_gemm(), _mm_gemmlowp(), _col2im_kernel(), _reshape_kernel(), _im2col_output(), _weights_reshaped(), _gemm_output(), _gemm_output_3d(),
96  _data_layout(DataLayout::NCHW), _skip_im2col(false), _skip_col2im(false), _is_quantized(false), _is_prepared(false), _aux_mem(AuxTensorIdx::Count)
97 {
98 }
100 
101 void CpuGemmConv2d::configure_mm(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst, const ActivationLayerInfo &act_info,
102  bool enable_fast_math, int gemm_3d_depth, bool fixed_format, arm_compute::WeightFormat weight_format)
103 {
104  ARM_COMPUTE_ERROR_ON_NULLPTR(src, weights);
105  ARM_COMPUTE_ERROR_THROW_ON(validate_mm(src, weights, biases, dst, act_info, enable_fast_math, gemm_3d_depth, _skip_im2col, fixed_format, weight_format));
106 
107  // Create GEMMInfo structure
108  const GEMMInfo &gemm_info = GEMMInfo(false, false, true /* Reshape weights only for the first run */,
109  gemm_3d_depth, _skip_im2col /* Reinterpret the input as 3D if im2col is skipped */,
110  false, GEMMLowpOutputStageInfo(), false, enable_fast_math, false, act_info, experimental::PostOpList<ITensorInfo *>(), fixed_format, weight_format);
111 
112  // Supported activations in GEMM
113  const std::set<ActivationLayerInfo::ActivationFunction> supported_acts = { ActivationLayerInfo::ActivationFunction::RELU,
116  };
117 
118  if(_is_quantized)
119  {
120  TensorInfo tmp_src{ *src };
121  TensorInfo tmp_weights{ *weights };
122  // Since we need negative offsets for computing convolution, we need to change QuantizationInfo()
123  // Extract and negate input and weights offset
124  const QuantizationInfo iqinfo = src->quantization_info();
125  const QuantizationInfo wqinfo = weights->quantization_info();
126  const QuantizationInfo oqinfo = (dst->total_size() == 0) ? iqinfo : dst->quantization_info();
127  const UniformQuantizationInfo uiqinfo = iqinfo.uniform();
128  const UniformQuantizationInfo uoqinfo = oqinfo.uniform();
129  const DataType data_type = src->data_type();
130 
131  tmp_src.set_quantization_info(QuantizationInfo(uiqinfo.scale, -uiqinfo.offset));
132  if(!is_data_type_quantized_per_channel(tmp_weights.data_type()))
133  {
134  const UniformQuantizationInfo uwqinfo = wqinfo.uniform();
135  tmp_weights.set_quantization_info(QuantizationInfo(uwqinfo.scale, -uwqinfo.offset));
136  }
137 
138  // Merge activation with output stage
139  PixelValue type_min{};
140  PixelValue type_max{};
141  std::tie(type_min, type_max) = get_min_max(data_type);
142  int32_t min_activation = type_min.get<int32_t>();
143  int32_t max_activation = type_max.get<int32_t>();
144 
145  if(supported_acts.count(act_info.activation()) != 0)
146  {
147  std::tie(min_activation, max_activation) = get_quantized_activation_min_max(act_info, data_type, uoqinfo);
148  }
149 
152  output_info.gemmlowp_offset = uoqinfo.offset;
153  output_info.gemmlowp_min_bound = min_activation;
154  output_info.gemmlowp_max_bound = max_activation;
155  output_info.is_quantized_per_channel = (tmp_weights.data_type() == DataType::QSYMM8_PER_CHANNEL);
156  quantization::calculate_quantized_multipliers(iqinfo, wqinfo, oqinfo, output_info);
157 
158  _mm_gemmlowp = std::make_unique<CpuGemmLowpMatrixMultiplyCore>();
159  _mm_gemmlowp->configure(&tmp_src, &tmp_weights, biases, dst, GEMMInfo(false, false, true, gemm_3d_depth, _skip_im2col, false, output_info, false, enable_fast_math, false, act_info,
160  experimental::PostOpList<ITensorInfo *>(), fixed_format, weight_format));
161 
162  auto mm_mem_req = _mm_gemmlowp->workspace();
163  for(unsigned int cont = 0; cont < mm_mem_req.size(); ++cont)
164  {
165  _aux_mem[cont] = mm_mem_req[cont];
166  }
167  }
168  else
169  {
170  // Configure matrix multiply function
171  _mm_gemm = std::make_unique<CpuGemm>();
172  _mm_gemm->configure(src, weights, biases, dst, 1.0f, 0.0f, gemm_info);
173  auto mm_mem_req = _mm_gemm->workspace();
174  for(unsigned int cont = 0; cont < mm_mem_req.size(); ++cont)
175  {
176  _aux_mem[cont] = mm_mem_req[cont];
177  }
178  }
179 }
180 
181 Status CpuGemmConv2d::validate_mm(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst,
182  const ActivationLayerInfo &act_info, bool enable_fast_math, int gemm_3d_depth, bool skip_im2col, bool fixed_format, arm_compute::WeightFormat weight_format)
183 {
184  const DataType data_type = src->data_type();
185  const bool is_quantized = is_data_type_quantized_asymmetric(data_type);
186  const bool is_activation_enabled = act_info.enabled();
187 
188  // Create GEMMInfo structure
189  const GEMMInfo gemm_info = GEMMInfo(false, false, true /* Reshape weights only for the first run */,
190  gemm_3d_depth, skip_im2col /* Reinterpret the input as 3D if im2col is skipped */,
191  false, GEMMLowpOutputStageInfo(), false, enable_fast_math, false, act_info, experimental::PostOpList<ITensorInfo *>(), fixed_format, weight_format);
192 
193  if(is_quantized)
194  {
195  // Since we need negative offsets for computing convolution, we need to change QuantizationInfo()
196  // Extract and negate input and weights offset
197  const QuantizationInfo &iqinfo = src->quantization_info();
198  const QuantizationInfo &wqinfo = weights->quantization_info();
199  const QuantizationInfo &oqinfo = (dst->total_size() == 0) ? iqinfo : dst->quantization_info();
200  const UniformQuantizationInfo uoqinfo = oqinfo.uniform();
201 
202  // Merge activation with output stage
203  PixelValue type_min{};
204  PixelValue type_max{};
205  std::tie(type_min, type_max) = get_min_max(data_type);
206  int32_t min_activation = type_min.get<int32_t>();
207  int32_t max_activation = type_max.get<int32_t>();
208 
209  const std::set<ActivationLayerInfo::ActivationFunction> supported_acts = { ActivationLayerInfo::ActivationFunction::RELU,
212  };
213  if(is_activation_enabled && supported_acts.count(act_info.activation()) != 0)
214  {
215  std::tie(min_activation, max_activation) = get_quantized_activation_min_max(act_info, data_type, uoqinfo);
216  }
217 
220  output_info.gemmlowp_offset = uoqinfo.offset;
221  output_info.gemmlowp_min_bound = min_activation;
222  output_info.gemmlowp_max_bound = max_activation;
225 
226  // Perform validation step on GEMMLowp
227  std::unique_ptr<ITensorInfo> input_qa = src->clone();
228  std::unique_ptr<ITensorInfo> weights_qa = weights->clone();
229  input_qa->set_quantization_info(QuantizationInfo(iqinfo.uniform().scale, -iqinfo.uniform().offset));
230  weights_qa->set_quantization_info(QuantizationInfo(wqinfo.uniform().scale, -wqinfo.uniform().offset));
231 
232  return CpuGemmLowpMatrixMultiplyCore::validate(input_qa.get(), weights_qa.get(), biases, dst, GEMMInfo(false, false, true, gemm_3d_depth, skip_im2col, false, output_info, false, enable_fast_math,
233  false, act_info));
234  }
235  else
236  {
237  // Perform validation step on Matrix multiply function
238  return CpuGemm::validate(src, weights, nullptr, dst, 1.0f, 0.0f, gemm_info);
239  }
240 }
241 
242 Status CpuGemmConv2d::validate_gemm3d(const ITensorInfo *input_info, const ITensorInfo *weights_info, const ActivationLayerInfo &act_info, int gemm_3d_depth, bool skip_im2col)
243 {
244  const DataType data_type = input_info->data_type();
245  const unsigned int mult_y = skip_im2col ? 1U : gemm_3d_depth;
246  const unsigned int mult_z = skip_im2col ? gemm_3d_depth : 1U;
247 
248  // Set dummy tensor shapes for the validation
249  const TensorInfo dummy_input_info(TensorShape(4U, 4U * mult_y, 1U * mult_z), 1, data_type, input_info->quantization_info());
250  const TensorInfo dummy_weights_info(TensorShape(4U, 4U), 1, data_type, weights_info->quantization_info());
251  const TensorInfo dummy_output_info(TensorShape(4U, 4U, gemm_3d_depth), 1, data_type, input_info->quantization_info());
252 
253  return validate_mm(&dummy_input_info, &dummy_weights_info, nullptr, &dummy_output_info, act_info, false, gemm_3d_depth, skip_im2col);
254 }
255 
256 void CpuGemmConv2d::configure(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst, const PadStrideInfo &conv_info, const WeightsInfo &weights_info,
257  const Size2D &dilation, const ActivationLayerInfo &act_info, bool enable_fast_math, unsigned int num_groups)
258 {
259  ARM_COMPUTE_ERROR_ON_NULLPTR(src, weights, dst);
260  ARM_COMPUTE_UNUSED(num_groups, weights_info);
262  weights,
263  biases,
264  dst,
265  conv_info,
266  weights_info,
267  dilation,
268  act_info,
269  enable_fast_math,
270  num_groups));
271  ARM_COMPUTE_LOG_PARAMS(src, weights, biases, dst, conv_info, weights_info, dilation, act_info, enable_fast_math, num_groups);
272 
273  const DataType data_type = src->data_type();
274  const DataLayout data_layout = src->data_layout();
275  const int idx_width = get_data_layout_dimension_index(data_layout, DataLayoutDimension::WIDTH);
276  const int idx_height = get_data_layout_dimension_index(data_layout, DataLayoutDimension::HEIGHT);
277  const int idx_kernels = get_data_layout_dimension_index(data_layout, DataLayoutDimension::BATCHES);
278 
279  const unsigned int kernel_width = weights->dimension(idx_width);
280  const unsigned int kernel_height = weights->dimension(idx_height);
281 
282  _is_prepared = weights_info.retain_internal_weights();
283  _is_quantized = is_data_type_quantized_asymmetric(src->data_type());
284  _data_layout = data_layout;
285  _skip_im2col = (data_layout == DataLayout::NHWC && kernel_width == 1 && kernel_height == 1 && conv_info.stride().first == 1 && conv_info.stride().second == 1);
286 
287  const ITensorInfo *gemm_input_to_use = src;
288  ITensorInfo *gemm_output_to_use = dst;
289 
290  // Get convolved dimensions
291  unsigned int conv_w = 0;
292  unsigned int conv_h = 0;
293  std::tie(conv_w, conv_h) = scaled_dimensions(src->dimension(idx_width),
294  src->dimension(idx_height),
295  kernel_width,
296  kernel_height,
297  conv_info,
298  dilation);
299 
300  ARM_COMPUTE_ERROR_ON_MSG((dst->dimension(idx_width) != conv_w) || (dst->dimension(idx_height) != conv_h),
301  "Output shape does not match the expected one");
302 
303  // Check if GEMM3D is supported
304  const CpuGemmConv2d::SkipInfo skip_info = CpuGemmConv2d::skip_im_col_info(src, weights, conv_info, dilation, act_info);
305  _skip_im2col = skip_info.skip_im2col;
306  _skip_col2im = skip_info.skip_col2im;
307 
308  // Get parameters from conv_info
309  unsigned int stride_x = 0;
310  unsigned int stride_y = 0;
311  std::tie(stride_x, stride_y) = conv_info.stride();
312 
313  unsigned int mat_weights_cols = weights->dimension(idx_kernels);
314 
315  // _weights_reshaped will be auto configured in the kernel.
316  // Just append biases and do not transpose 1xW as it will be reshaped in CpuGemm
317  _weights_reshape_kernel = std::make_unique<kernels::CpuWeightsReshapeKernel>();
318  _weights_reshape_kernel->configure(weights, nullptr, &_weights_reshaped);
319  _weights_reshaped.set_quantization_info(weights->quantization_info());
320 
321  // Create tensor to store im2col reshaped inputs
322  if(!_skip_im2col)
323  {
324  // Configure
325  _im2col_kernel = std::make_unique<kernels::CpuIm2ColKernel>();
326  _im2col_kernel->configure(src, &_im2col_output, Size2D(kernel_width, kernel_height), conv_info, false, dilation);
327 
328  // Update GEMM input
329  gemm_input_to_use = &_im2col_output;
330  }
331 
332  // Create temporary GEMM output tensor in case we cannot skip col2im
333  const DataType output_data_type = data_type == DataType::BFLOAT16 ? DataType::F32 : data_type;
334  if(!_skip_col2im)
335  {
336  TensorShape shape_gemm;
337 
338  // Calculate GEMM output shape
339  shape_gemm = _im2col_output.tensor_shape();
340  shape_gemm.set(0, mat_weights_cols);
341  shape_gemm.set(1, conv_w * conv_h);
342 
343  _gemm_output = TensorInfo(shape_gemm, 1, output_data_type);
345  _gemm_output_3d = TensorInfo(_gemm_output);
346 
347  // Update GEMM output
348  gemm_output_to_use = &_gemm_output;
349  }
350  else
351  {
352  _gemm_output_3d = TensorInfo(*dst);
353  _gemm_output_3d.set_data_type(output_data_type).set_data_layout(src->data_layout()).set_is_resizable(true);
354  _gemm_output = TensorInfo(_gemm_output_3d);
355 
356  // Update GEMM output
357  gemm_output_to_use = &_gemm_output_3d;
358  }
359 
360  // Configure GEMM
361  // In case we need to skip col2im, GEMM3D (gemm_3d_depth != 0) must be called in order to avoid reshaping the output matrix
362  const unsigned int gemm_3d_depth = _skip_col2im ? conv_h : 0;
363  const bool fixed_format = weights_info.weight_format() != arm_compute::WeightFormat::UNSPECIFIED;
364  configure_mm(gemm_input_to_use, &_weights_reshaped, biases, gemm_output_to_use, act_info, enable_fast_math, gemm_3d_depth, fixed_format, weights_info.weight_format());
365 
366  if(!_skip_col2im && _data_layout == DataLayout::NCHW)
367  {
368  // Configure col2im
369  _col2im_kernel = std::make_unique<kernels::CpuCol2ImKernel>();
370  _col2im_kernel->configure(gemm_output_to_use, dst, Size2D(conv_w, conv_h));
371  }
372  else
373  {
374  // Configure reshape layer
375  _reshape_kernel = std::make_unique<kernels::CpuReshapeKernel>();
376  _reshape_kernel->configure(gemm_output_to_use, dst);
377  }
378 
379  // Check if GEMM transforms weights
380  // Modernise through COMPMID-4535
381  bool gemm_trans_wei = _aux_mem[1].size > 0; // Asm Pretranspose
382  gemm_trans_wei = _mm_gemm != nullptr ? _aux_mem[3].size > 0 : gemm_trans_wei; // Tranpose RHS
383  gemm_trans_wei = _mm_gemmlowp != nullptr ? _aux_mem[5].size > 0 : gemm_trans_wei; // Transpose RHS
384 
385  // Check lifetime
386  _aux_mem[Im2ColOutput] = MemoryInfo(offset_int_vec(Im2ColOutput), MemoryLifetime::Temporary, _im2col_output.total_size());
387  _aux_mem[WeightsReshaped] = MemoryInfo(offset_int_vec(WeightsReshaped), gemm_trans_wei ? MemoryLifetime::Prepare : MemoryLifetime::Persistent, _weights_reshaped.total_size());
388  _aux_mem[GemmOutput] = MemoryInfo(offset_int_vec(GemmOutput), MemoryLifetime::Temporary, _gemm_output.total_size());
389 }
390 
391 Status CpuGemmConv2d::has_opt_impl(arm_compute::WeightFormat &expected_weight_format, const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst,
392  const PadStrideInfo &conv_info,
393  const WeightsInfo &weights_info, const Size2D &dilation, const ActivationLayerInfo &act_info, const bool enable_fast_math)
394 {
395  const DataLayout data_layout = src->data_layout();
396  const int idx_width = get_data_layout_dimension_index(data_layout, DataLayoutDimension::WIDTH);
397  const int idx_height = get_data_layout_dimension_index(data_layout, DataLayoutDimension::HEIGHT);
398  const unsigned int kernel_width = weights->dimension(idx_width);
399  const unsigned int kernel_height = weights->dimension(idx_height);
400  unsigned int conv_w = 0;
401  unsigned int conv_h = 0;
402  std::tie(conv_w, conv_h) = scaled_dimensions(src->dimension(idx_width),
403  src->dimension(idx_height),
404  kernel_width,
405  kernel_height,
406  conv_info,
407  dilation);
408 
409  const CpuGemmConv2d::SkipInfo skip_info = CpuGemmConv2d::skip_im_col_info(src, weights, conv_info,
410  dilation, act_info);
411 
412  const bool skip_im2col = skip_info.skip_im2col;
413  const bool skip_col2im = skip_info.skip_col2im;
414  const unsigned int gemm_3d_depth = skip_col2im ? conv_h : 0;
415  const bool fixed_format = weights_info.weight_format() != arm_compute::WeightFormat::UNSPECIFIED;
416  const GEMMInfo gemm_info = GEMMInfo(false, false, true /* Reshape weights only for the first run */,
417  gemm_3d_depth, skip_im2col /* Reinterpret the input as 3D if im2col is skipped */,
418  false, GEMMLowpOutputStageInfo(), false, enable_fast_math, false, act_info, experimental::PostOpList<ITensorInfo *>(), fixed_format, weights_info.weight_format());
419 
420  return CpuGemm::has_opt_impl(expected_weight_format, src, weights, biases, dst, gemm_info);
421 }
422 
423 Status CpuGemmConv2d::validate(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst, const PadStrideInfo &conv_info,
424  const WeightsInfo &weights_info, const Size2D &dilation, const ActivationLayerInfo &act_info, bool enable_fast_math, unsigned int num_groups)
425 {
426  ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(src, weights, dst);
427  ARM_COMPUTE_RETURN_ERROR_ON_MSG(weights_info.are_reshaped(), "Weights already reshaped are not supported!");
431  ARM_COMPUTE_RETURN_ERROR_ON_MSG(num_groups > 1, "Grouping (num_groups != 1) is not supported");
432 
433  const DataLayout data_layout = src->data_layout();
434  const DataType data_type = src->data_type();
435  const int idx_width = get_data_layout_dimension_index(data_layout, DataLayoutDimension::WIDTH);
436  const int idx_height = get_data_layout_dimension_index(data_layout, DataLayoutDimension::HEIGHT);
437  const int idx_channel = get_data_layout_dimension_index(data_layout, DataLayoutDimension::CHANNEL);
438  const int idx_kernels = get_data_layout_dimension_index(data_layout, DataLayoutDimension::BATCHES);
439 
440  const unsigned int kernel_width = weights->dimension(idx_width);
441  const unsigned int kernel_height = weights->dimension(idx_height);
442 
443  TensorInfo im2col_reshaped_info{};
444  TensorInfo info_gemm{};
445  TensorInfo tmp_info{};
446  TensorInfo weights_reshaped_info{};
447  const ITensorInfo *gemm_input_to_use = src;
448  const ITensorInfo *gemm_output_to_use = dst;
449  const ITensorInfo *weights_to_use = weights;
450 
451  const bool append_bias = false;
452  const bool is_quantized = is_data_type_quantized_asymmetric(data_type);
453  const bool is_bf16 = data_type == DataType::BFLOAT16;
454 
455  // Get convolved dimensions
456  unsigned int conv_w = 0;
457  unsigned int conv_h = 0;
458 
459  std::tie(conv_w, conv_h) = scaled_dimensions(src->dimension(idx_width),
460  src->dimension(idx_height),
461  kernel_width,
462  kernel_height,
463  conv_info,
464  dilation);
465 
466  // Check if GEMM3D is supported
467  const CpuGemmConv2d::SkipInfo skip_info = CpuGemmConv2d::skip_im_col_info(src, weights, conv_info,
468  dilation, act_info);
469  const bool skip_im2col = skip_info.skip_im2col, skip_col2im = skip_info.skip_col2im;
470 
471  ARM_COMPUTE_RETURN_ERROR_ON(weights->dimension(idx_channel) != src->dimension(idx_channel));
473 
474  // Validate biases
475  if(biases != nullptr)
476  {
477  if(is_quantized)
478  {
480  }
481  else if(is_bf16)
482  {
484  }
485  else
486  {
488  }
489  ARM_COMPUTE_RETURN_ERROR_ON(biases->dimension(0) != dst->dimension(idx_channel));
491  }
492 
493  unsigned int mat_weights_cols = weights->dimension(idx_kernels);
494  unsigned int mat_weights_rows = weights->dimension(idx_width) * weights->dimension(idx_height) * weights->dimension(idx_channel);
495 
496  weights_reshaped_info = TensorInfo(compute_weights_reshaped_shape(*weights, append_bias), 1, data_type);
497  weights_reshaped_info.set_quantization_info(weights->quantization_info());
498  weights_to_use = &weights_reshaped_info;
499 
500  if(!skip_im2col)
501  {
502  // Create tensor info for im2col reshaped inputs
503  // For CPU, the batch size is on the fourth dimension
504  TensorShape shape_im2col = src->tensor_shape();
505  shape_im2col.set(0, mat_weights_rows);
506  shape_im2col.set(1, conv_w * conv_h);
507  shape_im2col.set(2, 1);
508 
509  im2col_reshaped_info = TensorInfo(shape_im2col, 1, data_type);
510  im2col_reshaped_info.set_quantization_info(src->quantization_info());
511  ARM_COMPUTE_RETURN_ON_ERROR(kernels::CpuIm2ColKernel::validate(src, &im2col_reshaped_info, Size2D(kernel_width, kernel_height), conv_info, append_bias, dilation, 1));
512  gemm_input_to_use = &im2col_reshaped_info;
513  }
514 
515  // Create temporary GEMM output tensor in case we cannot skip col2im
516  const DataType output_data_type = data_type == DataType::BFLOAT16 ? DataType::F32 : data_type;
517  if(!skip_col2im)
518  {
519  TensorShape shape_gemm = gemm_input_to_use->tensor_shape();
520  shape_gemm.set(0, mat_weights_cols);
521  shape_gemm.set(1, conv_w * conv_h);
522  info_gemm = TensorInfo(shape_gemm, 1, output_data_type);
523  }
524  else
525  {
526  info_gemm = TensorInfo(dst->tensor_shape(), 1, output_data_type);
527  }
529  gemm_output_to_use = &info_gemm;
530  const bool fixed_format = weights_info.weight_format() != arm_compute::WeightFormat::UNSPECIFIED;
531 
532  ARM_COMPUTE_RETURN_ON_ERROR(validate_mm(gemm_input_to_use, weights_to_use, biases, gemm_output_to_use, act_info, enable_fast_math, skip_col2im ? conv_h : 0, skip_im2col, fixed_format,
533  weights_info.weight_format()));
534 
535  // Validate Col2Im/ReshapeLayer
536  if(!skip_col2im && (data_layout == DataLayout::NCHW))
537  {
538  ARM_COMPUTE_RETURN_ON_ERROR(kernels::CpuCol2ImKernel::validate(gemm_output_to_use, dst, Size2D(conv_w, conv_h)));
539  }
540 
541  return Status{};
542 }
543 
545 {
546  prepare(tensors);
547 
548  auto src = tensors.get_const_tensor(ACL_SRC_0);
549  auto dst = tensors.get_tensor(ACL_DST);
550  auto gemm_input_to_use = src;
551 
552  CpuAuxTensorHandler im2col_output(offset_int_vec(Im2ColOutput), _im2col_output, tensors, false);
553  CpuAuxTensorHandler gemm_output(offset_int_vec(GemmOutput), _gemm_output, tensors, false);
554  CpuAuxTensorHandler reshaped_wei(offset_int_vec(WeightsReshaped), _weights_reshaped, tensors, false);
555 
556  bool out_has_padding = _skip_col2im && (dst->info()->padding().bottom != 0 || dst->info()->padding().top != 0);
557  if(!_skip_im2col)
558  {
559  // Run input reshaping
560  unsigned int y_dim = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::HEIGHT);
561  ITensorPack pack =
562  {
563  { TensorType::ACL_SRC, src },
564  { TensorType::ACL_DST, im2col_output.get() }
565  };
566  NEScheduler::get().schedule_op(_im2col_kernel.get(), y_dim, _im2col_kernel->window(), pack);
567  gemm_input_to_use = im2col_output.get();
568  }
569 
570  // Handle the case where output has top/bottom padding
571  const ITensor *out_to_use = out_has_padding ? gemm_output.get() : dst;
572  Tensor gemm3d;
573  _gemm_output_3d.extend_padding(out_to_use->info()->padding());
574  gemm3d.allocator()->soft_init(_gemm_output_3d);
575  gemm3d.allocator()->import_memory(out_to_use->buffer());
576  auto gemm_output_to_use = gemm_output.get();
577 
578  if(_skip_im2col)
579  {
580  gemm_output_to_use = &gemm3d;
581  }
582  if(_skip_col2im && !out_has_padding)
583  {
584  gemm_output_to_use = dst;
585  }
586 
587  // Runs CpuGemm or CpuGemmLowpMatrixMultiplyCore functions
588  ITensorPack pack_mm = tensors;
589  pack_mm.add_const_tensor(TensorType::ACL_SRC_0, gemm_input_to_use);
590  if(!this->isVarWeightsKernel())
591  {
592  pack_mm.add_const_tensor(TensorType::ACL_SRC_1, reshaped_wei.get());
593  }
594  pack_mm.add_tensor(TensorType::ACL_DST, gemm_output_to_use);
595  if(_is_quantized)
596  {
597  // Run gemmlowp
598  _mm_gemmlowp->run(pack_mm);
599  }
600  else
601  {
602  // Run gemm
603  _mm_gemm->run(pack_mm);
604  }
605 
606  // Reshape output matrix
607  if(!_skip_col2im)
608  {
609  if(_data_layout == DataLayout::NCHW)
610  {
611  ITensorPack pack =
612  {
613  { TensorType::ACL_SRC, gemm_output.get() },
614  { TensorType::ACL_DST, dst }
615  };
616  NEScheduler::get().schedule_op(_col2im_kernel.get(), Window::DimY, _col2im_kernel->window(), pack);
617  }
618  else
619  {
620  ITensorPack pack =
621  {
622  { TensorType::ACL_SRC, gemm_output_to_use },
623  { TensorType::ACL_DST, dst }
624  };
625  NEScheduler::get().schedule_op(_reshape_kernel.get(), Window::DimY, _reshape_kernel->window(), pack);
626  }
627  }
628  else if(out_has_padding)
629  {
630  ITensorPack pack =
631  {
632  { TensorType::ACL_SRC, gemm_output_to_use },
633  { TensorType::ACL_DST, dst }
634  };
635  NEScheduler::get().schedule_op(_reshape_kernel.get(), Window::DimY, _reshape_kernel->window(), pack);
636  }
637 }
638 
640 {
641  if(!_is_prepared)
642  {
643  // Variable weights executions that use fixed-format kernels
644  // need no reshaping of the weights.
645  if(this->isVarWeightsKernel())
646  {
647  _is_quantized ? _mm_gemmlowp->prepare(tensors) : _mm_gemm->prepare(tensors);
648  _is_prepared = true;
649  return;
650  }
651 
652  // Run weights reshaping and mark original weights tensor as unused
653  CpuAuxTensorHandler weights_reshaped(offset_int_vec(WeightsReshaped), _weights_reshaped, tensors);
654  auto weights = tensors.get_const_tensor(TensorType::ACL_SRC_1);
655  ITensorPack pack =
656  {
657  { TensorType::ACL_SRC, weights },
658  { TensorType::ACL_DST, weights_reshaped.get() }
659  };
660  NEScheduler::get().schedule_op(_weights_reshape_kernel.get(), 3, _weights_reshape_kernel->window(), pack);
661  weights->mark_as_unused();
662  ITensorPack gemm_pack = tensors;
663  gemm_pack.add_const_tensor(TensorType::ACL_SRC_1, weights_reshaped.get());
664  _is_quantized ? _mm_gemmlowp->prepare(gemm_pack) : _mm_gemm->prepare(gemm_pack);
665  _is_prepared = true;
666  }
667 }
669 {
670  return _aux_mem;
671 }
672 bool CpuGemmConv2d::isVarWeightsKernel() const
673 {
674  return _mm_gemm && _mm_gemm->isVarWeightsKernel();
675 }
676 } // namespace cpu
677 } // namespace arm_compute
unsigned int top
top of the border
Definition: Types.h:390
virtual size_t num_dimensions() const =0
The number of dimensions of the tensor (rank)
Class describing the value of a pixel for any image format.
Definition: PixelValue.h:34
Shape of a tensor.
Definition: TensorShape.h:39
Quantize using a fixed point multiplication.
void soft_init(TensorInfo &input, size_t alignment=0)
Initialize a tensor based with a reference TensorInfo.
static Status has_opt_impl(arm_compute::WeightFormat &weight_format, const ITensorInfo *a, const ITensorInfo *b, const ITensorInfo *c, const ITensorInfo *d, const GEMMInfo &gemm_info=GEMMInfo())
Indicates whether or not there is an optimal assembly implementation that can be used to process the ...
Definition: CpuGemm.cpp:371
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_LAYOUT(...)
Definition: Validate.h:490
bool enabled() const
Check if initialised.
Definition: Types.h:1694
virtual size_t dimension(size_t index) const =0
Return the size of the requested dimension.
void add_const_tensor(int id, const ITensor *tensor)
Add const tensor to the pack.
Definition: ITensorPack.cpp:49
#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.
virtual void schedule_op(ICPPKernel *kernel, const Hints &hints, const Window &window, ITensorPack &tensors)=0
Runs the kernel in the same thread as the caller synchronously.
static Status validate(const ITensorInfo *a, const ITensorInfo *b, const ITensorInfo *c, const ITensorInfo *d, float alpha, float beta, const GEMMInfo &gemm_info=GEMMInfo())
Static function to check if given info will lead to a valid configuration of CpuGemm.
Definition: CpuGemm.cpp:153
bool extend_padding(const PaddingSize &padding) override
Update the offset to the first element, the strides and the total size.
Definition: TensorInfo.cpp:267
bool are_reshaped() const
Flag which specifies if the weights tensor has been reshaped.
Definition: Types.h:2099
1 channel, 1 F32 per channel
ITensorInfo & set_data_type(DataType data_type) override
Set the data type to the specified value.
Definition: TensorInfo.cpp:307
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.
unsigned int bottom
bottom of the border
Definition: Types.h:392
WeightFormat
Memory layouts for the weights tensor.
Definition: Types.h:2015
int32_t gemmlowp_offset
GEMMLowp output stage offset used for quantizing to QASYMM8.
Definition: Types.h:2290
Status class.
Definition: Error.h:52
int32_t gemmlowp_max_bound
GEMMLowp max value used to saturate down the output result before converting back to QASYMM8...
Definition: Types.h:2294
#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:1639
GEMMLowpOutputStageType type
GEMMLowp output stage type.
Definition: Types.h:2289
Interface for CPU tensor.
Definition: ITensor.h:36
static Status has_opt_impl(arm_compute::WeightFormat &expected_weight_format, const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *output, const PadStrideInfo &conv_info, const WeightsInfo &weights_info=WeightsInfo(), const Size2D &dilation=Size2D(1U, 1U), const ActivationLayerInfo &act_info=ActivationLayerInfo(), const bool enable_fast_math=false)
Indicates whether or not there is an optimal assembly implementation that can be used to process the ...
void prepare(ITensorPack &tensors) override
Prepare the function for executing.
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
std::pair< unsigned int, unsigned int > scaled_dimensions(int width, int height, int kernel_width, int kernel_height, const PadStrideInfo &pad_stride_info, const Size2D &dilation=Size2D(1U, 1U))
Returns expected width and height of output scaled tensor depending on dimensions rounding mode...
Definition: Utils.cpp:429
ITensorInfo & set_quantization_info(const QuantizationInfo &quantization_info) override
Set the quantization settings (scale and offset) of the tensor.
Definition: TensorInfo.cpp:366
TensorAllocator * allocator()
Return a pointer to the tensor&#39;s allocator.
Definition: Tensor.cpp:48
bool is_quantized_per_channel
GEMMLowp quantized per-channel flag.
Definition: Types.h:2298
Convolution Layer Weights Information class.
Definition: Types.h:2073
#define ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(...)
Definition: Validate.h:159
void run(ITensorPack &tensors) override
Run the kernels contained in the function.
1 channel, 1 S32 per channel
16-bit brain floating-point number
const ITensor * get_const_tensor(int id) const
Get constant tensor of a given id.
Definition: ITensorPack.cpp:54
Quantization information.
static Status validate(const ITensorInfo *src, const ITensorInfo *dst, const Size2D &convolved_dims)
Static function to check if given info will lead to a valid configuration.
#define ARM_COMPUTE_UNUSED(...)
To avoid unused variables warnings.
Definition: Error.h:152
bool is_data_type_quantized_per_channel(DataType dt)
Check if a given data type is of per channel type.
Definition: Utils.h:1107
virtual const TensorShape & tensor_shape() const =0
Size for each dimension of the tensor.
virtual ITensorInfo & set_data_layout(const DataLayout &data_layout)=0
Set the data layout of the tensor.
std::pair< int32_t, int32_t > get_quantized_activation_min_max(ActivationLayerInfo act_info, DataType data_type, UniformQuantizationInfo oq_info)
Returns a pair of minimum and maximum values for a quantized activation.
Definition: Utils.cpp:558
Status calculate_quantized_multipliers(const QuantizationInfo &iq_info, const QuantizationInfo &wq_info, const QuantizationInfo &oq_info, GEMMLowpOutputStageInfo &stage_info)
Calculate quantized representation of per-channel multipliers.
static Status validate(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *output, const PadStrideInfo &conv_info, const WeightsInfo &weights_info=WeightsInfo(), const Size2D &dilation=Size2D(1U, 1U), const ActivationLayerInfo &act_info=ActivationLayerInfo(), bool enable_fast_math=false, unsigned int num_groups=1)
Static function to check if given info will lead to a valid configuration.
quantized, asymmetric fixed-point 8-bit number unsigned
#define ARM_COMPUTE_ERROR_ON_MSG(cond, msg)
Definition: Error.h:456
const unsigned int num_groups
Definition: Im2Col.cpp:153
size_t total_size() const override
Returns the total size of the tensor in bytes.
Definition: TensorInfo.h:250
virtual uint8_t * buffer() const =0
Interface to be implemented by the child class to return a pointer to CPU memory. ...
std::pair< unsigned int, unsigned int > stride() const
Get the stride.
Definition: Types.h:717
experimental::MemoryRequirements workspace() const override
Return the memory requirements required by the workspace.
UniformQuantizationInfo uniform() const
Return per layer quantization info.
virtual std::unique_ptr< T > clone() const =0
Provide a clone of the current object of class T.
GEMMLowp output stage info.
Definition: Types.h:2287
virtual ITensorInfo * info() const =0
Interface to be implemented by the child class to return the tensor&#39;s metadata.
Basic implementation of the tensor interface.
Definition: Tensor.h:37
Padding and stride information class.
Definition: Types.h:669
virtual PaddingSize padding() const =0
Padding of tensor.
virtual QuantizationInfo quantization_info() const =0
Get the quantization settings (scale and offset) of the tensor.
Num samples, channels, height, width.
src_info set_data_layout(data_layout)
bool is_data_type_quantized_asymmetric(DataType dt)
Check if a given data type is of asymmetric quantized type.
Definition: Utils.h:1052
quantized, symmetric per channel fixed-point 8-bit number
static constexpr size_t DimY
Alias for dimension 1 also known as Y dimension.
Definition: Window.h:45
ITensor * get_tensor(int id)
Get tensor of a given id from the pac.
Definition: ITensorPack.cpp:64
virtual size_t total_size() const =0
Returns the total size of the tensor in bytes.
TensorShape compute_weights_reshaped_shape(const ITensorInfo &weights, bool has_bias=false, unsigned int num_groups=1)
Calculate the reshaped shape of the weights.
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_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
Status import_memory(void *memory)
Import an existing memory as a tensor&#39;s backing memory.
#define ARM_COMPUTE_RETURN_ERROR_ON_MSG(cond, msg)
If the condition is true, an error is returned.
Definition: Error.h:244
arm_compute::WeightFormat weight_format() const
Definition: Types.h:2123
Tensor packing service.
Definition: ITensorPack.h:39
#define ARM_COMPUTE_LOG_PARAMS(...)
#define ARM_COMPUTE_ERROR_ON_NULLPTR(...)
Definition: Validate.h:157
Store the tensor&#39;s metadata.
Definition: TensorInfo.h:43
int offset_int_vec(int offset)
Definition: MemoryHelpers.h:38
GEMM information class.
Definition: Types.h:2339
ActivationFunction activation() const
Get the type of activation function.
Definition: Types.h:1679
quantized, asymmetric fixed-point 8-bit number signed
int32_t gemmlowp_min_bound
GEMMLowp min value used to saturate down the output result before converting back to QASYMM8...
Definition: Types.h:2293
const TensorShape & tensor_shape() const override
Size for each dimension of the tensor.
Definition: TensorInfo.h:234
void configure(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst, const PadStrideInfo &conv_info, const WeightsInfo &weights_info=WeightsInfo(), const Size2D &dilation=Size2D(1U, 1U), const ActivationLayerInfo &act_info=ActivationLayerInfo(), bool enable_fast_math=false, unsigned int num_groups=1)
Set the input and output tensors.
DataType
Available data types.
Definition: Types.h:79
DataLayout
[DataLayout enum definition]
Definition: Types.h:113
A sequence of PostOps that can be appended to the end of other operators.
Definition: IPostOp.h:119
std::tuple< PixelValue, PixelValue > get_min_max(DataType dt)
Compute the mininum and maximum values a data type can take.
Definition: Utils.h:564
TensorShape & set(size_t dimension, size_t value, bool apply_dim_correction=true, bool increase_dim_unit=true)
Accessor to set the value of one of the dimensions.
Definition: TensorShape.h:79
bool retain_internal_weights() const
Definition: Types.h:2119
void add_tensor(int id, ITensor *tensor)
Add tensor to the pack.
Definition: ITensorPack.cpp:39
static Status validate(const ITensorInfo *src, const ITensorInfo *dst, const Size2D &kernel_dims, const PadStrideInfo &conv_info, bool has_bias, const Size2D &dilation=Size2D(1U, 1U), unsigned int num_groups=1)
Static function to check if given info will lead to a valid configuration.
virtual DataLayout data_layout() const =0
Get the data layout of the tensor.
static IScheduler & get()
Access the scheduler singleton.
Definition: Scheduler.cpp:94
static Status validate(const ITensorInfo *a, const ITensorInfo *b, const ITensorInfo *c, const ITensorInfo *dst, const GEMMInfo &gemm_info=GEMMInfo())
Static function to check if given info will lead to a valid configuration.