blob: 6d77c614f7a881d60feb8f40a8e1a9580124c258 [file] [log] [blame]
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +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/CpuFullyConnected.h"
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +010025
26#include "arm_compute/core/Helpers.h"
27#include "arm_compute/core/ITensorPack.h"
28#include "arm_compute/core/Validate.h"
29#include "arm_compute/core/utils/misc/ShapeCalculator.h"
30#include "arm_compute/core/utils/quantization/AsymmHelpers.h"
31#include "arm_compute/runtime/NEON/NEScheduler.h"
ramelg013ae3d882021-09-12 23:07:47 +010032#include "src/common/utils/Log.h"
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +010033#include "src/core/helpers/AutoConfiguration.h"
34#include "src/core/helpers/MemoryHelpers.h"
Georgios Pinitas7891a732021-08-20 21:39:25 +010035#include "src/cpu/kernels/CpuTransposeKernel.h"
36#include "src/cpu/operators/CpuConvertFullyConnectedWeights.h"
37#include "src/cpu/operators/CpuFlatten.h"
38#include "src/cpu/operators/CpuGemm.h"
39#include "src/cpu/operators/CpuGemmLowpMatrixMultiplyCore.h"
40#include "src/cpu/utils/CpuAuxTensorHandler.h"
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +010041
42namespace arm_compute
43{
44namespace cpu
45{
46using namespace arm_compute::experimental;
47using namespace arm_compute::misc::shape_calculator;
48
49namespace
50{
51// Get min, max bound of a quantized asymmetric dst tensor, with the effect of fused activation
52std::pair<PixelValue, PixelValue> get_quantized_asymmetric_output_min_max(const QuantizationInfo &q_info, const ActivationLayerInfo &act_info, DataType data_type)
53{
54 PixelValue type_min{};
55 PixelValue type_max{};
56 std::tie(type_min, type_max) = get_min_max(data_type);
57 const UniformQuantizationInfo q_unif = q_info.uniform();
58
59 if(act_info.enabled())
60 {
61 switch(act_info.activation())
62 {
63 case ActivationLayerInfo::ActivationFunction::RELU:
64 type_min = PixelValue(q_unif.offset);
65 break;
66 case ActivationLayerInfo::ActivationFunction::BOUNDED_RELU:
67 type_min = PixelValue(q_unif.offset);
68 type_max = PixelValue(act_info.a(), data_type, q_info);
69 break;
70 case ActivationLayerInfo::ActivationFunction::LU_BOUNDED_RELU:
71 type_min = PixelValue(act_info.b(), data_type, q_info);
72 type_max = PixelValue(act_info.a(), data_type, q_info);
73 break;
74 default:
75 ARM_COMPUTE_ERROR("Activation function not supported.");
76 break;
77 }
78 }
79
80 return std::make_pair(type_min, type_max);
81}
82
83Status get_gemmlowp_output_stage_info(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *dst, const ActivationLayerInfo &act,
84 GEMMLowpOutputStageInfo &gemmlowp_output_stage_info)
85{
86 const auto data_type = src->data_type();
87 const QuantizationInfo oq_info = dst->quantization_info();
88 const UniformQuantizationInfo iq_unif = src->quantization_info().uniform();
89 const UniformQuantizationInfo wq_unif = weights->quantization_info().uniform();
90 const UniformQuantizationInfo oq_unif = oq_info.uniform();
91
92 float multiplier = (iq_unif.scale * wq_unif.scale) / oq_unif.scale;
93 int32_t output_multiplier;
94 int32_t output_shift;
95
96 ARM_COMPUTE_RETURN_ON_ERROR(quantization::calculate_quantized_multiplier(multiplier, &output_multiplier, &output_shift));
97
98 PixelValue type_min{};
99 PixelValue type_max{};
100 std::tie(type_min, type_max) = get_quantized_asymmetric_output_min_max(oq_info, act, data_type);
101
102 gemmlowp_output_stage_info.gemmlowp_multiplier = output_multiplier;
103 gemmlowp_output_stage_info.gemmlowp_shift = output_shift;
104 gemmlowp_output_stage_info.gemmlowp_offset = oq_unif.offset;
105 gemmlowp_output_stage_info.type = GEMMLowpOutputStageType::QUANTIZE_DOWN_FIXEDPOINT;
106 gemmlowp_output_stage_info.gemmlowp_min_bound = type_min.get<int32_t>();
107 gemmlowp_output_stage_info.gemmlowp_max_bound = type_max.get<int32_t>();
108
109 return Status{};
110}
111
cfRodf2c022e2021-11-05 11:29:53 +0000112Status validate_mm(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst, const ActivationLayerInfo &act, bool enable_fast_math)
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100113{
114 if(is_data_type_quantized_asymmetric(src->data_type()))
115 {
116 // Since we need negative offsets for computing convolution, we need to change QuantizationInfo()
117 // Extract and negate src and weights offset
118 const QuantizationInfo src_quantization_info(src->quantization_info().uniform().scale, -src->quantization_info().uniform().offset);
119 const QuantizationInfo weights_quantization_info(weights->quantization_info().uniform().scale, -weights->quantization_info().uniform().offset);
120
121 GEMMLowpOutputStageInfo gemmlowp_output_stage_info;
122 ARM_COMPUTE_RETURN_ON_ERROR(get_gemmlowp_output_stage_info(src, weights, dst, act, gemmlowp_output_stage_info));
123
124 GEMMInfo gemm_info;
125 gemm_info.set_gemmlowp_output_stage(gemmlowp_output_stage_info);
cfRodf2c022e2021-11-05 11:29:53 +0000126 gemm_info.set_fast_math(enable_fast_math);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100127
128 // Validate gemmlowp function
129 TensorInfo src_info = src->clone()->set_quantization_info(src_quantization_info);
130 TensorInfo weights_info = weights->clone()->set_quantization_info(weights_quantization_info);
131 ARM_COMPUTE_RETURN_ON_ERROR(CpuGemmLowpMatrixMultiplyCore::validate(&src_info,
132 &weights_info,
133 biases,
134 dst,
135 gemm_info));
136 }
137 else
138 {
cfRodf2c022e2021-11-05 11:29:53 +0000139 GEMMInfo gemm_info(false, false, true /* Reshape weights only for the first run */);
140 gemm_info.set_fast_math(enable_fast_math);
141 ARM_COMPUTE_RETURN_ON_ERROR(CpuGemm::validate(src, weights, biases, dst, 1.f, 1.0f, gemm_info));
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100142 }
143
144 return Status{};
145}
146} // namespace
147
148CpuFullyConnected::CpuFullyConnected()
149 : _flatten(nullptr),
150 _convert_weights(nullptr),
151 _transpose_weights(nullptr),
152 _mm_gemm(nullptr),
153 _mm_gemmlowp(nullptr),
154 _flattened_src(),
155 _converted_weights(),
156 _reshaped_weights(),
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100157 _trans_weights(),
158 _trans_weights_idx(AuxTensorIdx::Count),
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100159 _aux_mem(Count),
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100160 _needs_weights_conversion(false),
161 _needs_weights_reshape(false),
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100162 _is_fc_after_conv(false),
163 _is_quantized_asymmetric(false),
cfRodf2c022e2021-11-05 11:29:53 +0000164 _is_prepared(false),
165 _enable_fast_math(false)
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100166
167{
168}
169
170CpuFullyConnected::~CpuFullyConnected() = default;
171
172void CpuFullyConnected::configure_mm(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst, const ActivationLayerInfo &act)
173{
174 if(_is_quantized_asymmetric)
175 {
176 // Since we need negative offsets for computing convolution, we need to change QuantizationInfo()
177 // Extract and negate src and weights offset
178 const QuantizationInfo src_quantization_info(src->quantization_info().uniform().scale, -src->quantization_info().uniform().offset);
179 const QuantizationInfo weights_quantization_info(weights->quantization_info().uniform().scale, -weights->quantization_info().uniform().offset);
180
181 TensorInfo src_info = src->clone()->set_quantization_info(src_quantization_info);
182 TensorInfo weights_info = weights->clone()->set_quantization_info(weights_quantization_info);
183
184 // Configure gemmlowp function and output stage for asymmetric quantized types
185 GEMMLowpOutputStageInfo gemmlowp_output_stage_info;
186 const Status status = get_gemmlowp_output_stage_info(&src_info, &weights_info, dst, act, gemmlowp_output_stage_info);
187 ARM_COMPUTE_ERROR_ON(status.error_code() != ErrorCode::OK);
188
189 GEMMInfo gemm_info;
190 gemm_info.set_gemmlowp_output_stage(gemmlowp_output_stage_info);
191 gemm_info.set_activation_info(act);
cfRodf2c022e2021-11-05 11:29:53 +0000192 gemm_info.set_fast_math(_enable_fast_math);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100193 _mm_gemmlowp = std::make_unique<CpuGemmLowpMatrixMultiplyCore>();
194 _mm_gemmlowp->configure(&src_info, &weights_info, biases, dst, gemm_info);
195 }
196 else
197 {
198 // Configure matrix multiply kernel
199 GEMMInfo gemm_info(false, false, true /* Reshape weights only for the first run */);
200 gemm_info.set_activation_info(act);
cfRodf2c022e2021-11-05 11:29:53 +0000201 gemm_info.set_fast_math(_enable_fast_math);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100202 _mm_gemm = std::make_unique<CpuGemm>();
203 _mm_gemm->configure(src, weights, biases, dst, 1.f, 1.0f, gemm_info);
204 }
205}
206
207void CpuFullyConnected::configure_conv_fc(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst, const ActivationLayerInfo &act)
208{
209 ARM_COMPUTE_ERROR_ON((weights->dimension(1) != (src->dimension(0) * src->dimension(1) * src->dimension(2))));
210
211 // If the fully connected layer is called after a convolution layer, the src tensor must be linearized
212
213 // Initialize output tensor for flatten
214 auto_init_if_empty(_flattened_src, src->clone()->set_tensor_shape(compute_flatten_shape(src)));
215
216 _flatten = std::make_unique<CpuFlatten>();
217 _flatten->configure(src, &_flattened_src);
218
219 // Configure matrix multiply kernel
220 configure_mm(&_flattened_src, weights, biases, dst, act);
221}
222
223void CpuFullyConnected::configure_fc_fc(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst, const ActivationLayerInfo &act)
224{
225 ARM_COMPUTE_ERROR_ON(src->dimension(0) != weights->dimension(1));
226
227 // Configure matrix multiply kernel
228 configure_mm(src, weights, biases, dst, act);
229}
230
231void CpuFullyConnected::configure(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst,
232 FullyConnectedLayerInfo fc_info)
233{
234 // Perform validate step
235 ARM_COMPUTE_ERROR_ON_NULLPTR(src, weights, dst);
236 ARM_COMPUTE_ERROR_THROW_ON(CpuFullyConnected::validate(src,
237 weights,
238 biases != nullptr ? biases : nullptr,
239 dst,
240 fc_info));
ramelg013ae3d882021-09-12 23:07:47 +0100241 ARM_COMPUTE_LOG_PARAMS(src, weights, biases, dst, fc_info);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100242
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100243 _needs_weights_conversion = false;
244 _needs_weights_reshape = fc_info.transpose_weights ? !fc_info.are_weights_reshaped : false;
245 _needs_weights_reshape = _needs_weights_reshape && !fc_info.retain_internal_weights;
246 _is_fc_after_conv = true;
247 _is_quantized_asymmetric = is_data_type_quantized_asymmetric(src->data_type());
248 _is_prepared = false;
249 _trans_weights_idx = AuxTensorIdx::Count;
cfRodf2c022e2021-11-05 11:29:53 +0000250 _enable_fast_math = fc_info.enable_fast_math;
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100251
252 // With the Fully Connected layer we can have 4 different cases:
253 // 1) Convolution layer -> Fully Connected layer without batches
254 // 2) Fully Connected layer -> Fully Connected layer without batches
255 // 3) Convolution layer -> Fully Connected layer with batches
256 // 4) Fully Connected layer -> Fully Connected layer with batches
257
258 const ITensorInfo *weights_to_use = weights;
259
260 // Check if we have a fully connected layer with batches
261 const bool is_batched_fc_layer = dst->dimension(1) > 1;
262 if(is_batched_fc_layer)
263 {
264 _is_fc_after_conv = (TensorShape::num_max_dimensions >= 4) && (std::equal(src->tensor_shape().cbegin() + 3,
265 src->tensor_shape().cend(),
266 dst->tensor_shape().cbegin() + 1));
267 }
268 else
269 {
270 _is_fc_after_conv = src->num_dimensions() > 1;
271 }
272
273 // Reshape weights if needed
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100274 if(_needs_weights_reshape)
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100275 {
276 // Reshape the weights
277 _transpose_weights = std::make_unique<kernels::CpuTransposeKernel>();
278 _transpose_weights->configure(weights, &_reshaped_weights);
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100279 weights_to_use = &_reshaped_weights;
280 _trans_weights_idx = AuxTensorIdx::TransposedWeights;
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100281 }
282
283 // Convert weights if needed
284 if(_is_fc_after_conv && (src->data_layout() != fc_info.weights_trained_layout))
285 {
286 // Convert weights
287 _convert_weights = std::make_unique<CpuConvertFullyConnectedWeights>();
288 _convert_weights->configure(weights_to_use,
289 &_converted_weights,
290 src->tensor_shape(),
291 fc_info.weights_trained_layout);
292
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100293 weights_to_use = &_converted_weights;
294 _needs_weights_conversion = true;
295 _trans_weights_idx = AuxTensorIdx::ConvertedWeights;
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100296 }
297
298 if(_is_fc_after_conv)
299 {
300 // Fully Connected layer after a Convolution Layer without batches
301 configure_conv_fc(src, weights_to_use, biases, dst, fc_info.activation_info);
302 }
303 else
304 {
305 // Fully Connected layer after a Fully Connected Layer without batches
306 configure_fc_fc(src, weights_to_use, biases, dst, fc_info.activation_info);
307 }
308
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100309 // Retain the tensorinfo with the weights to use
310 if(_needs_weights_reshape || _needs_weights_conversion)
311 {
312 _trans_weights = *weights_to_use;
313 }
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100314
315 // Set auxiliary memory requirements
316 auto gemm_mem_req = (_is_quantized_asymmetric) ? _mm_gemmlowp->workspace() : _mm_gemm->workspace();
317 for(unsigned int i = 0; i < gemm_mem_req.size(); ++i)
318 {
319 _aux_mem[i] = gemm_mem_req[i];
320 }
321
322 if(_aux_mem[Pretranspose].size > 0)
323 {
Giorgio Arena63e0beb2021-09-24 14:04:27 +0100324 // Release permuted weights at the end of prepare as they are further transposed by the assembly dispatch
325 // Do not release them if biases are dynamic and data type is quantized, since the weights tensor will be used for biases offset calculation
326 _aux_mem[TransposedWeights] = MemoryInfo(offset_int_vec(TransposedWeights), (_is_quantized_asymmetric
327 && biases && !(biases->are_values_constant())) ?
328 MemoryLifetime::Persistent :
329 MemoryLifetime::Prepare,
330 _reshaped_weights.total_size());
331 _aux_mem[ConvertedWeights] = MemoryInfo(offset_int_vec(ConvertedWeights), MemoryLifetime::Prepare, _converted_weights.total_size());
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100332 }
333 else
334 {
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100335 _aux_mem[TransposedWeights] = MemoryInfo(offset_int_vec(TransposedWeights), _needs_weights_conversion ? MemoryLifetime::Prepare : MemoryLifetime::Persistent, _reshaped_weights.total_size());
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100336 _aux_mem[ConvertedWeights] = MemoryInfo(offset_int_vec(ConvertedWeights), MemoryLifetime::Persistent, _converted_weights.total_size());
337 }
338 _aux_mem[FlattenedSrc] = MemoryInfo(offset_int_vec(FlattenedSrc), MemoryLifetime::Temporary, _flattened_src.total_size());
339}
340
341Status CpuFullyConnected::validate(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst,
342 FullyConnectedLayerInfo fc_info)
343{
344 ARM_COMPUTE_UNUSED(fc_info.retain_internal_weights);
345 ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(src, weights, dst);
346 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(src, 1, DataType::QASYMM8, DataType::QASYMM8_SIGNED, DataType::F16, DataType::F32);
347 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src, weights, dst);
348 ARM_COMPUTE_RETURN_ERROR_ON(weights->num_dimensions() > 2);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100349 ARM_COMPUTE_RETURN_ERROR_ON(fc_info.activation_info.enabled() && is_data_type_quantized(src->data_type()) && fc_info.activation_info.activation() != ActivationLayerInfo::ActivationFunction::RELU
350 && fc_info.activation_info.activation() != ActivationLayerInfo::ActivationFunction::BOUNDED_RELU && fc_info.activation_info.activation() != ActivationLayerInfo::ActivationFunction::LU_BOUNDED_RELU);
Giorgio Arena63e0beb2021-09-24 14:04:27 +0100351 ARM_COMPUTE_RETURN_ERROR_ON(!weights->are_values_constant() && (!fc_info.are_weights_reshaped || fc_info.transpose_weights));
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100352
353 bool weights_reshaped = fc_info.transpose_weights ? fc_info.are_weights_reshaped : true;
354 bool is_fc_after_conv = true;
355
356 const ITensorInfo &flatten_src = TensorInfo(src->clone()->set_is_resizable(true).reset_padding().set_tensor_shape(compute_flatten_shape(src)));
357 const ITensorInfo &reshaped_weights = TensorInfo(weights->clone()->set_is_resizable(true).reset_padding().set_tensor_shape(compute_transposed_shape(*weights)));
358 const ITensorInfo &converted_weights = weights_reshaped ? TensorInfo(weights->clone()->set_is_resizable(true).reset_padding()) : TensorInfo(*reshaped_weights.clone());
359
360 // With the Fully Connected layer we can have 4 different cases:
361 // 1) Convolution layer -> Fully Connected layer without batches
362 // 2) Fully Connected layer -> Fully Connected layer without batches
363 // 3) Convolution layer -> Fully Connected layer with batches
364 // 4) Fully Connected layer -> Fully Connected layer with batches
365
366 const ITensorInfo *src_to_use = src;
367 const ITensorInfo *weights_to_use = weights;
368
369 // Check if we have a fully connected layer with batches
370 const bool is_batched_fc_layer = dst->dimension(1) > 1;
371
Giorgio Arena63e0beb2021-09-24 14:04:27 +0100372 if(biases != nullptr)
373 {
374 ARM_COMPUTE_RETURN_ERROR_ON(biases->num_dimensions() > 1);
375 if(is_data_type_quantized(src->data_type()))
376 {
377 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(biases, 1, DataType::S32);
378 }
379 else
380 {
381 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src, biases);
382 }
383 }
384
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100385 if(is_batched_fc_layer)
386 {
387 is_fc_after_conv = (TensorShape::num_max_dimensions >= 4) && (std::equal(src->tensor_shape().cbegin() + 3,
388 src->tensor_shape().cend(),
389 dst->tensor_shape().cbegin() + 1));
390 }
391 else
392 {
393 is_fc_after_conv = src->num_dimensions() > 1;
394 }
395
396 if(!weights_reshaped)
397 {
398 // Validate reshape weights kernel
399 ARM_COMPUTE_RETURN_ON_ERROR(kernels::CpuTransposeKernel::validate(weights, &reshaped_weights));
400 weights_to_use = &reshaped_weights;
401 }
402
403 if(is_fc_after_conv && (src->data_layout() != fc_info.weights_trained_layout))
404 {
405 // Validate convert weights kernel
406 ARM_COMPUTE_RETURN_ON_ERROR(CpuConvertFullyConnectedWeights::validate(weights_to_use,
407 &converted_weights,
408 src->tensor_shape(),
409 fc_info.weights_trained_layout));
410 weights_to_use = &converted_weights;
411 }
412
413 if(is_fc_after_conv)
414 {
415 // Fully Connected layer after a Convolution Layer without batches
416 ARM_COMPUTE_RETURN_ERROR_ON((weights_to_use->dimension(1) != (src->dimension(0) * src->dimension(1) * src->dimension(2))));
417
418 // Validate flatten kernel
419 ARM_COMPUTE_RETURN_ON_ERROR(CpuFlatten::validate(src, &flatten_src));
420 src_to_use = &flatten_src;
421 }
422 else
423 {
424 // Fully Connected layer after a Fully Connected Layer without batches
425 ARM_COMPUTE_RETURN_ERROR_ON(src->dimension(0) != weights_to_use->dimension(1));
426 }
427 // Validate matrix multiply kernel
cfRodf2c022e2021-11-05 11:29:53 +0000428 ARM_COMPUTE_RETURN_ON_ERROR(validate_mm(src_to_use, weights_to_use, biases, dst, fc_info.activation_info, fc_info.enable_fast_math));
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100429
430 return Status{};
431}
432
433void CpuFullyConnected::run(ITensorPack &tensors)
434{
435 prepare(tensors);
436
437 auto src = tensors.get_const_tensor(ACL_SRC_0);
438
439 CpuAuxTensorHandler flattened_src(offset_int_vec(FlattenedSrc), _flattened_src, tensors, false);
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100440 CpuAuxTensorHandler transformed_wei(offset_int_vec(_trans_weights_idx), _trans_weights, tensors, false);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100441
442 // Linearize src if it comes from a convolutional layer
443 if(_is_fc_after_conv)
444 {
445 ITensorPack flatten_pack{ { ACL_SRC, src }, { ACL_DST, flattened_src.get() } };
446 _flatten->run(flatten_pack);
447 }
448
449 ITensorPack gemm_pack = tensors;
450 gemm_pack.add_const_tensor(ACL_SRC_0, (_is_fc_after_conv) ? flattened_src.get() : src);
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100451 if(_needs_weights_reshape || _needs_weights_conversion)
452 {
453 gemm_pack.add_const_tensor(ACL_SRC_1, transformed_wei.get());
454 }
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100455
456 // Run matrix multiply
457 if(_is_quantized_asymmetric)
458 {
459 _mm_gemmlowp->run(gemm_pack);
460 }
461 else
462 {
463 _mm_gemm->run(gemm_pack);
464 }
465}
466
467void CpuFullyConnected::prepare(ITensorPack &tensors)
468{
469 if(!_is_prepared)
470 {
471 auto weights = tensors.get_const_tensor(ACL_SRC_1);
472
473 CpuAuxTensorHandler reshaped_weights(offset_int_vec(TransposedWeights), _reshaped_weights, tensors, false);
474 CpuAuxTensorHandler converted_weights(offset_int_vec(ConvertedWeights), _converted_weights, tensors, false);
475
476 // Pointer to current weights
477 const ITensor *cur_weights = weights;
478
479 // Reshape of the weights (happens only once)
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100480 if(_needs_weights_reshape)
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100481 {
482 // Run reshape weights kernel and mark weights as unused
483 ITensorPack transpose_pack{ { ACL_SRC, weights }, { ACL_DST, reshaped_weights.get() } };
484 NEScheduler::get().schedule_op(_transpose_weights.get(), Window::DimY, _transpose_weights->window(), transpose_pack);
485
486 cur_weights->mark_as_unused();
487 cur_weights = reshaped_weights.get();
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100488 }
489
490 // Convert weights if needed (happens only once)
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100491 if(_needs_weights_conversion)
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100492 {
493 ITensorPack convert_pack{ { ACL_SRC, cur_weights }, { ACL_DST, converted_weights.get() } };
494 _convert_weights->run(convert_pack);
495
496 cur_weights->mark_as_unused();
497 cur_weights = converted_weights.get();
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100498 }
499
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100500 ITensorPack gemm_pack = tensors;
501 gemm_pack.add_const_tensor(ACL_SRC_1, cur_weights);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100502
503 // Prepare GEMM prepare and release unused weights
504 if(!_is_quantized_asymmetric)
505 {
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100506 _mm_gemm->prepare(gemm_pack);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100507 }
508 else
509 {
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100510 _mm_gemmlowp->prepare(gemm_pack);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100511 }
512
513 _is_prepared = true;
514 }
515}
516
517experimental::MemoryRequirements CpuFullyConnected::workspace() const
518{
519 return _aux_mem;
520}
521} // namespace cpu
522} // namespace arm_compute