2 * Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * Copyright (c) 2017-2019 ARM Limited.
20 * SPDX-License-Identifier: MIT
22 * Permission is hereby granted, free of charge, to any person obtaining a copy
23 * of this software and associated documentation files (the "Software"), to
24 * deal in the Software without restriction, including without limitation the
25 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
26 * sell copies of the Software, and to permit persons to whom the Software is
27 * furnished to do so, subject to the following conditions:
29 * The above copyright notice and this permission notice shall be included in all
30 * copies or substantial portions of the Software.
32 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
33 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
34 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
35 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
36 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
37 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
41 #include "arm_compute/runtime/CL/functions/CLFullyConnectedLayerEx.h"
43 #include "arm_compute/core/Size2D.h"
44 #include "arm_compute/core/Validate.h"
45 #include "arm_compute/core/utils/misc/Cast.h"
46 #include "arm_compute/core/utils/misc/ShapeCalculator.h"
47 #include "arm_compute/core/utils/quantization/AsymmHelpers.h"
48 #include "arm_compute/runtime/CL/CLScheduler.h"
49 #include "support/MemorySupport.h"
55 using namespace arm_compute::misc::shape_calculator;
56 using namespace arm_compute::utils::cast;
60 Status construct_gemmlowp_output_stage(const ITensorInfo &input, const ITensorInfo &weights,
61 const ITensorInfo &output,
62 GEMMLowpOutputStageInfo &gemmlowp_output_stage)
64 gemmlowp_output_stage.type = GEMMLowpOutputStageType::QUANTIZE_DOWN_FIXEDPOINT;
65 gemmlowp_output_stage.gemmlowp_offset = 0;
66 gemmlowp_output_stage.gemmlowp_multiplier = 0;
67 gemmlowp_output_stage.gemmlowp_shift = 0;
69 // Configure output stage for quantized case
70 if (is_data_type_quantized_asymmetric(input.data_type()))
72 const UniformQuantizationInfo iq_info = input.quantization_info().uniform();
73 const UniformQuantizationInfo wq_info = weights.quantization_info().uniform();
74 const UniformQuantizationInfo oq_info = output.quantization_info().uniform();
76 const auto output_quant_info = (output.total_size() == 0) ? iq_info : oq_info;
78 const float multiplier = (iq_info.scale * wq_info.scale) / output_quant_info.scale;
79 int output_multiplier = 0;
81 ARM_COMPUTE_RETURN_ON_ERROR(quantization::calculate_quantized_multiplier_less_than_one(
82 multiplier, &output_multiplier, &output_shift));
84 // Set the GEMMLowp output stage info
85 gemmlowp_output_stage.gemmlowp_offset = output_quant_info.offset;
86 gemmlowp_output_stage.gemmlowp_multiplier = output_multiplier;
87 gemmlowp_output_stage.gemmlowp_shift = output_shift;
88 gemmlowp_output_stage.gemmlowp_min_bound = 0;
89 gemmlowp_output_stage.gemmlowp_max_bound = 255;
90 gemmlowp_output_stage.gemmlowp_multipliers.push_back(output_multiplier);
91 gemmlowp_output_stage.gemmlowp_shifts.push_back(output_shift);
97 Status validate_mm(const ITensorInfo &input, const ITensorInfo &weights, const ITensorInfo *bias,
98 const ITensorInfo &output, const FullyConnectedLayerInfo &fc_info)
100 GEMMLowpOutputStageInfo gemmlowp_output_stage;
101 ARM_COMPUTE_RETURN_ON_ERROR(
102 construct_gemmlowp_output_stage(input, weights, output, gemmlowp_output_stage));
104 const GEMMInfo &gemm_info = GEMMInfo(false, // is_a_reshaped
105 false, // is_b_reshaped
106 true, // reshape_b_only_on_first_run
107 0, // depth_output_gemm3d
108 false, // reinterpret_input_as_3d
109 fc_info.retain_internal_weights, // retain_internal_weights
110 gemmlowp_output_stage, // gemmlowp_output_stage
111 fc_info.fp_mixed_precision, // fp_mixed_precision
112 true, // broadcast_bias
113 ActivationLayerInfo()); // activation_info
115 if (is_data_type_quantized_asymmetric(input.data_type()))
117 const UniformQuantizationInfo iq_info = input.quantization_info().uniform();
118 const UniformQuantizationInfo wq_info = weights.quantization_info().uniform();
120 // Since we need negative offsets for computing convolution, we need to change
121 // QuantizationInfo()
122 // Extract and negate input and weights offset
123 const QuantizationInfo input_quantization_info(iq_info.scale, -iq_info.offset);
124 const QuantizationInfo weights_quantization_info(wq_info.scale, -wq_info.offset);
126 // Validate gemmlowp function
127 ARM_COMPUTE_RETURN_ON_ERROR(CLGEMMLowpMatrixMultiplyCore::validate(
128 &input.clone()->set_quantization_info(input_quantization_info),
129 &weights.clone()->set_quantization_info(weights_quantization_info), bias, &output,
134 ARM_COMPUTE_RETURN_ON_ERROR(
135 CLGEMM::validate(&input, &weights, bias, &output, 1.f, 1.f, gemm_info));
142 void CLFullyConnectedLayerReshapeWeightsEx::configure(const ICLTensor *input, ICLTensor *output)
144 auto k = support::cpp14::make_unique<CLTransposeKernel>();
145 k->configure(input, output);
146 _kernel = std::move(k);
149 Status CLFullyConnectedLayerReshapeWeightsEx::validate(const ITensorInfo *input,
150 const ITensorInfo *output)
152 return CLTransposeKernel::validate(input, output);
155 CLFullyConnectedLayerEx::CLFullyConnectedLayerEx(std::shared_ptr<IMemoryManager> memory_manager,
156 IWeightsManager *weights_manager)
157 : _memory_group(memory_manager), _weights_manager(weights_manager), _convert_weights(),
158 _convert_weights_managed(), _reshape_weights_managed_function(), _flatten_layer(),
159 _reshape_weights_function(), _mm_gemm(memory_manager, weights_manager),
160 _mm_gemmlowp(memory_manager), _flatten_output(), _converted_weights_output(),
161 _reshape_weights_output(), _are_weights_converted(true), _are_weights_reshaped(true),
162 _is_fc_after_conv(true), _is_quantized(false), _is_prepared(false), _original_weights(nullptr)
165 void CLFullyConnectedLayerEx::configure_mm(const ICLTensor *input, const ICLTensor *weights,
166 const ICLTensor *bias, ICLTensor *output,
167 const FullyConnectedLayerInfo &fc_info)
169 GEMMLowpOutputStageInfo gemmlowp_output_stage;
170 construct_gemmlowp_output_stage(*input->info(), *weights->info(), *output->info(),
171 gemmlowp_output_stage);
173 const GEMMInfo &gemm_info = GEMMInfo(false, // is_a_reshaped
174 false, // is_b_reshaped
175 true, // reshape_b_only_on_first_run
176 0, // depth_output_gemm3d
177 false, // reinterpret_input_as_3d
178 fc_info.retain_internal_weights, // retain_internal_weights
179 gemmlowp_output_stage, // gemmlowp_output_stage
180 fc_info.fp_mixed_precision, // fp_mixed_precision
181 true, // broadcast_bias
182 ActivationLayerInfo()); // activation_info
186 // Since we need negative offsets for computing convolution, we need to change
187 // QuantizationInfo()
188 // Extract and negate input and weights offset
189 const QuantizationInfo input_quantization_info = input->info()->quantization_info();
190 const QuantizationInfo weights_quantization_info = weights->info()->quantization_info();
192 input->info()->set_quantization_info(QuantizationInfo(
193 input_quantization_info.uniform().scale, -input_quantization_info.uniform().offset));
194 weights->info()->set_quantization_info(QuantizationInfo(
195 weights_quantization_info.uniform().scale, -weights_quantization_info.uniform().offset));
197 // Configure gemmlowp function
198 _mm_gemmlowp.configure(input, weights, bias, output, gemm_info);
200 // Revert back QuantizatioInfo as input and weights could be used in other fully connected
202 input->info()->set_quantization_info(input_quantization_info);
203 weights->info()->set_quantization_info(weights_quantization_info);
207 // Configure matrix multiply kernel
208 _mm_gemm.configure(input, weights, bias, output, 1.f, 1.f, gemm_info);
212 void CLFullyConnectedLayerEx::configure_conv_fc(const ICLTensor *input, const ICLTensor *weights,
213 const ICLTensor *bias, ICLTensor *output,
214 const FullyConnectedLayerInfo &fc_info)
216 ARM_COMPUTE_ERROR_ON(
217 (weights->info()->dimension(1) !=
218 (input->info()->dimension(0) * input->info()->dimension(1) * input->info()->dimension(2))));
220 // If the fully connected layer is called after a convolution layer, the input tensor must be
223 // Initialize output tensor for flatten
224 TensorShape shape_flatten = compute_flatten_shape(input->info());
225 _flatten_output.allocator()->init(input->info()
227 ->set_is_resizable(true)
229 .set_tensor_shape(shape_flatten)
230 .set_data_layout(DataLayout::NCHW));
232 // Configure flatten kernel
233 _memory_group.manage(&_flatten_output);
234 _flatten_layer.configure(input, &_flatten_output);
236 // Configure matrix multiply kernel
237 configure_mm(&_flatten_output, weights, bias, output, fc_info);
239 // Allocate the output tensor for flatten once all the configure methods have been called
240 _flatten_output.allocator()->allocate();
243 void CLFullyConnectedLayerEx::configure_fc_fc(const ICLTensor *input, const ICLTensor *weights,
244 const ICLTensor *bias, ICLTensor *output,
245 const FullyConnectedLayerInfo &fc_info)
247 ARM_COMPUTE_ERROR_ON(input->info()->dimension(0) != weights->info()->dimension(1));
249 // Configure matrix multiply kernel
250 configure_mm(input, weights, bias, output, fc_info);
253 void CLFullyConnectedLayerEx::configure(const ICLTensor *input, const ICLTensor *weights,
254 const ICLTensor *biases, ICLTensor *output,
255 FullyConnectedLayerInfo fc_info)
257 ARM_COMPUTE_ERROR_ON_NULLPTR(input, weights, output);
259 // Perform validate step
260 ARM_COMPUTE_ERROR_THROW_ON(CLFullyConnectedLayerEx::validate(
261 input->info(), weights->info(), biases != nullptr ? biases->info() : nullptr, output->info(),
264 _are_weights_converted = true;
265 _are_weights_reshaped = fc_info.transpose_weights ? fc_info.are_weights_reshaped : true;
266 _is_fc_after_conv = true;
267 _is_quantized = is_data_type_quantized_asymmetric(input->info()->data_type());
268 _is_prepared = fc_info.retain_internal_weights;
269 _original_weights = weights;
271 if (_weights_manager)
273 _weights_manager->manage(weights);
276 const ICLTensor *weights_to_use = weights;
278 // With the Fully Connected layer we can have 4 different cases:
279 // 1) Convolution layer -> Fully Connected layer without batches
280 // 2) Fully Connected layer -> Fully Connected layer without batches
281 // 3) Convolution layer -> Fully Connected layer with batches
282 // 4) Fully Connected layer -> Fully Connected layer with batches
284 // Check if we have a fully connected layer with batches
285 const bool is_batched_fc_layer = output->info()->dimension(1) > 1;
286 if (is_batched_fc_layer)
289 (TensorShape::num_max_dimensions >= 4) &&
290 (std::equal(input->info()->tensor_shape().cbegin() + 3, input->info()->tensor_shape().cend(),
291 output->info()->tensor_shape().cbegin() + 1));
295 _is_fc_after_conv = input->info()->num_dimensions() > 1;
298 // Reshape weights if needed
299 if (!_are_weights_reshaped)
301 if (_weights_manager && _weights_manager->are_weights_managed(weights))
303 _reshape_weights_managed_function.configure(weights);
304 weights_to_use = utils::cast::polymorphic_downcast<ICLTensor *>(
305 _weights_manager->acquire(weights, &_reshape_weights_managed_function));
309 // Reshape the weights
310 _reshape_weights_function.configure(weights, &_reshape_weights_output);
311 weights_to_use = &_reshape_weights_output;
315 // Convert weights if needed
316 if (_is_fc_after_conv && (input->info()->data_layout() != fc_info.weights_trained_layout))
318 if (_weights_manager && _weights_manager->are_weights_managed(weights_to_use))
320 _convert_weights_managed.configure(weights_to_use, input->info()->tensor_shape(),
321 fc_info.weights_trained_layout);
322 weights_to_use = utils::cast::polymorphic_downcast<ICLTensor *>(
323 _weights_manager->acquire(weights, &_convert_weights_managed));
328 _convert_weights.configure(weights_to_use, &_converted_weights_output,
329 input->info()->tensor_shape(), fc_info.weights_trained_layout);
331 weights_to_use = &_converted_weights_output;
333 _are_weights_converted = false;
336 if (_is_fc_after_conv)
338 // Fully Connected layer after a Convolution Layer without batches
339 configure_conv_fc(input, weights_to_use, biases, output, fc_info);
343 // Fully Connected layer after a Fully Connected Layer without batches
344 configure_fc_fc(input, weights_to_use, biases, output, fc_info);
348 Status CLFullyConnectedLayerEx::validate(const ITensorInfo *input, const ITensorInfo *weights,
349 const ITensorInfo *biases, const ITensorInfo *output,
350 FullyConnectedLayerInfo fc_info)
352 ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(input, weights, output);
353 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input, 1, DataType::QASYMM8, DataType::F16,
355 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, weights, output);
356 ARM_COMPUTE_RETURN_ERROR_ON(weights->num_dimensions() > 2);
358 bool weights_reshaped = fc_info.transpose_weights ? fc_info.are_weights_reshaped : true;
359 bool is_fc_after_conv = true;
361 const ITensorInfo &flatten_input = TensorInfo(input->clone()
362 ->set_is_resizable(true)
364 .set_tensor_shape(compute_flatten_shape(input))
365 .set_data_layout(DataLayout::NCHW));
366 const ITensorInfo &reshaped_weights =
367 TensorInfo(weights->clone()->set_is_resizable(true).reset_padding().set_tensor_shape(
368 compute_transposed_shape(*weights)));
369 const ITensorInfo &converted_weights =
370 weights_reshaped ? TensorInfo(weights->clone()->set_is_resizable(true).reset_padding())
371 : TensorInfo(*reshaped_weights.clone());
373 // With the Fully Connected layer we can have 4 different cases:
374 // 1) Convolution layer -> Fully Connected layer without batches
375 // 2) Fully Connected layer -> Fully Connected layer without batches
376 // 3) Convolution layer -> Fully Connected layer with batches
377 // 4) Fully Connected layer -> Fully Connected layer with batches
379 const ITensorInfo *input_to_use = input;
380 const ITensorInfo *weights_to_use = weights;
382 // Check if we have a fully connected layer with batches
383 const bool is_batched_fc_layer = output->dimension(1) > 1;
384 if (is_batched_fc_layer)
386 is_fc_after_conv = (TensorShape::num_max_dimensions >= 4) &&
387 (std::equal(input->tensor_shape().cbegin() + 3, input->tensor_shape().cend(),
388 output->tensor_shape().cbegin() + 1));
392 is_fc_after_conv = input->num_dimensions() > 1;
395 if (!weights_reshaped)
397 // Validate reshape weights kernel
398 ARM_COMPUTE_RETURN_ON_ERROR(
399 CLFullyConnectedLayerReshapeWeightsEx::validate(weights, &reshaped_weights));
400 weights_to_use = &reshaped_weights;
403 if (is_fc_after_conv && (input->data_layout() != fc_info.weights_trained_layout))
405 // Validate convert weights kernel
406 ARM_COMPUTE_RETURN_ON_ERROR(CLConvertFullyConnectedWeights::validate(
407 weights_to_use, &converted_weights, input->tensor_shape(), fc_info.weights_trained_layout));
408 weights_to_use = &converted_weights;
411 if (is_fc_after_conv)
413 // Fully Connected layer after a Convolution Layer without batches
414 ARM_COMPUTE_RETURN_ERROR_ON(
415 (weights_to_use->dimension(1) !=
416 (input->dimension(0) * input->dimension(1) * input->dimension(2))));
418 // Validate flatten kernel
419 ARM_COMPUTE_RETURN_ON_ERROR(CLFlattenLayer::validate(input, &flatten_input));
420 input_to_use = &flatten_input;
424 // Fully Connected layer after a Fully Connected Layer without batches
425 ARM_COMPUTE_RETURN_ERROR_ON(input->dimension(0) != weights_to_use->dimension(1));
428 // Validate matrix multiply kernel
429 ARM_COMPUTE_RETURN_ON_ERROR(
430 validate_mm(*input_to_use, *weights_to_use, biases, *output, fc_info));
435 void CLFullyConnectedLayerEx::run()
439 if (!_are_weights_reshaped)
440 _reshape_weights_output.allocator()->allocate();
441 if (!_are_weights_converted)
442 _converted_weights_output.allocator()->allocate();
447 if (!_weights_manager)
449 ARM_COMPUTE_ERROR_ON(!_original_weights->is_used());
452 // Pointer to current weights
453 const ICLTensor *cur_weights = _original_weights;
454 // Reshape of the weights
455 if (!_are_weights_reshaped)
457 if (_weights_manager && _weights_manager->are_weights_managed(cur_weights))
459 _original_weights = utils::cast::polymorphic_downcast<ICLTensor *>(
460 _weights_manager->run(cur_weights, &_reshape_weights_managed_function));
464 _reshape_weights_function.run();
465 cur_weights = &_reshape_weights_output;
469 // Convert weights if needed
470 if (!_are_weights_converted)
472 if (_weights_manager && _weights_manager->are_weights_managed(cur_weights))
474 _weights_manager->run(cur_weights, &_convert_weights_managed);
478 _convert_weights.run();
482 // Prepare GEMM prepare
489 MemoryGroupResourceScope scope_mg(_memory_group);
491 // Linearize input if it comes from a convolutional layer
492 if (_is_fc_after_conv)
494 _flatten_layer.run();
497 // Run matrix multiply
508 void CLFullyConnectedLayerEx::prepare()
510 #if 0 // TODO Remove this block
513 if(!_weights_manager)
515 ARM_COMPUTE_ERROR_ON(!_original_weights->is_used());
518 auto release_unused = [](CLTensor * w)
522 CLScheduler::get().queue().finish();
523 w->allocator()->free();
527 // Pointer to current weights
528 const ICLTensor *cur_weights = _original_weights;
530 // Reshape of the weights if needed (happens only once)
531 if(!_are_weights_reshaped)
533 if(_weights_manager && _weights_manager->are_weights_managed(_original_weights))
535 cur_weights = utils::cast::polymorphic_downcast<ICLTensor *>(_weights_manager->run(cur_weights, &_reshape_weights_managed_function));
539 // Run reshape weights kernel and mark weights as unused
540 _reshape_weights_output.allocator()->allocate();
541 _reshape_weights_function.run();
543 cur_weights->mark_as_unused();
544 cur_weights = &_reshape_weights_output;
546 _are_weights_reshaped = true;
549 // Convert weights if needed (happens only once)
550 if(!_are_weights_converted)
552 if(_weights_manager && _weights_manager->are_weights_managed(cur_weights))
554 _weights_manager->run(cur_weights, &_convert_weights_managed);
558 _converted_weights_output.allocator()->allocate();
559 _convert_weights.run();
560 cur_weights->mark_as_unused();
563 _are_weights_converted = true;
566 // Release reshaped weights if unused
567 release_unused(&_reshape_weights_output);
569 // Prepare GEMM prepare and release unused weights
575 // Release converted weights if unused
576 release_unused(&_reshape_weights_output);
577 release_unused(&_converted_weights_output);
583 } // namespace arm_compute