blob: d925f8edd96e86cad378b28b0ed420e7a8bc13ff [file] [log] [blame]
Manuel Bottini29599d02021-07-06 15:01:35 +01001/*
2 * Copyright (c) 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 */
Georgios Pinitas7891a732021-08-20 21:39:25 +010024#include "src/cpu/operators/CpuGemmConv2d.h"
Manuel Bottini29599d02021-07-06 15:01:35 +010025
26#include "arm_compute/core/Size2D.h"
27#include "arm_compute/core/TensorInfo.h"
28#include "arm_compute/core/Utils.h"
29#include "arm_compute/core/Validate.h"
30#include "arm_compute/core/utils/misc/ShapeCalculator.h"
31#include "arm_compute/core/utils/quantization/AsymmHelpers.h"
32#include "arm_compute/runtime/NEON/NEScheduler.h"
33
ramelg013ae3d882021-09-12 23:07:47 +010034#include "src/common/utils/Log.h"
Manuel Bottini29599d02021-07-06 15:01:35 +010035#include "src/core/helpers/MemoryHelpers.h"
Georgios Pinitas7891a732021-08-20 21:39:25 +010036#include "src/cpu/kernels/CpuCol2ImKernel.h"
37#include "src/cpu/kernels/CpuIm2ColKernel.h"
38#include "src/cpu/kernels/CpuReshapeKernel.h"
39#include "src/cpu/kernels/CpuWeightsReshapeKernel.h"
40#include "src/cpu/operators/CpuGemm.h"
41#include "src/cpu/operators/CpuGemmLowpMatrixMultiplyCore.h"
42#include "src/cpu/operators/CpuGemmLowpOutputStage.h"
43#include "src/cpu/utils/CpuAuxTensorHandler.h"
Manuel Bottini29599d02021-07-06 15:01:35 +010044
45#include <set>
46#include <tuple>
47
48using namespace arm_compute::misc::shape_calculator;
49using namespace arm_compute::experimental;
50
51namespace arm_compute
52{
53namespace cpu
54{
Georgios Pinitas19884632021-08-16 12:38:54 +010055CpuGemmConv2d::CpuGemmConv2d()
Manuel Bottini29599d02021-07-06 15:01:35 +010056 : _weights_reshape_kernel(nullptr), _im2col_kernel(), _mm_gemm(), _mm_gemmlowp(), _col2im_kernel(), _reshape_kernel(), _im2col_output(), _weights_reshaped(), _gemm_output(), _gemm_output_3d(),
57 _data_layout(DataLayout::NCHW), _skip_im2col(false), _skip_col2im(false), _is_quantized(false), _is_prepared(false), _aux_mem(AuxTensorIdx::Count)
58{
59}
Georgios Pinitas19884632021-08-16 12:38:54 +010060CpuGemmConv2d::~CpuGemmConv2d() = default;
Manuel Bottini29599d02021-07-06 15:01:35 +010061
Georgios Pinitas19884632021-08-16 12:38:54 +010062void CpuGemmConv2d::configure_mm(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst, const ActivationLayerInfo &act_info,
63 bool enable_fast_math, int gemm_3d_depth)
Manuel Bottini29599d02021-07-06 15:01:35 +010064{
65 ARM_COMPUTE_ERROR_ON_NULLPTR(src, weights);
Georgios Pinitas69a9ac42021-07-22 13:30:13 +010066 ARM_COMPUTE_ERROR_THROW_ON(validate_mm(src, weights, biases, dst, act_info, enable_fast_math, gemm_3d_depth, _skip_im2col));
Manuel Bottini29599d02021-07-06 15:01:35 +010067
68 // Create GEMMInfo structure
69 const GEMMInfo &gemm_info = GEMMInfo(false, false, true /* Reshape weights only for the first run */,
70 gemm_3d_depth, _skip_im2col /* Reinterpret the input as 3D if im2col is skipped */,
Georgios Pinitas69a9ac42021-07-22 13:30:13 +010071 false, GEMMLowpOutputStageInfo(), false, enable_fast_math, false, act_info);
Manuel Bottini29599d02021-07-06 15:01:35 +010072
73 // Supported activations in GEMM
74 const std::set<ActivationLayerInfo::ActivationFunction> supported_acts = { ActivationLayerInfo::ActivationFunction::RELU,
75 ActivationLayerInfo::ActivationFunction::BOUNDED_RELU,
76 ActivationLayerInfo::ActivationFunction::LU_BOUNDED_RELU
77 };
78
79 if(_is_quantized)
80 {
81 TensorInfo tmp_src{ *src };
82 TensorInfo tmp_weights{ *weights };
83 // Since we need negative offsets for computing convolution, we need to change QuantizationInfo()
84 // Extract and negate input and weights offset
85 const QuantizationInfo iqinfo = src->quantization_info();
86 const QuantizationInfo wqinfo = weights->quantization_info();
87 const QuantizationInfo oqinfo = (dst->total_size() == 0) ? iqinfo : dst->quantization_info();
88 const UniformQuantizationInfo uiqinfo = iqinfo.uniform();
89 const UniformQuantizationInfo uoqinfo = oqinfo.uniform();
90 const DataType data_type = src->data_type();
91
92 tmp_src.set_quantization_info(QuantizationInfo(uiqinfo.scale, -uiqinfo.offset));
93 if(!is_data_type_quantized_per_channel(tmp_weights.data_type()))
94 {
95 const UniformQuantizationInfo uwqinfo = wqinfo.uniform();
96 tmp_weights.set_quantization_info(QuantizationInfo(uwqinfo.scale, -uwqinfo.offset));
97 }
98
99 // Merge activation with output stage
100 PixelValue type_min{};
101 PixelValue type_max{};
102 std::tie(type_min, type_max) = get_min_max(data_type);
103 int32_t min_activation = type_min.get<int32_t>();
104 int32_t max_activation = type_max.get<int32_t>();
105
106 if(supported_acts.count(act_info.activation()) != 0)
107 {
108 std::tie(min_activation, max_activation) = get_quantized_activation_min_max(act_info, data_type, uoqinfo);
109 }
110
111 GEMMLowpOutputStageInfo output_info;
112 output_info.type = GEMMLowpOutputStageType::QUANTIZE_DOWN_FIXEDPOINT;
113 output_info.gemmlowp_offset = uoqinfo.offset;
114 output_info.gemmlowp_min_bound = min_activation;
115 output_info.gemmlowp_max_bound = max_activation;
116 output_info.is_quantized_per_channel = (tmp_weights.data_type() == DataType::QSYMM8_PER_CHANNEL);
117 quantization::calculate_quantized_multipliers(iqinfo, wqinfo, oqinfo, output_info);
118
119 _mm_gemmlowp = std::make_unique<CpuGemmLowpMatrixMultiplyCore>();
Georgios Pinitas69a9ac42021-07-22 13:30:13 +0100120 _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));
Manuel Bottini29599d02021-07-06 15:01:35 +0100121
122 auto mm_mem_req = _mm_gemmlowp->workspace();
123 for(unsigned int cont = 0; cont < mm_mem_req.size(); ++cont)
124 {
125 _aux_mem[cont] = mm_mem_req[cont];
126 }
127 }
128 else
129 {
130 // Configure matrix multiply function
131 _mm_gemm = std::make_unique<CpuGemm>();
132 _mm_gemm->configure(src, weights, biases, dst, 1.0f, 0.0f, gemm_info);
133 auto mm_mem_req = _mm_gemm->workspace();
134 for(unsigned int cont = 0; cont < mm_mem_req.size(); ++cont)
135 {
136 _aux_mem[cont] = mm_mem_req[cont];
137 }
138 }
139}
140
Georgios Pinitas19884632021-08-16 12:38:54 +0100141Status CpuGemmConv2d::validate_mm(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst,
142 const ActivationLayerInfo &act_info, bool enable_fast_math, int gemm_3d_depth, bool skip_im2col)
Manuel Bottini29599d02021-07-06 15:01:35 +0100143{
144 const DataType data_type = src->data_type();
145 const bool is_quantized = is_data_type_quantized_asymmetric(data_type);
146 const bool is_activation_enabled = act_info.enabled();
147
148 // Create GEMMInfo structure
149 const GEMMInfo gemm_info = GEMMInfo(false, false, true /* Reshape weights only for the first run */,
150 gemm_3d_depth, skip_im2col /* Reinterpret the input as 3D if im2col is skipped */,
Georgios Pinitas69a9ac42021-07-22 13:30:13 +0100151 false, GEMMLowpOutputStageInfo(), false, enable_fast_math, false, act_info);
Manuel Bottini29599d02021-07-06 15:01:35 +0100152
153 if(is_quantized)
154 {
155 // Since we need negative offsets for computing convolution, we need to change QuantizationInfo()
156 // Extract and negate input and weights offset
157 const QuantizationInfo &iqinfo = src->quantization_info();
158 const QuantizationInfo &wqinfo = weights->quantization_info();
159 const QuantizationInfo &oqinfo = (dst->total_size() == 0) ? iqinfo : dst->quantization_info();
160 const UniformQuantizationInfo uoqinfo = oqinfo.uniform();
161
162 // Merge activation with output stage
163 PixelValue type_min{};
164 PixelValue type_max{};
165 std::tie(type_min, type_max) = get_min_max(data_type);
166 int32_t min_activation = type_min.get<int32_t>();
167 int32_t max_activation = type_max.get<int32_t>();
168
169 const std::set<ActivationLayerInfo::ActivationFunction> supported_acts = { ActivationLayerInfo::ActivationFunction::RELU,
170 ActivationLayerInfo::ActivationFunction::BOUNDED_RELU,
171 ActivationLayerInfo::ActivationFunction::LU_BOUNDED_RELU
172 };
173 if(is_activation_enabled && supported_acts.count(act_info.activation()) != 0)
174 {
175 std::tie(min_activation, max_activation) = get_quantized_activation_min_max(act_info, data_type, uoqinfo);
176 }
177
178 GEMMLowpOutputStageInfo output_info;
179 output_info.type = GEMMLowpOutputStageType::QUANTIZE_DOWN_FIXEDPOINT;
180 output_info.gemmlowp_offset = uoqinfo.offset;
181 output_info.gemmlowp_min_bound = min_activation;
182 output_info.gemmlowp_max_bound = max_activation;
183 output_info.is_quantized_per_channel = (weights->data_type() == DataType::QSYMM8_PER_CHANNEL);
184 ARM_COMPUTE_RETURN_ON_ERROR(quantization::calculate_quantized_multipliers(iqinfo, wqinfo, oqinfo, output_info));
185
186 // Perform validation step on GEMMLowp
187 std::unique_ptr<ITensorInfo> input_qa = src->clone();
188 std::unique_ptr<ITensorInfo> weights_qa = weights->clone();
189 input_qa->set_quantization_info(QuantizationInfo(iqinfo.uniform().scale, -iqinfo.uniform().offset));
190 weights_qa->set_quantization_info(QuantizationInfo(wqinfo.uniform().scale, -wqinfo.uniform().offset));
Georgios Pinitas69a9ac42021-07-22 13:30:13 +0100191 return CpuGemmLowpMatrixMultiplyCore::validate(input_qa.get(), weights_qa.get(), biases, dst, GEMMInfo(false, false, true, gemm_3d_depth, skip_im2col, false, output_info,
192 false, enable_fast_math, false, act_info));
Manuel Bottini29599d02021-07-06 15:01:35 +0100193 }
194 else
195 {
196 // Perform validation step on Matrix multiply function
197 return CpuGemm::validate(src, weights, nullptr, dst, 1.0f, 0.0f, gemm_info);
198 }
199}
200
Georgios Pinitas19884632021-08-16 12:38:54 +0100201Status CpuGemmConv2d::validate_gemm3d(const ITensorInfo *input_info, const ITensorInfo *weights_info, const ActivationLayerInfo &act_info, int gemm_3d_depth, bool skip_im2col)
Manuel Bottini29599d02021-07-06 15:01:35 +0100202{
203 const DataType data_type = input_info->data_type();
204 const unsigned int mult_y = skip_im2col ? 1U : gemm_3d_depth;
205 const unsigned int mult_z = skip_im2col ? gemm_3d_depth : 1U;
206
207 // Set dummy tensor shapes for the validation
208 const TensorInfo dummy_input_info(TensorShape(4U, 4U * mult_y, 1U * mult_z), 1, data_type, input_info->quantization_info());
209 const TensorInfo dummy_weights_info(TensorShape(4U, 4U), 1, data_type, weights_info->quantization_info());
210 const TensorInfo dummy_output_info(TensorShape(4U, 4U, gemm_3d_depth), 1, data_type, input_info->quantization_info());
211
Georgios Pinitasa8297fb2021-07-23 17:47:53 +0100212 return validate_mm(&dummy_input_info, &dummy_weights_info, nullptr, &dummy_output_info, act_info, false, gemm_3d_depth, skip_im2col);
Manuel Bottini29599d02021-07-06 15:01:35 +0100213}
214
Georgios Pinitas19884632021-08-16 12:38:54 +0100215void CpuGemmConv2d::configure(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst, const PadStrideInfo &conv_info, const WeightsInfo &weights_info,
216 const Size2D &dilation, const ActivationLayerInfo &act_info, bool enable_fast_math, unsigned int num_groups)
Manuel Bottini29599d02021-07-06 15:01:35 +0100217{
218 ARM_COMPUTE_ERROR_ON_NULLPTR(src, weights, dst);
219 ARM_COMPUTE_UNUSED(num_groups, weights_info);
Georgios Pinitas19884632021-08-16 12:38:54 +0100220 ARM_COMPUTE_ERROR_THROW_ON(CpuGemmConv2d::validate(src,
221 weights,
222 biases,
223 dst,
224 conv_info,
225 weights_info,
226 dilation,
227 act_info,
228 enable_fast_math,
229 num_groups));
ramelg013ae3d882021-09-12 23:07:47 +0100230 ARM_COMPUTE_LOG_PARAMS(src, weights, biases, dst, conv_info, weights_info, dilation, act_info, enable_fast_math, num_groups);
Manuel Bottini29599d02021-07-06 15:01:35 +0100231
232 const DataType data_type = src->data_type();
233 const DataLayout data_layout = src->data_layout();
234 const int idx_width = get_data_layout_dimension_index(data_layout, DataLayoutDimension::WIDTH);
235 const int idx_height = get_data_layout_dimension_index(data_layout, DataLayoutDimension::HEIGHT);
236 const int idx_kernels = get_data_layout_dimension_index(data_layout, DataLayoutDimension::BATCHES);
237
238 const unsigned int kernel_width = weights->dimension(idx_width);
239 const unsigned int kernel_height = weights->dimension(idx_height);
240
241 _is_prepared = weights_info.retain_internal_weights();
242 _is_quantized = is_data_type_quantized_asymmetric(src->data_type());
243 _data_layout = data_layout;
244 _skip_im2col = (data_layout == DataLayout::NHWC && kernel_width == 1 && kernel_height == 1 && conv_info.stride().first == 1 && conv_info.stride().second == 1);
245
246 const ITensorInfo *gemm_input_to_use = src;
247 ITensorInfo *gemm_output_to_use = dst;
248
249 // Get convolved dimensions
250 unsigned int conv_w = 0;
251 unsigned int conv_h = 0;
252 std::tie(conv_w, conv_h) = scaled_dimensions(src->dimension(idx_width),
253 src->dimension(idx_height),
254 kernel_width,
255 kernel_height,
256 conv_info,
257 dilation);
258 ARM_COMPUTE_ERROR_ON_MSG((dst->dimension(idx_width) != conv_w) || (dst->dimension(idx_height) != conv_h),
259 "Output shape does not match the expected one");
260
261 // Check if GEMM3D is supported
262 if(data_layout == DataLayout::NHWC)
263 {
264 _skip_col2im = bool(validate_gemm3d(src, weights, act_info, conv_h, true));
265 // If not supported, we need to perform im2col and col2im (or reshape layer)
266 if(!_skip_col2im)
267 {
268 _skip_im2col = false;
269 }
270 }
271 else
272 {
273 _skip_col2im = false;
274 }
275
276 // Get parameters from conv_info
277 unsigned int stride_x = 0;
278 unsigned int stride_y = 0;
279 std::tie(stride_x, stride_y) = conv_info.stride();
280
281 unsigned int mat_weights_cols = weights->dimension(idx_kernels);
282
283 // _weights_reshaped will be auto configured in the kernel.
284 // Just append biases and do not transpose 1xW as it will be reshaped in CpuGemm
285 _weights_reshape_kernel = std::make_unique<kernels::CpuWeightsReshapeKernel>();
286 _weights_reshape_kernel->configure(weights, nullptr, &_weights_reshaped);
287 _weights_reshaped.set_quantization_info(weights->quantization_info());
288
289 // Create tensor to store im2col reshaped inputs
290 if(!_skip_im2col)
291 {
292 // Configure
293 _im2col_kernel = std::make_unique<kernels::CpuIm2ColKernel>();
294 _im2col_kernel->configure(src, &_im2col_output, Size2D(kernel_width, kernel_height), conv_info, false, dilation);
295
296 // Update GEMM input
297 gemm_input_to_use = &_im2col_output;
298 }
299
300 // Create temporary GEMM output tensor in case we cannot skip col2im
301 const DataType output_data_type = data_type == DataType::BFLOAT16 ? DataType::F32 : data_type;
302 if(!_skip_col2im)
303 {
304 TensorShape shape_gemm;
305
306 // Calculate GEMM output shape
307 shape_gemm = _im2col_output.tensor_shape();
308 shape_gemm.set(0, mat_weights_cols);
309 shape_gemm.set(1, conv_w * conv_h);
310
311 _gemm_output = TensorInfo(shape_gemm, 1, output_data_type);
312 _gemm_output.set_quantization_info(dst->quantization_info()).set_data_layout(src->data_layout());
313 _gemm_output_3d = TensorInfo(_gemm_output);
314
315 // Update GEMM output
316 gemm_output_to_use = &_gemm_output;
317 }
318 else
319 {
320 _gemm_output_3d = TensorInfo(*dst);
321 _gemm_output_3d.set_data_type(output_data_type).set_data_layout(src->data_layout()).set_is_resizable(true);
322 _gemm_output = TensorInfo(_gemm_output_3d);
323
324 // Update GEMM output
325 gemm_output_to_use = &_gemm_output_3d;
326 }
327
328 // Configure GEMM
329 // In case we need to skip col2im, GEMM3D (gemm_3d_depth != 0) must be called in order to avoid reshaping the output matrix
330 const unsigned int gemm_3d_depth = _skip_col2im ? conv_h : 0;
Georgios Pinitas69a9ac42021-07-22 13:30:13 +0100331 configure_mm(gemm_input_to_use, &_weights_reshaped, biases, gemm_output_to_use, act_info, enable_fast_math, gemm_3d_depth);
Manuel Bottini29599d02021-07-06 15:01:35 +0100332
333 if(!_skip_col2im && _data_layout == DataLayout::NCHW)
334 {
335 // Configure col2im
336 _col2im_kernel = std::make_unique<kernels::CpuCol2ImKernel>();
337 _col2im_kernel->configure(gemm_output_to_use, dst, Size2D(conv_w, conv_h));
338 }
339 else
340 {
341 // Configure reshape layer
342 _reshape_kernel = std::make_unique<kernels::CpuReshapeKernel>();
343 _reshape_kernel->configure(gemm_output_to_use, dst);
344 }
345
Georgios Pinitasd4a5bc52021-08-12 07:42:51 +0100346 // Check if GEMM transforms weights
347 // Modernise through COMPMID-4535
348 bool gemm_trans_wei = _aux_mem[1].size > 0; // Asm Pretranspose
349 gemm_trans_wei = _mm_gemm != nullptr ? _aux_mem[3].size > 0 : gemm_trans_wei; // Tranpose RHS
350 gemm_trans_wei = _mm_gemmlowp != nullptr ? _aux_mem[5].size > 0 : gemm_trans_wei; // Transpose RHS
351
352 // Check lifetime
Manuel Bottini29599d02021-07-06 15:01:35 +0100353 _aux_mem[Im2ColOutput] = MemoryInfo(offset_int_vec(Im2ColOutput), MemoryLifetime::Temporary, _im2col_output.total_size());
Georgios Pinitasd4a5bc52021-08-12 07:42:51 +0100354 _aux_mem[WeightsReshaped] = MemoryInfo(offset_int_vec(WeightsReshaped), gemm_trans_wei ? MemoryLifetime::Prepare : MemoryLifetime::Persistent, _weights_reshaped.total_size());
Manuel Bottini29599d02021-07-06 15:01:35 +0100355 _aux_mem[GemmOutput] = MemoryInfo(offset_int_vec(GemmOutput), MemoryLifetime::Temporary, _gemm_output.total_size());
Manuel Bottini29599d02021-07-06 15:01:35 +0100356}
357
Georgios Pinitas19884632021-08-16 12:38:54 +0100358Status CpuGemmConv2d::validate(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst, const PadStrideInfo &conv_info,
359 const WeightsInfo &weights_info, const Size2D &dilation, const ActivationLayerInfo &act_info, bool enable_fast_math, unsigned int num_groups)
Manuel Bottini29599d02021-07-06 15:01:35 +0100360{
361 ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(src, weights, dst);
362 ARM_COMPUTE_RETURN_ERROR_ON_MSG(weights_info.are_reshaped(), "Weights already reshaped are not supported!");
363 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(src, 1, DataType::QASYMM8, DataType::QASYMM8_SIGNED, DataType::BFLOAT16, DataType::F16, DataType::F32);
364 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(weights, 1, DataType::QASYMM8, DataType::QASYMM8_SIGNED, DataType::QSYMM8_PER_CHANNEL, DataType::BFLOAT16, DataType::F16, DataType::F32);
365 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_LAYOUT(src, weights);
366 ARM_COMPUTE_RETURN_ERROR_ON_MSG(num_groups > 1, "Grouping (num_groups != 1) is not supported");
367
368 const DataLayout data_layout = src->data_layout();
369 const DataType data_type = src->data_type();
370 const int idx_width = get_data_layout_dimension_index(data_layout, DataLayoutDimension::WIDTH);
371 const int idx_height = get_data_layout_dimension_index(data_layout, DataLayoutDimension::HEIGHT);
372 const int idx_channel = get_data_layout_dimension_index(data_layout, DataLayoutDimension::CHANNEL);
373 const int idx_kernels = get_data_layout_dimension_index(data_layout, DataLayoutDimension::BATCHES);
374
375 const unsigned int kernel_width = weights->dimension(idx_width);
376 const unsigned int kernel_height = weights->dimension(idx_height);
377
378 TensorInfo im2col_reshaped_info{};
379 TensorInfo info_gemm{};
380 TensorInfo tmp_info{};
381 TensorInfo weights_reshaped_info{};
382 const ITensorInfo *gemm_input_to_use = src;
383 const ITensorInfo *gemm_output_to_use = dst;
384 const ITensorInfo *weights_to_use = weights;
385
386 const bool append_bias = false;
387 const bool is_quantized = is_data_type_quantized_asymmetric(data_type);
388 const bool is_bf16 = data_type == DataType::BFLOAT16;
389 bool skip_im2col = (data_layout == DataLayout::NHWC && kernel_width == 1 && kernel_height == 1 && conv_info.stride().first == 1 && conv_info.stride().second == 1);
390
391 // Get convolved dimensions
392 unsigned int conv_w = 0;
393 unsigned int conv_h = 0;
394
395 std::tie(conv_w, conv_h) = scaled_dimensions(src->dimension(idx_width),
396 src->dimension(idx_height),
397 kernel_width,
398 kernel_height,
399 conv_info,
400 dilation);
401
402 // Check if GEMM3D is supported
403 bool skip_col2im = false;
404 if(data_layout == DataLayout::NHWC)
405 {
406 skip_col2im = bool(validate_gemm3d(src, weights, act_info, conv_h, true));
407 // If not supported, we need to perform im2col and col2im (or reshape layer)
408 if(!skip_col2im)
409 {
410 skip_im2col = false;
411 }
412 }
413
414 if(skip_col2im)
415 {
416 // If not supported, we need to perform im2col and col2im (or reshape layer)
417 if(!bool(validate_gemm3d(src, weights, act_info, conv_h, skip_im2col)))
418 {
419 skip_im2col = false;
420 skip_col2im = false;
421 }
422 }
423
424 ARM_COMPUTE_RETURN_ERROR_ON(weights->dimension(idx_channel) != src->dimension(idx_channel));
425 ARM_COMPUTE_RETURN_ERROR_ON(weights->num_dimensions() > 4);
426
427 // Validate biases
428 if(biases != nullptr)
429 {
430 if(is_quantized)
431 {
432 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(biases, 1, DataType::S32);
433 }
434 else if(is_bf16)
435 {
436 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(biases, 1, DataType::F32);
437 }
438 else
439 {
440 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src, biases);
441 }
442 ARM_COMPUTE_RETURN_ERROR_ON(biases->dimension(0) != weights->dimension(idx_kernels));
443 ARM_COMPUTE_RETURN_ERROR_ON(biases->num_dimensions() > 1);
444 }
445
446 unsigned int mat_weights_cols = weights->dimension(idx_kernels);
447 unsigned int mat_weights_rows = weights->dimension(idx_width) * weights->dimension(idx_height) * weights->dimension(idx_channel);
448
449 weights_reshaped_info = TensorInfo(compute_weights_reshaped_shape(*weights, append_bias), 1, data_type);
450 weights_reshaped_info.set_quantization_info(weights->quantization_info());
451 weights_to_use = &weights_reshaped_info;
452
453 if(!skip_im2col)
454 {
455 // Create tensor info for im2col reshaped inputs
456 // For CPU, the batch size is on the fourth dimension
457 TensorShape shape_im2col = src->tensor_shape();
458 shape_im2col.set(0, mat_weights_rows);
459 shape_im2col.set(1, conv_w * conv_h);
460 shape_im2col.set(2, 1);
461
462 im2col_reshaped_info = TensorInfo(shape_im2col, 1, data_type);
463 im2col_reshaped_info.set_quantization_info(src->quantization_info());
464 ARM_COMPUTE_RETURN_ON_ERROR(kernels::CpuIm2ColKernel::validate(src, &im2col_reshaped_info, Size2D(kernel_width, kernel_height), conv_info, append_bias, dilation));
465 gemm_input_to_use = &im2col_reshaped_info;
466 }
467
468 // Create temporary GEMM output tensor in case we cannot skip col2im
469 const DataType output_data_type = data_type == DataType::BFLOAT16 ? DataType::F32 : data_type;
470 if(!skip_col2im)
471 {
472 TensorShape shape_gemm = gemm_input_to_use->tensor_shape();
473 shape_gemm.set(0, mat_weights_cols);
474 shape_gemm.set(1, conv_w * conv_h);
475 info_gemm = TensorInfo(shape_gemm, 1, output_data_type);
476 }
477 else
478 {
479 info_gemm = TensorInfo(dst->tensor_shape(), 1, output_data_type);
480 }
481 info_gemm.set_quantization_info(dst->quantization_info()).set_data_layout(src->data_layout());
482 gemm_output_to_use = &info_gemm;
Georgios Pinitas69a9ac42021-07-22 13:30:13 +0100483 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));
Manuel Bottini29599d02021-07-06 15:01:35 +0100484
485 // Validate Col2Im/ReshapeLayer
486 if(!skip_col2im && (data_layout == DataLayout::NCHW))
487 {
488 ARM_COMPUTE_RETURN_ON_ERROR(kernels::CpuCol2ImKernel::validate(gemm_output_to_use, dst, Size2D(conv_w, conv_h)));
489 }
490
491 return Status{};
492}
493
Georgios Pinitas19884632021-08-16 12:38:54 +0100494void CpuGemmConv2d::run(ITensorPack &tensors)
Manuel Bottini29599d02021-07-06 15:01:35 +0100495{
496 prepare(tensors);
497
498 auto src = tensors.get_const_tensor(ACL_SRC_0);
Manuel Bottini29599d02021-07-06 15:01:35 +0100499 auto dst = tensors.get_tensor(ACL_DST);
500 auto gemm_input_to_use = src;
501
502 CpuAuxTensorHandler im2col_output(offset_int_vec(Im2ColOutput), _im2col_output, tensors, false);
503 CpuAuxTensorHandler gemm_output(offset_int_vec(GemmOutput), _gemm_output, tensors, false);
Georgios Pinitasd4a5bc52021-08-12 07:42:51 +0100504 CpuAuxTensorHandler reshaped_wei(offset_int_vec(WeightsReshaped), _weights_reshaped, tensors, false);
Manuel Bottini29599d02021-07-06 15:01:35 +0100505
506 bool out_has_padding = _skip_col2im && (dst->info()->padding().bottom != 0 || dst->info()->padding().top != 0);
507 if(!_skip_im2col)
508 {
509 // Run input reshaping
510 unsigned int y_dim = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::HEIGHT);
511 ITensorPack pack =
512 {
513 { TensorType::ACL_SRC, src },
514 { TensorType::ACL_DST, im2col_output.get() }
515 };
516 NEScheduler::get().schedule_op(_im2col_kernel.get(), y_dim, _im2col_kernel->window(), pack);
517 gemm_input_to_use = im2col_output.get();
518 }
519
520 // Handle the case where output has top/bottom padding
521 const ITensor *out_to_use = out_has_padding ? gemm_output.get() : dst;
Georgios Pinitasd4a5bc52021-08-12 07:42:51 +0100522 Tensor gemm3d;
Manuel Bottini29599d02021-07-06 15:01:35 +0100523 _gemm_output_3d.extend_padding(out_to_use->info()->padding());
Georgios Pinitasd4a5bc52021-08-12 07:42:51 +0100524 gemm3d.allocator()->soft_init(_gemm_output_3d);
525 gemm3d.allocator()->import_memory(out_to_use->buffer());
526 auto gemm_output_to_use = gemm_output.get();
527
Manuel Bottini29599d02021-07-06 15:01:35 +0100528 if(_skip_im2col)
529 {
Georgios Pinitasd4a5bc52021-08-12 07:42:51 +0100530 gemm_output_to_use = &gemm3d;
Manuel Bottini29599d02021-07-06 15:01:35 +0100531 }
532 if(_skip_col2im && !out_has_padding)
533 {
534 gemm_output_to_use = dst;
535 }
536
537 // Runs CpuGemm or CpuGemmLowpMatrixMultiplyCore functions
Georgios Pinitas22f5ed52021-07-23 18:58:43 +0100538 ITensorPack pack_mm = tensors;
539 pack_mm.add_const_tensor(TensorType::ACL_SRC_0, gemm_input_to_use);
Georgios Pinitasd4a5bc52021-08-12 07:42:51 +0100540 pack_mm.add_const_tensor(TensorType::ACL_SRC_1, reshaped_wei.get());
Georgios Pinitas22f5ed52021-07-23 18:58:43 +0100541 pack_mm.add_tensor(TensorType::ACL_DST, gemm_output_to_use);
Manuel Bottini29599d02021-07-06 15:01:35 +0100542 if(_is_quantized)
543 {
544 // Run gemmlowp
545 _mm_gemmlowp->run(pack_mm);
546 }
547 else
548 {
549 // Run gemm
550 _mm_gemm->run(pack_mm);
551 }
552
553 // Reshape output matrix
554 if(!_skip_col2im)
555 {
556 if(_data_layout == DataLayout::NCHW)
557 {
558 ITensorPack pack =
559 {
560 { TensorType::ACL_SRC, gemm_output.get() },
561 { TensorType::ACL_DST, dst }
562 };
563 NEScheduler::get().schedule_op(_col2im_kernel.get(), Window::DimY, _col2im_kernel->window(), pack);
564 }
565 else
566 {
567 ITensorPack pack =
568 {
569 { TensorType::ACL_SRC, gemm_output_to_use },
570 { TensorType::ACL_DST, dst }
571 };
572 NEScheduler::get().schedule_op(_reshape_kernel.get(), Window::DimY, _reshape_kernel->window(), pack);
573 }
574 }
575 else if(out_has_padding)
576 {
577 ITensorPack pack =
578 {
579 { TensorType::ACL_SRC, gemm_output_to_use },
580 { TensorType::ACL_DST, dst }
581 };
582 NEScheduler::get().schedule_op(_reshape_kernel.get(), Window::DimY, _reshape_kernel->window(), pack);
583 }
584}
585
Georgios Pinitas19884632021-08-16 12:38:54 +0100586void CpuGemmConv2d::prepare(ITensorPack &tensors)
Manuel Bottini29599d02021-07-06 15:01:35 +0100587{
588 if(!_is_prepared)
589 {
590 // Run weights reshaping and mark original weights tensor as unused
Michalis Spyroub55f8e82021-07-22 11:23:11 +0100591 CpuAuxTensorHandler weights_reshaped(offset_int_vec(WeightsReshaped), _weights_reshaped, tensors);
Manuel Bottini29599d02021-07-06 15:01:35 +0100592 auto weights = tensors.get_const_tensor(TensorType::ACL_SRC_1);
593 ITensorPack pack =
594 {
595 { TensorType::ACL_SRC, weights },
596 { TensorType::ACL_DST, weights_reshaped.get() }
597 };
598 NEScheduler::get().schedule_op(_weights_reshape_kernel.get(), 3, _weights_reshape_kernel->window(), pack);
Georgios Pinitasd4a5bc52021-08-12 07:42:51 +0100599 weights->mark_as_unused();
Manuel Bottini29599d02021-07-06 15:01:35 +0100600
601 // Prepare GEMM
Georgios Pinitasd4a5bc52021-08-12 07:42:51 +0100602 ITensorPack gemm_pack = tensors;
603 gemm_pack.add_const_tensor(TensorType::ACL_SRC_1, weights_reshaped.get());
604 _is_quantized ? _mm_gemmlowp->prepare(gemm_pack) : _mm_gemm->prepare(gemm_pack);
605
Manuel Bottini29599d02021-07-06 15:01:35 +0100606 _is_prepared = true;
607 }
608}
Georgios Pinitas19884632021-08-16 12:38:54 +0100609experimental::MemoryRequirements CpuGemmConv2d::workspace() const
Manuel Bottini29599d02021-07-06 15:01:35 +0100610{
611 return _aux_mem;
612}
613} // namespace cpu
614} // namespace arm_compute