blob: f71bf41d9cb7386a9198a7913af41e3ca46ca855 [file] [log] [blame]
Georgios Pinitas529b5a22021-07-27 15:55:30 +01001/*
Jakub Sujak617ed502023-03-29 11:16:18 +01002 * Copyright (c) 2017-2021, 2023 Arm Limited.
Georgios Pinitas529b5a22021-07-27 15:55:30 +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/gpu/cl/operators/ClFullyConnected.h"
Georgios Pinitas529b5a22021-07-27 15:55:30 +010025
26#include "arm_compute/core/Size2D.h"
27#include "arm_compute/core/Validate.h"
28#include "arm_compute/core/utils/misc/ShapeCalculator.h"
29#include "arm_compute/core/utils/quantization/AsymmHelpers.h"
30#include "arm_compute/runtime/CL/CLScheduler.h"
31#include "src/core/CL/kernels/CLFillBorderKernel.h"
32
33#include "src/core/helpers/MemoryHelpers.h"
Georgios Pinitas7891a732021-08-20 21:39:25 +010034#include "src/gpu/cl/operators/ClConvertFullyConnectedWeights.h"
35#include "src/gpu/cl/operators/ClFlatten.h"
36#include "src/gpu/cl/operators/ClGemm.h"
37#include "src/gpu/cl/operators/ClGemmLowpMatrixMultiplyCore.h"
Mohammed Suhail Munshi2e0714d2023-07-19 14:44:38 +010038#include "src/gpu/cl/operators/ClMatMul.h"
Georgios Pinitas7891a732021-08-20 21:39:25 +010039#include "src/gpu/cl/operators/ClTranspose.h"
40#include "src/gpu/cl/utils/ClAuxTensorHandler.h"
Georgios Pinitas529b5a22021-07-27 15:55:30 +010041
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +010042#include "src/runtime/heuristics/matmul_native/ClMatMulNativeKernelConfig.h"
43#include "src/runtime/heuristics/matmul_native/IClMatMulNativeKernelConfig.h"
44
ramelg012e53f172021-09-22 10:48:25 +010045#include "src/common/utils/Log.h"
Georgios Pinitas529b5a22021-07-27 15:55:30 +010046#include "support/Cast.h"
47
48#include <algorithm>
49
50namespace arm_compute
51{
52namespace opencl
53{
54using namespace arm_compute::experimental;
55using namespace arm_compute::misc::shape_calculator;
56
57namespace
58{
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +010059// Function to calculate batched tensor shape in format [M, 1, B0, B1 ..] which is the format matmul expects
60inline TensorShape get_reshaped_matmul_tensor(const TensorShape &src)
61{
62 return TensorShape(src.x(), 1, src.y(), src.collapsed_from(2).z()); // Return value optimisation
63}
64
Georgios Pinitas529b5a22021-07-27 15:55:30 +010065Status construct_gemmlowp_output_stage(const ITensorInfo &src, const ITensorInfo &weights, const ITensorInfo &dst,
66 GEMMLowpOutputStageInfo &gemmlowp_output_stage, ActivationLayerInfo activation_info)
67{
68 gemmlowp_output_stage.type = GEMMLowpOutputStageType::QUANTIZE_DOWN_FIXEDPOINT;
69 gemmlowp_output_stage.gemmlowp_offset = 0;
70 gemmlowp_output_stage.gemmlowp_multiplier = 0;
71 gemmlowp_output_stage.gemmlowp_shift = 0;
72
73 const auto data_type = src.data_type();
74
75 // Configure output stage for quantized case
76 if(is_data_type_quantized_asymmetric(data_type))
77 {
78 const QuantizationInfo oq_info = dst.quantization_info();
79 const UniformQuantizationInfo iq_unif = src.quantization_info().uniform();
80 const UniformQuantizationInfo wq_unif = weights.quantization_info().uniform();
81 const UniformQuantizationInfo oq_unif = oq_info.uniform();
82
83 const auto output_quant_info = (dst.total_size() == 0) ? iq_unif : oq_unif;
84
85 const float multiplier = (iq_unif.scale * wq_unif.scale) / output_quant_info.scale;
86 int output_multiplier = 0;
87 int output_shift = 0;
88 ARM_COMPUTE_RETURN_ON_ERROR(quantization::calculate_quantized_multiplier(multiplier, &output_multiplier, &output_shift));
89
90 PixelValue type_min{};
91 PixelValue type_max{};
92 std::tie(type_min, type_max) = get_min_max(data_type);
93
94 if(activation_info.enabled())
95 {
96 std::tie(type_min, type_max) = get_quantized_activation_min_max(activation_info, data_type, output_quant_info);
97 }
98
99 // Set the GEMMLowp output stage info
100 gemmlowp_output_stage.gemmlowp_offset = output_quant_info.offset;
101 gemmlowp_output_stage.gemmlowp_multiplier = output_multiplier;
102 gemmlowp_output_stage.gemmlowp_shift = output_shift;
103 gemmlowp_output_stage.gemmlowp_multipliers.push_back(output_multiplier);
104 gemmlowp_output_stage.gemmlowp_shifts.push_back(output_shift);
105 type_min.get(gemmlowp_output_stage.gemmlowp_min_bound);
106 type_max.get(gemmlowp_output_stage.gemmlowp_max_bound);
107 }
108
109 return Status{};
110}
111
Mohammed Suhail Munshi2e0714d2023-07-19 14:44:38 +0100112Status validate_mm(const ITensorInfo &src, const ITensorInfo &weights, const ITensorInfo *bias, const ITensorInfo &dst, const FullyConnectedLayerInfo &fc_info, bool use_matmul)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100113{
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100114 // Note : If input is dynamic and data is not batched, use matmul, else use gemm
115 const bool transpose_weights = fc_info.transpose_weights ? !fc_info.are_weights_reshaped : false;
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100116 const bool use_dynamic_gemm = !use_matmul && !weights.are_values_constant() && transpose_weights; // use dynamic gemm as fallback for matmul
117 const bool is_quantized = is_data_type_quantized_asymmetric(src.data_type());
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100118
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100119 if(use_matmul)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100120 {
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100121 const MatMulInfo m_info = MatMulInfo().adj_rhs(transpose_weights);
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100122
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100123 // Note: LHS is reshaped here to match ClMatMul expectations of batch index - From [M, B0, B1] to [M, 1, B0, B1]
124 TensorInfo lhs_to_use = src.clone()->set_tensor_shape(get_reshaped_matmul_tensor(src.tensor_shape()));
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100125
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100126 const GPUTarget gpu_target = CLScheduler::get().target();
127 std::unique_ptr<cl_matmul::IClMatMulNativeKernelConfig> t = cl_matmul::ClMatMulNativeKernelConfigurationFactory::create(gpu_target);
128 const MatMulKernelInfo kernel_info = t->configure(&lhs_to_use, &weights, m_info);
129
130 return is_quantized ? kernels::ClMatMulLowpNativeKernel::validate(&lhs_to_use, &weights, bias, &dst, kernel_info, fc_info.activation_info) :
131 kernels::ClMatMulNativeKernel::validate(&lhs_to_use, &weights, bias, &dst, kernel_info, fc_info.activation_info);
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100132 }
133 else
134 {
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100135 GEMMLowpOutputStageInfo gemmlowp_output_stage;
136 ARM_COMPUTE_RETURN_ON_ERROR(construct_gemmlowp_output_stage(src, weights, dst, gemmlowp_output_stage, fc_info.activation_info));
137
138 const GEMMInfo &gemm_info = GEMMInfo(false, // is_a_reshaped
139 false, // is_b_reshaped
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100140 !use_dynamic_gemm, // reshape_b_only_on_first_run
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100141 0, // depth_output_gemm3d
142 false, // reinterpret_input_as_3d
143 fc_info.retain_internal_weights, // retain_internal_weights
144 gemmlowp_output_stage, // gemmlowp_output_stage
145 fc_info.fp_mixed_precision, // fp_mixed_precision
146 false, // fast_math
147 true, // broadcast_bias
148 ActivationLayerInfo()); // activation_info
149
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100150 if(is_quantized)
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100151 {
152 const UniformQuantizationInfo iq_info = src.quantization_info().uniform();
153 const UniformQuantizationInfo wq_info = weights.quantization_info().uniform();
154
155 // Since we need negative offsets for computing convolution, we need to change QuantizationInfo()
156 // Extract and negate src and weights offset
157 const QuantizationInfo src_quantization_info(iq_info.scale, -iq_info.offset);
158 const QuantizationInfo weights_quantization_info(wq_info.scale, -wq_info.offset);
159
160 // Validate gemmlowp function
161 ARM_COMPUTE_RETURN_ON_ERROR(ClGemmLowpMatrixMultiplyCore::validate(&src.clone()->set_quantization_info(src_quantization_info),
162 &weights.clone()->set_quantization_info(weights_quantization_info),
163 bias,
164 &dst,
165 gemm_info));
166 }
167 else
168 {
169 ARM_COMPUTE_RETURN_ON_ERROR(ClGemm::validate(&src, &weights, bias, &dst, 1.f, 1.f, gemm_info));
170 }
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100171 }
172
173 return Status{};
174}
175} // namespace
176
177ClFullyConnected::ClFullyConnected()
178 : _convert_weights(nullptr),
179 _flatten(nullptr),
180 _reshape_weights(nullptr),
181 _mm_gemm(nullptr),
182 _mm_gemmlowp(nullptr),
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100183 _matmul_native_kernel(nullptr),
184 _matmul_lowp_native_kernel(nullptr),
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100185 _aux_mem(Count)
186{
187}
188
189ClFullyConnected::~ClFullyConnected() = default;
190
191void ClFullyConnected::configure_mm(const CLCompileContext &compile_context, ITensorInfo *src, ITensorInfo *weights, ITensorInfo *bias, ITensorInfo *dst,
192 const FullyConnectedLayerInfo &fc_info)
193{
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100194 // If weights are dynamic and matmul is supported use matmul, else use gemm
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100195 if(_use_matmul)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100196 {
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100197 // Specify whether transpose weights is necessary in matmul info
198 const MatMulInfo mat_info = MatMulInfo().adj_rhs(_transpose_weights);
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100199
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100200 // Note: MatMul does not need offset negation unlike gemm
201 // 1. Change shape when calling matmul to fit batch expectations.
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100202 _lhs_to_use = src->clone()->set_tensor_shape(get_reshaped_matmul_tensor(_lhs_to_use.tensor_shape()));
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100203
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100204 // 2. Use heuristics to get kernel info object
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100205 const GPUTarget gpu_target = CLScheduler::get().target();
206 std::unique_ptr<cl_matmul::IClMatMulNativeKernelConfig> kernel_config = cl_matmul::ClMatMulNativeKernelConfigurationFactory::create(gpu_target);
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100207 MatMulKernelInfo kernel_info = kernel_config->configure(src, weights, mat_info);
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100208
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100209 // 3. Configure relevant matmul kernel
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100210 if(_is_quantized)
211 {
212 _matmul_lowp_native_kernel = std::make_unique<kernels::ClMatMulLowpNativeKernel>();
213 _matmul_lowp_native_kernel->set_target(gpu_target);
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100214 _matmul_lowp_native_kernel->configure(compile_context, src, weights, bias, dst, kernel_info, fc_info.activation_info);
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100215 }
216 else
217 {
218 _matmul_native_kernel = std::make_unique<kernels::ClMatMulNativeKernel>();
219 _matmul_native_kernel->set_target(gpu_target);
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100220 _matmul_native_kernel->configure(compile_context, src, weights, bias, dst, kernel_info, fc_info.activation_info);
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100221 }
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100222 }
223 else
224 {
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100225 // Configure GEMM
226 GEMMLowpOutputStageInfo gemmlowp_output_stage;
227 construct_gemmlowp_output_stage(*src, *weights, *dst, gemmlowp_output_stage, fc_info.activation_info);
228
229 const GEMMInfo &gemm_info = GEMMInfo(false, // is_a_reshaped
230 false, // is_b_reshaped
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100231 !_dynamic_gemm, // reshape_b_only_on_first_run
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100232 0, // depth_output_gemm3d
233 false, // reinterpret_input_as_3d
234 fc_info.retain_internal_weights, // retain_internal_weights
235 gemmlowp_output_stage, // gemmlowp_output_stage
236 fc_info.fp_mixed_precision, // fp_mixed_precision
237 false, // fast_math
238 true, // broadcast_bias
239 fc_info.activation_info); // activation_info
240
241 if(_is_quantized)
242 {
243 // Since we need negative offsets for computing convolution, we need to change QuantizationInfo()
244 // Extract and negate input and weights offset
245 const QuantizationInfo src_quantization_info = src->quantization_info();
246 const QuantizationInfo weights_quantization_info = weights->quantization_info();
247
248 TensorInfo src_info = src->clone()->set_quantization_info(src_quantization_info);
249 TensorInfo weights_info = weights->clone()->set_quantization_info(weights_quantization_info);
250
251 src_info.set_quantization_info(QuantizationInfo(src_quantization_info.uniform().scale, -src_quantization_info.uniform().offset));
252 weights_info.set_quantization_info(QuantizationInfo(weights_quantization_info.uniform().scale, -weights_quantization_info.uniform().offset));
253
254 // Configure gemmlowp function
255 _mm_gemmlowp = std::make_unique<ClGemmLowpMatrixMultiplyCore>();
256 _mm_gemmlowp->configure(compile_context, &src_info, &weights_info, bias, dst, gemm_info);
257 }
258 else
259 {
260 // Configure matrix multiply kernel
261 _mm_gemm = std::make_unique<ClGemm>();
262 _mm_gemm->configure(compile_context, src, weights, bias, dst, 1.f, 1.f, gemm_info);
263 }
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100264 }
265}
266
267void ClFullyConnected::configure_conv_fc(const CLCompileContext &compile_context, ITensorInfo *src, ITensorInfo *weights, ITensorInfo *bias, ITensorInfo *dst,
268 const FullyConnectedLayerInfo &fc_info)
269{
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100270 // MatMul fuses transpose operation, so we use the first dimension for comparison where appropriate.
271 ARM_COMPUTE_ERROR_ON((weights->dimension((_use_matmul && _transpose_weights) ? 0 : 1) != (src->dimension(0) * src->dimension(1) * src->dimension(2))));
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100272
273 // If the fully connected layer is called after a convolution layer, the input tensor must be linearized
274
275 // Initialize output tensor for flatten
276 _flattened_src = src->clone()->set_is_resizable(true).reset_padding().set_tensor_shape(compute_flatten_shape(src)).set_data_layout(DataLayout::NCHW);
277
278 // Configure flatten kernel
279 _flatten = std::make_unique<ClFlatten>();
280 _flatten->configure(compile_context, src, &_flattened_src);
281
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100282 // Note: if flatten has > 1 dimensions after, these dimensions are batch
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100283 // Configure matrix multiply kernel
284 configure_mm(compile_context, &_flattened_src, weights, bias, dst, fc_info);
285}
286
287void ClFullyConnected::configure_fc_fc(const CLCompileContext &compile_context, ITensorInfo *src, ITensorInfo *weights, ITensorInfo *bias, ITensorInfo *dst,
288 const FullyConnectedLayerInfo &fc_info)
289{
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100290 // MatMul fuses transpose operation, so we use the first dimension for comparison where appropriate.
291 ARM_COMPUTE_ERROR_ON(src->dimension(0) != weights->dimension((_use_matmul && _transpose_weights) ? 0 : 1));
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100292
293 // Configure matrix multiply kernel
294 configure_mm(compile_context, src, weights, bias, dst, fc_info);
295}
296
297void ClFullyConnected::configure(const CLCompileContext &compile_context, ITensorInfo *src, ITensorInfo *weights, ITensorInfo *biases, ITensorInfo *dst,
298 FullyConnectedLayerInfo fc_info)
299{
300 ARM_COMPUTE_ERROR_ON_NULLPTR(src, weights, dst);
301
302 // Perform validate step
303 ARM_COMPUTE_ERROR_THROW_ON(ClFullyConnected::validate(src, weights, biases, dst, fc_info));
ramelg012e53f172021-09-22 10:48:25 +0100304 ARM_COMPUTE_LOG_PARAMS(src, weights, biases, dst, fc_info);
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100305
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100306 _transpose_weights = fc_info.transpose_weights ? !fc_info.are_weights_reshaped : false;
307 _is_fc_after_conv = true;
308 _is_quantized = is_data_type_quantized_asymmetric(src->data_type());
309 _is_prepared = fc_info.retain_internal_weights;
310 _weights_to_use = TensorInfo(*weights);
311 _weights_to_use_idx = ACL_SRC_1;
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100312
313 // When using dynamic weights - use matmul kernels.
Mohammed Suhail Munshi2e0714d2023-07-19 14:44:38 +0100314 // Note: MatMul is not used in the following cases (Gemm is used as fallback) :
315 // 1. When the weights tensor is not dynamic
316 // 2. MatMul does not support broadcasting batch dimension, and therefore is disabled if fc is batched.
317 // 3. When FC is after convolution and src tensor data layout does not match weights trained data layout (weights conversion kernel is required)
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100318 const bool is_batched_fc_layer = dst->dimension(1) > 1;
Mohammed Suhail Munshi2e0714d2023-07-19 14:44:38 +0100319 _use_matmul = !weights->are_values_constant() && !is_batched_fc_layer && !(src->num_dimensions() > 1 && (src->data_layout() != fc_info.weights_trained_layout));
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100320 _dynamic_gemm = !weights->are_values_constant() && _transpose_weights && !_use_matmul;
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100321
322 // With the Fully Connected layer we can have 4 different cases:
323 // 1) Convolution layer -> Fully Connected layer without batches
324 // 2) Fully Connected layer -> Fully Connected layer without batches
325 // 3) Convolution layer -> Fully Connected layer with batches
326 // 4) Fully Connected layer -> Fully Connected layer with batches
327
328 // Check if we have a fully connected layer with batches
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100329 if(is_batched_fc_layer)
330 {
331 _is_fc_after_conv = (TensorShape::num_max_dimensions >= 4) && (std::equal(src->tensor_shape().cbegin() + 3,
332 src->tensor_shape().cend(),
333 dst->tensor_shape().cbegin() + 1));
334 }
335 else
336 {
337 _is_fc_after_conv = src->num_dimensions() > 1;
338 }
339
340 ITensorInfo *weights_used = weights;
341
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100342 // Reshape weights if needed - Not needed when matmul is in use as matmul fuses transpose op.
343 if(_transpose_weights && !_use_matmul)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100344 {
345 // Reshape the weights
346 _reshape_weights = std::make_unique<ClTranspose>();
347 _reshape_weights->configure(compile_context, weights, &_reshaped_weights);
348 weights_used = &_reshaped_weights;
349 _weights_to_use_idx = offset_int_vec(TransposedWeights);
350 }
351
352 // Convert weights if needed
353 if(_is_fc_after_conv && (src->data_layout() != fc_info.weights_trained_layout))
354 {
355 // Convert weights
356 _convert_weights = std::make_unique<ClConvertFullyConnectedWeights>();
357 _convert_weights->configure(compile_context,
358 weights_used,
359 &_converted_weights,
360 src->tensor_shape(),
361 fc_info.weights_trained_layout);
362
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100363 weights_used = &_converted_weights;
364 _weights_to_use_idx = offset_int_vec(ConvertedWeights);
365 _run_convert_weights = true;
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100366 }
367
368 if(_is_fc_after_conv)
369 {
370 // Fully Connected layer after a Convolution Layer without batches
371 configure_conv_fc(compile_context, src, weights_used, biases, dst, fc_info);
372 }
373 else
374 {
375 // Fully Connected layer after a Fully Connected Layer without batches
376 configure_fc_fc(compile_context, src, weights_used, biases, dst, fc_info);
377 }
378 // Update TensorInfo of final weights used (Need to be done in the end due to padding expansion)
379 _weights_to_use = *weights_used;
380
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100381 if(_use_matmul)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100382 {
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100383 // Note : MatMul does not use transpose and does not need auxillary memory, so only converted weights are added to aux_mem
384 _aux_mem[ConvertedWeights] = MemoryInfo(offset_int_vec(ConvertedWeights), MemoryLifetime::Temporary, _converted_weights.total_size());
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100385 }
386 else
387 {
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100388 // Set auxiliary memory requirements for gemm operators
389 auto gemm_mem_req = (_is_quantized) ? _mm_gemmlowp->workspace() : _mm_gemm->workspace();
390 for(unsigned int i = 0; i < gemm_mem_req.size(); ++i)
391 {
392 _aux_mem[i] = gemm_mem_req[i];
393 }
394 if(_aux_mem[1].size > 0 || _aux_mem[2].size > 0) // Persistent weights memory on GEMMs
395 {
396 // Release permuted weights at the of prepare as they are further transposed by the assembly dispatch
397 // Keep all the auxiliary tensors in case of dynamic weights as they are recalculated every time
398 _aux_mem[TransposedWeights] = MemoryInfo(
399 offset_int_vec(TransposedWeights),
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100400 _dynamic_gemm ? MemoryLifetime::Temporary : MemoryLifetime::Prepare,
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100401 _reshaped_weights.total_size());
402 _aux_mem[ConvertedWeights] = MemoryInfo(
403 offset_int_vec(ConvertedWeights),
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100404 _dynamic_gemm ? MemoryLifetime::Temporary : MemoryLifetime::Prepare,
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100405 _converted_weights.total_size());
406 }
407 else
408 {
409 // Release permuted weights at the of prepare as they are further transposed by the assembly dispatch
410 const auto transposed_wei_lft = (_weights_to_use_idx == offset_int_vec(TransposedWeights)) ? MemoryLifetime::Persistent : MemoryLifetime::Prepare;
411 const auto converted_wei_lft = (_weights_to_use_idx == offset_int_vec(ConvertedWeights)) ? MemoryLifetime::Persistent : MemoryLifetime::Prepare;
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100412
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100413 _aux_mem[TransposedWeights] = MemoryInfo(
414 offset_int_vec(TransposedWeights),
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100415 _dynamic_gemm ? MemoryLifetime::Temporary : transposed_wei_lft,
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100416 _reshaped_weights.total_size());
417 _aux_mem[ConvertedWeights] = MemoryInfo(
418 offset_int_vec(ConvertedWeights),
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100419 _dynamic_gemm ? MemoryLifetime::Temporary : converted_wei_lft,
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100420 _converted_weights.total_size());
421 }
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100422 }
423 _aux_mem[FlattenedSrc] = MemoryInfo(offset_int_vec(FlattenedSrc), MemoryLifetime::Temporary, _flattened_src.total_size());
424}
425
426Status ClFullyConnected::validate(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst,
427 FullyConnectedLayerInfo fc_info)
428{
429 ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(src, weights, dst);
430 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(src, 1, DataType::QASYMM8, DataType::QASYMM8_SIGNED, DataType::F16, DataType::F32);
431 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src, weights, dst);
432 ARM_COMPUTE_RETURN_ERROR_ON(weights->num_dimensions() > 2);
433 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
434 && fc_info.activation_info.activation() != ActivationLayerInfo::ActivationFunction::BOUNDED_RELU && fc_info.activation_info.activation() != ActivationLayerInfo::ActivationFunction::LU_BOUNDED_RELU);
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100435
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100436 const bool transpose_weights = fc_info.transpose_weights ? !fc_info.are_weights_reshaped : false;
437 bool is_fc_after_conv = true;
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100438
439 // When using dynamic weights - use matmul kernels.
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100440 // Note: MatMul does not support broadcasting so fallback with batched cases.
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100441 const bool is_batched_fc_layer = dst->dimension(1) > 1;
Mohammed Suhail Munshi2e0714d2023-07-19 14:44:38 +0100442 const bool use_matmul = !weights->are_values_constant() && !is_batched_fc_layer && !(src->num_dimensions() > 1 && (src->data_layout() != fc_info.weights_trained_layout));
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100443
444 const ITensorInfo &flatten_src = TensorInfo(src->clone()->set_is_resizable(true).reset_padding().set_tensor_shape(compute_flatten_shape(src)).set_data_layout(DataLayout::NCHW));
445 const ITensorInfo &reshaped_weights = TensorInfo(weights->clone()->set_is_resizable(true).reset_padding().set_tensor_shape(compute_transposed_shape(*weights)));
Mohammed Suhail Munshi2e0714d2023-07-19 14:44:38 +0100446 const ITensorInfo &converted_weights = (transpose_weights && !use_matmul) ? TensorInfo(*reshaped_weights.clone()) : TensorInfo(weights->clone()->set_is_resizable(true).reset_padding());
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100447
448 // With the Fully Connected layer we can have 4 different cases:
449 // 1) Convolution layer -> Fully Connected layer without batches
450 // 2) Fully Connected layer -> Fully Connected layer without batches
451 // 3) Convolution layer -> Fully Connected layer with batches
452 // 4) Fully Connected layer -> Fully Connected layer with batches
453
454 const ITensorInfo *src_to_use = src;
455 const ITensorInfo *weights_to_use = weights;
456
Giorgio Arena63e0beb2021-09-24 14:04:27 +0100457 if(biases != nullptr)
458 {
459 ARM_COMPUTE_RETURN_ERROR_ON(biases->num_dimensions() > 1);
460 if(is_data_type_quantized(src->data_type()))
461 {
462 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(biases, 1, DataType::S32);
463 }
464 else
465 {
466 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src, biases);
467 }
468 }
469
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100470 // Check if FC is after conv (flatten kernel is run in case where FC is after conv.)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100471 if(is_batched_fc_layer)
472 {
473 is_fc_after_conv = (TensorShape::num_max_dimensions >= 4) && (std::equal(src->tensor_shape().cbegin() + 3,
474 src->tensor_shape().cend(),
475 dst->tensor_shape().cbegin() + 1));
476 }
477 else
478 {
479 is_fc_after_conv = src->num_dimensions() > 1;
480 }
481
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100482 // Transpose kernel does not run when matmul is supported as matmul fuses transpose op.
483 if(transpose_weights && !use_matmul)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100484 {
485 // Validate reshape weights kernel
486 ARM_COMPUTE_RETURN_ON_ERROR(ClTranspose::validate(weights, &reshaped_weights));
487 weights_to_use = &reshaped_weights;
488 }
489
490 if(is_fc_after_conv && (src->data_layout() != fc_info.weights_trained_layout))
491 {
492 // Validate convert weights kernel
493 ARM_COMPUTE_RETURN_ON_ERROR(ClConvertFullyConnectedWeights::validate(weights_to_use,
494 &converted_weights,
495 src->tensor_shape(),
496 fc_info.weights_trained_layout));
497 weights_to_use = &converted_weights;
498 }
499
500 if(is_fc_after_conv)
501 {
502 // Fully Connected layer after a Convolution Layer without batches
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100503 // K Index of matrix multiplication. MatMul performs transpose in kernel, so index is 0 when matmul and transpose enabled
504 const int weight_idx = (use_matmul && transpose_weights) ? 0 : 1;
505 ARM_COMPUTE_RETURN_ERROR_ON((weights_to_use->dimension(weight_idx) != (src->dimension(0) * src->dimension(1) * src->dimension(2))));
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100506
507 // Validate flatten kernel
508 ARM_COMPUTE_RETURN_ON_ERROR(ClFlatten::validate(src, &flatten_src));
509 src_to_use = &flatten_src;
510 }
511 else
512 {
513 // Fully Connected layer after a Fully Connected Layer without batches
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100514 // K Index of matrix multiplication. MatMul performs transpose in kernel, so index is 0 when matmul and transpose enabled
515 const int weight_idx = (use_matmul && transpose_weights) ? 0 : 1;
516 ARM_COMPUTE_RETURN_ERROR_ON(src->dimension(0) != weights_to_use->dimension(weight_idx));
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100517 }
518
519 // Validate matrix multiply kernel
Mohammed Suhail Munshi2e0714d2023-07-19 14:44:38 +0100520 ARM_COMPUTE_RETURN_ON_ERROR(validate_mm(*src_to_use, *weights_to_use, biases, *dst, fc_info, use_matmul));
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100521
522 return Status{};
523}
524
525void ClFullyConnected::run(ITensorPack &tensors)
526{
527 prepare(tensors);
528
Jakub Sujak617ed502023-03-29 11:16:18 +0100529#ifdef ARM_COMPUTE_ASSERTS_ENABLED
530 ++_asrt_run_count;
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100531 ARM_COMPUTE_ERROR_ON(_dynamic_gemm && _asrt_prepare_count != _asrt_run_count);
Jakub Sujak617ed502023-03-29 11:16:18 +0100532#endif // ARM_COMPUTE_ASSERTS_ENABLED
533
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100534 auto src = tensors.get_const_tensor(ACL_SRC_0);
535
536 CLAuxTensorHandler flattened_src(offset_int_vec(FlattenedSrc), _flattened_src, tensors, false);
537 CLAuxTensorHandler weights(_weights_to_use_idx, _weights_to_use, tensors, false);
538
539 // Linearize input if it comes from a convolutional layer
540 if(_is_fc_after_conv)
541 {
542 ITensorPack flatten_pack{ { ACL_SRC, src }, { ACL_DST, flattened_src.get() } };
543 _flatten->run(flatten_pack);
544 }
545
546 ITensorPack gemm_pack = tensors;
547 gemm_pack.add_const_tensor(ACL_SRC_0, (_is_fc_after_conv) ? flattened_src.get() : src);
548 if(_weights_to_use_idx != ACL_SRC_1)
549 {
550 gemm_pack.add_const_tensor(ACL_SRC_1, weights.get());
551 }
552
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100553 // Run MatMul Op
554 if(_use_matmul)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100555 {
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100556 // Run matmul kernels for matrix multiplication
557 if(_is_quantized)
558 {
559 CLScheduler::get().enqueue_op(*_matmul_lowp_native_kernel, gemm_pack, true);
560 }
561 else
562 {
563 CLScheduler::get().enqueue_op(*_matmul_native_kernel, gemm_pack, true);
564 }
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100565 }
566 else
567 {
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100568 // Run matrix multiply
569 if(_is_quantized)
570 {
571 _mm_gemmlowp->run(gemm_pack);
572 }
573 else
574 {
575 _mm_gemm->run(gemm_pack);
576 }
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100577 }
578}
579
580void ClFullyConnected::prepare(ITensorPack &tensors)
581{
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100582 // Note : Running prepare() each run when _use_matmul is true is unnecessary unless weights conversion is needed.
Mohammed Suhail Munshi2e0714d2023-07-19 14:44:38 +0100583 if(!_is_prepared || _dynamic_gemm)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100584 {
Jakub Sujak617ed502023-03-29 11:16:18 +0100585#ifdef ARM_COMPUTE_ASSERTS_ENABLED
586 ++_asrt_prepare_count;
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100587 ARM_COMPUTE_ERROR_ON(!_dynamic_gemm && !_use_matmul && _asrt_prepare_count > 1);
Jakub Sujak617ed502023-03-29 11:16:18 +0100588#endif // ARM_COMPUTE_ASSERTS_ENABLED
589
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100590 auto weights = tensors.get_const_tensor(ACL_SRC_1);
591
592 CLAuxTensorHandler reshaped_weights(offset_int_vec(TransposedWeights), _reshaped_weights, tensors, false);
593 CLAuxTensorHandler converted_weights(offset_int_vec(ConvertedWeights), _converted_weights, tensors, false);
594
595 // Pointer to current weights
596 const ITensor *cur_weights = weights;
597
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100598 // Reshape weights if needed. Disabled when matmul kernels are enabled as matmul fuses transpose.
599 if(_transpose_weights && !_use_matmul)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100600 {
601 // Run reshape weights kernel and mark weights as unused
602 ITensorPack transpose_pack{ { ACL_SRC, weights }, { ACL_DST, reshaped_weights.get() } };
603 _reshape_weights->run(transpose_pack);
604
605 cur_weights->mark_as_unused();
606 cur_weights = reshaped_weights.get();
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100607 }
608
Jakub Sujak617ed502023-03-29 11:16:18 +0100609 // Convert weights if needed
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100610 if(_run_convert_weights)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100611 {
612 ITensorPack convert_pack{ { ACL_SRC, cur_weights }, { ACL_DST, converted_weights.get() } };
613 _convert_weights->run(convert_pack);
614
615 cur_weights->mark_as_unused();
616 cur_weights = converted_weights.get();
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100617 }
618
Jakub Sujak617ed502023-03-29 11:16:18 +0100619 ITensorPack gemm_pack = tensors;
620 gemm_pack.add_const_tensor(ACL_SRC_1, cur_weights);
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100621
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100622 // Prepare GEMM prepare and release unused weights
623 if(_dynamic_gemm || !_use_matmul)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100624 {
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100625 if(!_is_quantized)
626 {
627 _mm_gemm->prepare(gemm_pack);
628 }
629 else
630 {
631 _mm_gemmlowp->prepare(gemm_pack);
632 }
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100633 }
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100634
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100635 _is_prepared = true;
636 }
637}
638
639experimental::MemoryRequirements ClFullyConnected::workspace() const
640{
641 return _aux_mem;
642}
643} // namespace opencl
644} // namespace arm_compute