blob: 448d35353bd688eb5d0a0029e177751008dce3bf [file] [log] [blame]
Georgios Pinitas856f66e2021-04-22 21:13:21 +01001/*
2 * Copyright (c) 2019-2021 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 */
Georgios Pinitas7891a732021-08-20 21:39:25 +010024#include "src/gpu/cl/kernels/ClGemmMatrixMultiplyNativeKernel.h"
Georgios Pinitas856f66e2021-04-22 21:13:21 +010025
26#include "arm_compute/core/CL/CLHelpers.h"
27#include "arm_compute/core/CL/CLKernelLibrary.h"
28#include "arm_compute/core/CL/ICLTensor.h"
29#include "arm_compute/core/CL/OpenCL.h"
30#include "arm_compute/core/Helpers.h"
31#include "arm_compute/core/TensorInfo.h"
32#include "arm_compute/core/Utils.h"
33#include "arm_compute/core/Validate.h"
34#include "arm_compute/core/utils/misc/ShapeCalculator.h"
35#include "src/core/AccessWindowStatic.h"
36#include "src/core/helpers/AutoConfiguration.h"
37#include "src/core/helpers/WindowHelpers.h"
38#include "src/core/utils/helpers/float_ops.h"
39#include "support/Cast.h"
40#include "support/StringSupport.h"
41
42namespace arm_compute
43{
44namespace opencl
45{
46namespace kernels
47{
48namespace
49{
50using ElementsProcessed = Steps;
51
52Status validate_arguments(const ITensorInfo *src0, const ITensorInfo *src1, const ITensorInfo *src2, const ITensorInfo *dst, float alpha, float beta, const GEMMLHSMatrixInfo &lhs_info,
53 const GEMMRHSMatrixInfo &rhs_info,
54 const GEMMKernelInfo &gemm_info)
55{
56 ARM_COMPUTE_UNUSED(alpha);
57 ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(src0, src1, dst);
58 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(src0, 1, DataType::F32);
59 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src0, src1);
60 ARM_COMPUTE_RETURN_ERROR_ON_MSG(src0->num_dimensions() > 4, "The number of dimensions for the LHS matrix must be <= 4");
61 ARM_COMPUTE_RETURN_ERROR_ON_MSG(src1->num_dimensions() > 3, "The number of dimensions for the RHS matrix must be <= 3");
62 ARM_COMPUTE_RETURN_ERROR_ON_MSG(((rhs_info.k0 & (rhs_info.k0 - 1)) && rhs_info.k0 != 3), "Only 2,3,4,8,16 are supported for k0");
63 ARM_COMPUTE_RETURN_ERROR_ON(rhs_info.k0 > 16);
64 ARM_COMPUTE_RETURN_ERROR_ON(lhs_info.m0 < 1 || lhs_info.m0 > 8);
65 ARM_COMPUTE_RETURN_ERROR_ON_MSG(((rhs_info.n0 & (rhs_info.n0 - 1)) && rhs_info.n0 != 3), "Only 2,3,4,8,16 are supported for n0");
66 ARM_COMPUTE_RETURN_ERROR_ON_MSG((gemm_info.reinterpret_input_as_3d || gemm_info.depth_output_gemm3d != 0) && (src2 != nullptr)
67 && (!gemm_info.broadcast_bias),
68 "Bias addition only supported with broadcast mode in case the input or dst has to be reinterpreted as 3D");
69 ARM_COMPUTE_RETURN_ERROR_ON_MSG(gemm_info.fp_mixed_precision, "Mixed precision not supported");
70 ARM_COMPUTE_RETURN_ERROR_ON_MSG(rhs_info.export_to_cl_image, "Export to CLImage not supported for GEMM native");
71
72 const unsigned int m = gemm_info.m;
73 const unsigned int n = gemm_info.n;
74 const unsigned int k = gemm_info.k;
75
76 ARM_COMPUTE_UNUSED(m);
77 ARM_COMPUTE_UNUSED(n);
78 ARM_COMPUTE_UNUSED(k);
79
80 ARM_COMPUTE_RETURN_ERROR_ON(src0->dimension(0) != k);
81 ARM_COMPUTE_RETURN_ERROR_ON(src1->dimension(0) != n);
82 ARM_COMPUTE_RETURN_ERROR_ON(src1->dimension(1) != k);
83 if(gemm_info.reinterpret_input_as_3d)
84 {
85 ARM_COMPUTE_RETURN_ERROR_ON(src0->dimension(1) * src0->dimension(2) != m);
86 }
87 else
88 {
89 ARM_COMPUTE_RETURN_ERROR_ON(src0->dimension(1) != m);
90 }
91
92 if(src2 != nullptr && !(helpers::float_ops::is_zero(beta)))
93 {
94 const unsigned int src2_dim0 = src2->dimension(0);
95 const unsigned int src2_dim1 = src2->dimension(1);
96
97 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src2, src1);
98 if(gemm_info.broadcast_bias)
99 {
100 ARM_COMPUTE_RETURN_ERROR_ON_MSG((src2_dim1 != 1 || src2_dim0 != n), "Incorrect dimension of bias matrix which is to be broadcasted");
101 }
102 else
103 {
104 ARM_COMPUTE_RETURN_ERROR_ON_MSG((src2_dim0 != n || src2_dim1 != m), "Incorrect dimension of bias matrix");
105 }
106 }
107
108 if(dst->total_size() != 0)
109 {
110 const TensorInfo tensor_info_dst = dst->clone()->set_tensor_shape(misc::shape_calculator::compute_mm_shape(*src0, *src1, gemm_info));
111 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(dst, &tensor_info_dst);
112 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src0, dst);
113 }
114
115 return Status{};
116}
117
118std::pair<Status, Window> validate_and_configure_window(ITensorInfo *src0, ITensorInfo *src1, ITensorInfo *src2, ITensorInfo *dst, const GEMMLHSMatrixInfo &lhs_info,
119 const GEMMRHSMatrixInfo &rhs_info,
120 const GEMMKernelInfo &gemm_info, ElementsProcessed &num_elements_processed)
121{
122 unsigned int &num_elems_processed_per_iteration_x = num_elements_processed[0];
123 unsigned int &num_elems_processed_per_iteration_y = num_elements_processed[1];
124 bool reinterpret_input_as_3d = gemm_info.reinterpret_input_as_3d;
125 bool reinterpret_output_as_3d = gemm_info.depth_output_gemm3d != 0;
126
127 Window win{};
128 Window win_out{};
129 bool window_changed = false;
130
131 // In case both input and dst have to be reinterpreted as 3D tensors,
132 // force reinterpret_input_as_3d and reinterpret_output_as_3d to be false.
133 if(reinterpret_input_as_3d == reinterpret_output_as_3d)
134 {
135 reinterpret_output_as_3d = false;
136 }
137
138 // dst tensor auto initialization if not yet initialized
139 auto_init_if_empty(*dst, src0->clone()->set_tensor_shape(misc::shape_calculator::compute_mm_shape(*src0, *src1, gemm_info)));
140
141 TensorInfo tmp_info(*dst);
142
143 if(reinterpret_output_as_3d)
144 {
145 // Since the dst tensor has to be reinterpreted as 3D and the execute window is based on a 2D GEMM,
146 // the window needs to be constructed on the 2D collapsed version of the tensor
147 TensorShape tmp_shape(dst->tensor_shape());
148 tmp_shape.collapse(2U, 1U);
149 tmp_info.set_tensor_shape(tmp_shape);
150 }
151
152 // Configure kernel window
153 num_elems_processed_per_iteration_x = rhs_info.n0;
154 num_elems_processed_per_iteration_y = lhs_info.m0;
155
156 win = calculate_max_window(tmp_info, Steps(num_elems_processed_per_iteration_x, num_elems_processed_per_iteration_y));
157 win_out = calculate_max_window(*dst, Steps(num_elems_processed_per_iteration_x, num_elems_processed_per_iteration_y));
158
159 AccessWindowStatic src0_access(src0, 0, 0,
160 src0->dimension(0),
161 src0->dimension(1));
162 AccessWindowStatic src1_access(src1, 0, 0,
163 ceil_to_multiple(src1->dimension(0), num_elems_processed_per_iteration_x),
164 src1->dimension(1));
165 AccessWindowStatic dst_access(dst, 0, 0,
166 dst->dimension(0),
167 dst->dimension(1));
168
169 if(src2 != nullptr)
170 {
171 const int bias_processed_per_iteration_x = num_elems_processed_per_iteration_x;
172
173 AccessWindowStatic src2_access(src2, 0, 0,
174 ceil_to_multiple(src2->dimension(0), bias_processed_per_iteration_x),
175 src2->dimension(1));
176
177 window_changed = update_window_and_padding(win, src0_access, src1_access, src2_access) || // window used by the execute_window_loop
178 update_window_and_padding(win_out, dst_access); // window used to update the padding requirements of dst tensor
179 }
180 else
181 {
182 window_changed = update_window_and_padding(win, src0_access, src1_access) || // window used by the execute_window_loop
183 update_window_and_padding(win_out, dst_access); // window used to update the padding requirements of dst tensor
184 }
185
186 // Collapse along the Z direction
187 // This collapse needs to be here in order to tune the Z dimension of LWS
188 Window collapsed = win;
189 const unsigned int dimension_to_collapse = std::min(static_cast<unsigned int>(dst->num_dimensions()), 2u);
190 collapsed = win.collapse(win, dimension_to_collapse);
191
192 Status err = (window_changed) ? ARM_COMPUTE_CREATE_ERROR(ErrorCode::RUNTIME_ERROR, "Insufficient Padding!") : Status{};
193 return std::make_pair(err, collapsed);
194}
195} // namespace
196
Giorgio Arena4a95bba2021-06-28 11:00:27 +0100197ClGemmMatrixMultiplyNativeKernel::ClGemmMatrixMultiplyNativeKernel()
198{
199 _type = CLKernelType::GEMM;
200}
201
Georgios Pinitas856f66e2021-04-22 21:13:21 +0100202void ClGemmMatrixMultiplyNativeKernel::configure(const CLCompileContext &compile_context, ITensorInfo *src0, ITensorInfo *src1, ITensorInfo *src2, ITensorInfo *dst, float alpha,
203 float beta,
204 const GEMMLHSMatrixInfo &lhs_info,
205 const GEMMRHSMatrixInfo &rhs_info, const GEMMKernelInfo &gemm_info)
206{
207 ARM_COMPUTE_ERROR_ON_NULLPTR(src0, src1, dst);
208
209 ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(src0, src1, src2, dst, alpha, beta, lhs_info, rhs_info, gemm_info));
210
211 auto padding_info = get_padding_info({ src0, dst });
212 _reinterpret_input_as_3d = gemm_info.reinterpret_input_as_3d;
213 _reinterpret_output_as_3d = gemm_info.depth_output_gemm3d != 0;
214 _use_dummy_work_items = preferred_dummy_work_items_support(CLKernelLibrary::get().get_device());
215 _add_bias = src2 != nullptr;
216
217 // In case both input and dst have to be reinterpreted as 3D tensors,
218 // force reinterpret_input_as_3d and reinterpret_output_as_3d to be false.
219 if(_reinterpret_input_as_3d == _reinterpret_output_as_3d)
220 {
221 _reinterpret_input_as_3d = false;
222 _reinterpret_output_as_3d = false;
223 }
224
225 // Check if we need to slide the matrix B
226 const unsigned int num_dimensions_src0 = src0->num_dimensions();
227 _slide_matrix_b = (src1->num_dimensions() >= num_dimensions_src0);
228
229 ElementsProcessed num_elements_processed{};
230
231 // Configure kernel window
232 auto win_config = validate_and_configure_window(src0, src1, src2 != nullptr ? src2 : nullptr, dst, lhs_info, rhs_info, gemm_info, num_elements_processed);
233 ARM_COMPUTE_ERROR_THROW_ON(win_config.first);
234 IClKernel::configure_internal(win_config.second);
235
236 // If _reinterpret_input_as_3d = _reinterpret_output_as_3d = true,
237 // we will dispatch a batched-GEMM to reduce the complexity of the address calculation within the OpenCL kernel.
238 // This means that the actual m used by the kernel is given by dst->dimension(1) and not by gemm_info.m
239 const unsigned int internal_m = _reinterpret_output_as_3d ? gemm_info.m : dst->dimension(1);
240
241 const unsigned int h_gemm_3d = _reinterpret_output_as_3d ? dst->dimension(1) : src0->dimension(1);
242 const unsigned int d_gemm_3d = _reinterpret_output_as_3d ? dst->dimension(2) : src0->dimension(2);
243
244 // Calculate partial (store instead of load) M0 and partial N0 for the partial blocks at the end of a row/column if any. This is to avoid padding.
245 const unsigned int partial_store_m0 = internal_m % lhs_info.m0;
246 const unsigned int partial_store_n0 = gemm_info.n % rhs_info.n0;
247
248 // Shrink M0 to be always <= M (internal_m) to prevent out-of-bounds reads.
249 // NOTE: This might have implications on heuristics and performance
250 const unsigned int internal_m0 = std::min(internal_m, lhs_info.m0);
251
252 // Create build options
253 CLBuildOptions build_opts;
254 build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(src0->data_type()));
255 build_opts.add_option_if(!(helpers::float_ops::is_one(alpha)), "-DALPHA=" + float_to_string_with_full_precision(alpha));
256 build_opts.add_option_if(src2 != nullptr, "-DBETA=" + float_to_string_with_full_precision(beta));
257 build_opts.add_option_if(helpers::float_ops::is_one(beta), "-DUNIT_BETA");
258 build_opts.add_option_if(gemm_info.broadcast_bias, "-DBROADCAST_BIAS");
259 build_opts.add_option_if(_reinterpret_input_as_3d, "-DREINTERPRET_INPUT_AS_3D");
260 build_opts.add_option_if(_reinterpret_output_as_3d, "-DREINTERPRET_OUTPUT_AS_3D");
261 build_opts.add_option_if(_reinterpret_input_as_3d || _reinterpret_output_as_3d, "-DHEIGHT_GEMM3D=" + support::cpp11::to_string(h_gemm_3d));
262 build_opts.add_option_if(_reinterpret_input_as_3d || _reinterpret_output_as_3d, "-DDEPTH_GEMM3D=" + support::cpp11::to_string(d_gemm_3d));
263 build_opts.add_option_if(!_slide_matrix_b, "-DMATRIX_B_DEPTH=" + support::cpp11::to_string(src1->dimension(2)));
264 build_opts.add_option_if(_use_dummy_work_items, "-DDUMMY_WORK_ITEMS");
265 build_opts.add_option("-DM=" + support::cpp11::to_string(internal_m));
266 build_opts.add_option("-DN=" + support::cpp11::to_string(gemm_info.n));
267 build_opts.add_option("-DK=" + support::cpp11::to_string(gemm_info.k));
268 build_opts.add_option("-DM0=" + support::cpp11::to_string(internal_m0));
269 build_opts.add_option("-DN0=" + support::cpp11::to_string(rhs_info.n0));
270 build_opts.add_option("-DK0=" + support::cpp11::to_string(rhs_info.k0));
271 build_opts.add_option("-DPARTIAL_STORE_M0=" + support::cpp11::to_string(partial_store_m0));
272 build_opts.add_option("-DPARTIAL_STORE_N0=" + support::cpp11::to_string(partial_store_n0));
273 build_opts.add_option_if(gemm_info.activation_info.enabled(), "-DACTIVATION_TYPE=" + lower_string(string_from_activation_func(gemm_info.activation_info.activation())));
274 build_opts.add_option_if(gemm_info.activation_info.enabled(), "-DA_VAL=" + float_to_string_with_full_precision(gemm_info.activation_info.a()));
275 build_opts.add_option_if(gemm_info.activation_info.enabled(), "-DB_VAL=" + float_to_string_with_full_precision(gemm_info.activation_info.b()));
276
277 std::string kernel_name("gemm_mm_native");
278
279 // Create kernel
280 _kernel = create_kernel(compile_context, kernel_name, build_opts.options());
281
282 // Set config_id for enabling LWS tuning
283 _config_id = kernel_name;
284 _config_id += "_";
285 _config_id += (_add_bias ? "add_bias_" : "");
286 _config_id += (gemm_info.broadcast_bias ? "broadcast_bias_" : "");
287 _config_id += (_reinterpret_input_as_3d ? "3di_" : "");
288 _config_id += (_reinterpret_output_as_3d ? "3do_" : "");
289 _config_id += (gemm_info.activation_info.enabled() ? "fused_activation_" : "");
290 _config_id += lower_string(string_from_data_type(src0->data_type()));
291 _config_id += "_";
292 _config_id += support::cpp11::to_string(dst->dimension(1));
293 _config_id += "_";
294 _config_id += support::cpp11::to_string(dst->dimension(0));
295 _config_id += "_";
296 _config_id += support::cpp11::to_string(gemm_info.k);
297 _config_id += "_";
298 _config_id += support::cpp11::to_string(dst->dimension(2));
299 _config_id += "_";
300 _config_id += support::cpp11::to_string(lhs_info.m0);
301 _config_id += "_";
302 _config_id += support::cpp11::to_string(rhs_info.n0);
303 _config_id += "_";
304 _config_id += support::cpp11::to_string(rhs_info.k0);
305
306 ARM_COMPUTE_ERROR_ON(has_padding_changed(padding_info));
307}
308
309Status ClGemmMatrixMultiplyNativeKernel::validate(const ITensorInfo *src0, const ITensorInfo *src1, const ITensorInfo *src2, const ITensorInfo *dst, float alpha, float beta,
310 const GEMMLHSMatrixInfo &lhs_info,
311 const GEMMRHSMatrixInfo &rhs_info, const GEMMKernelInfo &gemm_info)
312{
313 ElementsProcessed num_elements_processed{};
314 ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(src0, src1, src2, dst, alpha, beta, lhs_info, rhs_info, gemm_info));
315 ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window(src0->clone().get(),
316 src1->clone().get(),
317 src2 != nullptr ? src2->clone().get() : nullptr,
318 dst->clone().get(),
319 lhs_info,
320 rhs_info,
321 gemm_info,
322 num_elements_processed)
323 .first);
324
325 return Status{};
326}
327
328void ClGemmMatrixMultiplyNativeKernel::run_op(ITensorPack &tensors, const Window &window, cl::CommandQueue &queue)
329{
330 ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
331 ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(ICLKernel::window(), window);
332
333 const auto src0 = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC_0));
334 const auto src1 = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC_1));
335 const auto src2 = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC_2));
336 auto dst = utils::cast::polymorphic_downcast<ICLTensor *>(tensors.get_tensor(TensorType::ACL_DST));
337
338 ARM_COMPUTE_ERROR_ON_NULLPTR(src0, src1, dst);
339 ARM_COMPUTE_ERROR_ON(_add_bias && src2 == nullptr);
340
341 if(src1->info()->num_dimensions() < 3)
342 {
343 // The stride_z for matrix B must be zero if we do not slice
344 ARM_COMPUTE_ERROR_ON(src1->info()->strides_in_bytes()[3] != 0);
345 }
346
347 Window slice = window.first_slice_window_3D();
348 Window slice_matrix_b = slice;
349
350 slice_matrix_b.set(Window::DimX, Window::Dimension(0, 1, 1));
351 slice_matrix_b.set(Window::DimY, Window::Dimension(0, 1, 1));
352
353 if(_reinterpret_input_as_3d)
354 {
355 // Pass bottom paddings to the kernel if the input has to be reinterpreted as 3D tensor
356 unsigned int idx0;
357 if(_add_bias)
358 {
359 idx0 = 4 * num_arguments_per_2D_tensor() + 4;
360 }
361 else
362 {
363 idx0 = 3 * num_arguments_per_2D_tensor() + 3;
364 }
365 const unsigned int total_cross_plane_pad = src0->info()->padding().top + src0->info()->padding().bottom;
366 _kernel.setArg<cl_uint>(idx0, static_cast<unsigned int>(total_cross_plane_pad));
367 }
368
369 if(_reinterpret_output_as_3d)
370 {
371 // Pass bottom paddings to the kernel if the dst has to be reinterpreted as 3D tensor
372 unsigned int idx0;
373 if(_add_bias)
374 {
375 idx0 = 4 * num_arguments_per_2D_tensor() + 4 + (_reinterpret_input_as_3d ? 1 : 0);
376 }
377 else
378 {
379 idx0 = 3 * num_arguments_per_2D_tensor() + 3 + (_reinterpret_input_as_3d ? 1 : 0);
380 }
381 const unsigned int total_cross_plane_pad = dst->info()->padding().top + dst->info()->padding().bottom;
382 _kernel.setArg<cl_uint>(idx0, static_cast<unsigned int>(total_cross_plane_pad));
383 }
384
385 do
386 {
387 Window slice_b = slice;
388 // Don't slice matrix B along the z dimension if matrix B has just 2 dimensions and matrix A more than 2
389 // This scenario can happen when the matrix multiplication is used to perform a convolution operation
390 if(!_slide_matrix_b)
391 {
392 slice_b = slice_matrix_b;
393 }
394
395 unsigned int idx = 0;
396 add_2D_tensor_argument(idx, src0, slice);
397 add_2D_tensor_argument(idx, src1, slice_b);
398 if(_add_bias)
399 {
400 add_2D_tensor_argument(idx, src2, slice);
401 }
402 add_2D_tensor_argument(idx, dst, slice);
403 _kernel.setArg<cl_uint>(idx++, static_cast<unsigned int>(src0->info()->strides_in_bytes()[2]));
404 _kernel.setArg<cl_uint>(idx++, static_cast<unsigned int>(src1->info()->strides_in_bytes()[2]));
405 if(_add_bias)
406 {
407 _kernel.setArg<cl_uint>(idx++, static_cast<unsigned int>(src2->info()->strides_in_bytes()[2]));
408 }
409 _kernel.setArg<cl_uint>(idx++, static_cast<unsigned int>(dst->info()->strides_in_bytes()[2]));
410 enqueue(queue, *this, slice, lws_hint(), _use_dummy_work_items);
411 }
412 while(window.slide_window_slice_3D(slice));
413}
414} // namespace kernels
415} // namespace opencl
416} // namespace arm_compute