• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2019-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 #include "arm_compute/runtime/NEON/functions/NEFFTConvolutionLayer.h"
25 
26 #include "arm_compute/core/ITensor.h"
27 #include "arm_compute/core/Utils.h"
28 #include "arm_compute/core/Validate.h"
29 #include "arm_compute/core/utils/misc/ShapeCalculator.h"
30 #include "src/core/NEON/kernels/NECopyKernel.h"
31 #include "src/core/NEON/kernels/NEFFTDigitReverseKernel.h"
32 #include "src/core/NEON/kernels/NEFFTRadixStageKernel.h"
33 #include "src/core/NEON/kernels/NEFFTScaleKernel.h"
34 #include "src/core/NEON/kernels/NEPadLayerKernel.h"
35 #include "src/core/NEON/kernels/NEReductionOperationKernel.h"
36 #include "src/core/helpers/AutoConfiguration.h"
37 #include "src/core/utils/helpers/fft.h"
38 
39 #include "support/MemorySupport.h"
40 
41 namespace arm_compute
42 {
43 namespace
44 {
pad_decomposable(int N)45 int pad_decomposable(int N)
46 {
47     const auto supported_radix = NEFFTRadixStageKernel::supported_radix();
48 
49     int  pad           = 0;
50     bool is_decomposed = false;
51     while(!is_decomposed)
52     {
53         const auto decomposed_vector = arm_compute::helpers::fft::decompose_stages(N++, supported_radix);
54         is_decomposed                = !decomposed_vector.empty();
55         if(!is_decomposed)
56         {
57             ++pad;
58         }
59     }
60     return pad;
61 }
62 } // namespace
63 
NEFFTConvolutionLayer(std::shared_ptr<IMemoryManager> memory_manager)64 NEFFTConvolutionLayer::NEFFTConvolutionLayer(std::shared_ptr<IMemoryManager> memory_manager)
65     : _memory_group(memory_manager),
66       _flip_weights_func(),
67       _permute_input_func(),
68       _permute_output_func(),
69       _permute_weights_func(),
70       _permute_bias_func(),
71       _pad_input_func(),
72       _pad_weights_func(),
73       _transform_input_func(memory_manager),
74       _transform_weights_func(),
75       _itransform_output_func(memory_manager),
76       _prod_func(),
77       _reduce_func(),
78       _extract_output_func(),
79       _bias_add_func(),
80       _activation_layer_func(),
81       _permuted_input(),
82       _permuted_weights(),
83       _permuted_bias(),
84       _permuted_output(),
85       _padded_input(),
86       _padded_weights(),
87       _flip_axis(),
88       _flipped_weights(),
89       _transformed_input(),
90       _transformed_weights(),
91       _input_weights_product(),
92       _output_product(),
93       _output_reduced(),
94       _itransformed_output(),
95       _reshaped_output(),
96       _bias_output(),
97       _original_weights(nullptr),
98       _original_bias(nullptr),
99       _is_activationlayer_enabled(false),
100       _needs_permute(false),
101       _has_bias(false),
102       _is_prepared(false)
103 {
104 }
105 NEFFTConvolutionLayer::~NEFFTConvolutionLayer() = default;
106 
configure(ITensor * input,const ITensor * weights,const ITensor * biases,ITensor * output,const PadStrideInfo & conv_info,const ActivationLayerInfo & act_info)107 void NEFFTConvolutionLayer::configure(ITensor *input, const ITensor *weights, const ITensor *biases, ITensor *output, const PadStrideInfo &conv_info,
108                                       const ActivationLayerInfo &act_info)
109 {
110     _original_weights = weights;
111     _original_bias    = biases;
112 
113     // Flat if bias addition is required
114     _has_bias = biases != nullptr;
115 
116     // Get indices for the width and height
117     const size_t idx_width  = get_data_layout_dimension_index(input->info()->data_layout(), DataLayoutDimension::WIDTH);
118     const size_t idx_height = get_data_layout_dimension_index(input->info()->data_layout(), DataLayoutDimension::HEIGHT);
119 
120     // Input shape, kernel size and output tile
121     const Size2D input_dims  = Size2D(input->info()->tensor_shape()[idx_width], input->info()->tensor_shape()[idx_height]);
122     const Size2D kernel_size = Size2D(weights->info()->tensor_shape()[idx_width], weights->info()->tensor_shape()[idx_height]);
123     const Size2D pad_valid   = Size2D(pad_decomposable(input_dims.x() + kernel_size.x() - 1),
124                                       pad_decomposable(input_dims.y() + kernel_size.y() - 1));
125     // Tensors to use
126     ITensor       *input_to_use   = input;
127     const ITensor *weights_to_use = weights;
128     ITensor       *output_to_use  = _has_bias ? &_bias_output : output;
129 
130     // Permute bias
131     if(biases != nullptr)
132     {
133         _permute_bias_func.configure(biases, &_permuted_bias, PermutationVector(1U, 2U, 0U));
134         _permuted_bias.info()->set_data_layout(DataLayout::NCHW);
135     }
136 
137     // Permute input if needed
138     _needs_permute = input->info()->data_layout() == DataLayout::NHWC;
139     if(_needs_permute)
140     {
141         _memory_group.manage(&_permuted_input);
142         // Configure the function to transform the input tensor from NHWC -> NCHW
143         _permute_input_func.configure(input, &_permuted_input, PermutationVector(1U, 2U, 0U));
144         _permuted_input.info()->set_data_layout(DataLayout::NCHW);
145 
146         // Configure the function to transform the weights tensor from HWI -> IHW
147         _permute_weights_func.configure(weights, &_permuted_weights, PermutationVector(1U, 2U, 0U));
148         _permuted_weights.info()->set_data_layout(DataLayout::NCHW);
149 
150         input_to_use   = &_permuted_input;
151         weights_to_use = &_permuted_weights;
152     }
153 
154     // Flip weights
155     _flipped_weights.allocator()->init(weights_to_use->info()->clone()->set_is_resizable(true).reset_padding());
156     _flip_axis.allocator()->init(TensorInfo(TensorShape(2U), 1, DataType::U32));
157     _flip_weights_func.configure(weights_to_use, &_flipped_weights, &_flip_axis);
158 
159     // Pad weights
160     const PaddingList padding_w = { { 0, input_dims.x() + pad_valid.x() - 1 }, { 0, input_dims.y() + pad_valid.y() - 1 } };
161     _pad_weights_func.configure(&_flipped_weights, &_padded_weights, padding_w);
162 
163     // Transform weights
164     _transform_weights_func = support::cpp14::make_unique<NEFFT2D>();
165     _transform_weights_func->configure(&_padded_weights, &_transformed_weights, FFT2DInfo());
166 
167     // Pad input
168     const PaddingList padding_in = { { 0, kernel_size.x() + pad_valid.x() - 1 }, { 0, kernel_size.y() + pad_valid.y() - 1 } };
169     _memory_group.manage(&_padded_input);
170     _pad_input_func.configure(input_to_use, &_padded_input, padding_in);
171     if(_needs_permute)
172     {
173         _permuted_input.allocator()->allocate();
174     }
175 
176     // Transform input
177     _memory_group.manage(&_transformed_input);
178     _transform_input_func.configure(&_padded_input, &_transformed_input, FFT2DInfo());
179     _padded_input.allocator()->allocate();
180 
181     // Perform product
182     _memory_group.manage(&_output_product);
183     _prod_func.configure(&_transformed_input, &_transformed_weights, &_output_product);
184     _transformed_input.allocator()->allocate();
185 
186     // Perform reduction
187     _memory_group.manage(&_output_reduced);
188     _reduce_func.configure(&_output_product, &_output_reduced, 2, ReductionOperation::SUM);
189     _output_product.allocator()->allocate();
190 
191     // Transform output
192     _memory_group.manage(&_itransformed_output);
193     FFT2DInfo itranform_info;
194     itranform_info.direction = FFTDirection::Inverse;
195     _itransformed_output.allocator()->init(_output_reduced.info()->clone()->set_is_resizable(true).set_num_channels(1).reset_padding());
196     _itransform_output_func.configure(&_output_reduced, &_itransformed_output, itranform_info);
197     _output_reduced.allocator()->allocate();
198 
199     // Reshape output
200     TensorShape reshaped_shape = _itransformed_output.info()->tensor_shape();
201     reshaped_shape.remove_dimension(2);
202     _reshaped_output.allocator()->init(_itransformed_output.info()->clone()->set_tensor_shape(reshaped_shape));
203 
204     // Extract correct region
205     const int start_left = kernel_size.x() - conv_info.pad_left() - 1;
206     const int start_top  = kernel_size.y() - conv_info.pad_top() - 1;
207     const int end_right  = _reshaped_output.info()->tensor_shape().x() - (kernel_size.x() - conv_info.pad_right() - 1) - pad_valid.x();
208     const int end_botton = _reshaped_output.info()->tensor_shape().y() - (kernel_size.y() - conv_info.pad_bottom() - 1) - pad_valid.y();
209     if(_has_bias)
210     {
211         _memory_group.manage(&_bias_output);
212     }
213     else if(_needs_permute)
214     {
215         output_to_use = &_permuted_output;
216         _memory_group.manage(&_permuted_output);
217     }
218     _extract_output_func.configure(&_reshaped_output, output_to_use, Coordinates(start_left, start_top), Coordinates(end_right, end_botton));
219     _reshaped_output.allocator()->allocate();
220     _itransformed_output.allocator()->allocate();
221 
222     // Add bias
223     if(biases != nullptr)
224     {
225         output_to_use = output;
226         if(_needs_permute)
227         {
228             output_to_use = &_permuted_output;
229             _memory_group.manage(&_permuted_output);
230         }
231         auto_init_if_empty(*output_to_use->info(), *_bias_output.info());
232         _bias_add_func.configure(&_bias_output, &_permuted_bias, output_to_use, ConvertPolicy::WRAP);
233         _bias_output.allocator()->allocate();
234     }
235 
236     // Permute output
237     if(_needs_permute)
238     {
239         // Configure the function to transform the convoluted output to ACL's native ordering format NCHW
240         _permuted_output.info()->set_data_layout(DataLayout::NCHW);
241         _permute_output_func.configure(&_permuted_output, output, PermutationVector(2U, 0U, 1U));
242 
243         // Allocate tensors
244         _permuted_output.allocator()->allocate();
245     }
246 
247     // Configure Activation Layer
248     _is_activationlayer_enabled = act_info.enabled();
249     if(_is_activationlayer_enabled)
250     {
251         _activation_layer_func.configure(output, nullptr, act_info);
252     }
253 
254     // Setup flip axis data
255     _flip_axis.allocator()->allocate();
256 
257     auto axis_data = reinterpret_cast<uint32_t *>(_flip_axis.buffer());
258     axis_data[0]   = 0;
259     axis_data[1]   = 1;
260 }
261 
validate(const ITensorInfo * input,const ITensorInfo * weights,const ITensorInfo * biases,const ITensorInfo * output,const PadStrideInfo & conv_info,const ActivationLayerInfo & act_info)262 Status NEFFTConvolutionLayer::validate(const ITensorInfo *input, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *output, const PadStrideInfo &conv_info,
263                                        const ActivationLayerInfo &act_info)
264 {
265     ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input, 1, DataType::F32);
266     ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, weights);
267 
268     // Get indices for the width and height
269     const size_t idx_width  = get_data_layout_dimension_index(input->data_layout(), DataLayoutDimension::WIDTH);
270     const size_t idx_height = get_data_layout_dimension_index(input->data_layout(), DataLayoutDimension::HEIGHT);
271 
272     // Input shape, kernel size and output tile
273     const Size2D kernel_size = Size2D(weights->tensor_shape()[idx_width], weights->tensor_shape()[idx_height]);
274 
275     // Strides
276     const auto strides = conv_info.stride();
277     ARM_COMPUTE_RETURN_ERROR_ON(strides.first != strides.second && strides.first != 1);
278     ARM_COMPUTE_RETURN_ERROR_ON(kernel_size.x() != kernel_size.y());
279     ARM_COMPUTE_RETURN_ERROR_ON(conv_info.pad_left() != (kernel_size.x() / 2) || conv_info.pad_right() != (kernel_size.x() / 2));
280     ARM_COMPUTE_RETURN_ERROR_ON(conv_info.pad_top() != (kernel_size.y() / 2) || conv_info.pad_bottom() != (kernel_size.y() / 2));
281 
282     // Validate biases
283     if(biases != nullptr)
284     {
285         const size_t idx_channels = get_data_layout_dimension_index(input->data_layout(), DataLayoutDimension::CHANNEL);
286         ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, biases);
287         ARM_COMPUTE_RETURN_ERROR_ON(input->tensor_shape()[idx_channels] != biases->tensor_shape().x());
288     }
289 
290     // Checks performed when output is configured
291     if((output != nullptr) && (output->total_size() != 0))
292     {
293         ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, output);
294         ARM_COMPUTE_RETURN_ERROR_ON((input->tensor_shape()[idx_height] != output->tensor_shape()[idx_height]) || (input->tensor_shape()[idx_width] != output->tensor_shape()[idx_width]));
295 
296         // Validate Activation Layer
297         if(act_info.enabled())
298         {
299             ARM_COMPUTE_RETURN_ON_ERROR(NEActivationLayer::validate(output, nullptr, act_info));
300         }
301     }
302 
303     return Status{};
304 }
305 
run()306 void NEFFTConvolutionLayer::run()
307 {
308     prepare();
309 
310     MemoryGroupResourceScope scope_mg(_memory_group);
311 
312     // Transform input
313     if(_needs_permute)
314     {
315         _permute_input_func.run();
316     }
317     _pad_input_func.run();
318     _transform_input_func.run();
319 
320     // Perform operations to frequency domain
321     _prod_func.run();
322 
323     _reduce_func.run();
324 
325     // Transform output
326     _itransform_output_func.run();
327     _reshaped_output.allocator()->import_memory(_itransformed_output.buffer());
328     _extract_output_func.run();
329 
330     // Add bias
331     if(_has_bias)
332     {
333         _bias_add_func.run();
334     }
335     if(_needs_permute)
336     {
337         _permute_output_func.run();
338     }
339 
340     // Run activation layer
341     if(_is_activationlayer_enabled)
342     {
343         _activation_layer_func.run();
344     }
345 }
346 
prepare()347 void NEFFTConvolutionLayer::prepare()
348 {
349     if(!_is_prepared)
350     {
351         // Permute bias to NCHW
352         if(_original_bias != nullptr)
353         {
354             _permuted_bias.allocator()->allocate();
355             _permute_bias_func.run();
356             _original_bias->mark_as_unused();
357         }
358 
359         const ITensor *cur_weights = _original_weights;
360 
361         // Permute weights
362         if(_needs_permute)
363         {
364             ARM_COMPUTE_ERROR_ON(!cur_weights->is_used());
365 
366             _permuted_weights.allocator()->allocate();
367             _permute_weights_func.run();
368             cur_weights->mark_as_unused();
369             cur_weights = &_permuted_weights;
370         }
371 
372         // Flip weights
373         _flipped_weights.allocator()->allocate();
374         _flip_weights_func.run();
375         cur_weights->mark_as_unused();
376 
377         // Pad weights
378         _padded_weights.allocator()->allocate();
379         _pad_weights_func.run();
380         _flipped_weights.mark_as_unused();
381         _flipped_weights.allocator()->free();
382 
383         // Transform weights to frequency domain
384         _transformed_weights.allocator()->allocate();
385         _transform_weights_func->run();
386         _transform_weights_func.reset();
387 
388         _padded_weights.mark_as_unused();
389         _padded_weights.allocator()->free();
390 
391         _is_prepared = true;
392     }
393 }
394 } // namespace arm_compute
395