Compute Library
 21.02
CLGEMMReshapeLHSMatrixKernel.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  */
25 
32 #include "arm_compute/core/Utils.h"
35 #include "src/core/CL/CLValidate.h"
38 #include "support/StringSupport.h"
39 
40 namespace arm_compute
41 {
43 
44 namespace
45 {
46 Status validate_arguments(const ITensorInfo *input, const ITensorInfo *output, const GEMMLHSMatrixInfo &lhs_info, bool reinterpret_input_as_3d)
47 {
49  ARM_COMPUTE_RETURN_ERROR_ON(lhs_info.m0 == 0);
50  ARM_COMPUTE_RETURN_ERROR_ON(lhs_info.k0 == 0);
51  ARM_COMPUTE_RETURN_ERROR_ON(lhs_info.v0 == 0);
52  ARM_COMPUTE_RETURN_ERROR_ON_MSG(((lhs_info.k0 & (lhs_info.k0 - 1)) && lhs_info.k0 != 3), "Only 2,3,4,8,16 are supported for k0");
53  ARM_COMPUTE_RETURN_ERROR_ON(lhs_info.k0 > 16);
54  ARM_COMPUTE_RETURN_ERROR_ON(lhs_info.m0 < 2 || lhs_info.m0 > 8);
55 
57  ARM_COMPUTE_RETURN_ERROR_ON(input->data_type() == DataType::UNKNOWN);
58 
59  if(output->total_size() != 0)
60  {
61  ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DIMENSIONS(output->tensor_shape(), compute_lhs_reshaped_shape(*input, lhs_info, reinterpret_input_as_3d));
64  }
65 
66  return Status{};
67 }
68 
69 std::pair<Status, Window> validate_and_configure_window(ITensorInfo *input, ITensorInfo *output, const GEMMLHSMatrixInfo &lhs_info, bool reinterpret_input_as_3d)
70 {
71  const unsigned int num_elems_processed_per_iteration_x = lhs_info.k0;
72  const unsigned int num_elems_processed_per_iteration_y = lhs_info.m0;
73  bool window_changed = false;
74 
75  TensorInfo tmp_info(*input);
76 
77  if(reinterpret_input_as_3d)
78  {
79  // Since the input tensor has to be reinterpreted as 3D and the execute window is based on a 2D interleave,
80  // the window needs to be constructed on the 2D collapsed version of the tensor
81  TensorShape tmp_shape(input->tensor_shape());
82  tmp_shape.collapse(2U, 1U);
83  tmp_info.set_tensor_shape(tmp_shape);
84  }
85 
86  // Output auto inizialitation if not yet initialized
87  auto_init_if_empty(*output, input->clone()->set_tensor_shape(compute_lhs_reshaped_shape(*input, lhs_info, reinterpret_input_as_3d)));
88 
89  // Configure window
90  Window win = calculate_max_window(tmp_info, Steps(num_elems_processed_per_iteration_x, num_elems_processed_per_iteration_y));
91  Window win_in = calculate_max_window(*input, Steps(num_elems_processed_per_iteration_x, num_elems_processed_per_iteration_y));
92 
93  AccessWindowStatic input_access(input, 0, 0,
94  input->dimension(0),
95  input->dimension(1));
96  AccessWindowStatic output_access(output, 0, 0, output->dimension(0), output->dimension(1));
97 
98  window_changed = update_window_and_padding(win_in, input_access) || // window used by the execute_window_loop
99  update_window_and_padding(win, output_access); // window used to update the padding requirements of output tensor
100  output_access.set_valid_region(win, ValidRegion(Coordinates(0, 0), output->tensor_shape()));
101 
102  // Collapse along the Z direction
103  // This collapse needs to be here in order to tune the Z dimension of LWS
104  Window collapsed = win.collapse(win, Window::DimZ);
105 
106  Status err = (window_changed) ? ARM_COMPUTE_CREATE_ERROR(ErrorCode::RUNTIME_ERROR, "Insufficient Padding!") : Status{};
107  return std::make_pair(err, collapsed);
108 }
109 } // namespace
110 
112  : _input(nullptr), _output(nullptr), _reinterpret_input_as_3d(false)
113 {
114 }
115 
116 void CLGEMMReshapeLHSMatrixKernel::configure(const ICLTensor *input, ICLTensor *output, const GEMMLHSMatrixInfo &lhs_info, bool reinterpret_input_as_3d)
117 {
118  configure(CLKernelLibrary::get().get_compile_context(), input, output, lhs_info, reinterpret_input_as_3d);
119 }
120 
121 void CLGEMMReshapeLHSMatrixKernel::configure(const CLCompileContext &compile_context, const ICLTensor *input, ICLTensor *output, const GEMMLHSMatrixInfo &lhs_info, bool reinterpret_input_as_3d)
122 {
123  ARM_COMPUTE_ERROR_ON_NULLPTR(input, output);
124 
125  // Perform validate step
126  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input->info(), output->info(), lhs_info, reinterpret_input_as_3d));
127 
128  auto padding_info = get_padding_info({ input });
129 
130  _input = input;
131  _output = output;
132  _reinterpret_input_as_3d = reinterpret_input_as_3d;
133 
134  const unsigned int src_w = input->info()->dimension(0);
135  const unsigned int src_h = _reinterpret_input_as_3d ? input->info()->dimension(1) * input->info()->dimension(2) : input->info()->dimension(1);
136  const unsigned int partial_load_m0 = src_h % lhs_info.m0;
137  const unsigned int partial_load_k0 = src_w % lhs_info.k0;
138 
139  // Create build options
140  CLBuildOptions build_opts;
141  build_opts.add_option("-DM0=" + support::cpp11::to_string(lhs_info.m0));
142  build_opts.add_option("-DK0=" + support::cpp11::to_string(lhs_info.k0));
143  build_opts.add_option("-DV0=" + support::cpp11::to_string(lhs_info.v0));
144  build_opts.add_option("-DSRC_WIDTH=" + support::cpp11::to_string(src_w));
145  build_opts.add_option("-DSRC_HEIGHT=" + support::cpp11::to_string(src_h));
146  build_opts.add_option_if(lhs_info.interleave, "-DINTERLEAVE");
147  build_opts.add_option_if(_reinterpret_input_as_3d, "-DREINTERPRET_INPUT_AS_3D");
148  build_opts.add_option_if(_reinterpret_input_as_3d, "-DHEIGHT_GEMM3D=" + support::cpp11::to_string(input->info()->dimension(1)));
149  build_opts.add_option_if(_reinterpret_input_as_3d, "-DDEPTH_GEMM3D=" + support::cpp11::to_string(input->info()->dimension(2)));
150  build_opts.add_option("-DDATA_TYPE=" + get_cl_unsigned_type_from_element_size(input->info()->element_size()));
151  build_opts.add_option("-DPARTIAL_LOAD_M0=" + support::cpp11::to_string(partial_load_m0));
152  build_opts.add_option("-DPARTIAL_LOAD_K0=" + support::cpp11::to_string(partial_load_k0));
153 
154  std::string kernel_name("gemm_reshape_lhs_matrix_");
155  kernel_name += lhs_info.transpose ? "t" : "nt";
156 
157  // Create kernel
158  _kernel = create_kernel(compile_context, kernel_name, build_opts.options());
159 
160  // Configure kernel window
161  auto win_config = validate_and_configure_window(input->info(), output->info(), lhs_info, reinterpret_input_as_3d);
162  ARM_COMPUTE_ERROR_THROW_ON(win_config.first);
163  ICLKernel::configure_internal(win_config.second);
164 
165  // Set config_id for enabling LWS tuning
166  _config_id = "gemm_reshape_lhs_matrix_";
167  _config_id += (_reinterpret_input_as_3d ? "3d_" : "");
168  _config_id += lower_string(string_from_data_type(input->info()->data_type()));
169  _config_id += "_";
170  _config_id += support::cpp11::to_string(output->info()->dimension(0));
171  _config_id += "_";
172  _config_id += support::cpp11::to_string(output->info()->dimension(1));
173  _config_id += "_";
174  _config_id += support::cpp11::to_string(output->info()->dimension(2));
175  _config_id += "_";
176  _config_id += support::cpp11::to_string(lhs_info.m0);
177  _config_id += "_";
178  _config_id += support::cpp11::to_string(lhs_info.k0);
179  _config_id += "_";
180  _config_id += support::cpp11::to_string(lhs_info.v0);
181  _config_id += "_";
182  _config_id += support::cpp11::to_string(lhs_info.interleave);
183  _config_id += "_";
184  _config_id += support::cpp11::to_string(lhs_info.transpose);
185 
187 }
188 
189 Status CLGEMMReshapeLHSMatrixKernel::validate(const ITensorInfo *input, const ITensorInfo *output, const GEMMLHSMatrixInfo &lhs_info, bool reinterpret_input_as_3d)
190 {
191  ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, lhs_info, reinterpret_input_as_3d));
192  ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window(input->clone().get(), output->clone().get(), lhs_info, reinterpret_input_as_3d).first);
193 
194  return Status{};
195 }
196 
197 void CLGEMMReshapeLHSMatrixKernel::run(const Window &window, cl::CommandQueue &queue)
198 {
201 
203 
204  if(_reinterpret_input_as_3d)
205  {
206  // Pass bottom paddings to the kernel if the input has to be reinterpreted as 3D tensor
207  const unsigned int idx0 = 2 * num_arguments_per_3D_tensor();
208  const unsigned int total_cross_plane_pad = _input->info()->padding().top + _input->info()->padding().bottom;
209  _kernel.setArg<cl_uint>(idx0, static_cast<unsigned int>(total_cross_plane_pad));
210  }
211 
212  do
213  {
214  unsigned int idx = 0;
215  add_3D_tensor_argument(idx, _input, slice);
216  add_3D_tensor_argument(idx, _output, slice);
217  enqueue(queue, *this, slice, lws_hint());
218  }
219  while(window.slide_window_slice_3D(slice));
220 }
221 } // namespace arm_compute
unsigned int top
top of the border
Definition: Types.h:375
Window calculate_max_window(const ValidRegion &valid_region, const Steps &steps, bool skip_border, BorderSize border_size)
#define ARM_COMPUTE_RETURN_ERROR_ON_F16_UNSUPPORTED(tensor)
Definition: CLValidate.h:35
const Window & window() const
The maximum window the kernel can be executed on.
Definition: IKernel.cpp:28
void run(const Window &window, cl::CommandQueue &queue) override
Enqueue the OpenCL kernel to process the given window on the passed OpenCL command queue...
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
void configure(const ICLTensor *input, ICLTensor *output, const GEMMLHSMatrixInfo &lhs_info, bool reinterpret_input_as_3d=false)
Initialise the kernel&#39;s input and output.
virtual size_t dimension(size_t index) const =0
Return the size of the requested dimension.
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_QUANTIZATION_INFO(...)
Definition: Validate.h:610
const StringSet & options() const
Gets the current options list set.
unsigned int v0
Number of vertical blocks of size (m0xk0) stored on the same output row.
Definition: Types.h:1977
cl::NDRange lws_hint() const
Return the Local-Workgroup-Size hint.
Definition: ICLKernel.h:276
static Status validate(const ITensorInfo *input, const ITensorInfo *output, const GEMMLHSMatrixInfo &lhs_info, bool reinterpret_input_as_3d)
Static function to check if given info will lead to a valid configuration of CLGEMMReshapeLHSMatrixKe...
#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.
#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
static CLKernelLibrary & get()
Access the KernelLibrary singleton.
GEMM LHS (Left Hand Side) matrix information.
Definition: Types.h:1968
Store the tensor&#39;s metadata.
Definition: ITensorInfo.h:40
#define ARM_COMPUTE_ERROR_THROW_ON(status)
Definition: Error.h:455
unsigned int bottom
bottom of the border
Definition: Types.h:377
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
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DIMENSIONS(...)
Definition: Validate.h:288
void add_3D_tensor_argument(unsigned int &idx, const ICLTensor *tensor, const Window &window)
Add the passed 3D tensor&#39;s parameters to the object&#39;s kernel&#39;s arguments starting from the index idx...
Definition: ICLKernel.h:172
bool interleave
True if the v0 (m0xk0) blocks have to be interleaved in the output row.
Definition: Types.h:1979
Copyright (c) 2017-2021 Arm Limited.
#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.
bool transpose
True if the (m0xk0) block has to be transposed before been stored.
Definition: Types.h:1978
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
const std::string & string_from_data_type(DataType dt)
Convert a data type identity into a string.
Definition: Utils.cpp:135
bool update_window_and_padding(Window &win, Ts &&... patterns)
Update window and padding size for each of the access patterns.
Definition: WindowHelpers.h:46
static constexpr unsigned int num_arguments_per_3D_tensor()
Returns the number of arguments enqueued per 3D tensor object.
Definition: ICLKernel.h:214
TensorShape compute_lhs_reshaped_shape(const ITensorInfo &a, const GEMMLHSMatrixInfo &lhs_info, bool reinterpret_input_as_3d=false)
Calculate the Left Hand Side matrix reshaped shape.
std::string kernel_name
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.
virtual ITensorInfo * info() const =0
Interface to be implemented by the child class to return the tensor&#39;s metadata.
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()
virtual PaddingSize padding() const =0
Padding of tensor.
bool slide_window_slice_3D(Window &slice) const
Slide the passed 3D window slice.
Definition: Window.h:335
#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.
Interface for OpenCL tensor.
Definition: ICLTensor.h:42
#define ARM_COMPUTE_CREATE_ERROR(error_code, msg)
Creates an error with a given message.
Definition: Error.h:159
static constexpr size_t DimZ
Alias for dimension 2 also known as Z dimension.
Definition: Window.h:47
Manages all the OpenCL kernels compilation and caching, provides accessors for the OpenCL Context...
#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)
Wrapper to configure the Khronos OpenCL C++ header.
#define ARM_COMPUTE_RETURN_ERROR_ON_MSG(cond, msg)
If the condition is true, an error is returned.
Definition: Error.h:244
#define ARM_COMPUTE_ERROR_ON_NULLPTR(...)
Definition: Validate.h:161
unsigned int k0
Number of partial accumulations performed by the matrix multiplication.
Definition: Types.h:1976
unsigned int m0
Number of rows processed by the matrix multiplication.
Definition: Types.h:1975
Window first_slice_window_3D() const
First 3D slice of the window.
Definition: Window.h:291
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)