Compute Library
 23.02.1
NEDeconvolutionLayer.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2017-2021, 2023 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 
27 #include "arm_compute/core/Utils.h"
31 #include "src/common/utils/Log.h"
33 
35 
36 namespace arm_compute
37 {
38 namespace
39 {
40 PadStrideInfo compute_upsample_info(const PadStrideInfo &info, uint32_t deconv_pad_x, uint32_t deconv_pad_y)
41 {
42  const unsigned int pad_left = info.pad_left();
43  const unsigned int pad_right = info.pad_right();
44  const unsigned int pad_top = info.pad_top();
45  const unsigned int pad_bottom = info.pad_bottom();
46  const unsigned int stride_x = info.stride().first;
47  const unsigned int stride_y = info.stride().second;
48 
49  // Find the upsampled dimensions and the padding needed for the convolution with stride 1 in order to match output shape
50  unsigned int deconv_pad_left = pad_right > pad_left ? pad_right - pad_left : 0;
51  unsigned int deconv_pad_right = pad_left > pad_right ? pad_left - pad_right : 0;
52  deconv_pad_x -= deconv_pad_left + deconv_pad_right;
53  ARM_COMPUTE_ERROR_ON((deconv_pad_x % 2) != 0);
54  deconv_pad_left += deconv_pad_x / 2;
55  deconv_pad_right += deconv_pad_x / 2;
56 
57  unsigned int deconv_pad_top = pad_bottom > pad_top ? pad_bottom - pad_top : 0;
58  unsigned int deconv_pad_bottom = pad_top > pad_bottom ? pad_top - pad_bottom : 0;
59  deconv_pad_y -= deconv_pad_top + deconv_pad_bottom;
60  ARM_COMPUTE_ERROR_ON((deconv_pad_y % 2) != 0);
61  deconv_pad_top += deconv_pad_y / 2;
62  deconv_pad_bottom += deconv_pad_y / 2;
63 
64  return PadStrideInfo(stride_x, stride_y, deconv_pad_left, deconv_pad_right, deconv_pad_top, deconv_pad_bottom, DimensionRoundingType::FLOOR);
65 }
66 
67 } // namespace
68 
69 NEDeconvolutionLayer::NEDeconvolutionLayer(std::shared_ptr<IMemoryManager> memory_manager) // NOLINT
70  : _memory_group(std::move(memory_manager)),
71  _conv_f(),
72  _upsample_f(),
73  _flip_weights(),
74  _scaled_output(),
75  _weights_flipped(),
76  _flip_axis(),
77  _original_weights(nullptr),
78  _input(nullptr),
79  _info(),
80  _is_prepared(false),
81  _do_upsampling(true)
82 {
83 }
84 
85 Status NEDeconvolutionLayer::validate(const ITensorInfo *input, const ITensorInfo *weights, const ITensorInfo *bias, const ITensorInfo *output, const PadStrideInfo &info, bool enable_fast_math)
86 {
87  ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(input, weights, output);
89  const unsigned int width_idx = get_data_layout_dimension_index(weights->data_layout(), DataLayoutDimension::WIDTH);
90  const unsigned int height_idx = get_data_layout_dimension_index(weights->data_layout(), DataLayoutDimension::HEIGHT);
91  ARM_COMPUTE_RETURN_ERROR_ON(weights->dimension(width_idx) != weights->dimension(height_idx));
92  ARM_COMPUTE_RETURN_ERROR_ON(weights->dimension(width_idx) < 1);
95  {
97  }
98  else
99  {
101  }
102 
103  auto out_dims = deconvolution_output_dimensions(input->dimension(width_idx), input->dimension(height_idx), weights->dimension(width_idx), weights->dimension(height_idx), info);
104 
105  if(bias != nullptr)
106  {
108  {
110  }
111  else
112  {
114  }
115  }
116 
117  if(output->tensor_shape().total_size() > 0)
118  {
120 
121  const TensorShape output_shape = compute_deconvolution_output_shape(out_dims, *input, *weights);
122 
123  ARM_COMPUTE_RETURN_ERROR_ON_MSG(output->dimension(Window::DimX) != output_shape.x(), "Output's width is invalid.");
124  ARM_COMPUTE_RETURN_ERROR_ON_MSG(output->dimension(Window::DimY) != output_shape.y(), "Output's height is invalid.");
125  ARM_COMPUTE_RETURN_ERROR_ON_MSG(output->dimension(Window::DimZ) != output_shape.z(), "Output's depth is invalid.");
126  }
127 
128  uint32_t deconv_pad_x = 0;
129  uint32_t deconv_pad_y = 0;
130  const unsigned int stride_x = info.stride().first;
131  const unsigned int stride_y = info.stride().second;
132  // Guard against overflows in compute_deconvolution_upsampled_shape()
133  const DataLayout data_layout = input->data_layout();
134  const size_t idx_w = get_data_layout_dimension_index(data_layout, DataLayoutDimension::WIDTH);
135  const size_t idx_h = get_data_layout_dimension_index(data_layout, DataLayoutDimension::HEIGHT);
136  const unsigned int out_x = (input->dimension(idx_w) - 1) * stride_x + 1;
137  const unsigned int out_y = (input->dimension(idx_h) - 1) * stride_y + 1;
138  ARM_COMPUTE_RETURN_ERROR_ON(weights->dimension(idx_w) > out_x);
139  ARM_COMPUTE_RETURN_ERROR_ON(weights->dimension(idx_h) > out_y);
140  ARM_COMPUTE_RETURN_ERROR_ON((out_x - weights->dimension(idx_w) + 1) > out_dims.first);
141  ARM_COMPUTE_RETURN_ERROR_ON((out_y - weights->dimension(idx_h) + 1) > out_dims.second);
142 
143  const TensorShape scale_out_shape = compute_deconvolution_upsampled_shape(*input, *weights, stride_x, stride_y, out_dims, deconv_pad_x, deconv_pad_y);
144  TensorInfo scale_out_info(input->clone()->set_is_resizable(true).reset_padding().set_tensor_shape(scale_out_shape));
145  const PadStrideInfo conv_info(1, 1, 0, 0, 0, 0, DimensionRoundingType::CEIL);
146 
147  const unsigned int batches_idx = get_data_layout_dimension_index(weights->data_layout(), DataLayoutDimension::BATCHES);
148  const unsigned int channel_idx = get_data_layout_dimension_index(weights->data_layout(), DataLayoutDimension::CHANNEL);
149  ARM_COMPUTE_RETURN_ERROR_ON(input->dimension(batches_idx) != scale_out_info.dimension(batches_idx));
150  ARM_COMPUTE_RETURN_ERROR_ON(input->dimension(channel_idx) != scale_out_info.dimension(channel_idx));
151 
152  ARM_COMPUTE_RETURN_ON_ERROR(NEConvolutionLayer::validate(&scale_out_info, weights, bias, output, conv_info, WeightsInfo(), Size2D(1U, 1U), ActivationLayerInfo(), enable_fast_math));
153 
154  return Status{};
155 }
156 
157 void NEDeconvolutionLayer::configure(ITensor *input, const ITensor *weights, const ITensor *bias, ITensor *output, const PadStrideInfo &info, bool enable_fast_math)
158 {
159  // Perform validation step
160  ARM_COMPUTE_ERROR_ON_NULLPTR(input, weights, output);
161  ARM_COMPUTE_ERROR_THROW_ON(NEDeconvolutionLayer::validate(input->info(), weights->info(), (bias == nullptr) ? nullptr : bias->info(), output->info(), info, enable_fast_math));
162  ARM_COMPUTE_LOG_PARAMS(input, weights, bias, output, info, enable_fast_math);
163 
164  const DataLayout data_layout = input->info()->data_layout();
165  const unsigned int width_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::WIDTH);
166  const unsigned int height_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::HEIGHT);
167  auto out_dims = deconvolution_output_dimensions(input->info()->dimension(width_idx), input->info()->dimension(height_idx),
168  weights->info()->dimension(width_idx), weights->info()->dimension(height_idx), info);
169 
170  const TensorShape output_shape = compute_deconvolution_output_shape(out_dims, *input->info(), *weights->info());
171 
172  _input = input;
173  _original_weights = weights;
174  _info = info;
175  _is_prepared = false;
176 
177  const unsigned int stride_x = info.stride().first;
178  const unsigned int stride_y = info.stride().second;
179 
180  // Do not perform upsampling when input is unit stride and weight shape is 1x1
181  _do_upsampling = stride_x != 1 || stride_y != 1 || weights->info()->dimension(width_idx) != 1 || weights->info()->dimension(height_idx) != 1;
182 
183  // Output auto initialization if not yet initialized
184  auto_init_if_empty(*output->info(), output_shape, 1, input->info()->data_type(), input->info()->quantization_info());
185 
186  _flip_axis.allocator()->init(TensorInfo(TensorShape(2U), 1, DataType::U32));
187 
188  _weights_flipped.allocator()->init(weights->info()->clone()->set_data_layout(data_layout));
189  _flip_weights.configure(weights, &_weights_flipped, &_flip_axis);
190 
191  // setup the function to convolve the upscaled output
192  const PadStrideInfo conv_info(1, 1, 0, 0, 0, 0, DimensionRoundingType::CEIL);
193  uint32_t deconv_pad_x = 0;
194  uint32_t deconv_pad_y = 0;
195 
196  // Setup flip axis data
197  _flip_axis.allocator()->allocate();
198  auto axis_data = reinterpret_cast<uint32_t *>(_flip_axis.buffer());
199  axis_data[0] = static_cast<uint32_t>(width_idx);
200  axis_data[1] = static_cast<uint32_t>(height_idx);
201 
202  // Setup convolution and upsampling, if needed
203  if (_do_upsampling)
204  {
205  _memory_group.manage(&_scaled_output);
206  const TensorShape scale_out_shape = compute_deconvolution_upsampled_shape(*input->info(), *weights->info(),
207  stride_x, stride_y,
208  out_dims, deconv_pad_x, deconv_pad_y);
209 
210  const PadStrideInfo upsample_info = compute_upsample_info(info, deconv_pad_x, deconv_pad_y);
211 
212  TensorInfo scale_out_info(scale_out_shape, 1, input->info()->data_type(), input->info()->quantization_info());
213  scale_out_info.set_data_layout(data_layout);
214  _scaled_output.allocator()->init(scale_out_info);
215 
216  _upsample_f.configure(input, &_scaled_output, upsample_info);
217 
218  _conv_f.configure(&_scaled_output, &_weights_flipped, bias, output, conv_info, WeightsInfo(), Size2D(1U, 1U), ActivationLayerInfo(), enable_fast_math);
219 
220  _scaled_output.allocator()->allocate();
221  }
222  else
223  {
224  _conv_f.configure(input, &_weights_flipped, bias, output, conv_info, WeightsInfo(), Size2D(1U, 1U), ActivationLayerInfo(), enable_fast_math);
225  }
226 }
227 
229 {
230  prepare();
231 
232  MemoryGroupResourceScope scope_mg(_memory_group);
233 
234  if(_do_upsampling)
235  {
236  _upsample_f.run();
237  }
238  _conv_f.run();
239 }
240 
242 {
243  if(!_is_prepared)
244  {
245  ARM_COMPUTE_ERROR_ON(!_original_weights->is_used());
246 
247  // Run weights flipping and mark original weights tensor as unused
248  _weights_flipped.allocator()->allocate();
249  _flip_weights.run();
250  _original_weights->mark_as_unused();
251 
252  // Prepare convolution
253  _conv_f.prepare();
254 
255  _is_prepared = true;
256  }
257 }
258 } // namespace arm_compute
bool is_data_type_quantized(DataType dt)
Check if a given data type is of quantized type.
Definition: Utils.h:1030
Shape of a tensor.
Definition: TensorShape.h:39
void run() override final
Run the kernels contained in the function.
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_LAYOUT(...)
Definition: Validate.h:490
void init(const TensorAllocator &allocator, const Coordinates &coords, TensorInfo &sub_info)
Shares the same backing memory with another tensor allocator, while the tensor info might be differen...
virtual size_t dimension(size_t index) const =0
Return the size of the requested dimension.
std::pair< unsigned int, unsigned int > deconvolution_output_dimensions(unsigned int in_width, unsigned int in_height, unsigned int kernel_width, unsigned int kernel_height, const PadStrideInfo &pad_stride_info)
Returns expected width and height of the deconvolution&#39;s output tensor.
Definition: Utils.cpp:409
void run() override
Run the kernels contained in the function.
#define ARM_COMPUTE_RETURN_ON_ERROR(status)
Checks if a status contains an error and returns it.
Definition: Error.h:204
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
#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(ITensor *input, const ITensor *weights, const ITensor *biases, ITensor *output, const PadStrideInfo &conv_info, const WeightsInfo &weights_info=WeightsInfo(), const Size2D &dilation=Size2D(1U, 1U), const ActivationLayerInfo &act_info=ActivationLayerInfo(), bool enable_fast_math=false, unsigned int num_groups=1)
Set the input and output tensors.
Store the tensor&#39;s metadata.
Definition: ITensorInfo.h:40
#define ARM_COMPUTE_ERROR_THROW_ON(status)
Definition: Error.h:455
void configure(ITensor *input, const ITensor *weights, const ITensor *bias, ITensor *output, const PadStrideInfo &info, bool enable_fast_math=false)
Set the input, weights, biases and output tensors.
Status class.
Definition: Error.h:52
#define ARM_COMPUTE_RETURN_ERROR_ON(cond)
If the condition is true, an error is returned.
Definition: Error.h:296
Activation Layer Information class.
Definition: Types.h:1641
Interface for CPU tensor.
Definition: ITensor.h:36
Copyright (c) 2017-2023 Arm Limited.
1 channel, 1 F16 per channel
void configure(const ITensor *input, ITensor *output, const ITensor *axis)
Initialize the function.
Definition: NEReverse.cpp:32
TensorAllocator * allocator()
Return a pointer to the tensor&#39;s allocator.
Definition: Tensor.cpp:48
Convolution Layer Weights Information class.
Definition: Types.h:2075
#define ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(...)
Definition: Validate.h:159
void run() override
Run the kernels contained in the function.
TensorShape compute_deconvolution_output_shape(const std::pair< unsigned int, unsigned int > &out_dims, const ITensorInfo &input, const ITensorInfo &weights)
Calculate the output shape of the deconvolution layer.
void mark_as_unused() const
Marks a tensor as unused.
Definition: ITensor.cpp:168
1 channel, 1 S32 per channel
void manage(IMemoryManageable *obj) override
Sets a object to be managed by the given memory group.
Definition: MemoryGroup.h:79
static Status validate(const ITensorInfo *input, const ITensorInfo *weights, const ITensorInfo *bias, const ITensorInfo *output, const PadStrideInfo &info, bool enable_fast_math=false)
Static function to check if given info will lead to a valid configuration of NEDeconvolutionLayer.
T x() const
Alias to access the size of the first dimension.
Definition: Dimensions.h:87
ITensorInfo & set_data_layout(const DataLayout &data_layout) override
Set the data layout of the tensor.
Definition: TensorInfo.cpp:386
static constexpr size_t DimX
Alias for dimension 0 also known as X dimension.
Definition: Window.h:43
1 channel, 1 U32 per channel
bool is_data_type_quantized_per_channel(DataType dt)
Check if a given data type is of per channel type.
Definition: Utils.h:1107
virtual const TensorShape & tensor_shape() const =0
Size for each dimension of the tensor.
quantized, asymmetric fixed-point 8-bit number unsigned
T z() const
Alias to access the size of the third dimension.
Definition: Dimensions.h:97
void allocate() override
Allocate size specified by TensorInfo of CPU memory.
std::pair< unsigned int, unsigned int > stride() const
Get the stride.
Definition: Types.h:719
size_t total_size() const
Collapses all dimensions to a single linear total size.
Definition: TensorShape.h:172
bool auto_init_if_empty(ITensorInfo &info, const TensorShape &shape, int num_channels, DataType data_type, QuantizationInfo quantization_info=QuantizationInfo())
Auto initialize the tensor info (shape, number of channels and data type) if the current assignment i...
virtual std::unique_ptr< T > clone() const =0
Provide a clone of the current object of class T.
virtual ITensorInfo * info() const =0
Interface to be implemented by the child class to return the tensor&#39;s metadata.
TensorShape compute_deconvolution_upsampled_shape(const ITensorInfo &input, const ITensorInfo &weights, unsigned int sx, unsigned int sy, std::pair< unsigned int, unsigned int > &out_dims, uint32_t &padx, uint32_t &pady)
Calculate the upsampled output shape used for deconvolution.
Padding and stride information class.
Definition: Types.h:671
virtual QuantizationInfo quantization_info() const =0
Get the quantization settings (scale and offset) of the tensor.
bool is_data_type_quantized_asymmetric(DataType dt)
Check if a given data type is of asymmetric quantized type.
Definition: Utils.h:1052
quantized, symmetric per channel fixed-point 8-bit number
static constexpr size_t DimY
Alias for dimension 1 also known as Y dimension.
Definition: Window.h:45
ScaleKernelInfo info(interpolation_policy, default_border_mode, PixelValue(), sampling_policy, false)
NEDeconvolutionLayer(std::shared_ptr< IMemoryManager > memory_manager=nullptr)
Constructor.
Memory group resources scope handling class.
Definition: IMemoryGroup.h:82
void prepare() override
Prepare the function for executing.
static constexpr size_t DimZ
Alias for dimension 2 also known as Z dimension.
Definition: Window.h:47
size_t get_data_layout_dimension_index(const DataLayout &data_layout, const DataLayoutDimension &data_layout_dimension)
Get the index of the given dimension.
Definition: Helpers.inl:193
Class for specifying the size of an image or rectangle.
Definition: Size2D.h:34
void configure(const ITensor *input, ITensor *output, const PadStrideInfo &info)
Configure the upsample CPP kernel.
Definition: CPPUpsample.cpp:32
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(...)
Definition: Validate.h:541
#define ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(t, c,...)
Definition: Validate.h:788
uint8_t * buffer() const override
Interface to be implemented by the child class to return a pointer to CPU memory. ...
Definition: Tensor.cpp:43
#define ARM_COMPUTE_RETURN_ERROR_ON_MSG(cond, msg)
If the condition is true, an error is returned.
Definition: Error.h:244
#define ARM_COMPUTE_LOG_PARAMS(...)
#define ARM_COMPUTE_ERROR_ON_NULLPTR(...)
Definition: Validate.h:157
Store the tensor&#39;s metadata.
Definition: TensorInfo.h:43
void run() override final
Run the kernels contained in the function.
T y() const
Alias to access the size of the second dimension.
Definition: Dimensions.h:92
quantized, asymmetric fixed-point 8-bit number signed
DataLayout
[DataLayout enum definition]
Definition: Types.h:113
static Status validate(const ITensorInfo *input, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *output, const PadStrideInfo &conv_info, const WeightsInfo &weights_info=WeightsInfo(), const Size2D &dilation=Size2D(1U, 1U), const ActivationLayerInfo &act_info=ActivationLayerInfo(), bool enable_fast_math=false, unsigned int num_groups=1)
Static function to check if given info will lead to a valid configuration of NEConvolutionLayer.
void prepare() override
Prepare the function for executing.
virtual DataLayout data_layout() const =0
Get the data layout of the tensor.
const int32_t * bias