267228eac0c4acbf427931043a813ee26a631216
[platform/core/ml/nnfw.git] / compute / ARMComputeEx / src / runtime / CL / functions / CLArgMinMaxLayerEx.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) 2018-2020 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/CLArgMinMaxLayerEx.h"
42
43 #include "arm_compute/core/Error.h"
44 #include "arm_compute/core/TensorInfo.h"
45 #include "arm_compute/core/Types.h"
46 #include "arm_compute/core/Validate.h"
47 #include "arm_compute/core/utils/misc/ShapeCalculator.h"
48 #include "arm_compute/runtime/Utils.h"
49
50 namespace arm_compute
51 {
52 CLArgMinMaxLayerEx::CLArgMinMaxLayerEx(std::shared_ptr<IMemoryManager> memory_manager)
53     : _memory_group(std::move(memory_manager)), _results_vector(), _not_reshaped_output(),
54       _reduction_kernels_vector(), _reshape_kernel(), _num_of_stages(), _reduction_axis()
55 {
56 }
57
58 Status CLArgMinMaxLayerEx::validate(const ITensorInfo *input, int axis, const ITensorInfo *output,
59                                     const ReductionOperation &op)
60 {
61   ARM_COMPUTE_ERROR_ON_NULLPTR(input, output);
62   ARM_COMPUTE_RETURN_ERROR_ON_MSG(op != ReductionOperation::ARG_IDX_MAX &&
63                                       op != ReductionOperation::ARG_IDX_MIN,
64                                   "Invalid reduction operation");
65   ARM_COMPUTE_RETURN_ERROR_ON_MSG(axis >= static_cast<int>(TensorShape::num_max_dimensions),
66                                   "Reduction axis greater than max number of dimensions");
67   ARM_COMPUTE_RETURN_ERROR_ON_MSG(axis > 3, "Unsupported reduction axis");
68   const unsigned int num_of_stages =
69       calculate_number_of_stages_only_x_axis(input->dimension(0), axis);
70
71   DataType output_data_type = DataType::S32;
72   TensorInfo not_reshaped_output;
73   const auto input_num_channles = input->num_channels();
74   const auto input_qinfo = input->quantization_info();
75
76   if (output->total_size() != 0)
77   {
78     output_data_type = output->data_type();
79     const TensorInfo expected_output_shape = output->clone()->set_tensor_shape(
80         arm_compute::misc::shape_calculator::compute_reduced_shape(input->tensor_shape(), axis,
81                                                                    false));
82     ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(&expected_output_shape, output);
83   }
84
85   auto shape_before_reshape = input->tensor_shape();
86   shape_before_reshape.set(axis, 1);
87   auto initialize_tensorinfo = [](TensorInfo &ti, TensorShape shape, DataType data_type,
88                                   int num_channels, QuantizationInfo qinfo) {
89     ti.set_data_type(data_type)
90         .set_tensor_shape(shape)
91         .set_num_channels(num_channels)
92         .set_quantization_info(qinfo);
93   };
94
95   initialize_tensorinfo(not_reshaped_output, shape_before_reshape, output_data_type,
96                         input_num_channles, input_qinfo);
97
98   if (num_of_stages == 1)
99   {
100     ARM_COMPUTE_RETURN_ON_ERROR(
101         CLArgMinMaxLayerKernelEx::validate(input, nullptr, &not_reshaped_output, axis, op));
102   }
103   else
104   {
105     // Create temporary tensor infos
106     std::vector<TensorInfo> sums_vector(num_of_stages - 1);
107
108     // Create intermediate tensor info
109     TensorShape shape{input->tensor_shape()};
110
111     for (unsigned int i = 0; i < num_of_stages - 1; i++)
112     {
113       shape.set(0, ceil(shape.x() / 128.f));
114       sums_vector[i].set_data_type(input->data_type());
115       sums_vector[i].set_tensor_shape(shape);
116       sums_vector[i].set_num_channels(input->num_channels());
117     }
118
119     // Validate ReductionOperation only on first kernel
120     ARM_COMPUTE_RETURN_ON_ERROR(
121         CLArgMinMaxLayerKernelEx::validate(input, nullptr, &sums_vector[0], axis, op));
122
123     // Validate ReductionOperation on intermediate stages
124     for (unsigned int i = 1; i < num_of_stages - 1; ++i)
125     {
126       ARM_COMPUTE_RETURN_ON_ERROR(CLArgMinMaxLayerKernelEx::validate(input, &sums_vector[i - 1],
127                                                                      &sums_vector[i], axis, op));
128     }
129
130     // Validate ReductionOperation on the last stage
131     const unsigned int last_stage = num_of_stages - 1;
132     ARM_COMPUTE_RETURN_ON_ERROR(CLArgMinMaxLayerKernelEx::validate(
133         input, &sums_vector[last_stage - 1], &not_reshaped_output, axis, op));
134   }
135   ARM_COMPUTE_RETURN_ON_ERROR(CLReshapeLayerKernel::validate(&not_reshaped_output, output));
136   return Status{};
137 }
138
139 void CLArgMinMaxLayerEx::configure(const ICLTensor *input, int axis, ICLTensor *output,
140                                    const ReductionOperation &op)
141 {
142   ARM_COMPUTE_ERROR_ON_NULLPTR(input, output);
143   _num_of_stages = calculate_number_of_stages_only_x_axis(input->info()->dimension(0), axis);
144   _reduction_axis = axis;
145
146   const TensorShape output_shape = arm_compute::misc::shape_calculator::compute_reduced_shape(
147       input->info()->tensor_shape(), axis, false);
148   DataType output_data_type = (output->info()->data_type() == DataType::UNKNOWN)
149                                   ? DataType::S32
150                                   : output->info()->data_type();
151   auto_init_if_empty(*output->info(), input->info()
152                                           ->clone()
153                                           ->set_tensor_shape(output_shape)
154                                           .set_data_type(output_data_type)
155                                           .reset_padding()
156                                           .set_is_resizable(true));
157
158   // Configure reduction operation kernels
159   _reduction_kernels_vector.resize(_num_of_stages);
160
161   _memory_group.manage(&_not_reshaped_output);
162   // Create temporary tensors
163   if (_num_of_stages == 1)
164   {
165     // Force an early initialization for int64 output type
166     TensorShape output_shape{input->info()->tensor_shape()};
167     output_shape.set(axis, 1);
168     auto_init_if_empty(*_not_reshaped_output.info(), input->info()
169                                                          ->clone()
170                                                          ->set_tensor_shape(output_shape)
171                                                          .set_data_type(output_data_type)
172                                                          .reset_padding()
173                                                          .set_is_resizable(true));
174     _not_reshaped_output.info()->set_tensor_shape(output_shape);
175     _reduction_kernels_vector[0].configure(input, nullptr, &_not_reshaped_output, axis, op);
176   }
177   else
178   {
179     _results_vector.resize(_num_of_stages - 1);
180     TensorShape shape{input->info()->tensor_shape()};
181     for (unsigned int i = 0; i < _num_of_stages - 1; i++)
182     {
183       shape.set(0, ceil(shape.x() / 128.f));
184       _results_vector[i].allocator()->init(
185           input->info()->clone()->set_tensor_shape(shape).set_data_type(output_data_type));
186     }
187
188     // Apply ReductionOperation only on first kernel
189     _memory_group.manage(&_results_vector[0]);
190     _reduction_kernels_vector[0].configure(input, nullptr, &_results_vector[0], axis, op);
191
192     // Apply ReductionOperation on intermediate stages
193     for (unsigned int i = 1; i < _num_of_stages - 1; ++i)
194     {
195       _memory_group.manage(&_results_vector[i]);
196       _reduction_kernels_vector[i].configure(input, &_results_vector[i - 1], &_results_vector[i],
197                                              axis, op);
198       _results_vector[i - 1].allocator()->allocate();
199     }
200
201     // Apply ReductionOperation on the last stage
202     const unsigned int last_stage = _num_of_stages - 1;
203     _reduction_kernels_vector[last_stage].configure(input, &_results_vector[last_stage - 1],
204                                                     &_not_reshaped_output, axis, op);
205     _results_vector[last_stage - 1].allocator()->allocate();
206   }
207   _reshape_kernel.configure(&_not_reshaped_output, output);
208   _not_reshaped_output.allocator()->allocate();
209 }
210
211 void CLArgMinMaxLayerEx::run()
212 {
213   MemoryGroupResourceScope scope_mg(_memory_group);
214
215   for (unsigned int i = 0; i < _num_of_stages; ++i)
216   {
217     CLScheduler::get().enqueue(_reduction_kernels_vector[i], false);
218   }
219   CLScheduler::get().enqueue(_reshape_kernel, false);
220 }
221 } // namespace arm_compute