Compute Library
 21.02
CLStridedSliceKernel.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2018-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  */
32 #include "support/Cast.h"
33 #include "support/StringSupport.h"
34 
35 namespace arm_compute
36 {
37 namespace
38 {
39 Status validate_arguments(const ITensorInfo *input, const ITensorInfo *output,
40  const Coordinates &starts, const Coordinates &ends, const BiStrides &strides,
41  int32_t begin_mask, int32_t end_mask, int32_t shrink_axis_mask)
42 {
44  ARM_COMPUTE_RETURN_ERROR_ON(input->data_type() == DataType::UNKNOWN);
45 
46  ARM_COMPUTE_RETURN_ERROR_ON(input->tensor_shape().num_dimensions() > 4);
47  ARM_COMPUTE_RETURN_ERROR_ON(starts.num_dimensions() > input->num_dimensions());
48  ARM_COMPUTE_RETURN_ERROR_ON(ends.num_dimensions() > input->num_dimensions());
49  ARM_COMPUTE_RETURN_ERROR_ON(strides.num_dimensions() > input->num_dimensions());
50  ARM_COMPUTE_RETURN_ERROR_ON(std::any_of(strides.cbegin(), strides.cbegin() + strides.num_dimensions(), [](int i)
51  {
52  return i == 0;
53  }));
54 
55  // Get expected output shape
56  const TensorShape exp_output_shape = arm_compute::misc::shape_calculator::compute_strided_slice_shape(*input,
57  starts, ends, strides,
58  begin_mask, end_mask, shrink_axis_mask);
59  ARM_COMPUTE_RETURN_ERROR_ON(exp_output_shape.total_size() == 0);
60 
61  // Checks output if configured
62  if(output->total_size() != 0)
63  {
64  const TensorInfo exp_output_info = output->clone()->set_tensor_shape(exp_output_shape);
65  ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(output, &exp_output_info);
67  }
68 
69  return Status{};
70 }
71 
72 std::pair<Status, Window> validate_and_configure_window(const ITensorInfo *input, ITensorInfo *output,
73  const Coordinates &starts, const Coordinates &ends, const BiStrides &strides,
74  int32_t begin_mask, int32_t end_mask, int32_t shrink_axis_mask)
75 {
76  // Output tensor auto initialization if not yet initialized
78  starts, ends, strides,
79  begin_mask, end_mask, shrink_axis_mask);
80  auto_init_if_empty(*output, input->clone()->set_tensor_shape(output_shape));
81 
82  // Create window
83  Window win = calculate_max_window(*output, Steps());
84  output->set_valid_region(ValidRegion(Coordinates(), output->tensor_shape()));
85 
86  return std::make_pair(Status{}, win);
87 }
88 } // namespace
89 
90 void CLStridedSliceKernel::configure(const CLCompileContext &compile_context, const ITensorInfo *input, ITensorInfo *output,
91  const Coordinates &starts, const Coordinates &ends, const BiStrides &strides,
92  int32_t begin_mask, int32_t end_mask, int32_t shrink_axis_mask)
93 {
94  ARM_COMPUTE_ERROR_ON_NULLPTR(input, output);
95  auto padding_info = get_padding_info({ input, output });
96  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input, output, starts, ends, strides, begin_mask, end_mask, shrink_axis_mask));
97 
98  const TensorShape &input_shape = input->tensor_shape();
99 
100  Coordinates starts_abs;
101  Coordinates ends_abs;
102  Coordinates final_strides;
103  std::tie(starts_abs, ends_abs, final_strides) = arm_compute::helpers::tensor_transform::calculate_strided_slice_coords(
104  input_shape,
105  starts, ends, strides,
106  begin_mask, end_mask, shrink_axis_mask);
107 
108  // Configure kernel window
109  auto win_config = validate_and_configure_window(input, output, starts, ends, strides, begin_mask, end_mask, shrink_axis_mask);
110  ARM_COMPUTE_ERROR_THROW_ON(win_config.first);
111 
112  // Enable multiple elements processing along x if stride_x is 1 and output width greater than the access vector size
113  const int vec_size_x = 16 / input->element_size();
114  const int output_width_x = output->tensor_shape().x();
115  const bool is_shrink_on_x = arm_compute::helpers::bit_ops::is_bit_set(shrink_axis_mask, 0);
116  const bool multi_access_x = !is_shrink_on_x && (final_strides.x() == 1) && (output_width_x / vec_size_x > 0);
117 
118  // Update window if needed
119  if(multi_access_x)
120  {
121  Window &updated_window = std::get<1>(win_config);
122  updated_window.set(Window::DimX,
123  Window::Dimension(updated_window.x().start(), ceil_to_multiple(updated_window.x().end(), vec_size_x), vec_size_x));
124  }
125  ICLKernel::configure_internal(win_config.second);
126 
127  // Create build options
128  CLBuildOptions build_opts;
129  build_opts.add_option("-DDATA_TYPE=" + get_cl_unsigned_type_from_element_size(data_size_from_type(input->data_type())));
130  for(unsigned int i = 0; i < input_shape.num_dimensions(); ++i)
131  {
132  const bool is_shrink = arm_compute::helpers::bit_ops::is_bit_set(shrink_axis_mask, i);
133  build_opts.add_option("-DSTART_" + support::cpp11::to_string(i) + "=" + support::cpp11::to_string(starts_abs[i]));
134  build_opts.add_option("-DSTRIDE_" + support::cpp11::to_string(i) + "=" + support::cpp11::to_string(final_strides[i]));
135  build_opts.add_option_if(is_shrink, "-DSHRINK_" + support::cpp11::to_string(i));
136  }
137  build_opts.add_option_if(multi_access_x, "-DLAST_ACCESSED_X=" + support::cpp11::to_string(std::max<int>(output_width_x - vec_size_x, 0)));
138  build_opts.add_option_if(multi_access_x, "-DVEC_SIZE=" + support::cpp11::to_string(vec_size_x));
139  build_opts.add_option_if_else(input_shape.num_dimensions() > 2,
140  "-DSRC_DEPTH=" + support::cpp11::to_string(input_shape.z()),
141  "-DSRC_DEPTH=1");
142  build_opts.add_option_if_else(output->num_dimensions() > 2,
143  "-DDST_DEPTH=" + support::cpp11::to_string(output->tensor_shape().z()),
144  "-DDST_DEPTH=1");
145 
146  // Create kernel
147  _kernel = create_kernel(compile_context, "strided_slice", build_opts.options());
148 
149  // Set config_id for enabling LWS tuning
150  _config_id = "strided_slice";
151  _config_id += "_";
152  _config_id += lower_string(string_from_data_type(input->data_type()));
153  for(unsigned int i = 0; i < input_shape.num_dimensions(); ++i)
154  {
155  _config_id += "_";
156  _config_id += support::cpp11::to_string(input->dimension(i));
157  _config_id += "_";
158  _config_id += support::cpp11::to_string(starts_abs[i]);
159  _config_id += "_";
160  _config_id += support::cpp11::to_string(ends_abs[i]);
161  _config_id += "_";
162  _config_id += support::cpp11::to_string(final_strides[i]);
163  }
165 }
166 
168  const Coordinates &starts, const Coordinates &ends, const BiStrides &strides,
169  int32_t begin_mask, int32_t end_mask, int32_t shrink_axis_mask)
170 {
171  ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, starts, ends, strides, begin_mask, end_mask, shrink_axis_mask));
172  ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window(input->clone().get(), output->clone().get(),
173  starts, ends, strides, begin_mask, end_mask, shrink_axis_mask)
174  .first);
175 
176  return Status{};
177 }
178 
179 void CLStridedSliceKernel::run_op(ITensorPack &tensors, const Window &window, cl::CommandQueue &queue)
180 {
183 
184  const auto src = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC));
185  auto dst = utils::cast::polymorphic_downcast<ICLTensor *>(tensors.get_tensor(TensorType::ACL_DST));
186 
187  Window window_collapsed = window.collapse_if_possible(ICLKernel::window(), Window::DimZ);
188  Window slice = window_collapsed.first_slice_window_4D();
189 
190  do
191  {
192  unsigned int idx = 0;
193  add_4D_tensor_argument(idx, src, slice);
194  add_4D_tensor_argument(idx, dst, slice);
195  enqueue(queue, *this, slice, lws_hint());
196  }
197  while(window_collapsed.slide_window_slice_4D(slice));
198 }
199 } // namespace arm_compute
virtual size_t num_dimensions() const =0
The number of dimensions of the tensor (rank)
Window calculate_max_window(const ValidRegion &valid_region, const Steps &steps, bool skip_border, BorderSize border_size)
std::tuple< Coordinates, Coordinates, Coordinates > calculate_strided_slice_coords(TensorShape input_shape, Coordinates starts, Coordinates ends, Coordinates strides, int32_t begin_mask=0, int32_t end_mask=0, int32_t shrink_axis_mask=0)
Calculate start, end and stride coordinates for a strided slice.
const Window & window() const
The maximum window the kernel can be executed on.
Definition: IKernel.cpp:28
Shape of a tensor.
Definition: TensorShape.h:39
void enqueue(IGCKernel &kernel, const Window &window, const gles::NDRange &lws=gles::NDRange(1U, 1U, 1U))
Add the kernel to the command queue with the given window.
Definition: IGCKernel.cpp:41
virtual size_t dimension(size_t index) const =0
Return the size of the requested dimension.
const StringSet & options() const
Gets the current options list set.
bool is_bit_set(T v, unsigned int idx)
Checks if the idx-th bit is set in an integral type.
Definition: bit_ops.h:45
cl::NDRange lws_hint() const
Return the Local-Workgroup-Size hint.
Definition: ICLKernel.h:276
void run_op(ITensorPack &tensors, const Window &window, cl::CommandQueue &queue) override
Enqueue the OpenCL kernel to process the given window on the passed OpenCL command queue...
#define ARM_COMPUTE_RETURN_ON_ERROR(status)
Checks if a status contains an error and returns it.
Definition: Error.h:204
std::string to_string(T &&value)
Convert integer and float values to string.
virtual DataType data_type() const =0
Data type used for each element of the tensor.
Coordinates BiStrides
Bidirectional strides.
Definition: Types.h:51
#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
Store the tensor&#39;s metadata.
Definition: ITensorInfo.h:40
#define ARM_COMPUTE_ERROR_THROW_ON(status)
Definition: Error.h:455
Describe one of the image&#39;s dimensions with a start, end and step.
Definition: Window.h:77
Status class.
Definition: Error.h:52
std::string lower_string(const std::string &val)
Lower a given string.
Definition: Utils.cpp:350
#define ARM_COMPUTE_RETURN_ERROR_ON(cond)
If the condition is true, an error is returned.
Definition: Error.h:296
SimpleTensor< float > src
Definition: DFT.cpp:155
Copyright (c) 2017-2021 Arm Limited.
TensorShape compute_strided_slice_shape(const ITensorInfo &input, const Coordinates &starts, const Coordinates &ends, const Coordinates &strides, int32_t begin_mask, int32_t end_mask, int32_t shrink_axis_mask)
Calculate the strided slice output shape of a tensor.
#define ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(...)
Definition: Validate.h:163
void add_option(std::string option)
Adds option to the existing build option list.
T x() const
Alias to access the size of the first dimension.
Definition: Dimensions.h:87
const ITensor * get_const_tensor(int id) const
Get constant tensor of a given id.
Definition: ITensorPack.cpp:40
cl::Kernel create_kernel(const CLCompileContext &ctx, const std::string &kernel_name, const std::set< std::string > &build_opts=std::set< std::string >())
Creates an opencl kernel using a compile context.
Definition: CLHelpers.cpp:403
TensorShape input_shape
Validate test suite is to test ARM_COMPUTE_RETURN_ON_* macros we use to check the validity of given a...
const std::string & string_from_data_type(DataType dt)
Convert a data type identity into a string.
Definition: Utils.cpp:135
static constexpr size_t DimX
Alias for dimension 0 also known as X dimension.
Definition: Window.h:43
Window collapse_if_possible(const Window &full_window, size_t first, size_t last, bool *has_collapsed=nullptr) const
Collapse the dimensions between first and last if possible.
Definition: Window.inl:68
static Status validate(const ITensorInfo *input, const ITensorInfo *output, const Coordinates &starts, const Coordinates &ends, const BiStrides &strides, int32_t begin_mask, int32_t end_mask, int32_t shrink_axis_mask)
Static function to check if given info will lead to a valid configuration of CLStridedSliceKernel.
virtual const TensorShape & tensor_shape() const =0
Size for each dimension of the tensor.
auto ceil_to_multiple(S value, T divisor) -> decltype(((value+divisor - 1)/divisor) *divisor)
Computes the smallest number larger or equal to value that is a multiple of divisor.
Definition: Utils.h:71
T z() const
Alias to access the size of the third dimension.
Definition: Dimensions.h:97
Coordinates of an item.
Definition: Coordinates.h:37
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.
size_t data_size_from_type(DataType data_type)
The size in bytes of the data type.
Definition: Utils.h:106
void add_option_if(bool cond, std::string option)
Adds option if a given condition is true;.
virtual size_t element_size() const =0
Element size in bytes calculated as data_size() * num_channels()
void set(size_t dimension, const Dimension &dim)
Set the values of a given dimension.
Definition: Window.inl:49
#define ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(k)
Definition: Validate.h:941
bool has_padding_changed(const std::unordered_map< const ITensorInfo *, PaddingSize > &padding_map)
Check if the previously stored padding info has changed after configuring a kernel.
Definition: Utils.cpp:528
CLCompileContext class.
ITensor * get_tensor(int id)
Get tensor of a given id from the pac.
Definition: ITensorPack.cpp:50
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(...)
Definition: Validate.h:443
void configure(const CLCompileContext &compile_context, const ITensorInfo *input, ITensorInfo *output, const Coordinates &starts, const Coordinates &ends, const BiStrides &strides, int32_t begin_mask, int32_t end_mask, int32_t shrink_axis_mask)
Configure kernel.
static constexpr size_t DimZ
Alias for dimension 2 also known as Z dimension.
Definition: Window.h:47
unsigned int num_dimensions() const
Returns the effective dimensionality of the tensor.
Definition: Dimensions.h:143
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(...)
Definition: Validate.h:545
std::string get_cl_unsigned_type_from_element_size(size_t element_size)
Translates the element size to an unsigned integer data type.
Definition: CLHelpers.cpp:103
std::unordered_map< const ITensorInfo *, PaddingSize > get_padding_info(std::initializer_list< const ITensorInfo *> infos)
Stores padding information before configuring a kernel.
Definition: Utils.cpp:513
Status validate_arguments(const ITensorInfo *input, const ITensorInfo *bias, const ITensorInfo *output, const GEMMLowpOutputStageInfo *output_stage)
Tensor packing service.
Definition: ITensorPack.h:37
#define ARM_COMPUTE_ERROR_ON_NULLPTR(...)
Definition: Validate.h:161
constexpr int end() const
Return the end of the dimension.
Definition: Window.h:99
void add_4D_tensor_argument(unsigned int &idx, const ICLTensor *tensor, const Window &window)
Add the passed 4D tensor&#39;s parameters to the object&#39;s kernel&#39;s arguments starting from the index idx...
Definition: ICLKernel.h:182
constexpr int start() const
Return the start of the dimension.
Definition: Window.h:94
Describe a multidimensional execution window.
Definition: Window.h:39
#define ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(f, s)
Definition: Validate.h:205
SimpleTensor< T > slice(const SimpleTensor< T > &src, Coordinates starts, Coordinates ends)
constexpr const Dimension & x() const
Alias to access the first dimension of the window.
Definition: Window.h:145
void add_option_if_else(bool cond, std::string option_true, std::string option_false)
Adds first option if condition is true else the second one.