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