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