blob: 734f8f9b4c934dc213ca5ab19ff295b6fa0f7afa [file] [log] [blame]
Gunes Bayir4bfc70e2021-12-10 16:17:56 +00001/*
Gian Marco Iodice3cce35d2022-12-30 16:07:45 +00002 * Copyright (c) 2022-2023 Arm Limited.
Gunes Bayir4bfc70e2021-12-10 16:17:56 +00003 *
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 */
24#include "src/gpu/cl/kernels/ClGemmMatrixMultiplyReshapedOnlyRhsMMULKernel.h"
25
Matthew Bentham314d3e22023-06-23 10:53:52 +000026#include "arm_compute/core/utils/ActivationFunctionUtils.h"
Gunes Bayir4bfc70e2021-12-10 16:17:56 +000027#include "arm_compute/core/CL/CLHelpers.h"
28#include "arm_compute/core/CL/CLKernelLibrary.h"
29#include "arm_compute/core/CL/ICLTensor.h"
30#include "arm_compute/core/CL/OpenCL.h"
31#include "arm_compute/core/Helpers.h"
32#include "arm_compute/core/TensorInfo.h"
Matthew Bentham314d3e22023-06-23 10:53:52 +000033#include "arm_compute/core/utils/StringUtils.h"
Gunes Bayir4bfc70e2021-12-10 16:17:56 +000034#include "arm_compute/core/Validate.h"
35#include "arm_compute/core/utils/misc/ShapeCalculator.h"
36#include "src/core/CL/CLUtils.h"
37#include "src/core/helpers/AutoConfiguration.h"
38#include "src/core/helpers/WindowHelpers.h"
39#include "src/core/utils/helpers/float_ops.h"
40#include "src/gpu/cl/kernels/gemm/ClGemmHelpers.h"
41#include "support/Cast.h"
42#include "support/StringSupport.h"
43
44namespace arm_compute
45{
46namespace opencl
47{
48namespace kernels
49{
50namespace
51{
52using ElementsProcessed = Steps;
53
54// Block size dimensions for the MMUL extension
55constexpr int mmul_m0 = 4;
56constexpr int mmul_n0 = 4;
57constexpr int mmul_k0 = 4;
58
59Status validate_arguments(const ITensorInfo *src0, const ITensorInfo *src1, const ITensorInfo *src2, const ITensorInfo *dst, float alpha, float beta, const GEMMLHSMatrixInfo &lhs_info,
60 const GEMMRHSMatrixInfo &rhs_info,
61 const GEMMKernelInfo &gemm_info)
62{
63 ARM_COMPUTE_UNUSED(alpha);
64 ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(src0, src1, dst);
65 ARM_COMPUTE_RETURN_ERROR_ON_MSG(!arm_matrix_multiply_supported(CLKernelLibrary::get().get_device()), "The extension cl_arm_matrix_multiply is not supported on the target platform");
66 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(src0, 1, DataType::F16, DataType::F32);
67 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src0, src1);
68 ARM_COMPUTE_RETURN_ERROR_ON_MSG(src0->num_dimensions() > 4, "The number of dimensions for the LHS matrix must be <= 4");
69 ARM_COMPUTE_RETURN_ERROR_ON_MSG(src1->num_dimensions() > 3, "The number of dimensions for the RHS matrix must be <= 3");
70 ARM_COMPUTE_RETURN_ERROR_ON_MSG(lhs_info.m0 < 1, "Only values greater than 0 are supported for m0");
71 ARM_COMPUTE_RETURN_ERROR_ON_MSG(rhs_info.n0 != 1 && rhs_info.n0 != 2 && rhs_info.n0 != 3 && rhs_info.n0 != 4 && rhs_info.n0 != 8 && rhs_info.n0 != 16, "Only 1,2,3,4,8, and 16 are supported for n0");
72 ARM_COMPUTE_RETURN_ERROR_ON_MSG((rhs_info.k0 != 1 || lhs_info.k0 != 1), "Only 1 is supported for k0");
73 ARM_COMPUTE_RETURN_ERROR_ON_MSG((rhs_info.h0 != 4), "Only 4 is supported for h0");
74 ARM_COMPUTE_RETURN_ERROR_ON_MSG(rhs_info.interleave != true, "Only true is supported for interleave with mmul extension enabled");
75 ARM_COMPUTE_RETURN_ERROR_ON_MSG(rhs_info.transpose != false, "Only false is supported for transpose with mmul extension enabled");
76 ARM_COMPUTE_RETURN_ERROR_ON_MSG(gemm_info.fp_mixed_precision, "Mixed precision not supported");
77 ARM_COMPUTE_RETURN_ON_ERROR(gemm::validate_image2d_support_on_rhs(*src1, rhs_info));
78
79 const unsigned int m = gemm_info.m;
80 const unsigned int n = gemm_info.n;
81 const unsigned int k = gemm_info.k;
82
83 ARM_COMPUTE_UNUSED(m);
84 ARM_COMPUTE_UNUSED(n);
85 ARM_COMPUTE_UNUSED(k);
86
87 ARM_COMPUTE_RETURN_ERROR_ON(src0->dimension(0) != k);
88
89 // Validate the reinterpreted-as-3D-case
90 if(gemm_info.depth_output_gemm3d != 0)
91 {
92 ARM_COMPUTE_RETURN_ERROR_ON(src0->dimension(1) * src0->dimension(2) != m);
93 }
94 else
95 {
96 ARM_COMPUTE_RETURN_ERROR_ON(src0->dimension(1) != m);
97 }
98
99 // Validate the gemm-batched case
100 if(src1->num_dimensions() > 2)
101 {
102 if(gemm_info.depth_output_gemm3d != 0)
103 {
104 ARM_COMPUTE_RETURN_ERROR_ON(src0->dimension(3) != src1->dimension(2));
105 }
106 else
107 {
108 ARM_COMPUTE_RETURN_ERROR_ON(src0->dimension(2) != src1->dimension(2));
109 }
110 }
111
112 if(src2 != nullptr && !(helpers::float_ops::is_zero(beta)))
113 {
114 const unsigned int src2_dim0 = src2->dimension(0);
115 const unsigned int src2_dim1 = src2->dimension(1);
116
117 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src2, src1);
118 if(gemm_info.broadcast_bias)
119 {
120 ARM_COMPUTE_RETURN_ERROR_ON_MSG((src2_dim1 != 1 || src2_dim0 != n), "Incorrect dimension of bias matrix which is to be broadcasted");
121 }
122 else
123 {
124 ARM_COMPUTE_RETURN_ERROR_ON_MSG((src2_dim0 != n || src2_dim1 != m), "Incorrect dimension of bias matrix");
125 }
126 }
127
128 TensorShape tensor_shape1{ src1->tensor_shape() };
129 tensor_shape1.set(0, n);
130 tensor_shape1.set(1, k);
131
132 const TensorInfo tensor_info1 = src1->clone()->set_tensor_shape(tensor_shape1);
133 const TensorInfo tensor_info_reshaped1 = src1->clone()->set_tensor_shape(misc::shape_calculator::compute_rhs_reshaped_shape(tensor_info1, rhs_info));
134
135 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(src1, &tensor_info_reshaped1);
136
137 if(dst->total_size() != 0)
138 {
139 const TensorInfo tensor_info_dst = dst->clone()->set_tensor_shape(misc::shape_calculator::compute_mm_shape(*src0, *src1, gemm_info));
140 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(dst, &tensor_info_dst);
141 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src0, dst);
142 }
143
144 return Status{};
145}
146
147std::pair<Status, Window> validate_and_configure_window(ITensorInfo *src0, ITensorInfo *src1, ITensorInfo *src2, ITensorInfo *dst, const GEMMLHSMatrixInfo &lhs_info,
148 const GEMMRHSMatrixInfo &rhs_info,
149 const GEMMKernelInfo &gemm_info)
150{
151 ARM_COMPUTE_UNUSED(src0, src1, src2);
152 bool reinterpret_output_as_3d = gemm_info.depth_output_gemm3d != 0;
153
154 // dst tensor auto initialization if not yet initialized
155 auto_init_if_empty(*dst, src0->clone()->set_tensor_shape(misc::shape_calculator::compute_mm_shape(*src0, *src1, gemm_info)));
156
157 TensorInfo tmp_info(*dst);
158
159 if(reinterpret_output_as_3d)
160 {
161 // Since the dst tensor has to be reinterpreted as 3D and the execute window is based on a 2D GEMM,
162 // the window needs to be constructed on the 2D collapsed version of the tensor
163 TensorShape tmp_shape(dst->tensor_shape());
164 tmp_shape.collapse(2U, 1U);
165 tmp_info.set_tensor_shape(tmp_shape);
166 }
167
168 Window win = calculate_max_window(tmp_info, Steps(1, 1));
169
170 // Collapse along the Z direction
171 // This collapse needs to be here in order to tune the Z dimension of LWS
172 const unsigned int dimension_to_collapse = std::min(static_cast<unsigned int>(dst->num_dimensions()), 2u);
173 Window collapsed = win.collapse(win, dimension_to_collapse);
174
175 // Reconfigure window size, one arm_matrix_multiply kernel needs 16 threads to finish.
176 Window::Dimension x_dimension = collapsed.x();
177 Window::Dimension y_dimension = collapsed.y();
178
179 // Make M and N multiple of M0 and N0 respectively
180 const unsigned int ceil_to_multiple_n_n0 = ceil_to_multiple(x_dimension.end(), rhs_info.n0);
181 const unsigned int ceil_to_multiple_m_m0 = ceil_to_multiple(y_dimension.end(), lhs_info.m0);
182
183 // Divide M and N by M0 and N0 respectively
184 const unsigned int n_div_n0 = ceil_to_multiple_n_n0 / rhs_info.n0;
185 const unsigned int m_div_m0 = ceil_to_multiple_m_m0 / lhs_info.m0;
186
187 // Make n_div_n0 and m_div_m0 multiple of mmul_n0 and mmul_k0 respectively
188 const unsigned int ceil_to_multiple_n_div_n0_mmul_n0 = ceil_to_multiple(n_div_n0, mmul_n0);
189 const unsigned int ceil_to_multiple_m_div_m0_mmul_k0 = ceil_to_multiple(m_div_m0, mmul_k0);
190
191 // Ensure x_dimension is multiple of MMUL block size (mmul_n0 * mmul_k0)
192 x_dimension.set_end(ceil_to_multiple_n_div_n0_mmul_n0 * mmul_k0);
193 y_dimension.set_end(ceil_to_multiple_m_div_m0_mmul_k0 / mmul_k0);
194
195 collapsed.set(Window::DimX, x_dimension);
196 collapsed.set(Window::DimY, y_dimension);
197
198 return std::make_pair(Status{}, collapsed);
199}
200} // namespace
201
202ClGemmMatrixMultiplyReshapedOnlyRhsMMULKernel::ClGemmMatrixMultiplyReshapedOnlyRhsMMULKernel()
203{
204 _type = CLKernelType::GEMM;
205}
206
207void ClGemmMatrixMultiplyReshapedOnlyRhsMMULKernel::configure(const CLCompileContext &compile_context, ITensorInfo *src0, ITensorInfo *src1, ITensorInfo *src2, ITensorInfo *dst, float alpha,
208 float beta,
209 const GEMMLHSMatrixInfo &lhs_info,
210 const GEMMRHSMatrixInfo &rhs_info, const GEMMKernelInfo &gemm_info)
211{
212 ARM_COMPUTE_ERROR_ON_NULLPTR(src0, src1, dst);
213
214 // dst tensor auto initialization if not yet initialized
215 auto_init_if_empty(*dst, src0->clone()->set_tensor_shape(misc::shape_calculator::compute_mm_shape(*src0, *src1, gemm_info)));
216
217 ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(src0, src1, src2, dst, alpha, beta, lhs_info, rhs_info, gemm_info));
218
219 auto padding_info = get_padding_info({ src0, src1, src2, dst });
220 _add_bias = src2 != nullptr;
221 _export_to_cl_image = rhs_info.export_to_cl_image;
222
223 // Configure kernel window
224 auto win_config = validate_and_configure_window(src0, src1, src2, dst, lhs_info, rhs_info, gemm_info);
225 ARM_COMPUTE_ERROR_THROW_ON(win_config.first);
226
227 IClKernel::configure_internal(win_config.second);
228
229 _m = gemm_info.m;
230 _n = gemm_info.n;
231 _k = gemm_info.k;
232
233 const unsigned int m0_leftover = _m % lhs_info.m0;
234 const unsigned int n0_leftover = _n % rhs_info.n0;
235
236 // Create build options
237 CLBuildOptions build_opts;
238 build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(src0->data_type()));
239 build_opts.add_option_if(!(helpers::float_ops::is_one(alpha)), "-DALPHA=" + float_to_string_with_full_precision(alpha));
240 build_opts.add_option_if(src2 != nullptr, "-DBETA=" + float_to_string_with_full_precision(beta));
241 build_opts.add_option_if(helpers::float_ops::is_one(beta), "-DUNIT_BETA");
242 build_opts.add_option_if(gemm_info.broadcast_bias, "-DBROADCAST_BIAS");
243 build_opts.add_option_if(src0->data_type() == DataType::F16, "-DHALF_PRECISION");
244 build_opts.add_option("-DM0=" + support::cpp11::to_string(lhs_info.m0));
245 build_opts.add_option("-DN0=" + support::cpp11::to_string(rhs_info.n0));
246 build_opts.add_option("-DK0=" + support::cpp11::to_string(rhs_info.k0));
247 build_opts.add_option("-DM0_LEFTOVER=" + support::cpp11::to_string(m0_leftover));
248 build_opts.add_option("-DN0_LEFTOVER=" + support::cpp11::to_string(n0_leftover));
249 build_opts.add_option("-DMMUL_M0=" + support::cpp11::to_string(mmul_m0));
250 build_opts.add_option("-DMMUL_N0=" + support::cpp11::to_string(mmul_n0));
251 build_opts.add_option("-DMMUL_K0=" + support::cpp11::to_string(mmul_k0));
252 build_opts.add_option("-DACTIVATION_TYPE=" + lower_string(string_from_activation_func(gemm_info.activation_info.activation())));
253 build_opts.add_option("-DA_VAL=" + float_to_string_with_full_precision(gemm_info.activation_info.a()));
254 build_opts.add_option("-DB_VAL=" + float_to_string_with_full_precision(gemm_info.activation_info.b()));
255
256 std::string kernel_name("gemm_mm_reshaped_only_rhs_nt_mmul");
257 kernel_name += rhs_info.export_to_cl_image ? "_texture" : "";
258
259 // A macro guard to compile ONLY the kernel of interest
260 build_opts.add_option("-D" + upper_string(kernel_name));
261
262 // Create kernel
263 _kernel = create_kernel(compile_context, kernel_name, build_opts.options());
264
265 // Set config_id for enabling LWS tuning
266 _config_id = kernel_name;
267 _config_id += "_";
268 _config_id += (_add_bias ? "add_bias_" : "");
269 _config_id += (gemm_info.broadcast_bias ? "broadcast_bias_" : "");
270 _config_id += (gemm_info.activation_info.enabled() ? "fused_activation_" : "");
271 _config_id += lower_string(string_from_data_type(src0->data_type()));
272 _config_id += "_";
273 _config_id += support::cpp11::to_string(_m);
274 _config_id += "_";
275 _config_id += support::cpp11::to_string(_n);
276 _config_id += "_";
277 _config_id += support::cpp11::to_string(_k);
278 _config_id += "_";
279 _config_id += support::cpp11::to_string(lhs_info.m0);
280 _config_id += "_";
281 _config_id += support::cpp11::to_string(rhs_info.n0);
282
283 ARM_COMPUTE_ERROR_ON(has_padding_changed(padding_info));
284}
285
286Status ClGemmMatrixMultiplyReshapedOnlyRhsMMULKernel::validate(const ITensorInfo *src0, const ITensorInfo *src1, const ITensorInfo *src2, const ITensorInfo *dst, float alpha, float beta,
287 const GEMMLHSMatrixInfo &lhs_info,
288 const GEMMRHSMatrixInfo &rhs_info, const GEMMKernelInfo &gemm_info)
289{
290 ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(src0, src1, src2, dst, alpha, beta, lhs_info, rhs_info, gemm_info));
291 ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window(src0->clone().get(),
292 src1->clone().get(),
293 src2 != nullptr ? src2->clone().get() : nullptr,
294 dst->clone().get(),
295 lhs_info,
296 rhs_info,
297 gemm_info)
298 .first);
299
300 return Status{};
301}
302
303void ClGemmMatrixMultiplyReshapedOnlyRhsMMULKernel::run_op(ITensorPack &tensors, const Window &window, cl::CommandQueue &queue)
304{
305 ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
306 ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(ICLKernel::window(), window);
307
308 const auto src0 = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC_0));
309 const auto src1 = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC_1));
310 const auto src2 = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC_2));
311 auto dst = utils::cast::polymorphic_downcast<ICLTensor *>(tensors.get_tensor(TensorType::ACL_DST));
312
313 ARM_COMPUTE_ERROR_ON_NULLPTR(src0, src1, dst);
314 ARM_COMPUTE_ERROR_ON(_add_bias && src2 == nullptr);
315
316 if(src1->info()->num_dimensions() < 3)
317 {
318 // The stride_z for matrix B must be zero if we do not slice
319 ARM_COMPUTE_ERROR_ON(src1->info()->strides_in_bytes()[3] != 0);
320 }
321
322 cl::Image2D src1_image2d;
323
324 if(_export_to_cl_image)
325 {
326 const TensorShape shape2d(src1->info()->dimension(0) / 4, src1->info()->dimension(1) * src1->info()->dimension(2));
327 const size_t image_row_pitch = src1->info()->strides_in_bytes()[1];
328
Gian Marco Iodice3cce35d2022-12-30 16:07:45 +0000329 src1_image2d = create_image2d_from_buffer(CLKernelLibrary::get().context(), src1->cl_buffer(), shape2d, src1->info()->data_type(), image_row_pitch, CLImage2DType::ReadOnly);
Gunes Bayir4bfc70e2021-12-10 16:17:56 +0000330 }
331
332 Window slice = window.first_slice_window_3D();
333
334 do
335 {
336 unsigned int idx = 0;
337
338 add_3d_tensor_nhw_argument(idx, src0);
339 if(_export_to_cl_image)
340 {
341 _kernel.setArg(idx++, src1_image2d);
342 }
343 add_3d_tensor_nhw_argument(idx, src1);
344
345 // Bias buffer (_add_bias == true)
346 if(_add_bias)
347 {
348 add_3d_tensor_nhw_argument(idx, src2);
349 }
350 // dst buffer
351 add_3d_tensor_nhw_argument(idx, dst);
352
353 // Pass m, n and k at runtime as signed ints, to ensure results of any subtractions they could be operand in, would still be signed.
354 _kernel.setArg<cl_int>(idx++, _m);
355 _kernel.setArg<cl_int>(idx++, _n);
356 _kernel.setArg<cl_int>(idx++, _k);
357
358 // LWS_x should be multiple of 16 at least. (32, 2) has been chosen to have more work-items on a single core
359 // LWS also enforces the order of execution of the workitems which improves cache utilization
360 enqueue(queue, *this, slice, cl::NDRange(32, 2), false);
361 }
362 while(window.slide_window_slice_3D(slice));
363}
364} // namespace kernels
365} // namespace opencl
366} // namespace arm_compute