Imported Upstream version 1.8.0
[platform/core/ml/nnfw.git] / compute / ARMComputeEx / src / runtime / CL / functions / CLFullyConnectedLayerEx.cpp
1 /*
2  * Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /*
18  * Copyright (c) 2017-2019 ARM Limited.
19  *
20  * SPDX-License-Identifier: MIT
21  *
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:
28  *
29  * The above copyright notice and this permission notice shall be included in all
30  * copies or substantial portions of the Software.
31  *
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
38  * SOFTWARE.
39  */
40
41 #include "arm_compute/runtime/CL/functions/CLFullyConnectedLayerEx.h"
42
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"
50
51 #include <algorithm>
52
53 namespace arm_compute
54 {
55 using namespace arm_compute::misc::shape_calculator;
56 using namespace arm_compute::utils::cast;
57
58 namespace
59 {
60 Status construct_gemmlowp_output_stage(const ITensorInfo &input, const ITensorInfo &weights,
61                                        const ITensorInfo &output,
62                                        GEMMLowpOutputStageInfo &gemmlowp_output_stage)
63 {
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;
68
69   // Configure output stage for quantized case
70   if (is_data_type_quantized_asymmetric(input.data_type()))
71   {
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();
75
76     const auto output_quant_info = (output.total_size() == 0) ? iq_info : oq_info;
77
78     const float multiplier = (iq_info.scale * wq_info.scale) / output_quant_info.scale;
79     int output_multiplier = 0;
80     int output_shift = 0;
81     ARM_COMPUTE_RETURN_ON_ERROR(quantization::calculate_quantized_multiplier_less_than_one(
82         multiplier, &output_multiplier, &output_shift));
83
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);
92   }
93
94   return Status{};
95 }
96
97 Status validate_mm(const ITensorInfo &input, const ITensorInfo &weights, const ITensorInfo *bias,
98                    const ITensorInfo &output, const FullyConnectedLayerInfo &fc_info)
99 {
100   GEMMLowpOutputStageInfo gemmlowp_output_stage;
101   ARM_COMPUTE_RETURN_ON_ERROR(
102       construct_gemmlowp_output_stage(input, weights, output, gemmlowp_output_stage));
103
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
114
115   if (is_data_type_quantized_asymmetric(input.data_type()))
116   {
117     const UniformQuantizationInfo iq_info = input.quantization_info().uniform();
118     const UniformQuantizationInfo wq_info = weights.quantization_info().uniform();
119
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);
125
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,
130         gemm_info));
131   }
132   else
133   {
134     ARM_COMPUTE_RETURN_ON_ERROR(
135         CLGEMM::validate(&input, &weights, bias, &output, 1.f, 1.f, gemm_info));
136   }
137
138   return Status{};
139 }
140 } // namespace
141
142 void CLFullyConnectedLayerReshapeWeightsEx::configure(const ICLTensor *input, ICLTensor *output)
143 {
144   auto k = support::cpp14::make_unique<CLTransposeKernel>();
145   k->configure(input, output);
146   _kernel = std::move(k);
147 }
148
149 Status CLFullyConnectedLayerReshapeWeightsEx::validate(const ITensorInfo *input,
150                                                        const ITensorInfo *output)
151 {
152   return CLTransposeKernel::validate(input, output);
153 }
154
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)
163 {
164 }
165 void CLFullyConnectedLayerEx::configure_mm(const ICLTensor *input, const ICLTensor *weights,
166                                            const ICLTensor *bias, ICLTensor *output,
167                                            const FullyConnectedLayerInfo &fc_info)
168 {
169   GEMMLowpOutputStageInfo gemmlowp_output_stage;
170   construct_gemmlowp_output_stage(*input->info(), *weights->info(), *output->info(),
171                                   gemmlowp_output_stage);
172
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
183
184   if (_is_quantized)
185   {
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();
191
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));
196
197     // Configure gemmlowp function
198     _mm_gemmlowp.configure(input, weights, bias, output, gemm_info);
199
200     // Revert back QuantizatioInfo as input and weights could be used in other fully connected
201     // layers
202     input->info()->set_quantization_info(input_quantization_info);
203     weights->info()->set_quantization_info(weights_quantization_info);
204   }
205   else
206   {
207     // Configure matrix multiply kernel
208     _mm_gemm.configure(input, weights, bias, output, 1.f, 1.f, gemm_info);
209   }
210 }
211
212 void CLFullyConnectedLayerEx::configure_conv_fc(const ICLTensor *input, const ICLTensor *weights,
213                                                 const ICLTensor *bias, ICLTensor *output,
214                                                 const FullyConnectedLayerInfo &fc_info)
215 {
216   ARM_COMPUTE_ERROR_ON(
217       (weights->info()->dimension(1) !=
218        (input->info()->dimension(0) * input->info()->dimension(1) * input->info()->dimension(2))));
219
220   // If the fully connected layer is called after a convolution layer, the input tensor must be
221   // linearized
222
223   // Initialize output tensor for flatten
224   TensorShape shape_flatten = compute_flatten_shape(input->info());
225   _flatten_output.allocator()->init(input->info()
226                                         ->clone()
227                                         ->set_is_resizable(true)
228                                         .reset_padding()
229                                         .set_tensor_shape(shape_flatten)
230                                         .set_data_layout(DataLayout::NCHW));
231
232   // Configure flatten kernel
233   _memory_group.manage(&_flatten_output);
234   _flatten_layer.configure(input, &_flatten_output);
235
236   // Configure matrix multiply kernel
237   configure_mm(&_flatten_output, weights, bias, output, fc_info);
238
239   // Allocate the output tensor for flatten once all the configure methods have been called
240   _flatten_output.allocator()->allocate();
241 }
242
243 void CLFullyConnectedLayerEx::configure_fc_fc(const ICLTensor *input, const ICLTensor *weights,
244                                               const ICLTensor *bias, ICLTensor *output,
245                                               const FullyConnectedLayerInfo &fc_info)
246 {
247   ARM_COMPUTE_ERROR_ON(input->info()->dimension(0) != weights->info()->dimension(1));
248
249   // Configure matrix multiply kernel
250   configure_mm(input, weights, bias, output, fc_info);
251 }
252
253 void CLFullyConnectedLayerEx::configure(const ICLTensor *input, const ICLTensor *weights,
254                                         const ICLTensor *biases, ICLTensor *output,
255                                         FullyConnectedLayerInfo fc_info)
256 {
257   ARM_COMPUTE_ERROR_ON_NULLPTR(input, weights, output);
258
259   // Perform validate step
260   ARM_COMPUTE_ERROR_THROW_ON(CLFullyConnectedLayerEx::validate(
261       input->info(), weights->info(), biases != nullptr ? biases->info() : nullptr, output->info(),
262       fc_info));
263
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;
270
271   if (_weights_manager)
272   {
273     _weights_manager->manage(weights);
274   }
275
276   const ICLTensor *weights_to_use = weights;
277
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
283
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)
287   {
288     _is_fc_after_conv = (TensorShape::num_max_dimensions >= 4) &&
289                         (std::equal(input->info()->tensor_shape().cbegin() + 3,
290                                     input->info()->tensor_shape().cend(),
291                                     output->info()->tensor_shape().cbegin() + 1));
292   }
293   else
294   {
295     _is_fc_after_conv = input->info()->num_dimensions() > 1;
296   }
297
298   // Reshape weights if needed
299   if (!_are_weights_reshaped)
300   {
301     if (_weights_manager && _weights_manager->are_weights_managed(weights))
302     {
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));
306     }
307     else
308     {
309       // Reshape the weights
310       _reshape_weights_function.configure(weights, &_reshape_weights_output);
311       weights_to_use = &_reshape_weights_output;
312     }
313   }
314
315   // Convert weights if needed
316   if (_is_fc_after_conv && (input->info()->data_layout() != fc_info.weights_trained_layout))
317   {
318     if (_weights_manager && _weights_manager->are_weights_managed(weights_to_use))
319     {
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));
324     }
325     else
326     {
327       // Convert weights
328       _convert_weights.configure(weights_to_use, &_converted_weights_output,
329                                  input->info()->tensor_shape(), fc_info.weights_trained_layout);
330
331       weights_to_use = &_converted_weights_output;
332     }
333     _are_weights_converted = false;
334   }
335
336   if (_is_fc_after_conv)
337   {
338     // Fully Connected layer after a Convolution Layer without batches
339     configure_conv_fc(input, weights_to_use, biases, output, fc_info);
340   }
341   else
342   {
343     // Fully Connected layer after a Fully Connected Layer without batches
344     configure_fc_fc(input, weights_to_use, biases, output, fc_info);
345   }
346 }
347
348 Status CLFullyConnectedLayerEx::validate(const ITensorInfo *input, const ITensorInfo *weights,
349                                          const ITensorInfo *biases, const ITensorInfo *output,
350                                          FullyConnectedLayerInfo fc_info)
351 {
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,
354                                                        DataType::F32);
355   ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, weights, output);
356   ARM_COMPUTE_RETURN_ERROR_ON(weights->num_dimensions() > 2);
357
358   bool weights_reshaped = fc_info.transpose_weights ? fc_info.are_weights_reshaped : true;
359   bool is_fc_after_conv = true;
360
361   const ITensorInfo &flatten_input = TensorInfo(input->clone()
362                                                     ->set_is_resizable(true)
363                                                     .reset_padding()
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());
372
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
378
379   const ITensorInfo *input_to_use = input;
380   const ITensorInfo *weights_to_use = weights;
381
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)
385   {
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));
389   }
390   else
391   {
392     is_fc_after_conv = input->num_dimensions() > 1;
393   }
394
395   if (!weights_reshaped)
396   {
397     // Validate reshape weights kernel
398     ARM_COMPUTE_RETURN_ON_ERROR(
399         CLFullyConnectedLayerReshapeWeightsEx::validate(weights, &reshaped_weights));
400     weights_to_use = &reshaped_weights;
401   }
402
403   if (is_fc_after_conv && (input->data_layout() != fc_info.weights_trained_layout))
404   {
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;
409   }
410
411   if (is_fc_after_conv)
412   {
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))));
417
418     // Validate flatten kernel
419     ARM_COMPUTE_RETURN_ON_ERROR(CLFlattenLayer::validate(input, &flatten_input));
420     input_to_use = &flatten_input;
421   }
422   else
423   {
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));
426   }
427
428   // Validate matrix multiply kernel
429   ARM_COMPUTE_RETURN_ON_ERROR(
430       validate_mm(*input_to_use, *weights_to_use, biases, *output, fc_info));
431
432   return Status{};
433 }
434
435 void CLFullyConnectedLayerEx::run()
436 {
437   if (!_is_prepared)
438   {
439     if (!_are_weights_reshaped)
440       _reshape_weights_output.allocator()->allocate();
441     if (!_are_weights_converted)
442       _converted_weights_output.allocator()->allocate();
443     _is_prepared = true;
444   }
445
446   {
447     if (!_weights_manager)
448     {
449       ARM_COMPUTE_ERROR_ON(!_original_weights->is_used());
450     }
451
452     // Pointer to current weights
453     const ICLTensor *cur_weights = _original_weights;
454     // Reshape of the weights
455     if (!_are_weights_reshaped)
456     {
457       if (_weights_manager && _weights_manager->are_weights_managed(cur_weights))
458       {
459         _original_weights = utils::cast::polymorphic_downcast<ICLTensor *>(
460             _weights_manager->run(cur_weights, &_reshape_weights_managed_function));
461       }
462       else
463       {
464         _reshape_weights_function.run();
465         cur_weights = &_reshape_weights_output;
466       }
467     }
468
469     // Convert weights if needed
470     if (!_are_weights_converted)
471     {
472       if (_weights_manager && _weights_manager->are_weights_managed(cur_weights))
473       {
474         _weights_manager->run(cur_weights, &_convert_weights_managed);
475       }
476       else
477       {
478         _convert_weights.run();
479       }
480     }
481
482     // Prepare GEMM prepare
483     if (!_is_quantized)
484     {
485       _mm_gemm.prepare();
486     }
487   }
488
489   MemoryGroupResourceScope scope_mg(_memory_group);
490
491   // Linearize input if it comes from a convolutional layer
492   if (_is_fc_after_conv)
493   {
494     _flatten_layer.run();
495   }
496
497   // Run matrix multiply
498   if (_is_quantized)
499   {
500     _mm_gemmlowp.run();
501   }
502   else
503   {
504     _mm_gemm.run();
505   }
506 }
507
508 void CLFullyConnectedLayerEx::prepare()
509 {
510 #if 0 // TODO Remove this block
511     if(!_is_prepared)
512     {
513         if(!_weights_manager)
514         {
515             ARM_COMPUTE_ERROR_ON(!_original_weights->is_used());
516         }
517
518         auto release_unused = [](CLTensor * w)
519         {
520             if(!w->is_used())
521             {
522                 CLScheduler::get().queue().finish();
523                 w->allocator()->free();
524             }
525         };
526
527         // Pointer to current weights
528         const ICLTensor *cur_weights = _original_weights;
529
530         // Reshape of the weights if needed (happens only once)
531         if(!_are_weights_reshaped)
532         {
533             if(_weights_manager && _weights_manager->are_weights_managed(_original_weights))
534             {
535                 cur_weights = utils::cast::polymorphic_downcast<ICLTensor *>(_weights_manager->run(cur_weights, &_reshape_weights_managed_function));
536             }
537             else
538             {
539                 // Run reshape weights kernel and mark weights as unused
540                 _reshape_weights_output.allocator()->allocate();
541                 _reshape_weights_function.run();
542
543                 cur_weights->mark_as_unused();
544                 cur_weights = &_reshape_weights_output;
545             }
546             _are_weights_reshaped = true;
547         }
548
549         // Convert weights if needed (happens only once)
550         if(!_are_weights_converted)
551         {
552             if(_weights_manager && _weights_manager->are_weights_managed(cur_weights))
553             {
554                 _weights_manager->run(cur_weights, &_convert_weights_managed);
555             }
556             else
557             {
558                 _converted_weights_output.allocator()->allocate();
559                 _convert_weights.run();
560                 cur_weights->mark_as_unused();
561             }
562
563             _are_weights_converted = true;
564         }
565
566         // Release reshaped weights if unused
567         release_unused(&_reshape_weights_output);
568
569         // Prepare GEMM prepare and release unused weights
570         if(!_is_quantized)
571         {
572             _mm_gemm.prepare();
573         }
574
575         // Release converted weights if unused
576         release_unused(&_reshape_weights_output);
577         release_unused(&_converted_weights_output);
578
579         _is_prepared = true;
580     }
581 #endif
582 }
583 } // namespace arm_compute