Compute Library
 23.11
NEReduceMean.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2018-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 
26 #include "arm_compute/core/Error.h"
28 
29 #include "src/common/utils/Log.h"
30 #include "src/core/CPP/Validate.h"
33 
34 namespace arm_compute
35 {
36 namespace
37 {
38 Status
39 validate_config(const ITensorInfo *input, const Coordinates &reduction_axis, bool keep_dims, const ITensorInfo *output)
40 {
41  ARM_COMPUTE_UNUSED(keep_dims);
46  ARM_COMPUTE_RETURN_ERROR_ON(reduction_axis.num_dimensions() < 1);
47  ARM_COMPUTE_RETURN_ERROR_ON(reduction_axis.num_dimensions() > input->num_dimensions());
48 
49  const unsigned int reduction_ops = reduction_axis.num_dimensions();
50  const int input_dims = input->num_dimensions();
51  Coordinates axis_local = reduction_axis;
52 
53  for (unsigned int i = 0; i < axis_local.num_dimensions(); ++i)
54  {
55  //axis: The dimensions to reduce. Must be in the range [-rank(input_tensor), rank(input_tensor)).
56  ARM_COMPUTE_RETURN_ERROR_ON(axis_local[i] < (-static_cast<int>(input->num_dimensions())));
57  ARM_COMPUTE_RETURN_ERROR_ON(axis_local[i] >= static_cast<int>(input->num_dimensions()));
58  }
59 
60  if (output->tensor_shape().total_size() != 0)
61  {
62  // Only validate if not using auto_init for the output tensor
63  TensorShape out_shape = input->tensor_shape();
64  // Validate output_shape only if not using auto_init
65  convert_negative_axis(axis_local, input_dims);
66  std::sort(axis_local.begin(), axis_local.begin() + reduction_ops);
67  for (unsigned int i = 0; i < reduction_ops; ++i)
68  {
69  ARM_COMPUTE_RETURN_ERROR_ON(axis_local[i] > 3);
70  ARM_COMPUTE_RETURN_ERROR_ON(static_cast<unsigned int>(axis_local[i]) > input->num_dimensions() - 1);
71  if (output->total_size() > 0 && keep_dims)
72  {
73  ARM_COMPUTE_RETURN_ERROR_ON(output->dimension(axis_local[i]) != 1);
74  }
75  if (keep_dims)
76  {
77  out_shape.set(axis_local[i], 1);
78  }
79  else
80  {
81  ARM_COMPUTE_RETURN_ERROR_ON(i > static_cast<unsigned int>(axis_local[i]));
82  const unsigned int remove_index = axis_local[i] - i;
83  ARM_COMPUTE_RETURN_ERROR_ON(remove_index >= out_shape.num_dimensions());
84  out_shape.remove_dimension(remove_index, false);
85  }
86  }
87  const TensorInfo out_info = input->clone()->set_tensor_shape(out_shape);
89  }
90  return Status{};
91 }
92 } // namespace
93 
94 NEReduceMean::~NEReduceMean() = default;
95 
96 NEReduceMean::NEReduceMean(std::shared_ptr<IMemoryManager> memory_manager)
97  : _memory_group(std::move(memory_manager)),
98  _reduction_kernels(),
99  _reduced_outs(),
100  _reshape(),
101  _reduction_ops(),
102  _keep_dims()
103 {
104 }
105 
107  const Coordinates &reduction_axis,
108  bool keep_dims,
109  const ITensorInfo *output)
110 {
111  return validate_config(input, reduction_axis, keep_dims, output);
112 }
113 
114 void NEReduceMean::configure(ITensor *input, const Coordinates &reduction_axis, bool keep_dims, ITensor *output)
115 {
116  ARM_COMPUTE_LOG_PARAMS(input, reduction_axis, keep_dims, output);
117 
118  // Perform validate step
119  ARM_COMPUTE_ERROR_THROW_ON(NEReduceMean::validate(input->info(), reduction_axis, keep_dims, output->info()));
120  // Output auto inizialitation if not yet initialized
121  const TensorShape output_shape =
123  auto_init_if_empty(*output->info(), input->info()->clone()->set_tensor_shape(output_shape));
124 
125  _reduction_ops = reduction_axis.num_dimensions();
126  _reduction_kernels.resize(_reduction_ops);
127  _reduced_outs.resize(_reduction_ops - (keep_dims ? 1 : 0));
128  _keep_dims = keep_dims;
129 
130  ITensor *tmp_input = input;
131  ITensor *tmp_output = output;
132 
133  Coordinates axis_local = reduction_axis;
134  const int input_dims = tmp_input->info()->num_dimensions();
135 
136  convert_negative_axis(axis_local, input_dims);
137 
138  // Perform reduction for every axis
139  for (int i = 0; i < _reduction_ops; ++i)
140  {
141  TensorShape out_shape =
142  i == 0 ? tmp_input->info()->tensor_shape() : (&_reduced_outs[i - 1])->info()->tensor_shape();
143  out_shape.set(axis_local[i], 1);
144  auto in = (i == 0) ? tmp_input : (&_reduced_outs[i - 1]);
145 
146  if (i == _reduction_ops - 1 && keep_dims)
147  {
148  _reduction_kernels[i].configure(in, tmp_output, axis_local[i], ReductionOperation::MEAN_SUM);
149  }
150  else
151  {
152  _reduced_outs[i].allocator()->init(TensorInfo(out_shape, tmp_output->info()->num_channels(),
153  tmp_output->info()->data_type(),
154  tmp_output->info()->quantization_info()));
155  _memory_group.manage(&_reduced_outs[i]);
156  _reduction_kernels[i].configure(in, &_reduced_outs[i], axis_local[i], ReductionOperation::MEAN_SUM);
157  }
158  }
159 
160  // Allocate intermediate tensors
161  for (int i = 0; i < _reduction_ops - (keep_dims ? 1 : 0); ++i)
162  {
163  _reduced_outs[i].allocator()->allocate();
164  }
165  // Configure reshape layer if we want to drop the dimensions
166  if (!keep_dims)
167  {
168  TensorShape out_shape = tmp_input->info()->tensor_shape();
169  // We have to sort the reduction axis vectors in order for remove_dimension
170  // to work properly
171  std::sort(axis_local.begin(), axis_local.begin() + _reduction_ops);
172  for (int i = 0; i < _reduction_ops; ++i)
173  {
174  out_shape.remove_dimension(axis_local[i] - i, false);
175  }
176  auto_init_if_empty(*tmp_output->info(), tmp_input->info()->clone()->set_tensor_shape(out_shape));
177  _reshape.configure(&_reduced_outs[_reduction_ops - 1], tmp_output);
178  }
179 }
180 
182 {
183  MemoryGroupResourceScope scope_mg(_memory_group);
184  for (auto &kernel : _reduction_kernels)
185  {
186  kernel.run();
187  }
188  if (!_keep_dims)
189  {
190  _reshape.run();
191  }
192 }
193 } // namespace arm_compute
arm_compute::NEReduceMean::run
void run() override
Run the kernels contained in the function.
Definition: NEReduceMean.cpp:181
arm_compute::NEReduceMean::validate
static Status validate(const ITensorInfo *input, const Coordinates &reduction_axis, bool keep_dims, const ITensorInfo *output)
Static function to check if given info will lead to a valid configuration of NEReduceMean.
Definition: NEReduceMean.cpp:106
arm_compute::ITensorInfo::num_channels
virtual size_t num_channels() const =0
The number of channels for each tensor element.
arm_compute::MemoryGroup::manage
void manage(IMemoryManageable *obj) override
Sets a object to be managed by the given memory group.
Definition: MemoryGroup.h:76
arm_compute::ITensorInfo::tensor_shape
virtual const TensorShape & tensor_shape() const =0
Size for each dimension of the tensor.
arm_compute::test::validation::output_shape
TensorShape output_shape
Definition: LSTMLayerQuantized.cpp:469
arm_compute::DataType::QASYMM8
@ QASYMM8
quantized, asymmetric fixed-point 8-bit number unsigned
arm_compute::TensorShape
Shape of a tensor.
Definition: TensorShape.h:39
ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(...)
Definition: Validate.h:574
arm_compute::NEReduceMean::NEReduceMean
NEReduceMean(std::shared_ptr< IMemoryManager > memory_manager=nullptr)
Constructor.
Definition: NEReduceMean.cpp:96
arm_compute::NEReshapeLayer::run
void run() override
Run the kernels contained in the function.
Definition: NEReshapeLayer.cpp:66
arm_compute::ITensor
Interface for CPU tensor.
Definition: ITensor.h:36
arm_compute::NEReduceMean::configure
void configure(ITensor *input, const Coordinates &reduction_axis, bool keep_dims, ITensor *output)
Configure kernel.
Definition: NEReduceMean.cpp:114
arm_compute::ReductionOperation::MEAN_SUM
@ MEAN_SUM
Mean of sum.
arm_compute::misc::shape_calculator::calculate_reduce_mean_shape
TensorShape calculate_reduce_mean_shape(ITensorInfo *input, const Coordinates &reduction_axis, bool keep_dims)
Calculate the output tensor shape for the reduce mean operation.
Definition: ShapeCalculator.h:51
Error.h
ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN
#define ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(t, c,...)
Definition: Validate.h:952
arm_compute::ITensor::info
virtual ITensorInfo * info() const =0
Interface to be implemented by the child class to return the tensor's metadata.
NEReduceMean.h
ARM_COMPUTE_ERROR_THROW_ON
#define ARM_COMPUTE_ERROR_THROW_ON(status)
Definition: Error.h:455
ARM_COMPUTE_RETURN_ERROR_ON
#define ARM_COMPUTE_RETURN_ERROR_ON(cond)
If the condition is true, an error is returned.
Definition: Error.h:298
ARM_COMPUTE_RETURN_ERROR_ON_CPU_F16_UNSUPPORTED
#define ARM_COMPUTE_RETURN_ERROR_ON_CPU_F16_UNSUPPORTED(tensor)
Definition: Validate.h:117
arm_compute::auto_init_if_empty
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...
Definition: AutoConfiguration.h:43
arm_compute::NEReduceMean::~NEReduceMean
~NEReduceMean()
Default destructor.
arm_compute::Status
Status class.
Definition: Error.h:52
arm_compute::DataType::QASYMM8_SIGNED
@ QASYMM8_SIGNED
quantized, asymmetric fixed-point 8-bit number signed
arm_compute::ITensorInfo::data_type
virtual DataType data_type() const =0
Data type used for each element of the tensor.
ARM_COMPUTE_UNUSED
#define ARM_COMPUTE_UNUSED(...)
To avoid unused variables warnings.
Definition: Error.h:151
arm_compute::Coordinates
Coordinates of an item.
Definition: Coordinates.h:37
arm_compute::Dimensions::begin
std::array< T, num_max_dimensions >::iterator begin()
Returns a read/write iterator that points to the first element in the dimension array.
Definition: Dimensions.h:214
AutoConfiguration.h
arm_compute::ITensorInfo::quantization_info
virtual QuantizationInfo quantization_info() const =0
Get the quantization settings (scale and offset) of the tensor.
arm_compute::misc::ICloneable::clone
virtual std::unique_ptr< T > clone() const =0
Provide a clone of the current object of class T.
ShapeCalculator.h
arm_compute::TensorInfo
Store the tensor's metadata.
Definition: TensorInfo.h:41
Validate.h
NEReductionOperationKernel.h
arm_compute::MemoryGroupResourceScope
Memory group resources scope handling class.
Definition: IMemoryGroup.h:82
arm_compute
Copyright (c) 2017-2023 Arm Limited.
Definition: introduction.dox:24
arm_compute::TensorShape::remove_dimension
void remove_dimension(size_t n, bool apply_dim_correction=true)
Accessor to remove the dimension n from the tensor shape.
Definition: TensorShape.h:111
arm_compute::DataType::F16
@ F16
16-bit floating-point number
Log.h
ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR
#define ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(...)
Definition: Validate.h:161
arm_compute::ITensorInfo
Store the tensor's metadata.
Definition: ITensorInfo.h:44
arm_compute::DataType::F32
@ F32
32-bit floating-point number
arm_compute::test::validation::info
ScaleKernelInfo info(interpolation_policy, default_border_mode, PixelValue(), sampling_policy, false)
arm_compute::NEReshapeLayer::configure
void configure(const ITensor *input, ITensor *output)
Initialise the kernel's inputs and outputs.
Definition: NEReshapeLayer.cpp:48
arm_compute::TensorShape::set
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:78
arm_compute::convert_negative_axis
Coordinates & convert_negative_axis(Coordinates &coords, int max_value)
Convert negative coordinates to positive in the range [0, num_dims_input].
Definition: Helpers.h:287
ARM_COMPUTE_LOG_PARAMS
#define ARM_COMPUTE_LOG_PARAMS(...)
Definition: Log.h:35
arm_compute::Dimensions::num_dimensions
unsigned int num_dimensions() const
Returns the effective dimensionality of the tensor.
Definition: Dimensions.h:142
arm_compute::test::validation::input
auto input
Definition: LSTMLayerQuantized.cpp:486
arm_compute::ITensorInfo::num_dimensions
virtual size_t num_dimensions() const =0
The number of dimensions of the tensor (rank)