1*c217d954SCole Faust /*
2*c217d954SCole Faust * Copyright (c) 2021-2023 Arm Limited.
3*c217d954SCole Faust *
4*c217d954SCole Faust * SPDX-License-Identifier: MIT
5*c217d954SCole Faust *
6*c217d954SCole Faust * Permission is hereby granted, free of charge, to any person obtaining a copy
7*c217d954SCole Faust * of this software and associated documentation files (the "Software"), to
8*c217d954SCole Faust * deal in the Software without restriction, including without limitation the
9*c217d954SCole Faust * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10*c217d954SCole Faust * sell copies of the Software, and to permit persons to whom the Software is
11*c217d954SCole Faust * furnished to do so, subject to the following conditions:
12*c217d954SCole Faust *
13*c217d954SCole Faust * The above copyright notice and this permission notice shall be included in all
14*c217d954SCole Faust * copies or substantial portions of the Software.
15*c217d954SCole Faust *
16*c217d954SCole Faust * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17*c217d954SCole Faust * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18*c217d954SCole Faust * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19*c217d954SCole Faust * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20*c217d954SCole Faust * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21*c217d954SCole Faust * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22*c217d954SCole Faust * SOFTWARE.
23*c217d954SCole Faust */
24*c217d954SCole Faust #include "src/cpu/operators/CpuFullyConnected.h"
25*c217d954SCole Faust
26*c217d954SCole Faust #include "arm_compute/core/Helpers.h"
27*c217d954SCole Faust #include "arm_compute/core/ITensorPack.h"
28*c217d954SCole Faust #include "arm_compute/core/Validate.h"
29*c217d954SCole Faust #include "arm_compute/core/utils/misc/ShapeCalculator.h"
30*c217d954SCole Faust #include "arm_compute/core/utils/quantization/AsymmHelpers.h"
31*c217d954SCole Faust #include "arm_compute/runtime/NEON/NEScheduler.h"
32*c217d954SCole Faust #include "src/common/utils/Log.h"
33*c217d954SCole Faust #include "src/core/helpers/AutoConfiguration.h"
34*c217d954SCole Faust #include "src/core/helpers/MemoryHelpers.h"
35*c217d954SCole Faust #include "src/cpu/kernels/CpuTransposeKernel.h"
36*c217d954SCole Faust #include "src/cpu/operators/CpuConvertFullyConnectedWeights.h"
37*c217d954SCole Faust #include "src/cpu/operators/CpuFlatten.h"
38*c217d954SCole Faust #include "src/cpu/operators/CpuGemm.h"
39*c217d954SCole Faust #include "src/cpu/operators/CpuGemmLowpMatrixMultiplyCore.h"
40*c217d954SCole Faust #include "src/cpu/utils/CpuAuxTensorHandler.h"
41*c217d954SCole Faust
42*c217d954SCole Faust namespace arm_compute
43*c217d954SCole Faust {
44*c217d954SCole Faust namespace cpu
45*c217d954SCole Faust {
46*c217d954SCole Faust using namespace arm_compute::experimental;
47*c217d954SCole Faust using namespace arm_compute::misc::shape_calculator;
48*c217d954SCole Faust
49*c217d954SCole Faust namespace
50*c217d954SCole Faust {
51*c217d954SCole Faust // Get min, max bound of a quantized asymmetric dst tensor, with the effect of fused activation
get_quantized_asymmetric_output_min_max(const QuantizationInfo & q_info,const ActivationLayerInfo & act_info,DataType data_type)52*c217d954SCole Faust std::pair<PixelValue, PixelValue> get_quantized_asymmetric_output_min_max(const QuantizationInfo &q_info, const ActivationLayerInfo &act_info, DataType data_type)
53*c217d954SCole Faust {
54*c217d954SCole Faust PixelValue type_min{};
55*c217d954SCole Faust PixelValue type_max{};
56*c217d954SCole Faust std::tie(type_min, type_max) = get_min_max(data_type);
57*c217d954SCole Faust const UniformQuantizationInfo q_unif = q_info.uniform();
58*c217d954SCole Faust
59*c217d954SCole Faust if(act_info.enabled())
60*c217d954SCole Faust {
61*c217d954SCole Faust switch(act_info.activation())
62*c217d954SCole Faust {
63*c217d954SCole Faust case ActivationLayerInfo::ActivationFunction::RELU:
64*c217d954SCole Faust type_min = PixelValue(q_unif.offset);
65*c217d954SCole Faust break;
66*c217d954SCole Faust case ActivationLayerInfo::ActivationFunction::BOUNDED_RELU:
67*c217d954SCole Faust type_min = PixelValue(q_unif.offset);
68*c217d954SCole Faust type_max = PixelValue(act_info.a(), data_type, q_info);
69*c217d954SCole Faust break;
70*c217d954SCole Faust case ActivationLayerInfo::ActivationFunction::LU_BOUNDED_RELU:
71*c217d954SCole Faust type_min = PixelValue(act_info.b(), data_type, q_info);
72*c217d954SCole Faust type_max = PixelValue(act_info.a(), data_type, q_info);
73*c217d954SCole Faust break;
74*c217d954SCole Faust default:
75*c217d954SCole Faust ARM_COMPUTE_ERROR("Activation function not supported.");
76*c217d954SCole Faust break;
77*c217d954SCole Faust }
78*c217d954SCole Faust }
79*c217d954SCole Faust
80*c217d954SCole Faust return std::make_pair(type_min, type_max);
81*c217d954SCole Faust }
82*c217d954SCole Faust
get_gemmlowp_output_stage_info(const ITensorInfo * src,const ITensorInfo * weights,const ITensorInfo * dst,const ActivationLayerInfo & act,GEMMLowpOutputStageInfo & gemmlowp_output_stage_info)83*c217d954SCole Faust Status get_gemmlowp_output_stage_info(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *dst, const ActivationLayerInfo &act,
84*c217d954SCole Faust GEMMLowpOutputStageInfo &gemmlowp_output_stage_info)
85*c217d954SCole Faust {
86*c217d954SCole Faust const auto data_type = src->data_type();
87*c217d954SCole Faust const QuantizationInfo oq_info = dst->quantization_info();
88*c217d954SCole Faust const UniformQuantizationInfo iq_unif = src->quantization_info().uniform();
89*c217d954SCole Faust const UniformQuantizationInfo wq_unif = weights->quantization_info().uniform();
90*c217d954SCole Faust const UniformQuantizationInfo oq_unif = oq_info.uniform();
91*c217d954SCole Faust
92*c217d954SCole Faust float multiplier = (iq_unif.scale * wq_unif.scale) / oq_unif.scale;
93*c217d954SCole Faust int32_t output_multiplier;
94*c217d954SCole Faust int32_t output_shift;
95*c217d954SCole Faust
96*c217d954SCole Faust ARM_COMPUTE_RETURN_ON_ERROR(quantization::calculate_quantized_multiplier(multiplier, &output_multiplier, &output_shift));
97*c217d954SCole Faust
98*c217d954SCole Faust PixelValue type_min{};
99*c217d954SCole Faust PixelValue type_max{};
100*c217d954SCole Faust std::tie(type_min, type_max) = get_quantized_asymmetric_output_min_max(oq_info, act, data_type);
101*c217d954SCole Faust
102*c217d954SCole Faust gemmlowp_output_stage_info.gemmlowp_multiplier = output_multiplier;
103*c217d954SCole Faust gemmlowp_output_stage_info.gemmlowp_shift = output_shift;
104*c217d954SCole Faust gemmlowp_output_stage_info.gemmlowp_offset = oq_unif.offset;
105*c217d954SCole Faust gemmlowp_output_stage_info.type = GEMMLowpOutputStageType::QUANTIZE_DOWN_FIXEDPOINT;
106*c217d954SCole Faust gemmlowp_output_stage_info.gemmlowp_min_bound = type_min.get<int32_t>();
107*c217d954SCole Faust gemmlowp_output_stage_info.gemmlowp_max_bound = type_max.get<int32_t>();
108*c217d954SCole Faust
109*c217d954SCole Faust return Status{};
110*c217d954SCole Faust }
111*c217d954SCole Faust
validate_mm(const ITensorInfo * src,const ITensorInfo * weights,const ITensorInfo * biases,const ITensorInfo * dst,const ActivationLayerInfo & act,bool enable_fast_math,WeightFormat weight_format)112*c217d954SCole Faust Status validate_mm(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst, const ActivationLayerInfo &act, bool enable_fast_math, WeightFormat weight_format)
113*c217d954SCole Faust {
114*c217d954SCole Faust if(is_data_type_quantized_asymmetric(src->data_type()))
115*c217d954SCole Faust {
116*c217d954SCole Faust // Since we need negative offsets for computing convolution, we need to change QuantizationInfo()
117*c217d954SCole Faust // Extract and negate src and weights offset
118*c217d954SCole Faust const QuantizationInfo src_quantization_info(src->quantization_info().uniform().scale, -src->quantization_info().uniform().offset);
119*c217d954SCole Faust const QuantizationInfo weights_quantization_info(weights->quantization_info().uniform().scale, -weights->quantization_info().uniform().offset);
120*c217d954SCole Faust
121*c217d954SCole Faust GEMMLowpOutputStageInfo gemmlowp_output_stage_info;
122*c217d954SCole Faust ARM_COMPUTE_RETURN_ON_ERROR(get_gemmlowp_output_stage_info(src, weights, dst, act, gemmlowp_output_stage_info));
123*c217d954SCole Faust
124*c217d954SCole Faust GEMMInfo gemm_info;
125*c217d954SCole Faust gemm_info.set_gemmlowp_output_stage(gemmlowp_output_stage_info);
126*c217d954SCole Faust gemm_info.set_fast_math(enable_fast_math);
127*c217d954SCole Faust
128*c217d954SCole Faust // Validate gemmlowp function
129*c217d954SCole Faust TensorInfo src_info = src->clone()->set_quantization_info(src_quantization_info);
130*c217d954SCole Faust TensorInfo weights_info = weights->clone()->set_quantization_info(weights_quantization_info);
131*c217d954SCole Faust ARM_COMPUTE_RETURN_ON_ERROR(CpuGemmLowpMatrixMultiplyCore::validate(&src_info,
132*c217d954SCole Faust &weights_info,
133*c217d954SCole Faust biases,
134*c217d954SCole Faust dst,
135*c217d954SCole Faust gemm_info));
136*c217d954SCole Faust }
137*c217d954SCole Faust else
138*c217d954SCole Faust {
139*c217d954SCole Faust GEMMInfo gemm_info(false, false, true /* Reshape weights only for the first run */);
140*c217d954SCole Faust gemm_info.set_weight_format(weight_format);
141*c217d954SCole Faust gemm_info.set_fixed_format(weight_format != WeightFormat::UNSPECIFIED);
142*c217d954SCole Faust gemm_info.set_fast_math(enable_fast_math);
143*c217d954SCole Faust ARM_COMPUTE_RETURN_ON_ERROR(CpuGemm::validate(src, weights, biases, dst, 1.f, 1.0f, gemm_info));
144*c217d954SCole Faust }
145*c217d954SCole Faust
146*c217d954SCole Faust return Status{};
147*c217d954SCole Faust }
148*c217d954SCole Faust } // namespace
149*c217d954SCole Faust
CpuFullyConnected()150*c217d954SCole Faust CpuFullyConnected::CpuFullyConnected()
151*c217d954SCole Faust : _flatten(nullptr),
152*c217d954SCole Faust _convert_weights(nullptr),
153*c217d954SCole Faust _transpose_weights(nullptr),
154*c217d954SCole Faust _mm_gemm(nullptr),
155*c217d954SCole Faust _mm_gemmlowp(nullptr),
156*c217d954SCole Faust _flattened_src(),
157*c217d954SCole Faust _converted_weights(),
158*c217d954SCole Faust _reshaped_weights(),
159*c217d954SCole Faust _trans_weights(),
160*c217d954SCole Faust _trans_weights_idx(AuxTensorIdx::Count),
161*c217d954SCole Faust _aux_mem(Count),
162*c217d954SCole Faust _needs_weights_conversion(false),
163*c217d954SCole Faust _needs_weights_reshape(false),
164*c217d954SCole Faust _is_fc_after_conv(false),
165*c217d954SCole Faust _is_quantized_asymmetric(false),
166*c217d954SCole Faust _is_prepared(false),
167*c217d954SCole Faust _enable_fast_math(false),
168*c217d954SCole Faust _fixed_format(false),
169*c217d954SCole Faust _weight_format(arm_compute::WeightFormat::UNSPECIFIED)
170*c217d954SCole Faust {
171*c217d954SCole Faust }
172*c217d954SCole Faust
173*c217d954SCole Faust CpuFullyConnected::~CpuFullyConnected() = default;
174*c217d954SCole Faust
configure_mm(const ITensorInfo * src,const ITensorInfo * weights,const ITensorInfo * biases,ITensorInfo * dst,const ActivationLayerInfo & act)175*c217d954SCole Faust void CpuFullyConnected::configure_mm(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst, const ActivationLayerInfo &act)
176*c217d954SCole Faust {
177*c217d954SCole Faust if(_is_quantized_asymmetric)
178*c217d954SCole Faust {
179*c217d954SCole Faust // Since we need negative offsets for computing convolution, we need to change QuantizationInfo()
180*c217d954SCole Faust // Extract and negate src and weights offset
181*c217d954SCole Faust const QuantizationInfo src_quantization_info(src->quantization_info().uniform().scale, -src->quantization_info().uniform().offset);
182*c217d954SCole Faust const QuantizationInfo weights_quantization_info(weights->quantization_info().uniform().scale, -weights->quantization_info().uniform().offset);
183*c217d954SCole Faust
184*c217d954SCole Faust TensorInfo src_info = src->clone()->set_quantization_info(src_quantization_info);
185*c217d954SCole Faust TensorInfo weights_info = weights->clone()->set_quantization_info(weights_quantization_info);
186*c217d954SCole Faust
187*c217d954SCole Faust // Configure gemmlowp function and output stage for asymmetric quantized types
188*c217d954SCole Faust GEMMLowpOutputStageInfo gemmlowp_output_stage_info;
189*c217d954SCole Faust const Status status = get_gemmlowp_output_stage_info(&src_info, &weights_info, dst, act, gemmlowp_output_stage_info);
190*c217d954SCole Faust ARM_COMPUTE_ERROR_ON(status.error_code() != ErrorCode::OK);
191*c217d954SCole Faust
192*c217d954SCole Faust GEMMInfo gemm_info;
193*c217d954SCole Faust gemm_info.set_gemmlowp_output_stage(gemmlowp_output_stage_info);
194*c217d954SCole Faust gemm_info.set_activation_info(act);
195*c217d954SCole Faust gemm_info.set_fast_math(_enable_fast_math);
196*c217d954SCole Faust _mm_gemmlowp = std::make_unique<CpuGemmLowpMatrixMultiplyCore>();
197*c217d954SCole Faust _mm_gemmlowp->configure(&src_info, &weights_info, biases, dst, gemm_info);
198*c217d954SCole Faust }
199*c217d954SCole Faust else
200*c217d954SCole Faust {
201*c217d954SCole Faust // Configure matrix multiply kernel
202*c217d954SCole Faust GEMMInfo gemm_info(false, false, true /* Reshape weights only for the first run */);
203*c217d954SCole Faust gemm_info.set_activation_info(act);
204*c217d954SCole Faust gemm_info.set_fast_math(_enable_fast_math);
205*c217d954SCole Faust gemm_info.set_fixed_format(_fixed_format);
206*c217d954SCole Faust gemm_info.set_weight_format(_weight_format);
207*c217d954SCole Faust _mm_gemm = std::make_unique<CpuGemm>();
208*c217d954SCole Faust _mm_gemm->configure(src, weights, biases, dst, 1.f, 1.0f, gemm_info);
209*c217d954SCole Faust }
210*c217d954SCole Faust }
211*c217d954SCole Faust
configure_conv_fc(const ITensorInfo * src,const ITensorInfo * weights,const ITensorInfo * biases,ITensorInfo * dst,const ActivationLayerInfo & act)212*c217d954SCole Faust void CpuFullyConnected::configure_conv_fc(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst, const ActivationLayerInfo &act)
213*c217d954SCole Faust {
214*c217d954SCole Faust ARM_COMPUTE_ERROR_ON((weights->dimension(1) != (src->dimension(0) * src->dimension(1) * src->dimension(2))));
215*c217d954SCole Faust
216*c217d954SCole Faust // If the fully connected layer is called after a convolution layer, the src tensor must be linearized
217*c217d954SCole Faust
218*c217d954SCole Faust // Initialize output tensor for flatten
219*c217d954SCole Faust auto_init_if_empty(_flattened_src, src->clone()->set_tensor_shape(compute_flatten_shape(src)));
220*c217d954SCole Faust
221*c217d954SCole Faust _flatten = std::make_unique<CpuFlatten>();
222*c217d954SCole Faust _flatten->configure(src, &_flattened_src);
223*c217d954SCole Faust
224*c217d954SCole Faust // Configure matrix multiply kernel
225*c217d954SCole Faust configure_mm(&_flattened_src, weights, biases, dst, act);
226*c217d954SCole Faust }
227*c217d954SCole Faust
configure_fc_fc(const ITensorInfo * src,const ITensorInfo * weights,const ITensorInfo * biases,ITensorInfo * dst,const ActivationLayerInfo & act)228*c217d954SCole Faust void CpuFullyConnected::configure_fc_fc(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst, const ActivationLayerInfo &act)
229*c217d954SCole Faust {
230*c217d954SCole Faust ARM_COMPUTE_ERROR_ON(src->dimension(0) != weights->dimension(1));
231*c217d954SCole Faust
232*c217d954SCole Faust // Configure matrix multiply kernel
233*c217d954SCole Faust configure_mm(src, weights, biases, dst, act);
234*c217d954SCole Faust }
235*c217d954SCole Faust
configure(const ITensorInfo * src,const ITensorInfo * weights,const ITensorInfo * biases,ITensorInfo * dst,FullyConnectedLayerInfo fc_info,const WeightsInfo & weights_info)236*c217d954SCole Faust void CpuFullyConnected::configure(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst,
237*c217d954SCole Faust FullyConnectedLayerInfo fc_info, const WeightsInfo &weights_info)
238*c217d954SCole Faust {
239*c217d954SCole Faust // Perform validate step
240*c217d954SCole Faust ARM_COMPUTE_ERROR_ON_NULLPTR(src, weights, dst);
241*c217d954SCole Faust ARM_COMPUTE_ERROR_THROW_ON(CpuFullyConnected::validate(src,
242*c217d954SCole Faust weights,
243*c217d954SCole Faust biases != nullptr ? biases : nullptr,
244*c217d954SCole Faust dst,
245*c217d954SCole Faust fc_info,
246*c217d954SCole Faust weights_info));
247*c217d954SCole Faust ARM_COMPUTE_LOG_PARAMS(src, weights, biases, dst, fc_info);
248*c217d954SCole Faust
249*c217d954SCole Faust _needs_weights_conversion = false;
250*c217d954SCole Faust _needs_weights_reshape = fc_info.transpose_weights ? !fc_info.are_weights_reshaped : false;
251*c217d954SCole Faust _needs_weights_reshape = _needs_weights_reshape && !fc_info.retain_internal_weights;
252*c217d954SCole Faust _is_fc_after_conv = true;
253*c217d954SCole Faust _is_quantized_asymmetric = is_data_type_quantized_asymmetric(src->data_type());
254*c217d954SCole Faust _is_prepared = false;
255*c217d954SCole Faust _trans_weights_idx = AuxTensorIdx::Count;
256*c217d954SCole Faust _enable_fast_math = fc_info.enable_fast_math;
257*c217d954SCole Faust _fixed_format = weights_info.weight_format() != WeightFormat::UNSPECIFIED;
258*c217d954SCole Faust _weight_format = weights_info.weight_format();
259*c217d954SCole Faust
260*c217d954SCole Faust // With the Fully Connected layer we can have 4 different cases:
261*c217d954SCole Faust // 1) Convolution layer -> Fully Connected layer without batches
262*c217d954SCole Faust // 2) Fully Connected layer -> Fully Connected layer without batches
263*c217d954SCole Faust // 3) Convolution layer -> Fully Connected layer with batches
264*c217d954SCole Faust // 4) Fully Connected layer -> Fully Connected layer with batches
265*c217d954SCole Faust
266*c217d954SCole Faust const ITensorInfo *weights_to_use = weights;
267*c217d954SCole Faust
268*c217d954SCole Faust // Check if we have a fully connected layer with batches
269*c217d954SCole Faust const bool is_batched_fc_layer = dst->dimension(1) > 1;
270*c217d954SCole Faust if(is_batched_fc_layer)
271*c217d954SCole Faust {
272*c217d954SCole Faust _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));
273*c217d954SCole Faust }
274*c217d954SCole Faust else
275*c217d954SCole Faust {
276*c217d954SCole Faust _is_fc_after_conv = src->num_dimensions() > 1;
277*c217d954SCole Faust }
278*c217d954SCole Faust
279*c217d954SCole Faust // Reshape weights if needed
280*c217d954SCole Faust if(_needs_weights_reshape)
281*c217d954SCole Faust {
282*c217d954SCole Faust // Reshape the weights
283*c217d954SCole Faust _transpose_weights = std::make_unique<kernels::CpuTransposeKernel>();
284*c217d954SCole Faust _transpose_weights->configure(weights, &_reshaped_weights);
285*c217d954SCole Faust weights_to_use = &_reshaped_weights;
286*c217d954SCole Faust _trans_weights_idx = AuxTensorIdx::TransposedWeights;
287*c217d954SCole Faust }
288*c217d954SCole Faust
289*c217d954SCole Faust // Convert weights if needed
290*c217d954SCole Faust if(_is_fc_after_conv && (src->data_layout() != fc_info.weights_trained_layout))
291*c217d954SCole Faust {
292*c217d954SCole Faust // Convert weights
293*c217d954SCole Faust _convert_weights = std::make_unique<CpuConvertFullyConnectedWeights>();
294*c217d954SCole Faust _convert_weights->configure(weights_to_use,
295*c217d954SCole Faust &_converted_weights,
296*c217d954SCole Faust src->tensor_shape(),
297*c217d954SCole Faust fc_info.weights_trained_layout);
298*c217d954SCole Faust
299*c217d954SCole Faust weights_to_use = &_converted_weights;
300*c217d954SCole Faust _needs_weights_conversion = true;
301*c217d954SCole Faust _trans_weights_idx = AuxTensorIdx::ConvertedWeights;
302*c217d954SCole Faust }
303*c217d954SCole Faust
304*c217d954SCole Faust if(_is_fc_after_conv)
305*c217d954SCole Faust {
306*c217d954SCole Faust // Fully Connected layer after a Convolution Layer without batches
307*c217d954SCole Faust configure_conv_fc(src, weights_to_use, biases, dst, fc_info.activation_info);
308*c217d954SCole Faust }
309*c217d954SCole Faust else
310*c217d954SCole Faust {
311*c217d954SCole Faust // Fully Connected layer after a Fully Connected Layer without batches
312*c217d954SCole Faust configure_fc_fc(src, weights_to_use, biases, dst, fc_info.activation_info);
313*c217d954SCole Faust }
314*c217d954SCole Faust
315*c217d954SCole Faust // Retain the tensorinfo with the weights to use
316*c217d954SCole Faust if(_needs_weights_reshape || _needs_weights_conversion)
317*c217d954SCole Faust {
318*c217d954SCole Faust _trans_weights = *weights_to_use;
319*c217d954SCole Faust }
320*c217d954SCole Faust
321*c217d954SCole Faust // Set auxiliary memory requirements
322*c217d954SCole Faust auto gemm_mem_req = (_is_quantized_asymmetric) ? _mm_gemmlowp->workspace() : _mm_gemm->workspace();
323*c217d954SCole Faust for(unsigned int i = 0; i < gemm_mem_req.size(); ++i)
324*c217d954SCole Faust {
325*c217d954SCole Faust _aux_mem[i] = gemm_mem_req[i];
326*c217d954SCole Faust }
327*c217d954SCole Faust
328*c217d954SCole Faust if(_aux_mem[Pretranspose].size > 0)
329*c217d954SCole Faust {
330*c217d954SCole Faust // Release permuted weights at the end of prepare as they are further transposed by the assembly dispatch
331*c217d954SCole Faust // Do not release them if biases are dynamic and data type is quantized, since the weights tensor will be used for biases offset calculation
332*c217d954SCole Faust _aux_mem[TransposedWeights] = MemoryInfo(offset_int_vec(TransposedWeights), (_is_quantized_asymmetric && biases
333*c217d954SCole Faust && !(biases->are_values_constant())) ? MemoryLifetime::Persistent : MemoryLifetime::Prepare,
334*c217d954SCole Faust _reshaped_weights.total_size());
335*c217d954SCole Faust _aux_mem[ConvertedWeights] = MemoryInfo(offset_int_vec(ConvertedWeights), MemoryLifetime::Prepare, _converted_weights.total_size());
336*c217d954SCole Faust }
337*c217d954SCole Faust else
338*c217d954SCole Faust {
339*c217d954SCole Faust _aux_mem[TransposedWeights] = MemoryInfo(offset_int_vec(TransposedWeights), _needs_weights_conversion ? MemoryLifetime::Prepare : MemoryLifetime::Persistent, _reshaped_weights.total_size());
340*c217d954SCole Faust _aux_mem[ConvertedWeights] = MemoryInfo(offset_int_vec(ConvertedWeights), MemoryLifetime::Persistent, _converted_weights.total_size());
341*c217d954SCole Faust }
342*c217d954SCole Faust _aux_mem[FlattenedSrc] = MemoryInfo(offset_int_vec(FlattenedSrc), MemoryLifetime::Temporary, _flattened_src.total_size());
343*c217d954SCole Faust }
344*c217d954SCole Faust
has_opt_impl(arm_compute::WeightFormat & expected_weight_format,const ITensorInfo * src,const ITensorInfo * weights,const ITensorInfo * biases,const ITensorInfo * dst,FullyConnectedLayerInfo fc_info,WeightsInfo weights_info)345*c217d954SCole Faust Status CpuFullyConnected::has_opt_impl(arm_compute::WeightFormat &expected_weight_format, const ITensorInfo *src, const ITensorInfo *weights,
346*c217d954SCole Faust const ITensorInfo *biases, const ITensorInfo *dst, FullyConnectedLayerInfo fc_info, WeightsInfo weights_info)
347*c217d954SCole Faust {
348*c217d954SCole Faust GEMMInfo gemm_info(false, false, true /* Reshape weights only for the first run */);
349*c217d954SCole Faust gemm_info.set_activation_info(fc_info.activation_info);
350*c217d954SCole Faust gemm_info.set_fast_math(fc_info.enable_fast_math);
351*c217d954SCole Faust gemm_info.set_fixed_format(weights_info.weight_format() != WeightFormat::UNSPECIFIED);
352*c217d954SCole Faust gemm_info.set_weight_format(weights_info.weight_format());
353*c217d954SCole Faust
354*c217d954SCole Faust return CpuGemm::has_opt_impl(expected_weight_format, src, weights, biases, dst, gemm_info);
355*c217d954SCole Faust }
356*c217d954SCole Faust
validate(const ITensorInfo * src,const ITensorInfo * weights,const ITensorInfo * biases,const ITensorInfo * dst,FullyConnectedLayerInfo fc_info,const WeightsInfo & weights_info)357*c217d954SCole Faust Status CpuFullyConnected::validate(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst,
358*c217d954SCole Faust FullyConnectedLayerInfo fc_info, const WeightsInfo &weights_info)
359*c217d954SCole Faust {
360*c217d954SCole Faust ARM_COMPUTE_UNUSED(fc_info.retain_internal_weights);
361*c217d954SCole Faust ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(src, weights, dst);
362*c217d954SCole Faust ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(src, 1, DataType::QASYMM8, DataType::QASYMM8_SIGNED, DataType::F16, DataType::F32);
363*c217d954SCole Faust
364*c217d954SCole Faust if (is_fixed_format_fast_math(weights_info.weight_format()))
365*c217d954SCole Faust {
366*c217d954SCole Faust ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_NOT_IN(src, DataType::F32);
367*c217d954SCole Faust ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_NOT_IN(weights, DataType::BFLOAT16);
368*c217d954SCole Faust ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_NOT_IN(dst, DataType::F32);
369*c217d954SCole Faust }
370*c217d954SCole Faust else
371*c217d954SCole Faust {
372*c217d954SCole Faust ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src, weights, dst);
373*c217d954SCole Faust }
374*c217d954SCole Faust
375*c217d954SCole Faust ARM_COMPUTE_RETURN_ERROR_ON(weights->num_dimensions() > 2);
376*c217d954SCole Faust 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
377*c217d954SCole Faust && fc_info.activation_info.activation() != ActivationLayerInfo::ActivationFunction::BOUNDED_RELU && fc_info.activation_info.activation() != ActivationLayerInfo::ActivationFunction::LU_BOUNDED_RELU);
378*c217d954SCole Faust ARM_COMPUTE_RETURN_ERROR_ON(!weights->are_values_constant() && (!fc_info.are_weights_reshaped || fc_info.transpose_weights));
379*c217d954SCole Faust
380*c217d954SCole Faust bool weights_reshaped = fc_info.transpose_weights ? fc_info.are_weights_reshaped : true;
381*c217d954SCole Faust bool is_fc_after_conv = true;
382*c217d954SCole Faust
383*c217d954SCole Faust const ITensorInfo &flatten_src = TensorInfo(src->clone()->set_is_resizable(true).reset_padding().set_tensor_shape(compute_flatten_shape(src)));
384*c217d954SCole Faust const ITensorInfo &reshaped_weights = TensorInfo(weights->clone()->set_is_resizable(true).reset_padding().set_tensor_shape(compute_transposed_shape(*weights)));
385*c217d954SCole Faust const ITensorInfo &converted_weights = weights_reshaped ? TensorInfo(weights->clone()->set_is_resizable(true).reset_padding()) : TensorInfo(*reshaped_weights.clone());
386*c217d954SCole Faust
387*c217d954SCole Faust // With the Fully Connected layer we can have 4 different cases:
388*c217d954SCole Faust // 1) Convolution layer -> Fully Connected layer without batches
389*c217d954SCole Faust // 2) Fully Connected layer -> Fully Connected layer without batches
390*c217d954SCole Faust // 3) Convolution layer -> Fully Connected layer with batches
391*c217d954SCole Faust // 4) Fully Connected layer -> Fully Connected layer with batches
392*c217d954SCole Faust
393*c217d954SCole Faust const ITensorInfo *src_to_use = src;
394*c217d954SCole Faust const ITensorInfo *weights_to_use = weights;
395*c217d954SCole Faust
396*c217d954SCole Faust // Check if we have a fully connected layer with batches
397*c217d954SCole Faust const bool is_batched_fc_layer = dst->dimension(1) > 1;
398*c217d954SCole Faust
399*c217d954SCole Faust if(biases != nullptr)
400*c217d954SCole Faust {
401*c217d954SCole Faust ARM_COMPUTE_RETURN_ERROR_ON(biases->num_dimensions() > 1);
402*c217d954SCole Faust if(is_data_type_quantized(src->data_type()))
403*c217d954SCole Faust {
404*c217d954SCole Faust ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(biases, 1, DataType::S32);
405*c217d954SCole Faust }
406*c217d954SCole Faust else
407*c217d954SCole Faust {
408*c217d954SCole Faust ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src, biases);
409*c217d954SCole Faust }
410*c217d954SCole Faust }
411*c217d954SCole Faust
412*c217d954SCole Faust if(is_batched_fc_layer)
413*c217d954SCole Faust {
414*c217d954SCole Faust 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));
415*c217d954SCole Faust }
416*c217d954SCole Faust else
417*c217d954SCole Faust {
418*c217d954SCole Faust is_fc_after_conv = src->num_dimensions() > 1;
419*c217d954SCole Faust }
420*c217d954SCole Faust
421*c217d954SCole Faust if(!weights_reshaped)
422*c217d954SCole Faust {
423*c217d954SCole Faust // Validate reshape weights kernel
424*c217d954SCole Faust ARM_COMPUTE_RETURN_ON_ERROR(kernels::CpuTransposeKernel::validate(weights, &reshaped_weights));
425*c217d954SCole Faust weights_to_use = &reshaped_weights;
426*c217d954SCole Faust }
427*c217d954SCole Faust
428*c217d954SCole Faust if(is_fc_after_conv && (src->data_layout() != fc_info.weights_trained_layout))
429*c217d954SCole Faust {
430*c217d954SCole Faust // Validate convert weights kernel
431*c217d954SCole Faust ARM_COMPUTE_RETURN_ON_ERROR(CpuConvertFullyConnectedWeights::validate(weights_to_use,
432*c217d954SCole Faust &converted_weights,
433*c217d954SCole Faust src->tensor_shape(),
434*c217d954SCole Faust fc_info.weights_trained_layout));
435*c217d954SCole Faust weights_to_use = &converted_weights;
436*c217d954SCole Faust }
437*c217d954SCole Faust
438*c217d954SCole Faust if(is_fc_after_conv)
439*c217d954SCole Faust {
440*c217d954SCole Faust // Fully Connected layer after a Convolution Layer without batches
441*c217d954SCole Faust ARM_COMPUTE_RETURN_ERROR_ON((weights_to_use->dimension(1) != (src->dimension(0) * src->dimension(1) * src->dimension(2))));
442*c217d954SCole Faust
443*c217d954SCole Faust // Validate flatten kernel
444*c217d954SCole Faust ARM_COMPUTE_RETURN_ON_ERROR(CpuFlatten::validate(src, &flatten_src));
445*c217d954SCole Faust src_to_use = &flatten_src;
446*c217d954SCole Faust }
447*c217d954SCole Faust else
448*c217d954SCole Faust {
449*c217d954SCole Faust // Fully Connected layer after a Fully Connected Layer without batches
450*c217d954SCole Faust ARM_COMPUTE_RETURN_ERROR_ON(src->dimension(0) != weights_to_use->dimension(1));
451*c217d954SCole Faust }
452*c217d954SCole Faust // Validate matrix multiply kernel
453*c217d954SCole Faust 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()));
454*c217d954SCole Faust
455*c217d954SCole Faust return Status{};
456*c217d954SCole Faust }
457*c217d954SCole Faust
run(ITensorPack & tensors)458*c217d954SCole Faust void CpuFullyConnected::run(ITensorPack &tensors)
459*c217d954SCole Faust {
460*c217d954SCole Faust prepare(tensors);
461*c217d954SCole Faust
462*c217d954SCole Faust auto src = tensors.get_const_tensor(ACL_SRC_0);
463*c217d954SCole Faust
464*c217d954SCole Faust CpuAuxTensorHandler flattened_src(offset_int_vec(FlattenedSrc), _flattened_src, tensors, false);
465*c217d954SCole Faust CpuAuxTensorHandler transformed_wei(offset_int_vec(_trans_weights_idx), _trans_weights, tensors, false);
466*c217d954SCole Faust
467*c217d954SCole Faust // Linearize src if it comes from a convolutional layer
468*c217d954SCole Faust if(_is_fc_after_conv)
469*c217d954SCole Faust {
470*c217d954SCole Faust ITensorPack flatten_pack{ { ACL_SRC, src }, { ACL_DST, flattened_src.get() } };
471*c217d954SCole Faust _flatten->run(flatten_pack);
472*c217d954SCole Faust }
473*c217d954SCole Faust
474*c217d954SCole Faust ITensorPack gemm_pack = tensors;
475*c217d954SCole Faust gemm_pack.add_const_tensor(ACL_SRC_0, (_is_fc_after_conv) ? flattened_src.get() : src);
476*c217d954SCole Faust if(_needs_weights_reshape || _needs_weights_conversion)
477*c217d954SCole Faust {
478*c217d954SCole Faust gemm_pack.add_const_tensor(ACL_SRC_1, transformed_wei.get());
479*c217d954SCole Faust }
480*c217d954SCole Faust
481*c217d954SCole Faust // Run matrix multiply
482*c217d954SCole Faust if(_is_quantized_asymmetric)
483*c217d954SCole Faust {
484*c217d954SCole Faust _mm_gemmlowp->run(gemm_pack);
485*c217d954SCole Faust }
486*c217d954SCole Faust else
487*c217d954SCole Faust {
488*c217d954SCole Faust _mm_gemm->run(gemm_pack);
489*c217d954SCole Faust }
490*c217d954SCole Faust }
491*c217d954SCole Faust
prepare(ITensorPack & tensors)492*c217d954SCole Faust void CpuFullyConnected::prepare(ITensorPack &tensors)
493*c217d954SCole Faust {
494*c217d954SCole Faust if(!_is_prepared)
495*c217d954SCole Faust {
496*c217d954SCole Faust auto weights = tensors.get_const_tensor(ACL_SRC_1);
497*c217d954SCole Faust
498*c217d954SCole Faust CpuAuxTensorHandler reshaped_weights(offset_int_vec(TransposedWeights), _reshaped_weights, tensors, false);
499*c217d954SCole Faust CpuAuxTensorHandler converted_weights(offset_int_vec(ConvertedWeights), _converted_weights, tensors, false);
500*c217d954SCole Faust
501*c217d954SCole Faust // Pointer to current weights
502*c217d954SCole Faust const ITensor *cur_weights = weights;
503*c217d954SCole Faust
504*c217d954SCole Faust // Reshape of the weights (happens only once)
505*c217d954SCole Faust if(_needs_weights_reshape)
506*c217d954SCole Faust {
507*c217d954SCole Faust // Run reshape weights kernel and mark weights as unused
508*c217d954SCole Faust ITensorPack transpose_pack{ { ACL_SRC, weights }, { ACL_DST, reshaped_weights.get() } };
509*c217d954SCole Faust NEScheduler::get().schedule_op(_transpose_weights.get(), Window::DimY, _transpose_weights->window(), transpose_pack);
510*c217d954SCole Faust
511*c217d954SCole Faust cur_weights->mark_as_unused();
512*c217d954SCole Faust cur_weights = reshaped_weights.get();
513*c217d954SCole Faust }
514*c217d954SCole Faust
515*c217d954SCole Faust // Convert weights if needed (happens only once)
516*c217d954SCole Faust if(_needs_weights_conversion)
517*c217d954SCole Faust {
518*c217d954SCole Faust ITensorPack convert_pack{ { ACL_SRC, cur_weights }, { ACL_DST, converted_weights.get() } };
519*c217d954SCole Faust _convert_weights->run(convert_pack);
520*c217d954SCole Faust
521*c217d954SCole Faust cur_weights->mark_as_unused();
522*c217d954SCole Faust cur_weights = converted_weights.get();
523*c217d954SCole Faust }
524*c217d954SCole Faust
525*c217d954SCole Faust ITensorPack gemm_pack = tensors;
526*c217d954SCole Faust gemm_pack.add_const_tensor(ACL_SRC_1, cur_weights);
527*c217d954SCole Faust
528*c217d954SCole Faust // Prepare GEMM prepare and release unused weights
529*c217d954SCole Faust if(!_is_quantized_asymmetric)
530*c217d954SCole Faust {
531*c217d954SCole Faust _mm_gemm->prepare(gemm_pack);
532*c217d954SCole Faust }
533*c217d954SCole Faust else
534*c217d954SCole Faust {
535*c217d954SCole Faust _mm_gemmlowp->prepare(gemm_pack);
536*c217d954SCole Faust }
537*c217d954SCole Faust
538*c217d954SCole Faust _is_prepared = true;
539*c217d954SCole Faust }
540*c217d954SCole Faust }
541*c217d954SCole Faust
workspace() const542*c217d954SCole Faust experimental::MemoryRequirements CpuFullyConnected::workspace() const
543*c217d954SCole Faust {
544*c217d954SCole Faust return _aux_mem;
545*c217d954SCole Faust }
546*c217d954SCole Faust } // namespace cpu
547*c217d954SCole Faust } // namespace arm_compute
548