blob: 5010792a28f31b961bd8fcb8c4413a03d13e2bda [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
Manuel Bottini29599d02021-07-06 15:01:35 +010034#include "src/core/helpers/MemoryHelpers.h"
Georgios Pinitas7891a732021-08-20 21:39:25 +010035#include "src/cpu/kernels/CpuCol2ImKernel.h"
36#include "src/cpu/kernels/CpuIm2ColKernel.h"
37#include "src/cpu/kernels/CpuReshapeKernel.h"
38#include "src/cpu/kernels/CpuWeightsReshapeKernel.h"
39#include "src/cpu/operators/CpuGemm.h"
40#include "src/cpu/operators/CpuGemmLowpMatrixMultiplyCore.h"
41#include "src/cpu/operators/CpuGemmLowpOutputStage.h"
42#include "src/cpu/utils/CpuAuxTensorHandler.h"
Manuel Bottini29599d02021-07-06 15:01:35 +010043
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{
Georgios Pinitas19884632021-08-16 12:38:54 +010054CpuGemmConv2d::CpuGemmConv2d()
Manuel Bottini29599d02021-07-06 15:01:35 +010055 : _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}
Georgios Pinitas19884632021-08-16 12:38:54 +010059CpuGemmConv2d::~CpuGemmConv2d() = default;
Manuel Bottini29599d02021-07-06 15:01:35 +010060
Georgios Pinitas19884632021-08-16 12:38:54 +010061void CpuGemmConv2d::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
Georgios Pinitas19884632021-08-16 12:38:54 +0100140Status CpuGemmConv2d::validate_mm(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst,
141 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
Georgios Pinitas19884632021-08-16 12:38:54 +0100200Status 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 +0100201{
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
Georgios Pinitas19884632021-08-16 12:38:54 +0100214void CpuGemmConv2d::configure(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst, const PadStrideInfo &conv_info, const WeightsInfo &weights_info,
215 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);
Georgios Pinitas19884632021-08-16 12:38:54 +0100219 ARM_COMPUTE_ERROR_THROW_ON(CpuGemmConv2d::validate(src,
220 weights,
221 biases,
222 dst,
223 conv_info,
224 weights_info,
225 dilation,
226 act_info,
227 enable_fast_math,
228 num_groups));
Manuel Bottini29599d02021-07-06 15:01:35 +0100229
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
Georgios Pinitasd4a5bc52021-08-12 07:42:51 +0100344 // Check if GEMM transforms weights
345 // Modernise through COMPMID-4535
346 bool gemm_trans_wei = _aux_mem[1].size > 0; // Asm Pretranspose
347 gemm_trans_wei = _mm_gemm != nullptr ? _aux_mem[3].size > 0 : gemm_trans_wei; // Tranpose RHS
348 gemm_trans_wei = _mm_gemmlowp != nullptr ? _aux_mem[5].size > 0 : gemm_trans_wei; // Transpose RHS
349
350 // Check lifetime
Manuel Bottini29599d02021-07-06 15:01:35 +0100351 _aux_mem[Im2ColOutput] = MemoryInfo(offset_int_vec(Im2ColOutput), MemoryLifetime::Temporary, _im2col_output.total_size());
Georgios Pinitasd4a5bc52021-08-12 07:42:51 +0100352 _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 +0100353 _aux_mem[GemmOutput] = MemoryInfo(offset_int_vec(GemmOutput), MemoryLifetime::Temporary, _gemm_output.total_size());
Manuel Bottini29599d02021-07-06 15:01:35 +0100354}
355
Georgios Pinitas19884632021-08-16 12:38:54 +0100356Status CpuGemmConv2d::validate(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst, const PadStrideInfo &conv_info,
357 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 +0100358{
359 ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(src, weights, dst);
360 ARM_COMPUTE_RETURN_ERROR_ON_MSG(weights_info.are_reshaped(), "Weights already reshaped are not supported!");
361 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(src, 1, DataType::QASYMM8, DataType::QASYMM8_SIGNED, DataType::BFLOAT16, DataType::F16, DataType::F32);
362 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);
363 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_LAYOUT(src, weights);
364 ARM_COMPUTE_RETURN_ERROR_ON_MSG(num_groups > 1, "Grouping (num_groups != 1) is not supported");
365
366 const DataLayout data_layout = src->data_layout();
367 const DataType data_type = src->data_type();
368 const int idx_width = get_data_layout_dimension_index(data_layout, DataLayoutDimension::WIDTH);
369 const int idx_height = get_data_layout_dimension_index(data_layout, DataLayoutDimension::HEIGHT);
370 const int idx_channel = get_data_layout_dimension_index(data_layout, DataLayoutDimension::CHANNEL);
371 const int idx_kernels = get_data_layout_dimension_index(data_layout, DataLayoutDimension::BATCHES);
372
373 const unsigned int kernel_width = weights->dimension(idx_width);
374 const unsigned int kernel_height = weights->dimension(idx_height);
375
376 TensorInfo im2col_reshaped_info{};
377 TensorInfo info_gemm{};
378 TensorInfo tmp_info{};
379 TensorInfo weights_reshaped_info{};
380 const ITensorInfo *gemm_input_to_use = src;
381 const ITensorInfo *gemm_output_to_use = dst;
382 const ITensorInfo *weights_to_use = weights;
383
384 const bool append_bias = false;
385 const bool is_quantized = is_data_type_quantized_asymmetric(data_type);
386 const bool is_bf16 = data_type == DataType::BFLOAT16;
387 bool skip_im2col = (data_layout == DataLayout::NHWC && kernel_width == 1 && kernel_height == 1 && conv_info.stride().first == 1 && conv_info.stride().second == 1);
388
389 // Get convolved dimensions
390 unsigned int conv_w = 0;
391 unsigned int conv_h = 0;
392
393 std::tie(conv_w, conv_h) = scaled_dimensions(src->dimension(idx_width),
394 src->dimension(idx_height),
395 kernel_width,
396 kernel_height,
397 conv_info,
398 dilation);
399
400 // Check if GEMM3D is supported
401 bool skip_col2im = false;
402 if(data_layout == DataLayout::NHWC)
403 {
404 skip_col2im = bool(validate_gemm3d(src, weights, act_info, conv_h, true));
405 // If not supported, we need to perform im2col and col2im (or reshape layer)
406 if(!skip_col2im)
407 {
408 skip_im2col = false;
409 }
410 }
411
412 if(skip_col2im)
413 {
414 // If not supported, we need to perform im2col and col2im (or reshape layer)
415 if(!bool(validate_gemm3d(src, weights, act_info, conv_h, skip_im2col)))
416 {
417 skip_im2col = false;
418 skip_col2im = false;
419 }
420 }
421
422 ARM_COMPUTE_RETURN_ERROR_ON(weights->dimension(idx_channel) != src->dimension(idx_channel));
423 ARM_COMPUTE_RETURN_ERROR_ON(weights->num_dimensions() > 4);
424
425 // Validate biases
426 if(biases != nullptr)
427 {
428 if(is_quantized)
429 {
430 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(biases, 1, DataType::S32);
431 }
432 else if(is_bf16)
433 {
434 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(biases, 1, DataType::F32);
435 }
436 else
437 {
438 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src, biases);
439 }
440 ARM_COMPUTE_RETURN_ERROR_ON(biases->dimension(0) != weights->dimension(idx_kernels));
441 ARM_COMPUTE_RETURN_ERROR_ON(biases->num_dimensions() > 1);
442 }
443
444 unsigned int mat_weights_cols = weights->dimension(idx_kernels);
445 unsigned int mat_weights_rows = weights->dimension(idx_width) * weights->dimension(idx_height) * weights->dimension(idx_channel);
446
447 weights_reshaped_info = TensorInfo(compute_weights_reshaped_shape(*weights, append_bias), 1, data_type);
448 weights_reshaped_info.set_quantization_info(weights->quantization_info());
449 weights_to_use = &weights_reshaped_info;
450
451 if(!skip_im2col)
452 {
453 // Create tensor info for im2col reshaped inputs
454 // For CPU, the batch size is on the fourth dimension
455 TensorShape shape_im2col = src->tensor_shape();
456 shape_im2col.set(0, mat_weights_rows);
457 shape_im2col.set(1, conv_w * conv_h);
458 shape_im2col.set(2, 1);
459
460 im2col_reshaped_info = TensorInfo(shape_im2col, 1, data_type);
461 im2col_reshaped_info.set_quantization_info(src->quantization_info());
462 ARM_COMPUTE_RETURN_ON_ERROR(kernels::CpuIm2ColKernel::validate(src, &im2col_reshaped_info, Size2D(kernel_width, kernel_height), conv_info, append_bias, dilation));
463 gemm_input_to_use = &im2col_reshaped_info;
464 }
465
466 // Create temporary GEMM output tensor in case we cannot skip col2im
467 const DataType output_data_type = data_type == DataType::BFLOAT16 ? DataType::F32 : data_type;
468 if(!skip_col2im)
469 {
470 TensorShape shape_gemm = gemm_input_to_use->tensor_shape();
471 shape_gemm.set(0, mat_weights_cols);
472 shape_gemm.set(1, conv_w * conv_h);
473 info_gemm = TensorInfo(shape_gemm, 1, output_data_type);
474 }
475 else
476 {
477 info_gemm = TensorInfo(dst->tensor_shape(), 1, output_data_type);
478 }
479 info_gemm.set_quantization_info(dst->quantization_info()).set_data_layout(src->data_layout());
480 gemm_output_to_use = &info_gemm;
Georgios Pinitas69a9ac42021-07-22 13:30:13 +0100481 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 +0100482
483 // Validate Col2Im/ReshapeLayer
484 if(!skip_col2im && (data_layout == DataLayout::NCHW))
485 {
486 ARM_COMPUTE_RETURN_ON_ERROR(kernels::CpuCol2ImKernel::validate(gemm_output_to_use, dst, Size2D(conv_w, conv_h)));
487 }
488
489 return Status{};
490}
491
Georgios Pinitas19884632021-08-16 12:38:54 +0100492void CpuGemmConv2d::run(ITensorPack &tensors)
Manuel Bottini29599d02021-07-06 15:01:35 +0100493{
494 prepare(tensors);
495
496 auto src = tensors.get_const_tensor(ACL_SRC_0);
Manuel Bottini29599d02021-07-06 15:01:35 +0100497 auto dst = tensors.get_tensor(ACL_DST);
498 auto gemm_input_to_use = src;
499
500 CpuAuxTensorHandler im2col_output(offset_int_vec(Im2ColOutput), _im2col_output, tensors, false);
501 CpuAuxTensorHandler gemm_output(offset_int_vec(GemmOutput), _gemm_output, tensors, false);
Georgios Pinitasd4a5bc52021-08-12 07:42:51 +0100502 CpuAuxTensorHandler reshaped_wei(offset_int_vec(WeightsReshaped), _weights_reshaped, tensors, false);
Manuel Bottini29599d02021-07-06 15:01:35 +0100503
504 bool out_has_padding = _skip_col2im && (dst->info()->padding().bottom != 0 || dst->info()->padding().top != 0);
505 if(!_skip_im2col)
506 {
507 // Run input reshaping
508 unsigned int y_dim = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::HEIGHT);
509 ITensorPack pack =
510 {
511 { TensorType::ACL_SRC, src },
512 { TensorType::ACL_DST, im2col_output.get() }
513 };
514 NEScheduler::get().schedule_op(_im2col_kernel.get(), y_dim, _im2col_kernel->window(), pack);
515 gemm_input_to_use = im2col_output.get();
516 }
517
518 // Handle the case where output has top/bottom padding
519 const ITensor *out_to_use = out_has_padding ? gemm_output.get() : dst;
Georgios Pinitasd4a5bc52021-08-12 07:42:51 +0100520 Tensor gemm3d;
Manuel Bottini29599d02021-07-06 15:01:35 +0100521 _gemm_output_3d.extend_padding(out_to_use->info()->padding());
Georgios Pinitasd4a5bc52021-08-12 07:42:51 +0100522 gemm3d.allocator()->soft_init(_gemm_output_3d);
523 gemm3d.allocator()->import_memory(out_to_use->buffer());
524 auto gemm_output_to_use = gemm_output.get();
525
Manuel Bottini29599d02021-07-06 15:01:35 +0100526 if(_skip_im2col)
527 {
Georgios Pinitasd4a5bc52021-08-12 07:42:51 +0100528 gemm_output_to_use = &gemm3d;
Manuel Bottini29599d02021-07-06 15:01:35 +0100529 }
530 if(_skip_col2im && !out_has_padding)
531 {
532 gemm_output_to_use = dst;
533 }
534
535 // Runs CpuGemm or CpuGemmLowpMatrixMultiplyCore functions
Georgios Pinitas22f5ed52021-07-23 18:58:43 +0100536 ITensorPack pack_mm = tensors;
537 pack_mm.add_const_tensor(TensorType::ACL_SRC_0, gemm_input_to_use);
Georgios Pinitasd4a5bc52021-08-12 07:42:51 +0100538 pack_mm.add_const_tensor(TensorType::ACL_SRC_1, reshaped_wei.get());
Georgios Pinitas22f5ed52021-07-23 18:58:43 +0100539 pack_mm.add_tensor(TensorType::ACL_DST, gemm_output_to_use);
Manuel Bottini29599d02021-07-06 15:01:35 +0100540 if(_is_quantized)
541 {
542 // Run gemmlowp
543 _mm_gemmlowp->run(pack_mm);
544 }
545 else
546 {
547 // Run gemm
548 _mm_gemm->run(pack_mm);
549 }
550
551 // Reshape output matrix
552 if(!_skip_col2im)
553 {
554 if(_data_layout == DataLayout::NCHW)
555 {
556 ITensorPack pack =
557 {
558 { TensorType::ACL_SRC, gemm_output.get() },
559 { TensorType::ACL_DST, dst }
560 };
561 NEScheduler::get().schedule_op(_col2im_kernel.get(), Window::DimY, _col2im_kernel->window(), pack);
562 }
563 else
564 {
565 ITensorPack pack =
566 {
567 { TensorType::ACL_SRC, gemm_output_to_use },
568 { TensorType::ACL_DST, dst }
569 };
570 NEScheduler::get().schedule_op(_reshape_kernel.get(), Window::DimY, _reshape_kernel->window(), pack);
571 }
572 }
573 else if(out_has_padding)
574 {
575 ITensorPack pack =
576 {
577 { TensorType::ACL_SRC, gemm_output_to_use },
578 { TensorType::ACL_DST, dst }
579 };
580 NEScheduler::get().schedule_op(_reshape_kernel.get(), Window::DimY, _reshape_kernel->window(), pack);
581 }
582}
583
Georgios Pinitas19884632021-08-16 12:38:54 +0100584void CpuGemmConv2d::prepare(ITensorPack &tensors)
Manuel Bottini29599d02021-07-06 15:01:35 +0100585{
586 if(!_is_prepared)
587 {
588 // Run weights reshaping and mark original weights tensor as unused
Michalis Spyroub55f8e82021-07-22 11:23:11 +0100589 CpuAuxTensorHandler weights_reshaped(offset_int_vec(WeightsReshaped), _weights_reshaped, tensors);
Manuel Bottini29599d02021-07-06 15:01:35 +0100590 auto weights = tensors.get_const_tensor(TensorType::ACL_SRC_1);
591 ITensorPack pack =
592 {
593 { TensorType::ACL_SRC, weights },
594 { TensorType::ACL_DST, weights_reshaped.get() }
595 };
596 NEScheduler::get().schedule_op(_weights_reshape_kernel.get(), 3, _weights_reshape_kernel->window(), pack);
Georgios Pinitasd4a5bc52021-08-12 07:42:51 +0100597 weights->mark_as_unused();
Manuel Bottini29599d02021-07-06 15:01:35 +0100598
599 // Prepare GEMM
Georgios Pinitasd4a5bc52021-08-12 07:42:51 +0100600 ITensorPack gemm_pack = tensors;
601 gemm_pack.add_const_tensor(TensorType::ACL_SRC_1, weights_reshaped.get());
602 _is_quantized ? _mm_gemmlowp->prepare(gemm_pack) : _mm_gemm->prepare(gemm_pack);
603
Manuel Bottini29599d02021-07-06 15:01:35 +0100604 _is_prepared = true;
605 }
606}
Georgios Pinitas19884632021-08-16 12:38:54 +0100607experimental::MemoryRequirements CpuGemmConv2d::workspace() const
Manuel Bottini29599d02021-07-06 15:01:35 +0100608{
609 return _aux_mem;
610}
611} // namespace cpu
612} // namespace arm_compute