Compute Library
 21.02
GCConvolutionLayer.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  */
24 
26 
29 #include "arm_compute/core/Utils.h"
32 
33 #include <cmath>
34 #include <tuple>
35 
36 using namespace arm_compute;
37 
39  : _weights_reshape_kernel()
40 {
41 }
42 
43 void GCConvolutionLayerReshapeWeights::configure(const IGCTensor *weights, const IGCTensor *biases, IGCTensor *output)
44 {
45  ARM_COMPUTE_ERROR_ON_NULLPTR(weights, output);
47  ARM_COMPUTE_ERROR_ON(weights->info()->num_dimensions() > 4);
48 
49  if(biases != nullptr)
50  {
53  ARM_COMPUTE_ERROR_ON(biases->info()->dimension(0) != weights->info()->dimension(3));
54  ARM_COMPUTE_ERROR_ON(biases->info()->num_dimensions() > 1);
55  }
56 
57  const bool append_biases = (biases != nullptr) && !is_data_type_quantized_asymmetric(weights->info()->data_type());
58  const IGCTensor *biases_to_use = (append_biases) ? biases : nullptr;
59 
60  _weights_reshape_kernel.configure(weights, biases_to_use, output);
61 }
62 
64 {
65  GCScheduler::get().dispatch(_weights_reshape_kernel);
66 }
67 
68 GCConvolutionLayer::GCConvolutionLayer(std::shared_ptr<IMemoryManager> memory_manager)
69  : _memory_group(std::move(memory_manager)), _reshape_weights(), _input_im2col_kernel(), _mm_gemm(), _output_col2im_kernel(), _fill_border(), _activationlayer_function(), _original_weights(nullptr),
70  _input_im2col_reshaped(), _input_interleaved_reshaped(), _weights_reshaped(), _weights_transposed(), _gemm_output(), _tmp_output(), _is_activationlayer_enabled(false), _is_prepared(false)
71 {
72 }
73 
74 void GCConvolutionLayer::configure_mm(const IGCTensor *input, const IGCTensor *weights, IGCTensor *output)
75 {
76  ARM_COMPUTE_ERROR_ON_NULLPTR(input, weights);
77  ARM_COMPUTE_ERROR_THROW_ON(validate_mm(input->info(), weights->info(), output->info()));
78 
79  _mm_gemm.configure(input, weights, nullptr, output, 1.f, 0.0f, GEMMInfo(false, false, true /* Reshape weights only for the first run */));
80 }
81 
82 Status GCConvolutionLayer::validate_mm(const ITensorInfo *input, const ITensorInfo *weights, const ITensorInfo *output)
83 {
84  // Perform validation step on Matrix multiply function
85  GCGEMM::validate(input, weights, nullptr, output, 1.0f, 0.0f, GEMMInfo(false, false, true /* Reshape weights only for the first run */));
86  return Status{};
87 }
88 
89 void GCConvolutionLayer::configure(const IGCTensor *input, const IGCTensor *weights, const IGCTensor *biases, IGCTensor *output, const PadStrideInfo &conv_info, const WeightsInfo &weights_info,
90  const Size2D &dilation, const ActivationLayerInfo &act_info, unsigned int num_groups)
91 {
92  ARM_COMPUTE_ERROR_ON_NULLPTR(input, weights);
95  ARM_COMPUTE_ERROR_ON_MSG(weights_info.are_reshaped(), "Weights already reshaped are not supported!");
96  ARM_COMPUTE_ERROR_ON(weights->info()->dimension(2) != input->info()->dimension(2));
97  ARM_COMPUTE_ERROR_ON(weights->info()->num_dimensions() > 4);
98  ARM_COMPUTE_ERROR_ON(num_groups > 1);
99  ARM_COMPUTE_UNUSED(num_groups);
100 
101  _is_prepared = false;
102  _original_weights = weights;
103 
104  if(biases != nullptr)
105  {
107  ARM_COMPUTE_ERROR_ON(biases->info()->dimension(0) != weights->info()->dimension(3));
108  ARM_COMPUTE_ERROR_ON(biases->info()->num_dimensions() > 1);
109  }
110 
111  const DataType dt = input->info()->data_type();
112 
113  // Set the GPU target for im2col and col2im
114  _input_im2col_kernel.set_target(GCScheduler::get().get_target());
115  _output_col2im_kernel.set_target(GCScheduler::get().get_target());
116 
117  const bool append_bias = (biases != nullptr);
118  const unsigned bias_element = (append_bias) ? 1 : 0;
119  const IGCTensor *biases_to_use = (append_bias) ? biases : nullptr;
120 
121  // Get parameters from conv_info
122  unsigned int stride_x = 0;
123  unsigned int stride_y = 0;
124  std::tie(stride_x, stride_y) = conv_info.stride();
125 
126  // Get convolved dimensions
127  unsigned int conv_w = 0;
128  unsigned int conv_h = 0;
129 
130  const unsigned int kernel_width = weights->info()->dimension(0);
131  const unsigned int kernel_height = weights->info()->dimension(1);
132  std::tie(conv_w, conv_h) = scaled_dimensions(input->info()->dimension(0), input->info()->dimension(1), kernel_width, kernel_height,
133  conv_info, dilation);
134 
135  unsigned int mat_weights_cols = weights->info()->dimension(3);
136  unsigned int mat_weights_rows = weights->info()->dimension(0) * weights->info()->dimension(1) * weights->info()->dimension(2) + bias_element;
137 
138  // _weights_reshaped will be auto configured in the kernel.
139  // Just append biases and do not transpose 1xW as it will be reshaped in GCGEMM
140  _reshape_weights.configure(weights, biases_to_use, &_weights_reshaped);
141 
142  weights = &_weights_reshaped;
143 
144  // Create tensor to store im2col reshaped inputs
145  const unsigned int mat_input_cols = mat_weights_rows;
146  const unsigned int mat_input_rows = conv_w * conv_h;
147  TensorShape shape_im2col = input->info()->tensor_shape();
148  shape_im2col.set(0, mat_input_cols);
149  shape_im2col.set(1, mat_input_rows);
150  shape_im2col.set(2, 1);
151 
152  // FIXME: input->clone() doesn't work with subtensors for grouped convolutions.
153  TensorInfo im2col_reshaped_info(shape_im2col, 1, dt);
154  _input_im2col_reshaped.allocator()->init(im2col_reshaped_info);
155  _memory_group.manage(&_input_im2col_reshaped);
156 
157  // Create GEMM output tensor
158  TensorShape shape_gemm = _input_im2col_reshaped.info()->tensor_shape();
159  shape_gemm.set(0, mat_weights_cols);
160  shape_gemm.set(1, mat_input_rows);
161  const DataType gemm_data_type = dt;
162 
163  // FIXME: input->clone() doesn't work with subtensors for grouped convolutions.
164  TensorInfo info_gemm(shape_gemm, 1, gemm_data_type);
165  _gemm_output.allocator()->init(info_gemm);
166  _memory_group.manage(&_gemm_output);
167 
168  if(dt == DataType::F16)
169  {
170  BorderSize border_size = BorderSize(conv_info.pad_top(), conv_info.pad_right(), conv_info.pad_bottom(), conv_info.pad_left());
171  input->info()->extend_padding(border_size);
172  _fill_border.configure(input, border_size, BorderMode::CONSTANT, PixelValue()); // for PAD of im2col fp16: consider it as border
173  }
174  // Configure im2col
175  _input_im2col_kernel.configure(input, &_input_im2col_reshaped, Size2D(kernel_width, kernel_height), conv_info, append_bias, dilation);
176 
177  // Configure GEMM
178  configure_mm(&_input_im2col_reshaped, weights, &_gemm_output);
179 
180  _input_im2col_reshaped.allocator()->allocate();
181 
182  // Configure Col2Im
183  _output_col2im_kernel.configure(&_gemm_output, output, std::make_pair(conv_w, conv_h));
184  _gemm_output.allocator()->allocate();
185 
186  ARM_COMPUTE_ERROR_ON_MSG((output->info()->dimension(0) != conv_w) || (output->info()->dimension(1) != conv_h), "Output shape does not match the expected one");
187 
188  //Configure Activation Layer
189  _is_activationlayer_enabled = act_info.enabled();
190 
191  if(_is_activationlayer_enabled)
192  {
193  _activationlayer_function.configure(output, nullptr, act_info);
194  }
195 
196  ARM_COMPUTE_UNUSED(weights_info);
197 }
198 
200 {
201  prepare();
202 
203  MemoryGroupResourceScope scope_mg(_memory_group);
204 
205  // Run im2col
206  GCScheduler::get().dispatch(_fill_border);
208  GCScheduler::get().dispatch(_input_im2col_kernel);
209 
210  // Run gemm on reshaped matrices
211  _mm_gemm.run();
213 
214  // Reshape output matrix
215  GCScheduler::get().dispatch(_output_col2im_kernel, false);
217 
218  // Run Activation Layer
219  if(_is_activationlayer_enabled)
220  {
221  _activationlayer_function.run();
222  }
223 }
224 
226 {
227  if(!_is_prepared)
228  {
229  ARM_COMPUTE_ERROR_ON(!_original_weights->is_used());
230 
231  // Run weights reshaping and mark as unused
232  _weights_reshaped.allocator()->allocate();
233  _reshape_weights.run();
234 
235  // Mark original weights tensor as unused
236  _original_weights->mark_as_unused();
237 
238  _is_prepared = true;
239  }
240 }
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)
Class describing the value of a pixel for any image format.
Definition: PixelValue.h:34
Shape of a tensor.
Definition: TensorShape.h:39
bool enabled() const
Check if initialised.
Definition: Types.h:1600
virtual size_t dimension(size_t index) const =0
Return the size of the requested dimension.
void prepare() override
Prepare the function for executing.
void dispatch(IGCKernel &kernel, bool flush=true)
Schedule the execution of the passed kernel if possible.
Definition: GCScheduler.cpp:77
Container for 2D border size.
Definition: Types.h:273
void run() override
Run the kernels contained in the function.
Definition: GCGEMM.cpp:161
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
bool are_reshaped() const
Flag which specifies if the weights tensor has been reshaped.
Definition: Types.h:1789
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
void configure(const IGCTensor *input, const IGCTensor *biases, IGCTensor *output)
Set the input and output of the kernel.
Store the tensor&#39;s metadata.
Definition: ITensorInfo.h:40
Interface for GLES Compute tensor.
Definition: IGCTensor.h:35
#define ARM_COMPUTE_ERROR_THROW_ON(status)
Definition: Error.h:455
Status class.
Definition: Error.h:52
Activation Layer Information class.
Definition: Types.h:1550
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
std::pair< unsigned int, unsigned int > scaled_dimensions(int width, int height, int kernel_width, int kernel_height, const PadStrideInfo &pad_stride_info, const Size2D &dilation=Size2D(1U, 1U))
Returns expected width and height of output scaled tensor depending on dimensions rounding mode...
Definition: Utils.cpp:419
void set_target(GPUTarget target)
Set the targeted GPU architecture.
Definition: IGCKernel.h:113
DataType dt
Convolution Layer Weights Information class.
Definition: Types.h:1765
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
void configure(const IGCTensor *weights, const IGCTensor *biases, IGCTensor *output)
Set the input and output tensors.
#define ARM_COMPUTE_UNUSED(...)
To avoid unused variables warnings.
Definition: Error.h:152
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
#define ARM_COMPUTE_ERROR_ON_MSG(cond, msg)
Definition: Error.h:456
const unsigned int num_groups
Definition: Im2Col.cpp:153
void run() override
Run the kernels contained in the function.
std::pair< unsigned int, unsigned int > stride() const
Get the stride.
Definition: Types.h:770
void configure(const IGCTensor *tensor, BorderSize border_size, BorderMode border_mode, const PixelValue &constant_border_value=PixelValue())
Initialise the kernel&#39;s input, output and border mode.
static Status validate(const ITensorInfo *a, const ITensorInfo *b, const IGCTensor *c, const ITensorInfo *output, const float alpha, const float beta, const GEMMInfo &gemm_info=GEMMInfo())
Static function to check if given info will lead to a valid configuration of GCGEMM.
Definition: GCGEMM.cpp:155
virtual ITensorInfo * info() const =0
Interface to be implemented by the child class to return the tensor&#39;s metadata.
Padding and stride information class.
Definition: Types.h:722
#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 run() override
Run the kernels contained in the function.
bool is_data_type_quantized_asymmetric(DataType dt)
Check if a given data type is of asymmetric quantized type.
Definition: Utils.h:1190
void configure(IGCTensor *input, IGCTensor *output, ActivationLayerInfo act_info)
Set the input and output tensor.
GCConvolutionLayer(std::shared_ptr< IMemoryManager > memory_manager=nullptr)
Default constructor.
Memory group resources scope handling class.
Definition: IMemoryGroup.h:82
TensorInfo * info() const override
Interface to be implemented by the child class to return the tensor&#39;s metadata.
Definition: GCTensor.cpp:39
void configure(const IGCTensor *input, const IGCTensor *weights, const IGCTensor *biases, IGCTensor *output, const PadStrideInfo &conv_info, const WeightsInfo &weights_info=WeightsInfo(), const Size2D &dilation=Size2D(1U, 1U), const ActivationLayerInfo &act_info=ActivationLayerInfo(), unsigned int num_groups=1)
Set the input and output tensors.
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.
#define ARM_COMPUTE_ERROR_ON_NULLPTR(...)
Definition: Validate.h:161
Store the tensor&#39;s metadata.
Definition: TensorInfo.h:45
GEMM information class.
Definition: Types.h:2003
void configure(const IGCTensor *a, const IGCTensor *b, const IGCTensor *c, IGCTensor *output, float alpha, float beta, const GEMMInfo &gemm_info=GEMMInfo())
Initialise the kernel&#39;s inputs and output.
Definition: GCGEMM.cpp:81
const TensorShape & tensor_shape() const override
Size for each dimension of the tensor.
Definition: TensorInfo.h:262
DataType
Available data types.
Definition: Types.h:77
ITensorAllocator * allocator()
Return a pointer to the tensor&#39;s allocator.
Definition: GCTensor.cpp:34
virtual bool extend_padding(const PaddingSize &padding)=0
Update the offset to the first element, the strides and the total size.
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
void configure(const IGCTensor *input, IGCTensor *output, std::pair< unsigned int, unsigned int > convolved_dims)
Set the input and output of the kernel.