Compute Library
 23.08
NEGatherKernel.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2019-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/Error.h"
35 
36 namespace arm_compute
37 {
38 namespace
39 {
40 Status validate_arguments(const ITensorInfo *input, const ITensorInfo *indices, const ITensorInfo *output, int axis)
41 {
43  ARM_COMPUTE_RETURN_ERROR_ON(input->num_dimensions() > 4);
44 
45  if(axis < 0)
46  {
47  axis += input->num_dimensions();
48  }
49 
50  ARM_COMPUTE_RETURN_ERROR_ON(0 > axis || axis >= static_cast<int32_t>(input->num_dimensions()));
51  ARM_COMPUTE_RETURN_ERROR_ON(input->num_dimensions() + indices->num_dimensions() - 1 > Coordinates::num_max_dimensions);
53 
54  if(output->total_size() != 0)
55  {
58  TensorShape output_shape = arm_compute::misc::shape_calculator::compute_gather_shape(input->tensor_shape(), indices->tensor_shape(), axis);
59  ARM_COMPUTE_RETURN_ERROR_ON(output_shape.total_size() != output->tensor_shape().total_size());
60  }
61 
63 
64  return Status{};
65 }
66 } // namespace
67 
69  : _input{}, _indices{}, _axis{}, _output{}, _func{}, _src_it_strides{}, _idx_it_strides{}
70 {
71 }
72 
73 template <typename TIndex>
74 void NEGatherKernel::gather_common(const Window &window, const ThreadInfo &info)
75 {
77 
78  auto dst_win = window;
79 
80  const auto src_info = _input->info();
81  const auto idx_info = _indices->info();
82  const auto dst_info = _output->info();
83 
84  const auto num_dims = dst_info->num_dimensions();
85  const auto chunk_stride = src_info->strides_in_bytes()[_axis];
86 
87  const auto window_start_x = window.x().start();
88  const auto window_end_x = window.x().end();
89  auto window_size_x = src_info->element_size();
90 
91  const auto idx_limit = static_cast<TIndex>(src_info->tensor_shape()[_axis]);
92 
93  if(_axis != 0)
94  {
95  dst_win.set(0, Window::Dimension(window_start_x, window_start_x + 1, 1));
96  window_size_x *= window_end_x - window_start_x;
97  }
98 
99  // Compute source and index tensors window based on the output window.
100  auto src_win = dst_win;
101  Window idx_win;
102 
103  for (size_t i = 0; i < idx_info->num_dimensions(); ++i)
104  {
105  src_win.set(_axis + i, Window::Dimension(0, 1, 1));
106  idx_win.set(_axis + i, window[_axis + i]);
107  }
108 
109  // Use the custom strides to access all three tensors using the same loop.
110  Iterator src_it(num_dims, _src_it_strides, _input->buffer(), src_info->offset_first_element_in_bytes(), src_win);
111  Iterator idx_it(num_dims, _idx_it_strides, _indices->buffer(), idx_info->offset_first_element_in_bytes(), idx_win);
112  Iterator dst_it(num_dims, dst_info->strides_in_bytes(), _output->buffer(), dst_info->offset_first_element_in_bytes(), dst_win);
113 
114  execute_window_loop(dst_win, [&](const Coordinates &) {
115  const auto idx = *reinterpret_cast<const TIndex *>(idx_it.ptr());
116 
117  if(idx >= 0 && idx < idx_limit)
118  {
119  const auto src_ptr = src_it.ptr() + idx * chunk_stride;
120 
121  std::copy_n(src_ptr, window_size_x, dst_it.ptr());
122  }
123  else
124  {
125  std::fill_n(dst_it.ptr(), window_size_x, 0);
126  }
127  }, src_it, idx_it, dst_it);
128 }
129 
130 void NEGatherKernel::configure(const ITensor *input, const ITensor *indices, ITensor *output, int axis)
131 {
132  ARM_COMPUTE_ERROR_ON_NULLPTR(input, output, indices);
133  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input->info(), indices->info(), output->info(), axis));
134 
135  _input = input;
136  _indices = indices;
137  _output = output;
138  _axis = axis;
139 
140  if(_axis < 0)
141  {
142  _axis += input->info()->num_dimensions();
143  }
144  ARM_COMPUTE_ERROR_ON(0 > _axis || _axis >= static_cast<int32_t>(input->info()->num_dimensions()));
145 
146  switch(_indices->info()->data_type())
147  {
148  case DataType::U32:
149  _func = &NEGatherKernel::gather_common<uint32_t>;
150  break;
151  case DataType::S32:
152  _func = &NEGatherKernel::gather_common<int32_t>;
153  break;
154  default:
155  ARM_COMPUTE_ERROR("Not supported");
156  break;
157  }
158 
159  // Output auto initialization if not yet initialized
160  const TensorShape output_shape = arm_compute::misc::shape_calculator::compute_gather_shape(input->info()->tensor_shape(), indices->info()->tensor_shape(), _axis);
161  auto_init_if_empty(*output->info(), input->info()->clone()->set_tensor_shape(output_shape));
162 
163  // Create window
164  Window win = calculate_max_window(*output->info(), Steps());
165 
166  INEKernel::configure(win);
167 
168  // Create input and indices strides that have the same number of dimensions as the output tensor.
169  // These will be used to iterate lock-step through all tensors (input, indices and output).
170  size_t dim_no = 0;
171 
172  const auto input_info = input->info();
173  const auto &input_strides = input_info->strides_in_bytes();
174 
175  const auto indices_info = indices->info();
176  const auto &indices_strides = indices_info->strides_in_bytes();
177  const auto indices_num_dims = indices_info->num_dimensions();
178 
179  for(; dim_no < static_cast<size_t>(_axis); ++dim_no)
180  {
181  _src_it_strides[dim_no] = input_strides[dim_no];
182  }
183 
184  for(; dim_no < static_cast<size_t>(_axis) + indices_num_dims; ++dim_no)
185  {
186  _idx_it_strides[dim_no] = indices_strides[dim_no - _axis];
187  }
188 
189  for(; dim_no < Coordinates::num_max_dimensions; ++dim_no)
190  {
191  _src_it_strides[dim_no] = input_strides[dim_no - indices_num_dims + 1];
192  }
193 }
194 
195 Status NEGatherKernel::validate(const ITensorInfo *input, const ITensorInfo *indices, const ITensorInfo *output, int axis)
196 {
197  ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, indices, output, axis));
198  return Status{};
199 }
200 
201 void NEGatherKernel::run(const Window &window, const ThreadInfo &info)
202 {
205  ARM_COMPUTE_ERROR_ON(_func == nullptr);
206 
207  (this->*_func)(window, info);
208 }
209 
210 } // namespace arm_compute
arm_compute::Steps
Class to describe a number of elements in each dimension.
Definition: Steps.h:40
arm_compute::Window::Dimension::start
constexpr int start() const
Return the start of the dimension.
Definition: Window.h:97
arm_compute::test::validation::input_info
input_info
Definition: DirectConvolutionLayer.cpp:547
arm_compute::ITensorInfo::tensor_shape
virtual const TensorShape & tensor_shape() const =0
Size for each dimension of the tensor.
Helpers.h
arm_compute::calculate_max_window
Window calculate_max_window(const ValidRegion &valid_region, const Steps &steps, bool skip_border, BorderSize border_size)
Definition: WindowHelpers.cpp:28
arm_compute::test::validation::output_shape
const auto output_shape
Definition: ConvolutionLayer.cpp:411
arm_compute::TensorShape
Shape of a tensor.
Definition: TensorShape.h:39
arm_compute::cpu::kernels::validate_arguments
Status validate_arguments(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *dst, const PadStrideInfo &conv_info)
Definition: CpuDirectConv2dKernel.cpp:60
ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL
#define ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(k)
Definition: Validate.h:1004
Window.h
ARM_COMPUTE_ERROR
#define ARM_COMPUTE_ERROR(msg)
Print the given message then throw an std::runtime_error.
Definition: Error.h:353
TensorInfo.h
arm_compute::ITensor
Interface for CPU tensor.
Definition: ITensor.h:36
arm_compute::TensorInfo::strides_in_bytes
const Strides & strides_in_bytes() const override
The strides in bytes for accessing each dimension of the tensor.
Definition: TensorInfo.h:214
arm_compute::misc::shape_calculator::compute_gather_shape
TensorShape compute_gather_shape(const TensorShape &input_shape, const TensorShape &indices_shape, uint32_t actual_axis)
Calculate the gather output shape of a tensor.
Definition: ShapeCalculator.h:1579
Error.h
ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(...)
Definition: Validate.h:630
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:877
ARM_COMPUTE_RETURN_ON_ERROR
#define ARM_COMPUTE_RETURN_ON_ERROR(status)
Checks if a status contains an error and returns it.
Definition: Error.h:204
ARM_COMPUTE_ERROR_ON_NULLPTR
#define ARM_COMPUTE_ERROR_ON_NULLPTR(...)
Definition: Validate.h:161
arm_compute::NEGatherKernel::NEGatherKernel
NEGatherKernel()
Default constructor.
Definition: NEGatherKernel.cpp:68
arm_compute::ITensor::info
virtual ITensorInfo * info() const =0
Interface to be implemented by the child class to return the tensor's metadata.
ARM_COMPUTE_ERROR_ON
#define ARM_COMPUTE_ERROR_ON(cond)
If the condition is true then an error message is printed and an exception thrown.
Definition: Error.h:467
ARM_COMPUTE_ERROR_THROW_ON
#define ARM_COMPUTE_ERROR_THROW_ON(status)
Definition: Error.h:456
arm_compute::DataType::U32
@ U32
unsigned 32-bit number
Coordinates.h
ARM_COMPUTE_RETURN_ERROR_ON
#define ARM_COMPUTE_RETURN_ERROR_ON(cond)
If the condition is true, an error is returned.
Definition: Error.h:297
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::Status
Status class.
Definition: Error.h:52
WindowHelpers.h
arm_compute::NEGatherKernel::configure
void configure(const ITensor *input, const ITensor *indices, ITensor *output, int axis=0)
Initialise the kernel's inputs and outputs.
Definition: NEGatherKernel.cpp:130
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:152
AutoConfiguration.h
arm_compute::IKernel::window
const Window & window() const
The maximum window the kernel can be executed on.
Definition: IKernel.cpp:28
ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_QUANTIZATION_INFO
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_QUANTIZATION_INFO(...)
Definition: Validate.h:695
arm_compute::ThreadInfo
Information about executing thread and CPU.
Definition: CPPTypes.h:180
ShapeCalculator.h
arm_compute::Window
Describe a multidimensional execution window.
Definition: Window.h:39
arm_compute
Copyright (c) 2017-2023 Arm Limited.
Definition: introduction.dox:24
arm_compute::DataType::S32
@ S32
signed 32-bit number
arm_compute::ITensorInfo::strides_in_bytes
virtual const Strides & strides_in_bytes() const =0
The strides in bytes for accessing each dimension of the tensor.
arm_compute::test::validation::src_info
TensorInfo src_info(src_shape, 1, data_type)
ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR
#define ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(...)
Definition: Validate.h:163
arm_compute::ITensorInfo
Store the tensor's metadata.
Definition: ITensorInfo.h:43
arm_compute::TensorInfo::offset_first_element_in_bytes
size_t offset_first_element_in_bytes() const override
The offset from the beginning of the memory allocation to the first element of the tensor.
Definition: TensorInfo.h:218
arm_compute::test::validation::info
ScaleKernelInfo info(interpolation_policy, default_border_mode, PixelValue(), sampling_policy, false)
arm_compute::NEGatherKernel::validate
static Status validate(const ITensorInfo *input, const ITensorInfo *indices, const ITensorInfo *output, int axis)
Static function to check if given info will lead to a valid configuration.
Definition: NEGatherKernel.cpp:195
arm_compute::execute_window_loop
void execute_window_loop(const Window &w, L &&lambda_function, Ts &&... iterators)
Iterate through the passed window, automatically adjusting the iterators and calling the lambda_funct...
Definition: Helpers.inl:77
arm_compute::DataType::UNKNOWN
@ UNKNOWN
Unknown data type.
arm_compute::Window::Dimension::end
constexpr int end() const
Return the end of the dimension.
Definition: Window.h:102
arm_compute::NEGatherKernel::run
void run(const Window &window, const ThreadInfo &info) override
Execute the kernel on the passed window.
Definition: NEGatherKernel.cpp:201
Validate.h
arm_compute::Dimensions::num_dimensions
unsigned int num_dimensions() const
Returns the effective dimensionality of the tensor.
Definition: Dimensions.h:143
arm_compute::Window::x
constexpr const Dimension & x() const
Alias to access the first dimension of the window.
Definition: Window.h:159
NEGatherKernel.h
arm_compute::TensorInfo::tensor_shape
const TensorShape & tensor_shape() const override
Size for each dimension of the tensor.
Definition: TensorInfo.h:235
arm_compute::Dimensions< int >::num_max_dimensions
static constexpr size_t num_max_dimensions
Number of dimensions the tensor has.
Definition: Dimensions.h:46
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)
arm_compute::TensorInfo::element_size
size_t element_size() const override
Element size in bytes calculated as data_size() * num_channels()
Definition: TensorInfo.h:223
arm_compute::ITensor::buffer
virtual uint8_t * buffer() const =0
Interface to be implemented by the child class to return a pointer to CPU memory.