blob: 395d8d2aa54ca8f1018e351264b355e1c352441a [file] [log] [blame]
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +01001/*
Jonathan Deakin464ed202023-01-12 11:41:14 +00002 * Copyright (c) 2021-2023 Arm Limited.
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +01003 *
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"
Viet-Hoa Doa62129a2023-04-26 15:38:45 +010035#include "src/core/utils/quantization/AsymmHelpers.h"
Georgios Pinitas7891a732021-08-20 21:39:25 +010036#include "src/cpu/kernels/CpuTransposeKernel.h"
37#include "src/cpu/operators/CpuConvertFullyConnectedWeights.h"
38#include "src/cpu/operators/CpuFlatten.h"
39#include "src/cpu/operators/CpuGemm.h"
40#include "src/cpu/operators/CpuGemmLowpMatrixMultiplyCore.h"
41#include "src/cpu/utils/CpuAuxTensorHandler.h"
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +010042
43namespace arm_compute
44{
45namespace cpu
46{
47using namespace arm_compute::experimental;
48using namespace arm_compute::misc::shape_calculator;
49
50namespace
51{
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +010052Status get_gemmlowp_output_stage_info(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *dst, const ActivationLayerInfo &act,
53 GEMMLowpOutputStageInfo &gemmlowp_output_stage_info)
54{
55 const auto data_type = src->data_type();
56 const QuantizationInfo oq_info = dst->quantization_info();
57 const UniformQuantizationInfo iq_unif = src->quantization_info().uniform();
58 const UniformQuantizationInfo wq_unif = weights->quantization_info().uniform();
59 const UniformQuantizationInfo oq_unif = oq_info.uniform();
60
61 float multiplier = (iq_unif.scale * wq_unif.scale) / oq_unif.scale;
62 int32_t output_multiplier;
63 int32_t output_shift;
64
65 ARM_COMPUTE_RETURN_ON_ERROR(quantization::calculate_quantized_multiplier(multiplier, &output_multiplier, &output_shift));
66
Viet-Hoa Doa62129a2023-04-26 15:38:45 +010067 int32_t type_min = 0;
68 int32_t type_max = 0;
Viet-Hoa Do9c7c2d22023-04-11 17:16:27 +010069 std::tie(type_min, type_max) = quantization::get_quantized_asymmetric_output_min_max(oq_info, act, data_type);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +010070
71 gemmlowp_output_stage_info.gemmlowp_multiplier = output_multiplier;
72 gemmlowp_output_stage_info.gemmlowp_shift = output_shift;
73 gemmlowp_output_stage_info.gemmlowp_offset = oq_unif.offset;
74 gemmlowp_output_stage_info.type = GEMMLowpOutputStageType::QUANTIZE_DOWN_FIXEDPOINT;
Viet-Hoa Doa62129a2023-04-26 15:38:45 +010075 gemmlowp_output_stage_info.gemmlowp_min_bound = type_min;
76 gemmlowp_output_stage_info.gemmlowp_max_bound = type_max;
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +010077
78 return Status{};
79}
80
Jonathan Deakin464ed202023-01-12 11:41:14 +000081Status validate_mm(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst, const ActivationLayerInfo &act, bool enable_fast_math, WeightFormat weight_format)
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +010082{
83 if(is_data_type_quantized_asymmetric(src->data_type()))
84 {
85 // Since we need negative offsets for computing convolution, we need to change QuantizationInfo()
86 // Extract and negate src and weights offset
87 const QuantizationInfo src_quantization_info(src->quantization_info().uniform().scale, -src->quantization_info().uniform().offset);
88 const QuantizationInfo weights_quantization_info(weights->quantization_info().uniform().scale, -weights->quantization_info().uniform().offset);
89
90 GEMMLowpOutputStageInfo gemmlowp_output_stage_info;
91 ARM_COMPUTE_RETURN_ON_ERROR(get_gemmlowp_output_stage_info(src, weights, dst, act, gemmlowp_output_stage_info));
92
93 GEMMInfo gemm_info;
94 gemm_info.set_gemmlowp_output_stage(gemmlowp_output_stage_info);
cfRodf2c022e2021-11-05 11:29:53 +000095 gemm_info.set_fast_math(enable_fast_math);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +010096
97 // Validate gemmlowp function
98 TensorInfo src_info = src->clone()->set_quantization_info(src_quantization_info);
99 TensorInfo weights_info = weights->clone()->set_quantization_info(weights_quantization_info);
100 ARM_COMPUTE_RETURN_ON_ERROR(CpuGemmLowpMatrixMultiplyCore::validate(&src_info,
101 &weights_info,
102 biases,
103 dst,
104 gemm_info));
105 }
106 else
107 {
Viet-Hoa Do9b0a6b42023-04-03 16:27:25 +0100108 GEMMInfo gemm_info;
Jonathan Deakin464ed202023-01-12 11:41:14 +0000109 gemm_info.set_weight_format(weight_format);
110 gemm_info.set_fixed_format(weight_format != WeightFormat::UNSPECIFIED);
cfRodf2c022e2021-11-05 11:29:53 +0000111 gemm_info.set_fast_math(enable_fast_math);
112 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 +0100113 }
114
115 return Status{};
116}
117} // namespace
118
119CpuFullyConnected::CpuFullyConnected()
120 : _flatten(nullptr),
121 _convert_weights(nullptr),
122 _transpose_weights(nullptr),
123 _mm_gemm(nullptr),
124 _mm_gemmlowp(nullptr),
125 _flattened_src(),
126 _converted_weights(),
127 _reshaped_weights(),
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100128 _trans_weights(),
129 _trans_weights_idx(AuxTensorIdx::Count),
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100130 _aux_mem(Count),
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100131 _needs_weights_conversion(false),
132 _needs_weights_reshape(false),
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100133 _is_fc_after_conv(false),
134 _is_quantized_asymmetric(false),
cfRodf2c022e2021-11-05 11:29:53 +0000135 _is_prepared(false),
Milos Puzovic13b623e2022-07-27 17:53:21 +0000136 _enable_fast_math(false),
137 _fixed_format(false),
Viet-Hoa Doa3e57c22023-03-13 16:20:04 +0000138 _weight_format(arm_compute::WeightFormat::UNSPECIFIED),
139 _dynamic_weights(false)
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100140{
141}
142
143CpuFullyConnected::~CpuFullyConnected() = default;
144
145void CpuFullyConnected::configure_mm(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst, const ActivationLayerInfo &act)
146{
147 if(_is_quantized_asymmetric)
148 {
149 // Since we need negative offsets for computing convolution, we need to change QuantizationInfo()
150 // Extract and negate src and weights offset
151 const QuantizationInfo src_quantization_info(src->quantization_info().uniform().scale, -src->quantization_info().uniform().offset);
152 const QuantizationInfo weights_quantization_info(weights->quantization_info().uniform().scale, -weights->quantization_info().uniform().offset);
153
154 TensorInfo src_info = src->clone()->set_quantization_info(src_quantization_info);
155 TensorInfo weights_info = weights->clone()->set_quantization_info(weights_quantization_info);
156
157 // Configure gemmlowp function and output stage for asymmetric quantized types
158 GEMMLowpOutputStageInfo gemmlowp_output_stage_info;
159 const Status status = get_gemmlowp_output_stage_info(&src_info, &weights_info, dst, act, gemmlowp_output_stage_info);
160 ARM_COMPUTE_ERROR_ON(status.error_code() != ErrorCode::OK);
161
Viet-Hoa Do9b0a6b42023-04-03 16:27:25 +0100162 GEMMInfo gemm_info;
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100163 gemm_info.set_gemmlowp_output_stage(gemmlowp_output_stage_info);
164 gemm_info.set_activation_info(act);
cfRodf2c022e2021-11-05 11:29:53 +0000165 gemm_info.set_fast_math(_enable_fast_math);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100166 _mm_gemmlowp = std::make_unique<CpuGemmLowpMatrixMultiplyCore>();
167 _mm_gemmlowp->configure(&src_info, &weights_info, biases, dst, gemm_info);
168 }
169 else
170 {
171 // Configure matrix multiply kernel
Viet-Hoa Do9b0a6b42023-04-03 16:27:25 +0100172 GEMMInfo gemm_info;
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100173 gemm_info.set_activation_info(act);
cfRodf2c022e2021-11-05 11:29:53 +0000174 gemm_info.set_fast_math(_enable_fast_math);
Milos Puzovic13b623e2022-07-27 17:53:21 +0000175 gemm_info.set_fixed_format(_fixed_format);
176 gemm_info.set_weight_format(_weight_format);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100177 _mm_gemm = std::make_unique<CpuGemm>();
178 _mm_gemm->configure(src, weights, biases, dst, 1.f, 1.0f, gemm_info);
179 }
180}
181
182void CpuFullyConnected::configure_conv_fc(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst, const ActivationLayerInfo &act)
183{
184 ARM_COMPUTE_ERROR_ON((weights->dimension(1) != (src->dimension(0) * src->dimension(1) * src->dimension(2))));
185
186 // If the fully connected layer is called after a convolution layer, the src tensor must be linearized
187
188 // Initialize output tensor for flatten
189 auto_init_if_empty(_flattened_src, src->clone()->set_tensor_shape(compute_flatten_shape(src)));
190
191 _flatten = std::make_unique<CpuFlatten>();
192 _flatten->configure(src, &_flattened_src);
193
194 // Configure matrix multiply kernel
195 configure_mm(&_flattened_src, weights, biases, dst, act);
196}
197
198void CpuFullyConnected::configure_fc_fc(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst, const ActivationLayerInfo &act)
199{
200 ARM_COMPUTE_ERROR_ON(src->dimension(0) != weights->dimension(1));
201
202 // Configure matrix multiply kernel
203 configure_mm(src, weights, biases, dst, act);
204}
205
206void CpuFullyConnected::configure(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst,
Milos Puzovic13b623e2022-07-27 17:53:21 +0000207 FullyConnectedLayerInfo fc_info, const WeightsInfo &weights_info)
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100208{
209 // Perform validate step
210 ARM_COMPUTE_ERROR_ON_NULLPTR(src, weights, dst);
211 ARM_COMPUTE_ERROR_THROW_ON(CpuFullyConnected::validate(src,
212 weights,
213 biases != nullptr ? biases : nullptr,
214 dst,
Jonathan Deakin464ed202023-01-12 11:41:14 +0000215 fc_info,
216 weights_info));
ramelg013ae3d882021-09-12 23:07:47 +0100217 ARM_COMPUTE_LOG_PARAMS(src, weights, biases, dst, fc_info);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100218
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100219 _needs_weights_conversion = false;
220 _needs_weights_reshape = fc_info.transpose_weights ? !fc_info.are_weights_reshaped : false;
221 _needs_weights_reshape = _needs_weights_reshape && !fc_info.retain_internal_weights;
222 _is_fc_after_conv = true;
223 _is_quantized_asymmetric = is_data_type_quantized_asymmetric(src->data_type());
224 _is_prepared = false;
225 _trans_weights_idx = AuxTensorIdx::Count;
cfRodf2c022e2021-11-05 11:29:53 +0000226 _enable_fast_math = fc_info.enable_fast_math;
Milos Puzovic13b623e2022-07-27 17:53:21 +0000227 _fixed_format = weights_info.weight_format() != WeightFormat::UNSPECIFIED;
228 _weight_format = weights_info.weight_format();
Viet-Hoa Doa3e57c22023-03-13 16:20:04 +0000229 _dynamic_weights = !weights->are_values_constant() && _needs_weights_reshape;
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100230
231 // With the Fully Connected layer we can have 4 different cases:
232 // 1) Convolution layer -> Fully Connected layer without batches
233 // 2) Fully Connected layer -> Fully Connected layer without batches
234 // 3) Convolution layer -> Fully Connected layer with batches
235 // 4) Fully Connected layer -> Fully Connected layer with batches
236
237 const ITensorInfo *weights_to_use = weights;
238
239 // Check if we have a fully connected layer with batches
240 const bool is_batched_fc_layer = dst->dimension(1) > 1;
241 if(is_batched_fc_layer)
242 {
Milos Puzovic13b623e2022-07-27 17:53:21 +0000243 _is_fc_after_conv = (TensorShape::num_max_dimensions >= 4) && (std::equal(src->tensor_shape().cbegin() + 3, src->tensor_shape().cend(), dst->tensor_shape().cbegin() + 1));
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100244 }
245 else
246 {
247 _is_fc_after_conv = src->num_dimensions() > 1;
248 }
249
250 // Reshape weights if needed
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100251 if(_needs_weights_reshape)
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100252 {
253 // Reshape the weights
254 _transpose_weights = std::make_unique<kernels::CpuTransposeKernel>();
255 _transpose_weights->configure(weights, &_reshaped_weights);
Viet-Hoa Do9b0a6b42023-04-03 16:27:25 +0100256 _reshaped_weights.set_are_values_constant(weights->are_values_constant());
257
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100258 weights_to_use = &_reshaped_weights;
259 _trans_weights_idx = AuxTensorIdx::TransposedWeights;
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100260 }
261
262 // Convert weights if needed
263 if(_is_fc_after_conv && (src->data_layout() != fc_info.weights_trained_layout))
264 {
265 // Convert weights
266 _convert_weights = std::make_unique<CpuConvertFullyConnectedWeights>();
267 _convert_weights->configure(weights_to_use,
268 &_converted_weights,
269 src->tensor_shape(),
270 fc_info.weights_trained_layout);
Viet-Hoa Do9b0a6b42023-04-03 16:27:25 +0100271 _converted_weights.set_are_values_constant(weights_to_use->are_values_constant());
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100272
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100273 weights_to_use = &_converted_weights;
274 _needs_weights_conversion = true;
275 _trans_weights_idx = AuxTensorIdx::ConvertedWeights;
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100276 }
277
278 if(_is_fc_after_conv)
279 {
280 // Fully Connected layer after a Convolution Layer without batches
281 configure_conv_fc(src, weights_to_use, biases, dst, fc_info.activation_info);
282 }
283 else
284 {
285 // Fully Connected layer after a Fully Connected Layer without batches
286 configure_fc_fc(src, weights_to_use, biases, dst, fc_info.activation_info);
287 }
288
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100289 // Retain the tensorinfo with the weights to use
290 if(_needs_weights_reshape || _needs_weights_conversion)
291 {
292 _trans_weights = *weights_to_use;
293 }
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100294
295 // Set auxiliary memory requirements
296 auto gemm_mem_req = (_is_quantized_asymmetric) ? _mm_gemmlowp->workspace() : _mm_gemm->workspace();
297 for(unsigned int i = 0; i < gemm_mem_req.size(); ++i)
298 {
299 _aux_mem[i] = gemm_mem_req[i];
300 }
301
302 if(_aux_mem[Pretranspose].size > 0)
303 {
Giorgio Arena63e0beb2021-09-24 14:04:27 +0100304 // Release permuted weights at the end of prepare as they are further transposed by the assembly dispatch
305 // Do not release them if biases are dynamic and data type is quantized, since the weights tensor will be used for biases offset calculation
Viet-Hoa Doa3e57c22023-03-13 16:20:04 +0000306 // Keep all the auxiliary tensors in case of dynamic weights as they are recalculated every time.
307 _aux_mem[TransposedWeights] = MemoryInfo(
308 offset_int_vec(TransposedWeights),
309 _dynamic_weights ? MemoryLifetime::Temporary :
310 (_is_quantized_asymmetric && biases && !(biases->are_values_constant())) ? MemoryLifetime::Persistent :
311 MemoryLifetime::Prepare,
312 _reshaped_weights.total_size());
313
314 _aux_mem[ConvertedWeights] = MemoryInfo(
315 offset_int_vec(ConvertedWeights),
316 _dynamic_weights ? MemoryLifetime::Temporary : MemoryLifetime::Prepare,
317 _converted_weights.total_size());
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100318 }
319 else
320 {
Viet-Hoa Doa3e57c22023-03-13 16:20:04 +0000321 _aux_mem[TransposedWeights] = MemoryInfo(
322 offset_int_vec(TransposedWeights),
323 _dynamic_weights ? MemoryLifetime::Temporary :
324 _needs_weights_conversion ? MemoryLifetime::Prepare :
325 MemoryLifetime::Persistent,
326 _reshaped_weights.total_size());
327
328 _aux_mem[ConvertedWeights] = MemoryInfo(
329 offset_int_vec(ConvertedWeights),
330 _dynamic_weights ? MemoryLifetime::Temporary : MemoryLifetime::Persistent,
331 _converted_weights.total_size());
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100332 }
333 _aux_mem[FlattenedSrc] = MemoryInfo(offset_int_vec(FlattenedSrc), MemoryLifetime::Temporary, _flattened_src.total_size());
334}
335
Milos Puzovic13b623e2022-07-27 17:53:21 +0000336Status CpuFullyConnected::has_opt_impl(arm_compute::WeightFormat &expected_weight_format, const ITensorInfo *src, const ITensorInfo *weights,
337 const ITensorInfo *biases, const ITensorInfo *dst, FullyConnectedLayerInfo fc_info, WeightsInfo weights_info)
338{
Viet-Hoa Do9b0a6b42023-04-03 16:27:25 +0100339 GEMMInfo gemm_info;
Milos Puzovic13b623e2022-07-27 17:53:21 +0000340 gemm_info.set_activation_info(fc_info.activation_info);
341 gemm_info.set_fast_math(fc_info.enable_fast_math);
342 gemm_info.set_fixed_format(weights_info.weight_format() != WeightFormat::UNSPECIFIED);
343 gemm_info.set_weight_format(weights_info.weight_format());
344
345 return CpuGemm::has_opt_impl(expected_weight_format, src, weights, biases, dst, gemm_info);
346}
347
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100348Status CpuFullyConnected::validate(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst,
Jonathan Deakin464ed202023-01-12 11:41:14 +0000349 FullyConnectedLayerInfo fc_info, const WeightsInfo &weights_info)
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100350{
351 ARM_COMPUTE_UNUSED(fc_info.retain_internal_weights);
352 ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(src, weights, dst);
353 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(src, 1, DataType::QASYMM8, DataType::QASYMM8_SIGNED, DataType::F16, DataType::F32);
Jonathan Deakin464ed202023-01-12 11:41:14 +0000354
355 if (is_fixed_format_fast_math(weights_info.weight_format()))
356 {
357 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_NOT_IN(src, DataType::F32);
358 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_NOT_IN(weights, DataType::BFLOAT16);
359 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_NOT_IN(dst, DataType::F32);
360 }
361 else
362 {
363 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src, weights, dst);
364 }
365
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100366 ARM_COMPUTE_RETURN_ERROR_ON(weights->num_dimensions() > 2);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100367 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
368 && fc_info.activation_info.activation() != ActivationLayerInfo::ActivationFunction::BOUNDED_RELU && fc_info.activation_info.activation() != ActivationLayerInfo::ActivationFunction::LU_BOUNDED_RELU);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100369
370 bool weights_reshaped = fc_info.transpose_weights ? fc_info.are_weights_reshaped : true;
371 bool is_fc_after_conv = true;
372
373 const ITensorInfo &flatten_src = TensorInfo(src->clone()->set_is_resizable(true).reset_padding().set_tensor_shape(compute_flatten_shape(src)));
374 const ITensorInfo &reshaped_weights = TensorInfo(weights->clone()->set_is_resizable(true).reset_padding().set_tensor_shape(compute_transposed_shape(*weights)));
375 const ITensorInfo &converted_weights = weights_reshaped ? TensorInfo(weights->clone()->set_is_resizable(true).reset_padding()) : TensorInfo(*reshaped_weights.clone());
376
377 // With the Fully Connected layer we can have 4 different cases:
378 // 1) Convolution layer -> Fully Connected layer without batches
379 // 2) Fully Connected layer -> Fully Connected layer without batches
380 // 3) Convolution layer -> Fully Connected layer with batches
381 // 4) Fully Connected layer -> Fully Connected layer with batches
382
383 const ITensorInfo *src_to_use = src;
384 const ITensorInfo *weights_to_use = weights;
385
386 // Check if we have a fully connected layer with batches
387 const bool is_batched_fc_layer = dst->dimension(1) > 1;
388
Giorgio Arena63e0beb2021-09-24 14:04:27 +0100389 if(biases != nullptr)
390 {
391 ARM_COMPUTE_RETURN_ERROR_ON(biases->num_dimensions() > 1);
392 if(is_data_type_quantized(src->data_type()))
393 {
394 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(biases, 1, DataType::S32);
395 }
396 else
397 {
398 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src, biases);
399 }
400 }
401
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100402 if(is_batched_fc_layer)
403 {
Milos Puzovic13b623e2022-07-27 17:53:21 +0000404 is_fc_after_conv = (TensorShape::num_max_dimensions >= 4) && (std::equal(src->tensor_shape().cbegin() + 3, src->tensor_shape().cend(), dst->tensor_shape().cbegin() + 1));
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100405 }
406 else
407 {
408 is_fc_after_conv = src->num_dimensions() > 1;
409 }
410
411 if(!weights_reshaped)
412 {
413 // Validate reshape weights kernel
414 ARM_COMPUTE_RETURN_ON_ERROR(kernels::CpuTransposeKernel::validate(weights, &reshaped_weights));
415 weights_to_use = &reshaped_weights;
416 }
417
418 if(is_fc_after_conv && (src->data_layout() != fc_info.weights_trained_layout))
419 {
420 // Validate convert weights kernel
421 ARM_COMPUTE_RETURN_ON_ERROR(CpuConvertFullyConnectedWeights::validate(weights_to_use,
422 &converted_weights,
423 src->tensor_shape(),
424 fc_info.weights_trained_layout));
425 weights_to_use = &converted_weights;
426 }
427
428 if(is_fc_after_conv)
429 {
430 // Fully Connected layer after a Convolution Layer without batches
431 ARM_COMPUTE_RETURN_ERROR_ON((weights_to_use->dimension(1) != (src->dimension(0) * src->dimension(1) * src->dimension(2))));
432
433 // Validate flatten kernel
434 ARM_COMPUTE_RETURN_ON_ERROR(CpuFlatten::validate(src, &flatten_src));
435 src_to_use = &flatten_src;
436 }
437 else
438 {
439 // Fully Connected layer after a Fully Connected Layer without batches
440 ARM_COMPUTE_RETURN_ERROR_ON(src->dimension(0) != weights_to_use->dimension(1));
441 }
442 // Validate matrix multiply kernel
Jonathan Deakin464ed202023-01-12 11:41:14 +0000443 ARM_COMPUTE_RETURN_ON_ERROR(validate_mm(src_to_use, weights_to_use, biases, dst, fc_info.activation_info, fc_info.enable_fast_math, weights_info.weight_format()));
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100444
445 return Status{};
446}
447
448void CpuFullyConnected::run(ITensorPack &tensors)
449{
450 prepare(tensors);
451
Viet-Hoa Doa3e57c22023-03-13 16:20:04 +0000452#ifdef ARM_COMPUTE_ASSERTS_ENABLED
453 ++_asrt_run_count;
454 ARM_COMPUTE_ERROR_ON(_dynamic_weights && _asrt_prepare_count != _asrt_run_count);
455#endif // ARM_COMPUTE_ASSERTS_ENABLED
456
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100457 auto src = tensors.get_const_tensor(ACL_SRC_0);
458
459 CpuAuxTensorHandler flattened_src(offset_int_vec(FlattenedSrc), _flattened_src, tensors, false);
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100460 CpuAuxTensorHandler transformed_wei(offset_int_vec(_trans_weights_idx), _trans_weights, tensors, false);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100461
462 // Linearize src if it comes from a convolutional layer
463 if(_is_fc_after_conv)
464 {
465 ITensorPack flatten_pack{ { ACL_SRC, src }, { ACL_DST, flattened_src.get() } };
466 _flatten->run(flatten_pack);
467 }
468
469 ITensorPack gemm_pack = tensors;
470 gemm_pack.add_const_tensor(ACL_SRC_0, (_is_fc_after_conv) ? flattened_src.get() : src);
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100471 if(_needs_weights_reshape || _needs_weights_conversion)
472 {
473 gemm_pack.add_const_tensor(ACL_SRC_1, transformed_wei.get());
474 }
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100475
476 // Run matrix multiply
477 if(_is_quantized_asymmetric)
478 {
479 _mm_gemmlowp->run(gemm_pack);
480 }
481 else
482 {
483 _mm_gemm->run(gemm_pack);
484 }
485}
486
487void CpuFullyConnected::prepare(ITensorPack &tensors)
488{
Viet-Hoa Doa3e57c22023-03-13 16:20:04 +0000489 if(!_is_prepared || _dynamic_weights)
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100490 {
Viet-Hoa Doa3e57c22023-03-13 16:20:04 +0000491#ifdef ARM_COMPUTE_ASSERTS_ENABLED
492 ++_asrt_prepare_count;
493 ARM_COMPUTE_ERROR_ON(!_dynamic_weights && _asrt_prepare_count > 1);
494#endif // ARM_COMPUTE_ASSERTS_ENABLED
495
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100496 auto weights = tensors.get_const_tensor(ACL_SRC_1);
497
498 CpuAuxTensorHandler reshaped_weights(offset_int_vec(TransposedWeights), _reshaped_weights, tensors, false);
499 CpuAuxTensorHandler converted_weights(offset_int_vec(ConvertedWeights), _converted_weights, tensors, false);
500
501 // Pointer to current weights
502 const ITensor *cur_weights = weights;
503
504 // Reshape of the weights (happens only once)
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100505 if(_needs_weights_reshape)
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100506 {
507 // Run reshape weights kernel and mark weights as unused
508 ITensorPack transpose_pack{ { ACL_SRC, weights }, { ACL_DST, reshaped_weights.get() } };
509 NEScheduler::get().schedule_op(_transpose_weights.get(), Window::DimY, _transpose_weights->window(), transpose_pack);
510
511 cur_weights->mark_as_unused();
512 cur_weights = reshaped_weights.get();
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100513 }
514
515 // Convert weights if needed (happens only once)
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100516 if(_needs_weights_conversion)
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100517 {
518 ITensorPack convert_pack{ { ACL_SRC, cur_weights }, { ACL_DST, converted_weights.get() } };
519 _convert_weights->run(convert_pack);
520
521 cur_weights->mark_as_unused();
522 cur_weights = converted_weights.get();
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100523 }
524
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100525 ITensorPack gemm_pack = tensors;
526 gemm_pack.add_const_tensor(ACL_SRC_1, cur_weights);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100527
528 // Prepare GEMM prepare and release unused weights
529 if(!_is_quantized_asymmetric)
530 {
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100531 _mm_gemm->prepare(gemm_pack);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100532 }
533 else
534 {
Georgios Pinitasfa1db172021-08-12 06:28:09 +0100535 _mm_gemmlowp->prepare(gemm_pack);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100536 }
537
538 _is_prepared = true;
539 }
540}
541
542experimental::MemoryRequirements CpuFullyConnected::workspace() const
543{
544 return _aux_mem;
545}
546} // namespace cpu
547} // namespace arm_compute