blob: 5845bbc69e9d41dbb280390f5a9da4270f2b3c7e [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);
ramy.elgammal@arm.comf77b9692023-08-07 17:07:02 +0100301 const GPUTarget gpu_target = get_arch_from_target(CLScheduler::get().target());
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100302
303 // Perform validate step
304 ARM_COMPUTE_ERROR_THROW_ON(ClFullyConnected::validate(src, weights, biases, dst, fc_info));
ramelg012e53f172021-09-22 10:48:25 +0100305 ARM_COMPUTE_LOG_PARAMS(src, weights, biases, dst, fc_info);
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100306
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100307 _transpose_weights = fc_info.transpose_weights ? !fc_info.are_weights_reshaped : false;
308 _is_fc_after_conv = true;
309 _is_quantized = is_data_type_quantized_asymmetric(src->data_type());
310 _is_prepared = fc_info.retain_internal_weights;
311 _weights_to_use = TensorInfo(*weights);
312 _weights_to_use_idx = ACL_SRC_1;
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100313
314 // When using dynamic weights - use matmul kernels.
Mohammed Suhail Munshi2e0714d2023-07-19 14:44:38 +0100315 // Note: MatMul is not used in the following cases (Gemm is used as fallback) :
316 // 1. When the weights tensor is not dynamic
317 // 2. MatMul does not support broadcasting batch dimension, and therefore is disabled if fc is batched.
318 // 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 +0100319 const bool is_batched_fc_layer = dst->dimension(1) > 1;
ramy.elgammal@arm.comf77b9692023-08-07 17:07:02 +0100320 _use_matmul = gpu_target != GPUTarget::MIDGARD && !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 +0100321 _dynamic_gemm = !weights->are_values_constant() && _transpose_weights && !_use_matmul;
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100322
323 // With the Fully Connected layer we can have 4 different cases:
324 // 1) Convolution layer -> Fully Connected layer without batches
325 // 2) Fully Connected layer -> Fully Connected layer without batches
326 // 3) Convolution layer -> Fully Connected layer with batches
327 // 4) Fully Connected layer -> Fully Connected layer with batches
328
329 // Check if we have a fully connected layer with batches
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100330 if(is_batched_fc_layer)
331 {
332 _is_fc_after_conv = (TensorShape::num_max_dimensions >= 4) && (std::equal(src->tensor_shape().cbegin() + 3,
333 src->tensor_shape().cend(),
334 dst->tensor_shape().cbegin() + 1));
335 }
336 else
337 {
338 _is_fc_after_conv = src->num_dimensions() > 1;
339 }
340
341 ITensorInfo *weights_used = weights;
342
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100343 // Reshape weights if needed - Not needed when matmul is in use as matmul fuses transpose op.
344 if(_transpose_weights && !_use_matmul)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100345 {
346 // Reshape the weights
347 _reshape_weights = std::make_unique<ClTranspose>();
348 _reshape_weights->configure(compile_context, weights, &_reshaped_weights);
349 weights_used = &_reshaped_weights;
350 _weights_to_use_idx = offset_int_vec(TransposedWeights);
351 }
352
353 // Convert weights if needed
354 if(_is_fc_after_conv && (src->data_layout() != fc_info.weights_trained_layout))
355 {
356 // Convert weights
357 _convert_weights = std::make_unique<ClConvertFullyConnectedWeights>();
358 _convert_weights->configure(compile_context,
359 weights_used,
360 &_converted_weights,
361 src->tensor_shape(),
362 fc_info.weights_trained_layout);
363
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100364 weights_used = &_converted_weights;
365 _weights_to_use_idx = offset_int_vec(ConvertedWeights);
366 _run_convert_weights = true;
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100367 }
368
369 if(_is_fc_after_conv)
370 {
371 // Fully Connected layer after a Convolution Layer without batches
372 configure_conv_fc(compile_context, src, weights_used, biases, dst, fc_info);
373 }
374 else
375 {
376 // Fully Connected layer after a Fully Connected Layer without batches
377 configure_fc_fc(compile_context, src, weights_used, biases, dst, fc_info);
378 }
379 // Update TensorInfo of final weights used (Need to be done in the end due to padding expansion)
380 _weights_to_use = *weights_used;
381
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100382 if(_use_matmul)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100383 {
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100384 // Note : MatMul does not use transpose and does not need auxillary memory, so only converted weights are added to aux_mem
385 _aux_mem[ConvertedWeights] = MemoryInfo(offset_int_vec(ConvertedWeights), MemoryLifetime::Temporary, _converted_weights.total_size());
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100386 }
387 else
388 {
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100389 // Set auxiliary memory requirements for gemm operators
390 auto gemm_mem_req = (_is_quantized) ? _mm_gemmlowp->workspace() : _mm_gemm->workspace();
391 for(unsigned int i = 0; i < gemm_mem_req.size(); ++i)
392 {
393 _aux_mem[i] = gemm_mem_req[i];
394 }
395 if(_aux_mem[1].size > 0 || _aux_mem[2].size > 0) // Persistent weights memory on GEMMs
396 {
397 // Release permuted weights at the of prepare as they are further transposed by the assembly dispatch
398 // Keep all the auxiliary tensors in case of dynamic weights as they are recalculated every time
399 _aux_mem[TransposedWeights] = MemoryInfo(
400 offset_int_vec(TransposedWeights),
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100401 _dynamic_gemm ? MemoryLifetime::Temporary : MemoryLifetime::Prepare,
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100402 _reshaped_weights.total_size());
403 _aux_mem[ConvertedWeights] = MemoryInfo(
404 offset_int_vec(ConvertedWeights),
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100405 _dynamic_gemm ? MemoryLifetime::Temporary : MemoryLifetime::Prepare,
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100406 _converted_weights.total_size());
407 }
408 else
409 {
410 // Release permuted weights at the of prepare as they are further transposed by the assembly dispatch
411 const auto transposed_wei_lft = (_weights_to_use_idx == offset_int_vec(TransposedWeights)) ? MemoryLifetime::Persistent : MemoryLifetime::Prepare;
412 const auto converted_wei_lft = (_weights_to_use_idx == offset_int_vec(ConvertedWeights)) ? MemoryLifetime::Persistent : MemoryLifetime::Prepare;
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100413
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100414 _aux_mem[TransposedWeights] = MemoryInfo(
415 offset_int_vec(TransposedWeights),
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100416 _dynamic_gemm ? MemoryLifetime::Temporary : transposed_wei_lft,
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100417 _reshaped_weights.total_size());
418 _aux_mem[ConvertedWeights] = MemoryInfo(
419 offset_int_vec(ConvertedWeights),
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100420 _dynamic_gemm ? MemoryLifetime::Temporary : converted_wei_lft,
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100421 _converted_weights.total_size());
422 }
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100423 }
424 _aux_mem[FlattenedSrc] = MemoryInfo(offset_int_vec(FlattenedSrc), MemoryLifetime::Temporary, _flattened_src.total_size());
425}
426
427Status ClFullyConnected::validate(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst,
428 FullyConnectedLayerInfo fc_info)
429{
430 ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(src, weights, dst);
431 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(src, 1, DataType::QASYMM8, DataType::QASYMM8_SIGNED, DataType::F16, DataType::F32);
432 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src, weights, dst);
433 ARM_COMPUTE_RETURN_ERROR_ON(weights->num_dimensions() > 2);
434 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
435 && fc_info.activation_info.activation() != ActivationLayerInfo::ActivationFunction::BOUNDED_RELU && fc_info.activation_info.activation() != ActivationLayerInfo::ActivationFunction::LU_BOUNDED_RELU);
ramy.elgammal@arm.comf77b9692023-08-07 17:07:02 +0100436 const GPUTarget gpu_target = get_arch_from_target(CLScheduler::get().target());
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100437
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100438 const bool transpose_weights = fc_info.transpose_weights ? !fc_info.are_weights_reshaped : false;
439 bool is_fc_after_conv = true;
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100440
441 // When using dynamic weights - use matmul kernels.
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100442 // Note: MatMul does not support broadcasting so fallback with batched cases.
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100443 const bool is_batched_fc_layer = dst->dimension(1) > 1;
ramy.elgammal@arm.comf77b9692023-08-07 17:07:02 +0100444 const bool use_matmul = gpu_target != GPUTarget::MIDGARD && !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 +0100445
446 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));
447 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 +0100448 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 +0100449
450 // With the Fully Connected layer we can have 4 different cases:
451 // 1) Convolution layer -> Fully Connected layer without batches
452 // 2) Fully Connected layer -> Fully Connected layer without batches
453 // 3) Convolution layer -> Fully Connected layer with batches
454 // 4) Fully Connected layer -> Fully Connected layer with batches
455
456 const ITensorInfo *src_to_use = src;
457 const ITensorInfo *weights_to_use = weights;
458
Giorgio Arena63e0beb2021-09-24 14:04:27 +0100459 if(biases != nullptr)
460 {
461 ARM_COMPUTE_RETURN_ERROR_ON(biases->num_dimensions() > 1);
462 if(is_data_type_quantized(src->data_type()))
463 {
464 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(biases, 1, DataType::S32);
465 }
466 else
467 {
468 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src, biases);
469 }
470 }
471
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100472 // Check if FC is after conv (flatten kernel is run in case where FC is after conv.)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100473 if(is_batched_fc_layer)
474 {
475 is_fc_after_conv = (TensorShape::num_max_dimensions >= 4) && (std::equal(src->tensor_shape().cbegin() + 3,
476 src->tensor_shape().cend(),
477 dst->tensor_shape().cbegin() + 1));
478 }
479 else
480 {
481 is_fc_after_conv = src->num_dimensions() > 1;
482 }
483
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100484 // Transpose kernel does not run when matmul is supported as matmul fuses transpose op.
485 if(transpose_weights && !use_matmul)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100486 {
487 // Validate reshape weights kernel
488 ARM_COMPUTE_RETURN_ON_ERROR(ClTranspose::validate(weights, &reshaped_weights));
489 weights_to_use = &reshaped_weights;
490 }
491
492 if(is_fc_after_conv && (src->data_layout() != fc_info.weights_trained_layout))
493 {
494 // Validate convert weights kernel
495 ARM_COMPUTE_RETURN_ON_ERROR(ClConvertFullyConnectedWeights::validate(weights_to_use,
496 &converted_weights,
497 src->tensor_shape(),
498 fc_info.weights_trained_layout));
499 weights_to_use = &converted_weights;
500 }
501
502 if(is_fc_after_conv)
503 {
504 // Fully Connected layer after a Convolution Layer without batches
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100505 // K Index of matrix multiplication. MatMul performs transpose in kernel, so index is 0 when matmul and transpose enabled
506 const int weight_idx = (use_matmul && transpose_weights) ? 0 : 1;
507 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 +0100508
509 // Validate flatten kernel
510 ARM_COMPUTE_RETURN_ON_ERROR(ClFlatten::validate(src, &flatten_src));
511 src_to_use = &flatten_src;
512 }
513 else
514 {
515 // Fully Connected layer after a Fully Connected Layer without batches
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100516 // K Index of matrix multiplication. MatMul performs transpose in kernel, so index is 0 when matmul and transpose enabled
517 const int weight_idx = (use_matmul && transpose_weights) ? 0 : 1;
518 ARM_COMPUTE_RETURN_ERROR_ON(src->dimension(0) != weights_to_use->dimension(weight_idx));
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100519 }
520
521 // Validate matrix multiply kernel
Mohammed Suhail Munshi2e0714d2023-07-19 14:44:38 +0100522 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 +0100523
524 return Status{};
525}
526
527void ClFullyConnected::run(ITensorPack &tensors)
528{
529 prepare(tensors);
530
Jakub Sujak617ed502023-03-29 11:16:18 +0100531#ifdef ARM_COMPUTE_ASSERTS_ENABLED
532 ++_asrt_run_count;
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100533 ARM_COMPUTE_ERROR_ON(_dynamic_gemm && _asrt_prepare_count != _asrt_run_count);
Jakub Sujak617ed502023-03-29 11:16:18 +0100534#endif // ARM_COMPUTE_ASSERTS_ENABLED
535
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100536 auto src = tensors.get_const_tensor(ACL_SRC_0);
537
538 CLAuxTensorHandler flattened_src(offset_int_vec(FlattenedSrc), _flattened_src, tensors, false);
539 CLAuxTensorHandler weights(_weights_to_use_idx, _weights_to_use, tensors, false);
540
541 // Linearize input if it comes from a convolutional layer
542 if(_is_fc_after_conv)
543 {
544 ITensorPack flatten_pack{ { ACL_SRC, src }, { ACL_DST, flattened_src.get() } };
545 _flatten->run(flatten_pack);
546 }
547
548 ITensorPack gemm_pack = tensors;
549 gemm_pack.add_const_tensor(ACL_SRC_0, (_is_fc_after_conv) ? flattened_src.get() : src);
550 if(_weights_to_use_idx != ACL_SRC_1)
551 {
552 gemm_pack.add_const_tensor(ACL_SRC_1, weights.get());
553 }
554
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100555 // Run MatMul Op
556 if(_use_matmul)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100557 {
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100558 // Run matmul kernels for matrix multiplication
559 if(_is_quantized)
560 {
561 CLScheduler::get().enqueue_op(*_matmul_lowp_native_kernel, gemm_pack, true);
562 }
563 else
564 {
565 CLScheduler::get().enqueue_op(*_matmul_native_kernel, gemm_pack, true);
566 }
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100567 }
568 else
569 {
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100570 // Run matrix multiply
571 if(_is_quantized)
572 {
573 _mm_gemmlowp->run(gemm_pack);
574 }
575 else
576 {
577 _mm_gemm->run(gemm_pack);
578 }
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100579 }
580}
581
582void ClFullyConnected::prepare(ITensorPack &tensors)
583{
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100584 // 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 +0100585 if(!_is_prepared || _dynamic_gemm)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100586 {
Jakub Sujak617ed502023-03-29 11:16:18 +0100587#ifdef ARM_COMPUTE_ASSERTS_ENABLED
588 ++_asrt_prepare_count;
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100589 ARM_COMPUTE_ERROR_ON(!_dynamic_gemm && !_use_matmul && _asrt_prepare_count > 1);
Jakub Sujak617ed502023-03-29 11:16:18 +0100590#endif // ARM_COMPUTE_ASSERTS_ENABLED
591
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100592 auto weights = tensors.get_const_tensor(ACL_SRC_1);
593
594 CLAuxTensorHandler reshaped_weights(offset_int_vec(TransposedWeights), _reshaped_weights, tensors, false);
595 CLAuxTensorHandler converted_weights(offset_int_vec(ConvertedWeights), _converted_weights, tensors, false);
596
597 // Pointer to current weights
598 const ITensor *cur_weights = weights;
599
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100600 // Reshape weights if needed. Disabled when matmul kernels are enabled as matmul fuses transpose.
601 if(_transpose_weights && !_use_matmul)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100602 {
603 // Run reshape weights kernel and mark weights as unused
604 ITensorPack transpose_pack{ { ACL_SRC, weights }, { ACL_DST, reshaped_weights.get() } };
605 _reshape_weights->run(transpose_pack);
606
607 cur_weights->mark_as_unused();
608 cur_weights = reshaped_weights.get();
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100609 }
610
Jakub Sujak617ed502023-03-29 11:16:18 +0100611 // Convert weights if needed
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100612 if(_run_convert_weights)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100613 {
614 ITensorPack convert_pack{ { ACL_SRC, cur_weights }, { ACL_DST, converted_weights.get() } };
615 _convert_weights->run(convert_pack);
616
617 cur_weights->mark_as_unused();
618 cur_weights = converted_weights.get();
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100619 }
620
Jakub Sujak617ed502023-03-29 11:16:18 +0100621 ITensorPack gemm_pack = tensors;
622 gemm_pack.add_const_tensor(ACL_SRC_1, cur_weights);
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100623
Mohammed Suhail Munshi8e2dede2023-06-27 14:25:58 +0100624 // Prepare GEMM prepare and release unused weights
625 if(_dynamic_gemm || !_use_matmul)
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100626 {
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100627 if(!_is_quantized)
628 {
629 _mm_gemm->prepare(gemm_pack);
630 }
631 else
632 {
633 _mm_gemmlowp->prepare(gemm_pack);
634 }
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100635 }
Mohammed Suhail Munshia2bb80e2023-06-19 14:57:57 +0100636
Georgios Pinitas529b5a22021-07-27 15:55:30 +0100637 _is_prepared = true;
638 }
639}
640
641experimental::MemoryRequirements ClFullyConnected::workspace() const
642{
643 return _aux_mem;
644}
645} // namespace opencl
646} // namespace arm_compute