Compute Library
 21.02
GCFullyConnectedLayer.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2017-2020 Arm Limited.
3  *
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  */
25 
28 
29 #include <algorithm>
30 
31 using namespace arm_compute;
32 
34 {
35  auto k = std::make_unique<GCTransposeKernel>();
36  k->configure(input, output);
37  _kernel = std::move(k);
38 }
39 
40 GCFullyConnectedLayer::GCFullyConnectedLayer(std::shared_ptr<IMemoryManager> memory_manager, IWeightsManager *weights_manager)
41  : _memory_group(std::move(memory_manager)), _weights_manager(std::move(weights_manager)), _im2col_kernel(), _reshape_weights_kernel(), _mm_kernel(), _accumulate_biases_kernel(), _im2col_output(),
42  _reshape_weights_output(), _original_weights(nullptr), _are_weights_reshaped(true), _is_fc_after_conv(true), _accumulate_biases(false)
43 {
44 }
45 
46 void GCFullyConnectedLayer::configure_conv_fc(const IGCTensor *input, const IGCTensor *weights, IGCTensor *output)
47 {
48  ARM_COMPUTE_ERROR_ON((weights->info()->dimension(1) != (input->info()->dimension(0) * input->info()->dimension(1) * input->info()->dimension(2))));
49 
50  const DataType dt = input->info()->data_type();
51 
52  // If the fully connected layer is called after a convolution layer, the input tensor must be linearized
53 
54  // Initialize output tensor for im2col
55  TensorShape shape_im2col;
56  shape_im2col.set(0, input->info()->dimension(0) * input->info()->dimension(1) * input->info()->dimension(2));
57  shape_im2col.set(1, input->info()->dimension(3));
58  shape_im2col.set(2, input->info()->dimension(4));
59  shape_im2col.set(3, input->info()->dimension(5));
60  _im2col_output.allocator()->init(TensorInfo(shape_im2col, 1, dt));
61 
62  // Configure im2col kernel
63  _memory_group.manage(&_im2col_output);
64  _im2col_kernel.configure(input, &_im2col_output, Size2D(1, 1), PadStrideInfo(1, 1, 0, 0), false);
65 
66  // Configure matrix multiply kernel
67  _mm_kernel.configure(&_im2col_output, weights, output, 1.0f, false);
68 
69  // Allocate the output tensor for im2col once all the configure methods have been called
70  _im2col_output.allocator()->allocate();
71 }
72 
73 void GCFullyConnectedLayer::configure_fc_fc(const IGCTensor *input, const IGCTensor *weights, IGCTensor *output)
74 {
75  ARM_COMPUTE_ERROR_ON(input->info()->dimension(0) != weights->info()->dimension(1));
76 
77  // Configure matrix multiply kernel
78  _mm_kernel.configure(input, weights, output, 1.0f, false);
79 }
80 
81 void GCFullyConnectedLayer::configure(const IGCTensor *input, const IGCTensor *weights, const IGCTensor *biases, IGCTensor *output,
83 {
85  ARM_COMPUTE_ERROR_ON_MISMATCHING_DATA_TYPES(input, weights, output);
86  ARM_COMPUTE_ERROR_ON(weights->info()->num_dimensions() > 2);
87 
88  _original_weights = weights;
89  _are_weights_reshaped = fc_info.transpose_weights ? fc_info.are_weights_reshaped : true;
90  _is_fc_after_conv = true;
91  _accumulate_biases = false;
92 
93  if(biases != nullptr)
94  {
96 
97  _accumulate_biases = true;
98 
99  // Configure accumulate biases kernel
100  _accumulate_biases_kernel.configure(output, biases);
101  }
102 
103  // With the Fully Connected layer we can have 4 different cases:
104  // 1) Convolution layer -> Fully Connected layer without batches
105  // 2) Fully Connected layer -> Fully Connected layer without batches
106  // 3) Convolution layer -> Fully Connected layer with batches
107  // 4) Fully Connected layer -> Fully Connected layer with batches
108 
109  const IGCTensor *weights_to_use = weights;
110 
111  if(!_are_weights_reshaped)
112  {
113  weights_to_use = &_reshape_weights_output;
114 
115  // Reshape the weights
116  _reshape_weights_kernel.configure(weights, &_reshape_weights_output);
117  }
118 
119  // Check if we have a fully connected layer with batches
120  const bool is_batched_fc_layer = output->info()->dimension(1) > 1;
121 
122  if(is_batched_fc_layer)
123  {
124  _is_fc_after_conv = (TensorShape::num_max_dimensions >= 4) && (std::equal(input->info()->tensor_shape().cbegin() + 3,
125  input->info()->tensor_shape().cend(),
126  output->info()->tensor_shape().cbegin() + 1));
127  }
128  else
129  {
130  _is_fc_after_conv = input->info()->num_dimensions() > 1;
131  }
132 
133  if(_is_fc_after_conv)
134  {
135  // Fully Connected layer after a Convolution Layer without batches
136  configure_conv_fc(input, weights_to_use, output);
137  }
138  else
139  {
140  // Fully Connected layer after a Fully Connected Layer without batches
141  configure_fc_fc(input, weights_to_use, output);
142  }
143 
144  ARM_COMPUTE_ERROR_ON(fc_info.retain_internal_weights && _reshape_weights_output.gc_buffer() == 0);
145  _are_weights_reshaped = _are_weights_reshaped || fc_info.retain_internal_weights;
146 }
147 
149 {
150  prepare();
151 
152  MemoryGroupResourceScope scope_mg(_memory_group);
153 
154  // Linearize input if it comes from a convolutional layer
155  if(_is_fc_after_conv)
156  {
157  GCScheduler::get().dispatch(_im2col_kernel, false);
158  }
159 
160  if(!_are_weights_reshaped || _is_fc_after_conv)
161  {
163  }
164 
165  // Run matrix multiply
166  GCScheduler::get().dispatch(_mm_kernel, !_accumulate_biases);
167 
168  // Accumulate biases if provided
169  if(_accumulate_biases)
170  {
172 
173  GCScheduler::get().dispatch(_accumulate_biases_kernel);
174  }
175 }
176 
178 {
179  // Reshape of the weights (happens only once)
180  if(!_are_weights_reshaped)
181  {
182  ARM_COMPUTE_ERROR_ON(!_original_weights->is_used());
183 
184  // Run reshape weights kernel and mark weights as unused
185  _reshape_weights_output.allocator()->allocate();
186  _reshape_weights_kernel.run();
187 
188  // Mark original weights tensor as unused
189  _original_weights->mark_as_unused();
190 
191  _are_weights_reshaped = true;
192  }
193 }
void configure(const IGCTensor *input, const IGCTensor *weights, const IGCTensor *biases, IGCTensor *output, FullyConnectedLayerInfo fc_info=FullyConnectedLayerInfo())
Set the input and output tensors.
void configure(const IGCTensor *input, IGCTensor *output, const Size2D &kernel_dims, const PadStrideInfo &conv_info, bool has_bias, const Size2D &dilation=Size2D(1U, 1U))
Set the input and output of the kernel.
virtual size_t num_dimensions() const =0
The number of dimensions of the tensor (rank)
Shape of a tensor.
Definition: TensorShape.h:39
virtual size_t dimension(size_t index) const =0
Return the size of the requested dimension.
void dispatch(IGCKernel &kernel, bool flush=true)
Schedule the execution of the passed kernel if possible.
Definition: GCScheduler.cpp:77
bool retain_internal_weights
Retain internal reshaped weights.
Definition: Types.h:1618
void run() override final
Run the kernels contained in the function.
virtual DataType data_type() const =0
Data type used for each element of the tensor.
bool is_used() const
Flags if the tensor is used or not.
Definition: ITensor.cpp:163
1 channel, 1 F32 per channel
void memory_barrier()
Defines a barrier ordering memory transactions.
Definition: GCScheduler.cpp:86
#define ARM_COMPUTE_ERROR_ON(cond)
If the condition is true then an error message is printed and an exception thrown.
Definition: Error.h:466
Fully connected layer info.
Definition: Types.h:1613
Interface for GLES Compute tensor.
Definition: IGCTensor.h:35
void init(const TensorInfo &input, size_t alignment=0)
Initialize a tensor based on the passed TensorInfo.
Copyright (c) 2017-2021 Arm Limited.
1 channel, 1 F16 per channel
DataType dt
void mark_as_unused() const
Marks a tensor as unused.
Definition: ITensor.cpp:168
void manage(IMemoryManageable *obj) override
Sets a object to be managed by the given memory group.
Definition: MemoryGroup.h:79
static GCScheduler & get()
Access the scheduler singleton.
Definition: GCScheduler.cpp:70
GLuint gc_buffer() const override
Interface to be implemented by the child class to return the tensor&#39;s gles compute buffer id...
Definition: GCTensor.cpp:54
virtual const TensorShape & tensor_shape() const =0
Size for each dimension of the tensor.
#define ARM_COMPUTE_ERROR_ON_MISMATCHING_DATA_TYPES(...)
Definition: Validate.h:543
void prepare() override
Prepare the function for executing.
bool are_weights_reshaped
Reshape the weights tensor if false.
Definition: Types.h:1617
void configure(const IGCTensor *input0, const IGCTensor *input1, IGCTensor *output, float alpha, bool is_interleaved_transposed=true, const GEMMReshapeInfo &reshape_info=GEMMReshapeInfo())
Initialise the kernel&#39;s input, output and alpha.
virtual ITensorInfo * info() const =0
Interface to be implemented by the child class to return the tensor&#39;s metadata.
void run() override
Run the kernels contained in the function.
Padding and stride information class.
Definition: Types.h:722
Weights manager interface to handle weights transformations.
#define ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(t, c,...)
Definition: Validate.h:790
virtual void allocate()=0
Interface to be implemented by the child class to allocate the tensor.
void configure(const IGCTensor *input, IGCTensor *output)
Set the input and output tensors.
std::array< T, num_max_dimensions >::const_iterator cend() const
Returns a read-only (constant) iterator that points one past the last element in the dimension array...
Definition: Dimensions.h:255
std::array< T, num_max_dimensions >::const_iterator cbegin() const
Returns a read-only (constant) iterator that points to the first element in the dimension array...
Definition: Dimensions.h:231
Memory group resources scope handling class.
Definition: IMemoryGroup.h:82
Class for specifying the size of an image or rectangle.
Definition: Size2D.h:34
Interface to enqueue GLES kernels and get/set the GLES CommandQueue.
bool transpose_weights
Transpose weights if true.
Definition: Types.h:1616
void configure(IGCTensor *accum, const IGCTensor *biases)
Set the accumulate buffer and the biases of the kernel.
Store the tensor&#39;s metadata.
Definition: TensorInfo.h:45
static constexpr size_t num_max_dimensions
Number of dimensions the tensor has.
Definition: Dimensions.h:46
DataType
Available data types.
Definition: Types.h:77
ITensorAllocator * allocator()
Return a pointer to the tensor&#39;s allocator.
Definition: GCTensor.cpp:34
GCFullyConnectedLayer(std::shared_ptr< IMemoryManager > memory_manager=nullptr, IWeightsManager *weights_manager=nullptr)
Constructor.
TensorShape & set(size_t dimension, size_t value, bool apply_dim_correction=true, bool increase_dim_unit=true)
Accessor to set the value of one of the dimensions.
Definition: TensorShape.h:79