aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRamy Elgammal <ramy.elgammal@arm.com>2023-03-09 21:15:37 +0000
committerGunes Bayir <gunes.bayir@arm.com>2023-03-17 11:00:57 +0000
commit2b6ebfe4270b06b09e45f306e8384950aeca7e4e (patch)
tree44a65551aa32352a57090bf550b96cbf5b54222f
parent40aab11ff88ed432d5028478e531f8d0fc404d4c (diff)
downloadComputeLibrary-2b6ebfe4270b06b09e45f306e8384950aeca7e4e.tar.gz
Implement OpenCL MatMul for Lhs NT Rhs T/NT FP32/16
- Implement ClNativeMatMulKernel class - Implement opencl kernel for LHS non-transposed and RHS non-transposed - Implement opencl kernel for LHS non-transposed and RHS transposed - Add test fixture and dataset for matmul - Implement transpose_tensor() for reference implementation to transpose high dimensional tensors Resolves: COMPMID-5944, COMPMID-5951 Co-authored-by: Gunes Bayir <gunes.bayir@arm.com> Co-authored-by: Ramy Elgammal <ramy.elgammal@arm.com> Change-Id: I1d5b8978f41be27baddb3153ade880472141573f Signed-off-by: Gunes Bayir <gunes.bayir@arm.com> Signed-off-by: Ramy Elgammal <ramy.elgammal@arm.com> Reviewed-on: https://review.mlplatform.org/c/ml/ComputeLibrary/+/9333 Tested-by: Arm Jenkins <bsgcomp@arm.com> Reviewed-by: Gian Marco Iodice <gianmarco.iodice@arm.com> Benchmark: Arm Jenkins <bsgcomp@arm.com>
-rw-r--r--Android.bp2
-rw-r--r--SConscript19
-rw-r--r--arm_compute/core/KernelDescriptors.h20
-rw-r--r--arm_compute/core/utils/misc/ShapeCalculator.h34
-rw-r--r--filelist.json7
-rw-r--r--src/core/CL/cl_kernels/common/mat_mul.cl299
-rw-r--r--src/core/CL/cl_kernels/tile_helpers.h21
-rw-r--r--src/gpu/cl/ClKernelLibrary.cpp8
-rw-r--r--src/gpu/cl/kernels/ClNativeMatMulKernel.cpp192
-rw-r--r--src/gpu/cl/kernels/ClNativeMatMulKernel.h70
-rw-r--r--tests/datasets/BatchMatMulDataset.h110
-rw-r--r--tests/datasets/LargeBatchMatMulDataset.h60
-rw-r--r--tests/datasets/SmallBatchMatMulDataset.h52
-rw-r--r--tests/validation/CL/BatchMatMul.cpp239
-rw-r--r--tests/validation/fixtures/BatchMatMulFixture.h203
-rw-r--r--utils/TypePrinter.h116
16 files changed, 1393 insertions, 59 deletions
diff --git a/Android.bp b/Android.bp
index 28bc7e20dc..42116d78ca 100644
--- a/Android.bp
+++ b/Android.bp
@@ -49,6 +49,7 @@ opencl_srcs = [
"src/core/CL/cl_kernels/common/generate_proposals_quantized.cl",
"src/core/CL/cl_kernels/common/instance_normalization.cl",
"src/core/CL/cl_kernels/common/l2_normalize.cl",
+ "src/core/CL/cl_kernels/common/mat_mul.cl",
"src/core/CL/cl_kernels/common/mean_stddev_normalization.cl",
"src/core/CL/cl_kernels/common/memset.cl",
"src/core/CL/cl_kernels/common/minmax_layer.cl",
@@ -689,6 +690,7 @@ cc_library_static {
"src/gpu/cl/kernels/ClIndirectConv2dAddressPrecalculationKernel.cpp",
"src/gpu/cl/kernels/ClIndirectConv2dKernel.cpp",
"src/gpu/cl/kernels/ClMulKernel.cpp",
+ "src/gpu/cl/kernels/ClNativeMatMulKernel.cpp",
"src/gpu/cl/kernels/ClPermuteKernel.cpp",
"src/gpu/cl/kernels/ClPool2dKernel.cpp",
"src/gpu/cl/kernels/ClPool3dKernel.cpp",
diff --git a/SConscript b/SConscript
index a480c45d62..205764b9a7 100644
--- a/SConscript
+++ b/SConscript
@@ -359,6 +359,7 @@ if env['opencl'] and env['embed_kernels']:
'src/core/CL/cl_kernels/common/cast.cl',
'src/core/CL/cl_kernels/common/comparisons.cl',
'src/core/CL/cl_kernels/common/concatenate.cl',
+ 'src/core/CL/cl_kernels/common/convolution_layer.cl',
'src/core/CL/cl_kernels/common/col2im.cl',
'src/core/CL/cl_kernels/common/convert_fc_weights.cl',
'src/core/CL/cl_kernels/common/copy_tensor.cl',
@@ -368,6 +369,9 @@ if env['opencl'] and env['embed_kernels']:
'src/core/CL/cl_kernels/common/elementwise_operation.cl',
'src/core/CL/cl_kernels/common/elementwise_operation_quantized.cl',
'src/core/CL/cl_kernels/common/elementwise_unary.cl',
+ 'src/core/CL/cl_kernels/common/experimental/gemm_fused_post_ops/act_eltwise_op_act/gemm_mm_native.cl',
+ 'src/core/CL/cl_kernels/common/experimental/gemm_fused_post_ops/act_eltwise_op_act/gemm_mm_reshaped.cl',
+ 'src/core/CL/cl_kernels/common/experimental/gemm_fused_post_ops/act_eltwise_op_act/gemm_mm_reshaped_only_rhs.cl',
'src/core/CL/cl_kernels/common/fft_digit_reverse.cl',
'src/core/CL/cl_kernels/common/fft.cl',
'src/core/CL/cl_kernels/common/fft_scale.cl',
@@ -377,21 +381,18 @@ if env['opencl'] and env['embed_kernels']:
'src/core/CL/cl_kernels/common/gemm.cl',
'src/core/CL/cl_kernels/common/gemm_reshaped_only_rhs_mmul.cl',
'src/core/CL/cl_kernels/common/gemm_utils.cl',
- 'src/core/CL/cl_kernels/common/experimental/gemm_fused_post_ops/act_eltwise_op_act/gemm_mm_native.cl',
- 'src/core/CL/cl_kernels/common/experimental/gemm_fused_post_ops/act_eltwise_op_act/gemm_mm_reshaped.cl',
- 'src/core/CL/cl_kernels/common/experimental/gemm_fused_post_ops/act_eltwise_op_act/gemm_mm_reshaped_only_rhs.cl',
- 'src/core/CL/cl_kernels/common/gemv.cl',
'src/core/CL/cl_kernels/common/gemmlowp.cl',
'src/core/CL/cl_kernels/common/gemmlowp_reshaped_only_rhs_mmul.cl',
+ 'src/core/CL/cl_kernels/common/gemv.cl',
'src/core/CL/cl_kernels/common/generate_proposals.cl',
'src/core/CL/cl_kernels/common/generate_proposals_quantized.cl',
'src/core/CL/cl_kernels/common/instance_normalization.cl',
'src/core/CL/cl_kernels/common/l2_normalize.cl',
+ 'src/core/CL/cl_kernels/common/mat_mul.cl',
'src/core/CL/cl_kernels/common/mean_stddev_normalization.cl',
- 'src/core/CL/cl_kernels/common/unpooling_layer.cl',
'src/core/CL/cl_kernels/common/memset.cl',
- 'src/core/CL/cl_kernels/common/nonmax.cl',
'src/core/CL/cl_kernels/common/minmax_layer.cl',
+ 'src/core/CL/cl_kernels/common/nonmax.cl',
'src/core/CL/cl_kernels/common/pad_layer.cl',
'src/core/CL/cl_kernels/common/permute.cl',
'src/core/CL/cl_kernels/common/pixelwise_mul_float.cl',
@@ -401,18 +402,18 @@ if env['opencl'] and env['embed_kernels']:
'src/core/CL/cl_kernels/common/range.cl',
'src/core/CL/cl_kernels/common/reduction_operation.cl',
'src/core/CL/cl_kernels/common/reshape_layer.cl',
- 'src/core/CL/cl_kernels/common/convolution_layer.cl',
'src/core/CL/cl_kernels/common/reverse.cl',
'src/core/CL/cl_kernels/common/roi_align_layer.cl',
'src/core/CL/cl_kernels/common/roi_align_layer_quantized.cl',
'src/core/CL/cl_kernels/common/roi_pooling_layer.cl',
'src/core/CL/cl_kernels/common/select.cl',
+ 'src/core/CL/cl_kernels/common/slice_ops.cl',
'src/core/CL/cl_kernels/common/softmax_layer.cl',
'src/core/CL/cl_kernels/common/softmax_layer_quantized.cl',
'src/core/CL/cl_kernels/common/stack_layer.cl',
- 'src/core/CL/cl_kernels/common/slice_ops.cl',
'src/core/CL/cl_kernels/common/tile.cl',
- 'src/core/CL/cl_kernels/common/transpose.cl'
+ 'src/core/CL/cl_kernels/common/transpose.cl',
+ 'src/core/CL/cl_kernels/common/unpooling_layer.cl'
]
# NCHW kernels
diff --git a/arm_compute/core/KernelDescriptors.h b/arm_compute/core/KernelDescriptors.h
index 19ac254c04..016e03d88e 100644
--- a/arm_compute/core/KernelDescriptors.h
+++ b/arm_compute/core/KernelDescriptors.h
@@ -21,8 +21,8 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
-#ifndef ARM_COMPUTE_CORE_KERNEL_DESCRIPTORS_H
-#define ARM_COMPUTE_CORE_KERNEL_DESCRIPTORS_H
+#ifndef ACL_ARM_COMPUTE_CORE_KERNELDESCRIPTORS
+#define ACL_ARM_COMPUTE_CORE_KERNELDESCRIPTORS
#include "arm_compute/core/PixelValue.h"
#include "arm_compute/core/Types.h"
@@ -223,5 +223,19 @@ struct ScaleKernelInfo
bool align_corners; /**< Align corners of input and output */
DataLayout data_layout; /**< Data layout to use */
};
+
+struct MatMulKernelInfo
+{
+ MatMulKernelInfo(bool adj_lhs = false, bool adj_rhs = false, int m0 = 1, int n0 = 1, int k0 = 1, bool export_rhs_to_cl_image = false)
+ : adj_lhs{ adj_lhs }, adj_rhs{ adj_rhs }, m0{ m0 }, n0{ n0 }, k0{ k0 }, export_rhs_to_cl_image{ export_rhs_to_cl_image }
+ {
+ }
+ bool adj_lhs{ false }; /**< Get Adjoint LHS flag value */
+ bool adj_rhs{ false }; /**< Get Adjoint RHS flag value */
+ int m0{ 1 }; /**< Number of output rows processed by each work-item*/
+ int n0{ 1 }; /**< Number of output columns processed by each work-item*/
+ int k0{ 1 }; /**< Number of inner accumulations */
+ bool export_rhs_to_cl_image{ false }; /**< Flag to know whether the RHS tensor should be exported to cl_image*/
+};
} // namespace arm_compute
-#endif /* ARM_COMPUTE_CORE_KERNEL_DESCRIPTORS_H */
+#endif /* ACL_ARM_COMPUTE_CORE_KERNELDESCRIPTORS */
diff --git a/arm_compute/core/utils/misc/ShapeCalculator.h b/arm_compute/core/utils/misc/ShapeCalculator.h
index 6655cc1439..75a063f75c 100644
--- a/arm_compute/core/utils/misc/ShapeCalculator.h
+++ b/arm_compute/core/utils/misc/ShapeCalculator.h
@@ -21,8 +21,8 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
-#ifndef ARM_COMPUTE_MISC_SHAPE_CALCULATOR_H
-#define ARM_COMPUTE_MISC_SHAPE_CALCULATOR_H
+#ifndef ACL_ARM_COMPUTE_CORE_UTILS_MISC_SHAPECALCULATOR
+#define ACL_ARM_COMPUTE_CORE_UTILS_MISC_SHAPECALCULATOR
#include "arm_compute/core/Helpers.h"
#include "arm_compute/core/ITensorInfo.h"
@@ -1008,6 +1008,34 @@ inline TensorShape compute_mm_shape(const ITensorInfo &input0, const ITensorInfo
/** Calculate the matrix multiplication output shape of two tensors
*
+ * @param[in] input0 First input tensor info
+ * @param[in] input1 Second input tensor info
+ * @param[in] matmul_info Batch MatMul Kernel info to know which matrix is transposed
+ *
+ * @return the calculated shape
+ */
+inline TensorShape compute_batchmatmul_shape(const TensorShape &input0, const TensorShape &input1, const MatMulKernelInfo &matmul_info)
+{
+ TensorShape output_shape{ input0 };
+
+ if(matmul_info.adj_lhs)
+ {
+ output_shape.set(1, input0[0]); // The vertical (M) dimension
+ }
+
+ if(matmul_info.adj_rhs)
+ {
+ output_shape.set(0, input1[1]); // The horizontal (N) dimension
+ }
+ else
+ {
+ output_shape.set(0, input1[0]); // The horizontal (N) dimension
+ }
+
+ return output_shape;
+}
+/** Calculate the matrix multiplication output shape of two tensors
+ *
* @param[in] input Input tensor info
* @param[in] gemm_3d_depth (Optional) GEMM 3d depth
* @param[in] batch_size_on_z (Optional) True if batch size is on z axis
@@ -1579,4 +1607,4 @@ inline TensorShape compute_gather_shape(const TensorShape &input_shape, const Te
} // namespace shape_calculator
} // namespace misc
} // namespace arm_compute
-#endif /* ARM_COMPUTE_MISC_SHAPE_CALCULATOR_H */
+#endif /* ACL_ARM_COMPUTE_CORE_UTILS_MISC_SHAPECALCULATOR */
diff --git a/filelist.json b/filelist.json
index 1b0d07bc42..f858c6a29f 100644
--- a/filelist.json
+++ b/filelist.json
@@ -509,6 +509,13 @@
]
}
},
+ "MatMul": {
+ "files": {
+ "common": [
+ "src/gpu/cl/kernels/ClNativeMatMulKernel.cpp"
+ ]
+ }
+ },
"GenerateProposals": {
"deps": [ "BoundingBoxTransform", "Dequantize", "Pad", "Permute", "Quantize", "Reshape" ],
"files": {
diff --git a/src/core/CL/cl_kernels/common/mat_mul.cl b/src/core/CL/cl_kernels/common/mat_mul.cl
new file mode 100644
index 0000000000..7c74e9d07b
--- /dev/null
+++ b/src/core/CL/cl_kernels/common/mat_mul.cl
@@ -0,0 +1,299 @@
+/*
+ * Copyright (c) 2023 Arm Limited.
+ *
+ * SPDX-License-Identifier: MIT
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+#include "helpers.h"
+#include "tile_helpers.h"
+
+#if defined(MAT_MUL_NATIVE_NT_NT)
+/** This OpenCL kernel performs the batch matrix multiplication (BatchMatMul): LHS non-transposed, RHS non-transposed - buffer only
+ *
+ * @note the "batch" here expresses the number of matrix multiplications to run in parallel. However, it
+ * should NOT be confused with the batch size of the model. For NHWC the "batch" is the "H" dimension
+ * @note The block's dimensions used for the LHS and RHS matrices (M0, N0 and K0) must be passed at compile time using -DN0, -DM0 and -DK0 (e.g. -DN0=8, -DM0=4, -DK0=4).
+ * @note The dimension K must be passed at compile time using -DK (e.g. -DK=6)
+ * @note Only the following configurations of M0, N0 and K0 are currently supported:
+ * - M0 > 0
+ * - N0 = 1, 2, 3, 4, 8, 16
+ * - K0 = 1, 2, 3, 4, 8, 16
+ * @note Values > 8 for M0 are not expected to be efficient
+ *
+ * @param[in] lhs_ptr Pointer to the lhs matrix. Supported data types: F32/F16
+ * @param[in] lhs_stride_y Stride of the lhs matrix in Y (2nd) dimension (in bytes)
+ * @param[in] lhs_stride_z Stride of the lhs tensor in Z (3rd) dimension (in bytes)
+ * @param[in] lhs_w The width of the lhs tensor
+ * @param[in] lhs_h The height of the lhs tensor
+ * @param[in] lhs_n Number of the matrices (buffers) in the batch
+ * @param[in] lhs_offset_first_element_in_bytes The offset of the first element in the lhs matrix
+ * @param[in] rhs_ptr Pointer to the rhs matrix. Supported data types: F32/F16
+ * @param[in] rhs_stride_y Stride of the rhs matrix in Y (2nd) dimension (in bytes)
+ * @param[in] rhs_stride_z Stride of the rhs tensor in Z (3rd) dimension (in bytes)
+ * @param[in] rhs_w The width of the rhs tensor
+ * @param[in] rhs_h The height of the rhs tensor
+ * @param[in] rhs_n Number of the matrices (buffers) in the batch
+ * @param[in] rhs_offset_first_element_in_bytes The offset of the first element in the rhs matrix
+ * @param[out] dst_ptr Pointer to the dst matrix. Supported data types: F32/F16
+ * @param[in] dst_stride_y Stride of the dst matrix in Y (2nd) dimension (in bytes)
+ * @param[in] dst_stride_z Stride of the dst tensor in Z (3rd) dimension (in bytes)
+ * @param[in] dst_w The width of the dst tensor
+ * @param[in] dst_h The height of the dst tensor
+ * @param[in] dst_n Number of the matrices (buffers) in the batch
+ * @param[in] dst_offset_first_element_in_bytes The offset of the first element in the dst matrix
+ */
+__kernel void mat_mul_native_nt_nt(
+ TENSOR3D_T(lhs, BUFFER),
+ TENSOR3D_T(rhs, BUFFER),
+ TENSOR3D_T(dst, BUFFER))
+{
+ const uint x = GET_SPATIAL_IDX(0, N0, PARTIAL_STORE_N0);
+ const uint y = GET_SPATIAL_IDX(1, M0, PARTIAL_STORE_M0);
+ const uint z = GET_SPATIAL_IDX(2, 1, 0);
+
+ // Compute LHS/RHS/DST matrix address
+ lhs_offset_first_element_in_bytes += y * lhs_stride_y + z * lhs_stride_z;
+ rhs_offset_first_element_in_bytes += x * sizeof(DATA_TYPE) + z * rhs_stride_z;
+ dst_offset_first_element_in_bytes += x * sizeof(DATA_TYPE) + y * dst_stride_y + z * dst_stride_z;
+
+ // Initialize the accumulators
+ TILE(DATA_TYPE, M0, N0, acc);
+
+ LOOP_UNROLLING(int, i, 0, 1, M0,
+ {
+ acc[i].v = 0.f;
+ })
+
+ int k;
+ for(k = 0; k <= K - K0; k += K0)
+ {
+ TILE(DATA_TYPE, M0, K0, a);
+ TILE(DATA_TYPE, K0, N0, b);
+
+ LOOP_UNROLLING(int, i, 0, 1, M0,
+ {
+ a[i].v = 0.f;
+ })
+
+ LOOP_UNROLLING(int, i, 0, 1, K0,
+ {
+ b[i].v = 0.f;
+ })
+
+ // Load tile from the lhs/rhs tensors
+ T_LOAD(DATA_TYPE, M0, K0, BUFFER, lhs, 0, 0, 1, lhs_stride_y, a);
+ T_LOAD(DATA_TYPE, K0, N0, BUFFER, rhs, 0, 0, 1, rhs_stride_y, b);
+
+ T_MMUL(DATA_TYPE, DATA_TYPE, DATA_TYPE, M0, N0, K0, NT, NT, a, b, acc);
+
+ lhs_offset_first_element_in_bytes += K0 * sizeof(DATA_TYPE);
+ rhs_offset_first_element_in_bytes += K0 * rhs_stride_y;
+ }
+
+#ifdef K % K0 != 0
+ for(; k < K; ++k)
+ {
+ TILE(DATA_TYPE, M0, 1, a);
+ TILE(DATA_TYPE, 1, N0, b);
+
+ LOOP_UNROLLING(int, i, 0, 1, M0,
+ {
+ a[i].v = 0.f;
+ })
+
+ LOOP_UNROLLING(int, i, 0, 1, 1,
+ {
+ b[i].v = 0.f;
+ })
+
+ // Load tile from the lhs/rhs tensors
+ T_LOAD(DATA_TYPE, M0, 1, BUFFER, lhs, 0, 0, 1, lhs_stride_y, a);
+ T_LOAD(DATA_TYPE, 1, N0, BUFFER, rhs, 0, 0, 1, rhs_stride_y, b);
+
+ T_MMUL(DATA_TYPE, DATA_TYPE, DATA_TYPE, M0, N0, 1, NT, NT, a, b, acc);
+
+ lhs_offset_first_element_in_bytes += 1 * sizeof(DATA_TYPE);
+ rhs_offset_first_element_in_bytes += 1 * rhs_stride_y;
+ }
+#endif // K % K0 != 0
+
+ const bool x_cond = PARTIAL_STORE_N0 != 0 && get_global_id(0) == 0;
+ const bool y_cond = PARTIAL_STORE_M0 != 0 && get_global_id(1) == 0;
+
+ TILE(int, M0, 1, indirect_buffer);
+ LOOP_UNROLLING(int, _i, 0, 1, M0,
+ {
+ indirect_buffer[_i].v = min(_i, select(M0 - 1, PARTIAL_STORE_M0 - 1, y_cond));
+ });
+
+ T_STORE_INDIRECT_WIDTH_SELECT(DATA_TYPE, M0, N0, PARTIAL_STORE_N0, BUFFER, dst, 0, dst_stride_y, x_cond, acc, indirect_buffer);
+}
+#endif // defined(MAT_MUL_NATIVE_NT_NT)
+
+#if defined(MAT_MUL_NATIVE_NT_T)
+/** This OpenCL kernel performs the batch matrix multiplication (BatchMatMul): LHS non-transposed, RHS transposed - buffer only
+ *
+ * @note the "batch" here expresses the number of matrix multiplications to run in parallel. However, it
+ * should NOT be confused with the batch size of the model. For NHWC the "batch" is the "H" dimension
+ * @note The block's dimensions used for the LHS and RHS matrices (M0, N0 and K0) must be passed at compile time using -DN0, -DM0 and -DK0 (e.g. -DN0=8, -DM0=4, -DK0=4).
+ * @note The dimension K must be passed at compile time using -DK (e.g. -DK=6)
+ * @note Only the following configurations of M0, N0 and K0 are currently supported:
+ * - M0 > 0
+ * - N0 = 1, 2, 3, 4, 8, 16
+ * - K0 = 1, 2, 3, 4, 8, 16
+ * @note Values > 8 for M0, N0 and K0 are not expected to be efficient
+ *
+ * @param[in] lhs_ptr Pointer to the lhs matrix. Supported data types: F32/F16
+ * @param[in] lhs_stride_y Stride of the lhs matrix in Y (2nd) dimension (in bytes)
+ * @param[in] lhs_stride_z Stride of the lhs tensor in Z (3rd) dimension (in bytes)
+ * @param[in] lhs_w The width of the lhs tensor
+ * @param[in] lhs_h The height of the lhs tensor
+ * @param[in] lhs_n Number of the matrices (buffers) in the batch
+ * @param[in] lhs_offset_first_element_in_bytes The offset of the first element in the lhs matrix
+ * @param[in] rhs_ptr Pointer to the rhs matrix. Supported data types: F32/F16
+ * @param[in] rhs_stride_y Stride of the rhs matrix in Y (2nd) dimension (in bytes)
+ * @param[in] rhs_stride_z Stride of the rhs tensor in Z (3rd) dimension (in bytes)
+ * @param[in] rhs_w The width of the rhs tensor
+ * @param[in] rhs_h The height of the rhs tensor
+ * @param[in] rhs_n Number of the matrices (buffers) in the batch
+ * @param[in] rhs_offset_first_element_in_bytes The offset of the first element in the rhs matrix
+ * @param[out] dst_ptr Pointer to the dst matrix. Supported data types: F32/F16
+ * @param[in] dst_stride_y Stride of the dst matrix in Y (2nd) dimension (in bytes)
+ * @param[in] dst_stride_z Stride of the dst tensor in Z (3rd) dimension (in bytes)
+ * @param[in] dst_w The width of the dst tensor
+ * @param[in] dst_h The height of the dst tensor
+ * @param[in] dst_n Number of the matrices (buffers) in the batch
+ * @param[in] dst_offset_first_element_in_bytes The offset of the first element in the dst matrix
+ */
+__kernel void mat_mul_native_nt_t(TENSOR3D_T(lhs, BUFFER),
+ TENSOR3D_T(rhs, BUFFER),
+ TENSOR3D_T(dst, BUFFER))
+
+{
+ const uint x = GET_SPATIAL_IDX(0, N0, PARTIAL_STORE_N0);
+ const uint y = GET_SPATIAL_IDX(1, M0, PARTIAL_STORE_M0);
+ const uint z = GET_SPATIAL_IDX(2, 1, 0);
+
+ // Compute LHS/RHS/DST matrix address
+ lhs_offset_first_element_in_bytes += y * lhs_stride_y + z * lhs_stride_z;
+ rhs_offset_first_element_in_bytes += x * rhs_stride_y + z * rhs_stride_z;
+ dst_offset_first_element_in_bytes += x * sizeof(DATA_TYPE) + y * dst_stride_y + z * dst_stride_z;
+
+ // Initialize the accumulators
+ TILE(DATA_TYPE, M0, N0, acc);
+
+ LOOP_UNROLLING(int, i, 0, 1, M0,
+ {
+ acc[i].v = 0.f;
+ })
+
+ int k;
+ for(k = 0; k <= K - K0; k += K0)
+ {
+ TILE(DATA_TYPE, M0, K0, a);
+ TILE(DATA_TYPE, N0, K0, b);
+
+ LOOP_UNROLLING(int, i, 0, 1, M0,
+ {
+ a[i].v = 0.f;
+ })
+
+ LOOP_UNROLLING(int, i, 0, 1, N0,
+ {
+ b[i].v = 0.f;
+ })
+
+ // Load tile from the lhs/rhs tensors
+ T_LOAD(DATA_TYPE, M0, K0, BUFFER, lhs, 0, 0, 1, lhs_stride_y, a);
+ T_LOAD(DATA_TYPE, N0, K0, BUFFER, rhs, 0, 0, 1, rhs_stride_y, b);
+
+#if GPU_ARCH == GPU_ARCH_MIDGARD
+ // This part is written to decrease the number of loop unrollings caused
+ // by T_MMUL. The NT/NT version is partly vectorized and uses less number
+ // of loop unrollings, and code behaves as expected. Although this is not
+ // a performant solution for the specified architecture, it is necessary
+ // to overcome some limitations.
+ TILE(DATA_TYPE, K0, N0, bt);
+ LOOP_UNROLLING(int, i, 0, 1, N0,
+ {
+ LOOP_UNROLLING(int, j, 0, 1, K0,
+ {
+ bt[j].s[i] = b[i].s[j];
+ })
+ })
+ T_MMUL(DATA_TYPE, DATA_TYPE, DATA_TYPE, M0, N0, K0, NT, NT, a, bt, acc);
+#else // GPU_ARCH == GPU_ARCH_MIDGARD
+ T_MMUL(DATA_TYPE, DATA_TYPE, DATA_TYPE, M0, N0, K0, NT, T, a, b, acc);
+#endif // GPU_ARCH == GPU_ARCH_MIDGARD
+
+ lhs_offset_first_element_in_bytes += K0 * sizeof(DATA_TYPE);
+ rhs_offset_first_element_in_bytes += K0 * sizeof(DATA_TYPE);
+ }
+
+#if K % K0 != 0
+ /* Leftover Loop */
+ for(; k < K; ++k)
+ {
+ TILE(DATA_TYPE, M0, 1, a);
+ TILE(DATA_TYPE, N0, 1, b);
+
+ LOOP_UNROLLING(int, i, 0, 1, M0,
+ {
+ a[i].v = 0.f;
+ })
+
+ LOOP_UNROLLING(int, i, 0, 1, N0,
+ {
+ b[i].v = 0.f;
+ })
+
+ // Load tile from the lhs/rhs tensors
+ T_LOAD(DATA_TYPE, M0, 1, BUFFER, lhs, 0, 0, 1, lhs_stride_y, a);
+ T_LOAD(DATA_TYPE, N0, 1, BUFFER, rhs, 0, 0, 1, rhs_stride_y, b);
+
+#if GPU_ARCH == GPU_ARCH_MIDGARD
+ // See the main loop for the explanation of this part
+ TILE(DATA_TYPE, 1, N0, bt);
+ LOOP_UNROLLING(int, i, 0, 1, N0,
+ {
+ bt[0].s[i] = b[i].s[0];
+ })
+ T_MMUL(DATA_TYPE, DATA_TYPE, DATA_TYPE, M0, N0, 1, NT, NT, a, bt, acc);
+#else // GPU_ARCH == GPU_ARCH_MIDGARD
+ T_MMUL(DATA_TYPE, DATA_TYPE, DATA_TYPE, M0, N0, 1, NT, T, a, b, acc);
+#endif // GPU_ARCH == GPU_ARCH_MIDGARD
+
+ lhs_offset_first_element_in_bytes += 1 * sizeof(DATA_TYPE);
+ rhs_offset_first_element_in_bytes += 1 * sizeof(DATA_TYPE);
+ }
+#endif // K % K0 != 0
+
+ const bool x_cond = PARTIAL_STORE_N0 != 0 && get_global_id(0) == 0;
+ const bool y_cond = PARTIAL_STORE_M0 != 0 && get_global_id(1) == 0;
+
+ TILE(int, M0, 1, indirect_buffer);
+ LOOP_UNROLLING(int, _i, 0, 1, M0,
+ {
+ indirect_buffer[_i].v = min(_i, select(M0 - 1, PARTIAL_STORE_M0 - 1, y_cond));
+ });
+
+ T_STORE_INDIRECT_WIDTH_SELECT(DATA_TYPE, M0, N0, PARTIAL_STORE_N0, BUFFER, dst, 0, dst_stride_y, x_cond, acc, indirect_buffer);
+}
+#endif // defined(MAT_MUL_NATIVE_NT_T) \ No newline at end of file
diff --git a/src/core/CL/cl_kernels/tile_helpers.h b/src/core/CL/cl_kernels/tile_helpers.h
index 1e4dddd2db..5d397ad333 100644
--- a/src/core/CL/cl_kernels/tile_helpers.h
+++ b/src/core/CL/cl_kernels/tile_helpers.h
@@ -21,8 +21,8 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
-#ifndef SRC_CORE_CL_CL_KERNELS_TILE_HELPERS
-#define SRC_CORE_CL_CL_KERNELS_TILE_HELPERS
+#ifndef ACL_SRC_CORE_CL_CL_KERNELS_TILE_HELPERS
+#define ACL_SRC_CORE_CL_CL_KERNELS_TILE_HELPERS
// *INDENT-OFF*
// clang-format off
@@ -1282,6 +1282,21 @@
}) \
}
+#define T_MMUL_NT_NT(LHS_DATA_TYPE, RHS_DATA_TYPE, DST_DATA_TYPE, M0, N0, K0, lhs, rhs, dst) T_MMUL_NT_NT_##LHS_DATA_TYPE##_##RHS_DATA_TYPE##_##DST_DATA_TYPE(LHS_DATA_TYPE, RHS_DATA_TYPE, DST_DATA_TYPE, M0, N0, K0, lhs, rhs, dst)
+#define T_MMUL_NT_NT_float_float_float(LHS_DATA_TYPE, RHS_DATA_TYPE, DST_DATA_TYPE, M0, N0, K0, lhs, rhs, dst) T_MMUL_NT_NT_FLOAT(LHS_DATA_TYPE, RHS_DATA_TYPE, DST_DATA_TYPE, M0, N0, K0, lhs, rhs, dst)
+#define T_MMUL_NT_NT_half_half_float(LHS_DATA_TYPE, RHS_DATA_TYPE, DST_DATA_TYPE, M0, N0, K0, lhs, rhs, dst) T_MMUL_NT_NT_FLOAT(LHS_DATA_TYPE, RHS_DATA_TYPE, DST_DATA_TYPE, M0, N0, K0, lhs, rhs, dst)
+#define T_MMUL_NT_NT_half_half_half(LHS_DATA_TYPE, RHS_DATA_TYPE, DST_DATA_TYPE, M0, N0, K0, lhs, rhs, dst) T_MMUL_NT_NT_FLOAT(LHS_DATA_TYPE, RHS_DATA_TYPE, DST_DATA_TYPE, M0, N0, K0, lhs, rhs, dst)
+#define T_MMUL_NT_NT_FLOAT(LHS_DATA_TYPE, RHS_DATA_TYPE, DST_DATA_TYPE, M0, N0, K0, lhs, rhs, dst) \
+ { \
+ LOOP_UNROLLING(int, _m, 0, 1, M0, \
+ { \
+ LOOP_UNROLLING(int, _k, 0, 1, K0, \
+ { \
+ dst[_m].v = fma((DST_DATA_TYPE)(lhs[_m].s[_k]), (rhs[_k].v), dst[_m].v); \
+ }) \
+ }) \
+ }
+
#define T_MMUL_NT_T_INTEGER8(LHS_DATA_TYPE, RHS_DATA_TYPE, DST_DATA_TYPE, M0, N0, K0, lhs, rhs, dst) \
({ \
LOOP_UNROLLING(int, _m, 0, 1, M0, \
@@ -1293,4 +1308,4 @@
}) \
})
-#endif /* SRC_CORE_CL_CL_KERNELS_TILE_HELPERS */
+#endif /* ACL_SRC_CORE_CL_CL_KERNELS_TILE_HELPERS */
diff --git a/src/gpu/cl/ClKernelLibrary.cpp b/src/gpu/cl/ClKernelLibrary.cpp
index f788bedc34..482e8c341d 100644
--- a/src/gpu/cl/ClKernelLibrary.cpp
+++ b/src/gpu/cl/ClKernelLibrary.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016-2022 Arm Limited.
+ * Copyright (c) 2016-2023 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
@@ -358,6 +358,8 @@ const std::map<std::string, std::string> ClKernelLibrary::_kernel_program_map =
{ "strided_slice", "common/slice_ops.cl" },
{ "tile", "common/tile.cl" },
{ "transpose", "common/transpose.cl" },
+ { "mat_mul_native_nt_nt", "common/mat_mul.cl" },
+ { "mat_mul_native_nt_t", "common/mat_mul.cl" },
#ifdef ENABLE_NCHW_KERNELS
{ "batch_to_space_nchw", "nchw/batch_to_space.cl" },
{ "batch_to_space_static_nchw", "nchw/batch_to_space.cl" },
@@ -781,6 +783,10 @@ const std::map<std::string, std::string> ClKernelLibrary::_program_source_map =
"common/unpooling_layer.cl",
#include "./cl_kernels/common/unpooling_layer.clembed"
},
+ {
+ "common/mat_mul.cl",
+#include "./cl_kernels/common/mat_mul.clembed"
+ },
#ifdef ENABLE_NCHW_KERNELS
{
"nchw/batch_to_space.cl",
diff --git a/src/gpu/cl/kernels/ClNativeMatMulKernel.cpp b/src/gpu/cl/kernels/ClNativeMatMulKernel.cpp
new file mode 100644
index 0000000000..6a4db65922
--- /dev/null
+++ b/src/gpu/cl/kernels/ClNativeMatMulKernel.cpp
@@ -0,0 +1,192 @@
+/*
+ * Copyright (c) 2023 Arm Limited.
+ *
+ * SPDX-License-Identifier: MIT
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+#include "src/gpu/cl/kernels/ClNativeMatMulKernel.h"
+#include "arm_compute/core/CL/ICLTensor.h"
+#include "arm_compute/core/TensorInfo.h"
+#include "arm_compute/core/utils/misc/ShapeCalculator.h"
+#include "src/core/helpers/AutoConfiguration.h"
+
+#include "arm_compute/core/ITensorPack.h"
+#include "src/common/utils/Log.h"
+#include "src/core/helpers/WindowHelpers.h"
+#include "support/Cast.h"
+#include "utils/TypePrinter.h"
+
+namespace arm_compute
+{
+namespace opencl
+{
+namespace kernels
+{
+namespace
+{
+Status validate_matmul_kernel_info(const MatMulKernelInfo &matmul_kernel_info)
+{
+ const bool adj_lhs = matmul_kernel_info.adj_lhs;
+ const bool adj_rhs = matmul_kernel_info.adj_rhs;
+ const int m0 = matmul_kernel_info.m0;
+ const int n0 = matmul_kernel_info.n0;
+ const int k0 = matmul_kernel_info.k0;
+
+ // Validate M0
+ if(!adj_lhs)
+ {
+ // We support any positive integer, but will test & benchmark only 1 to 8 because > 8 will not efficient
+ ARM_COMPUTE_RETURN_ERROR_ON_MSG(m0 < 1, "Only positive integers are supported for M0 for Lhs non-transposed");
+ }
+ else
+ {
+ ARM_COMPUTE_RETURN_ERROR_ON_MSG((m0 & (m0 - 1)) && (m0 != 3) && (m0 > 16), "Only 1,2,3,4,8,16 are supported for N0 for Lhs transposed");
+ }
+
+ // Validate N0
+ ARM_COMPUTE_RETURN_ERROR_ON_MSG((n0 & (n0 - 1)) && (n0 != 3) && (n0 > 16), "Only 1,2,3,4,8,16 are supported for N0");
+
+ // Validate K0
+ if(adj_lhs && !adj_rhs)
+ {
+ // We support any positive integer, but will test & benchmark only 1 to 8 because > 8 will not efficient
+ ARM_COMPUTE_RETURN_ERROR_ON_MSG(k0 < 1, "Only positive integers are supported for K0 for Lhs transposed & Rhs non-transposed");
+ }
+ else
+ {
+ ARM_COMPUTE_RETURN_ERROR_ON_MSG((k0 & (k0 - 1)) && (k0 != 3) && (k0 > 16), "Only 1,2,3,4,8,16 are supported for K0");
+ }
+
+ return Status{};
+}
+}
+ClNativeMatMulKernel::ClNativeMatMulKernel()
+{
+ _type = CLKernelType::GEMM;
+}
+Status ClNativeMatMulKernel::validate(const ITensorInfo *lhs, const ITensorInfo *rhs, const ITensorInfo *output, const MatMulKernelInfo &matmul_kernel_info)
+{
+ ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(lhs, rhs, output);
+ ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(lhs, 1, DataType::F32, DataType::F16);
+ ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(lhs, rhs);
+ ARM_COMPUTE_RETURN_ON_ERROR(validate_matmul_kernel_info(matmul_kernel_info));
+
+ if(output->total_size() != 0)
+ {
+ const TensorInfo tensor_info_output = output->clone()->set_tensor_shape(misc::shape_calculator::compute_batchmatmul_shape(lhs->tensor_shape(), rhs->tensor_shape(), matmul_kernel_info));
+ ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(output, &tensor_info_output);
+ ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(lhs, output);
+ }
+ ARM_COMPUTE_RETURN_ERROR_ON_MSG(matmul_kernel_info.adj_lhs && matmul_kernel_info.adj_rhs, "LHS T and RHS T not implemented");
+ ARM_COMPUTE_RETURN_ERROR_ON_MSG(matmul_kernel_info.adj_lhs && !matmul_kernel_info.adj_rhs, "LHS T and RHS NT not implemented");
+
+ return Status{};
+}
+void ClNativeMatMulKernel::configure(const ClCompileContext &compile_context, ITensorInfo *lhs, ITensorInfo *rhs, ITensorInfo *output, const MatMulKernelInfo &matmul_kernel_info)
+{
+ ARM_COMPUTE_ERROR_ON_NULLPTR(lhs, rhs, output, &compile_context, &matmul_kernel_info);
+ ARM_COMPUTE_LOG_PARAMS(lhs, rhs, output, matmul_kernel_info);
+
+ // output tensor auto initialization if not yet initialized
+ auto_init_if_empty(*output, lhs->clone()->set_tensor_shape(misc::shape_calculator::compute_batchmatmul_shape(lhs->tensor_shape(), rhs->tensor_shape(), matmul_kernel_info)));
+ ARM_COMPUTE_ERROR_THROW_ON(validate(lhs, rhs, output, matmul_kernel_info));
+
+ const int m = output->dimension(1);
+ const int n = output->dimension(0);
+ const int k = matmul_kernel_info.adj_lhs ? lhs->tensor_shape().y() : lhs->tensor_shape().x();
+
+ int m0 = std::min(matmul_kernel_info.m0, m);
+ int n0 = adjust_vec_size(matmul_kernel_info.n0, n);
+
+ // Configure kernel window
+ Window win = calculate_max_window(*output, Steps(n0, m0));
+ win = win.collapse(win, Window::DimZ);
+ IClKernel::configure_internal(win);
+
+ // 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.
+ const unsigned int partial_store_m0 = m % m0; // M is output->dimension(1)
+ const unsigned int partial_store_n0 = n % n0; // N is output->dimension(0)
+
+ CLBuildOptions build_opts;
+ build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(lhs->data_type()));
+ build_opts.add_option("-DM0=" + support::cpp11::to_string(m0));
+ build_opts.add_option("-DN0=" + support::cpp11::to_string(n0));
+ build_opts.add_option("-DK0=" + support::cpp11::to_string(matmul_kernel_info.k0));
+ build_opts.add_option("-DPARTIAL_STORE_M0=" + support::cpp11::to_string(partial_store_m0));
+ build_opts.add_option("-DPARTIAL_STORE_N0=" + support::cpp11::to_string(partial_store_n0));
+ build_opts.add_option("-DK=" + support::cpp11::to_string(k));
+
+ std::string kernel_name("mat_mul_native");
+ kernel_name += matmul_kernel_info.adj_lhs ? "_t" : "_nt";
+ kernel_name += matmul_kernel_info.adj_rhs ? "_t" : "_nt";
+
+ if(matmul_kernel_info.adj_lhs)
+ {
+ ARM_COMPUTE_ERROR("Only Implemented LHS non-transposed kernels");
+ }
+
+ // A macro guard to compile ONLY the kernel of interest
+ build_opts.add_option("-D" + upper_string(kernel_name));
+
+ // Create kernel
+ _kernel = create_kernel(compile_context, kernel_name, build_opts.options());
+
+ // Set config_id for enabling LWS tuning
+ _config_id = kernel_name;
+ _config_id += "_";
+ _config_id += lower_string(string_from_data_type(lhs->data_type()));
+ _config_id += "_";
+ _config_id += support::cpp11::to_string(output->dimension(1));
+ _config_id += "_";
+ _config_id += support::cpp11::to_string(output->dimension(0));
+ _config_id += "_";
+ _config_id += support::cpp11::to_string(output->dimension(2));
+ _config_id += "_";
+ _config_id += support::cpp11::to_string(m0);
+ _config_id += "_";
+ _config_id += support::cpp11::to_string(n0);
+ _config_id += "_";
+ _config_id += support::cpp11::to_string(matmul_kernel_info.k0);
+}
+
+void ClNativeMatMulKernel::run_op(ITensorPack &tensors, const Window &window, cl::CommandQueue &queue)
+{
+ ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
+ ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(ICLKernel::window(), window);
+
+ const ICLTensor *lhs = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC_0));
+ const ICLTensor *rhs = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC_1));
+ ICLTensor *output = utils::cast::polymorphic_downcast<ICLTensor *>(tensors.get_tensor(TensorType::ACL_DST));
+ ARM_COMPUTE_ERROR_ON_NULLPTR(lhs, rhs, output);
+ ARM_COMPUTE_LOG_PARAMS(lhs, rhs, output);
+
+ unsigned int idx = 0;
+ Window window_collapsed = window.collapse(ICLKernel::window(), Window::DimZ);
+
+ add_3d_tensor_nhw_argument(idx, lhs);
+ add_3d_tensor_nhw_argument(idx, rhs);
+ add_3d_tensor_nhw_argument(idx, output);
+
+ enqueue(queue, *this, window_collapsed, lws_hint());
+}
+
+} // namespace kernels
+} // namespace opencl
+} // namespace arm_compute
diff --git a/src/gpu/cl/kernels/ClNativeMatMulKernel.h b/src/gpu/cl/kernels/ClNativeMatMulKernel.h
new file mode 100644
index 0000000000..1cd74365df
--- /dev/null
+++ b/src/gpu/cl/kernels/ClNativeMatMulKernel.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2023 Arm Limited.
+ *
+ * SPDX-License-Identifier: MIT
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+#ifndef ACL_SRC_GPU_CL_KERNELS_CLNATIVEMATMULKERNEL
+#define ACL_SRC_GPU_CL_KERNELS_CLNATIVEMATMULKERNEL
+
+#include "arm_compute/core/CL/CLHelpers.h"
+#include "arm_compute/core/CL/CLKernelLibrary.h"
+#include "arm_compute/core/KernelDescriptors.h"
+#include "src/core/common/Macros.h"
+#include "src/gpu/cl/ClCompileContext.h"
+#include "src/gpu/cl/IClKernel.h"
+
+namespace arm_compute
+{
+namespace opencl
+{
+namespace kernels
+{
+class ClNativeMatMulKernel : public IClKernel
+{
+public:
+ ClNativeMatMulKernel();
+ ARM_COMPUTE_DISALLOW_COPY_ALLOW_MOVE(ClNativeMatMulKernel);
+ /** Initialise the kernel's input and output.
+ *
+ * @param[in] compile_context The compile context to be used.
+ * @param[in] lhs Input tensor for the LHS matrix. Data type supported: F32/F16.
+ * Dimensions above 2 are collapsed onto dimension 2 and represent the batch.
+ * @param[in] rhs Input tensor for the RHS matrix. Data type supported: same as @p lhs.
+ * Dimensions above 2 are collapsed onto dimension 2 and represent the batch.
+ * @param[out] output Output tensor info. Data type supported: same as @p lhs
+ * @param[in] matmul_info Attributes for Batch MatMul Kernel
+ */
+ void configure(const ClCompileContext &compile_context, ITensorInfo *lhs, ITensorInfo *rhs, ITensorInfo *output, const MatMulKernelInfo &matmul_info);
+ /** Static function to check if given info will lead to a valid configuration
+ *
+ * Similar to @ref ClNativeMatMulKernel::configure()
+ *
+ * @return a status
+ */
+ static Status validate(const ITensorInfo *lhs, const ITensorInfo *rhs, const ITensorInfo *output, const MatMulKernelInfo &matmul_info);
+
+ // Inherited methods overridden:
+ void run_op(ITensorPack &tensors, const Window &window, cl::CommandQueue &queue) override;
+};
+} // namespace kernels
+} // namespace opencl
+} // namespace arm_compute
+#endif /* ACL_SRC_GPU_CL_KERNELS_CLNATIVEMATMULKERNEL */
diff --git a/tests/datasets/BatchMatMulDataset.h b/tests/datasets/BatchMatMulDataset.h
new file mode 100644
index 0000000000..dad7cc0af4
--- /dev/null
+++ b/tests/datasets/BatchMatMulDataset.h
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 2023 Arm Limited.
+ *
+ * SPDX-License-Identifier: MIT
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+#ifndef TESTS_DATASETS_BATCHMATMULDATASET
+#define TESTS_DATASETS_BATCHMATMULDATASET
+
+#include "arm_compute/core/TensorShape.h"
+#include "utils/TypePrinter.h"
+
+namespace arm_compute
+{
+namespace test
+{
+namespace datasets
+{
+class BatchMatMulDataset
+{
+public:
+ using type = std::tuple<TensorShape, TensorShape, TensorShape>;
+
+ struct iterator
+ {
+ iterator(std::vector<TensorShape>::const_iterator a_it,
+ std::vector<TensorShape>::const_iterator b_it,
+ std::vector<TensorShape>::const_iterator dst_it)
+ : _a_it{ std::move(a_it) },
+ _b_it{ std::move(b_it) },
+ _dst_it{ std::move(dst_it) }
+ {
+ }
+
+ std::string description() const
+ {
+ std::stringstream description;
+ description << "A=" << *_a_it << ":";
+ description << "B=" << *_b_it << ":";
+ description << "Out=" << *_dst_it << ":";
+ return description.str();
+ }
+
+ BatchMatMulDataset::type operator*() const
+ {
+ return std::make_tuple(*_a_it, *_b_it, *_dst_it);
+ }
+
+ iterator &operator++()
+ {
+ ++_a_it;
+ ++_b_it;
+ ++_dst_it;
+
+ return *this;
+ }
+
+ private:
+ std::vector<TensorShape>::const_iterator _a_it;
+ std::vector<TensorShape>::const_iterator _b_it;
+ std::vector<TensorShape>::const_iterator _dst_it;
+ };
+
+ iterator begin() const
+ {
+ return iterator(_a_shapes.begin(), _b_shapes.begin(), _dst_shapes.begin());
+ }
+
+ int size() const
+ {
+ return std::min(_a_shapes.size(), std::min(_b_shapes.size(), _dst_shapes.size()));
+ }
+
+ void add_config(TensorShape a, TensorShape b, TensorShape dst)
+ {
+ _a_shapes.emplace_back(std::move(a));
+ _b_shapes.emplace_back(std::move(b));
+ _dst_shapes.emplace_back(std::move(dst));
+ }
+
+protected:
+ BatchMatMulDataset() = default;
+ BatchMatMulDataset(BatchMatMulDataset &&) = default;
+
+private:
+ std::vector<TensorShape> _a_shapes{};
+ std::vector<TensorShape> _b_shapes{};
+ std::vector<TensorShape> _dst_shapes{};
+};
+} // namespace datasets
+} // namespace test
+} // namespace arm_compute
+#endif /* TESTS_DATASETS_BATCHMATMULDATASET */
diff --git a/tests/datasets/LargeBatchMatMulDataset.h b/tests/datasets/LargeBatchMatMulDataset.h
new file mode 100644
index 0000000000..0d8ff913cf
--- /dev/null
+++ b/tests/datasets/LargeBatchMatMulDataset.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2023 Arm Limited.
+ *
+ * SPDX-License-Identifier: MIT
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+#ifndef ACL_TESTS_DATASETS_LARGEBATCHMATMULDATASET
+#define ACL_TESTS_DATASETS_LARGEBATCHMATMULDATASET
+
+#include "arm_compute/core/TensorShape.h"
+#include "arm_compute/core/Types.h"
+#include "tests/datasets/BatchMatMulDataset.h"
+
+namespace arm_compute
+{
+namespace test
+{
+namespace datasets
+{
+class LargeBatchMatMulDataset final : public BatchMatMulDataset
+{
+public:
+ LargeBatchMatMulDataset()
+ {
+ add_config(TensorShape(21U, 13U, 3U, 2U), TensorShape(33U, 21U, 3U, 2U), TensorShape(33U, 13U, 3U, 2U));
+ add_config(TensorShape(38U, 12U, 1U, 5U), TensorShape(21U, 38U, 1U, 5U), TensorShape(21U, 12U, 1U, 5U));
+ add_config(TensorShape(45U, 38U, 3U, 2U), TensorShape(21U, 45U, 3U, 2U), TensorShape(21U, 38U, 3U, 2U));
+ }
+};
+
+class HighDimensionalBatchMatMulDataset final : public BatchMatMulDataset
+{
+public:
+ HighDimensionalBatchMatMulDataset()
+ {
+ add_config(TensorShape(5U, 5U, 2U, 2U, 2U, 2U), TensorShape(5U, 5U, 2U, 2U, 2U, 2U), TensorShape(5U, 5U, 2U, 2U, 2U, 2U)); // 6D tensor
+ }
+};
+
+} // namespace datasets
+} // namespace test
+} // namespace arm_compute
+#endif /* ACL_TESTS_DATASETS_LARGEBATCHMATMULDATASET */
diff --git a/tests/datasets/SmallBatchMatMulDataset.h b/tests/datasets/SmallBatchMatMulDataset.h
new file mode 100644
index 0000000000..cfe76bea6d
--- /dev/null
+++ b/tests/datasets/SmallBatchMatMulDataset.h
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2023 Arm Limited.
+ *
+ * SPDX-License-Identifier: MIT
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+#ifndef ACL_TESTS_DATASETS_SMALLBATCHMATMULDATASET
+#define ACL_TESTS_DATASETS_SMALLBATCHMATMULDATASET
+
+#include "arm_compute/core/TensorShape.h"
+#include "arm_compute/core/Types.h"
+#include "tests/datasets/BatchMatMulDataset.h"
+
+namespace arm_compute
+{
+namespace test
+{
+namespace datasets
+{
+class SmallBatchMatMulDataset final : public BatchMatMulDataset
+{
+public:
+ SmallBatchMatMulDataset()
+ {
+ add_config(TensorShape(3U, 4U, 2U, 2U), TensorShape(2U, 3U, 2U, 2U), TensorShape(2U, 4U, 2U, 2U));
+ add_config(TensorShape(9U, 6U), TensorShape(5U, 9U), TensorShape(5U, 6U));
+ add_config(TensorShape(31U, 1U), TensorShape(23U, 31U), TensorShape(23U, 1U));
+ add_config(TensorShape(8U, 4U, 2U), TensorShape(16U, 8U, 2U), TensorShape(16U, 4U, 2U));
+ add_config(TensorShape(32U, 2U), TensorShape(17U, 32U), TensorShape(17U, 2U));
+ }
+};
+} // namespace datasets
+} // namespace test
+} // namespace arm_compute
+#endif /* ACL_TESTS_DATASETS_SMALLBATCHMATMULDATASET */
diff --git a/tests/validation/CL/BatchMatMul.cpp b/tests/validation/CL/BatchMatMul.cpp
new file mode 100644
index 0000000000..fd84526000
--- /dev/null
+++ b/tests/validation/CL/BatchMatMul.cpp
@@ -0,0 +1,239 @@
+/*
+ * Copyright (c) 2023 Arm Limited.
+ *
+ * SPDX-License-Identifier: MIT
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#include "arm_compute/runtime/CL/CLTensor.h"
+#include "src/gpu/cl/kernels/ClNativeMatMulKernel.h"
+#include "tests/datasets/LargeBatchMatMulDataset.h"
+#include "tests/datasets/SmallBatchMatMulDataset.h"
+#include "tests/framework/Macros.h"
+#include "tests/framework/datasets/Datasets.h"
+#include "tests/validation/Validation.h"
+#include "tests/validation/fixtures/BatchMatMulFixture.h"
+
+namespace arm_compute
+{
+namespace test
+{
+namespace validation
+{
+namespace
+{
+RelativeTolerance<float> tolerance_f32(0.001f); /**< Tolerance value for comparing reference's output against implementation's output for floating point data types */
+constexpr float abs_tolerance_f32(
+ 0.0001f); /**< Absolute tolerance value for comparing reference's output against implementation's output for floating point data types in case using relative tolerance fails because of small values */
+constexpr float abs_tolerance_f16(
+ 0.001f); /**< Absolute tolerance value for comparing reference's output against implementation's output for fp16 data types in case using relative tolerance fails because of small values */
+RelativeTolerance<half_float::half> tolerance_f16(half(0.01)); /**< Tolerance value for comparing reference's output against implementation's output for floating point data types */
+} // namespace
+
+/** M0 values to test --precommit*/
+const auto m0_values_precommit = framework::dataset::make("M0", { 1, 3 });
+
+/** N0 values to test --precommit*/
+const auto n0_values_precommit = framework::dataset::make("N0", { 2, 4 });
+
+/** K0 values to test --precommit*/
+const auto k0_values_precommit = framework::dataset::make("K0", { 2, 3 });
+
+/** M0 values to test --nightly*/
+const auto m0_values_nightly_lhs_nt = framework::dataset::make("M0", { 1, 2, 3, 4, 5, 6, 7, 8 });
+// const auto m0_values_nightly_lhs_t = framework::dataset::make("M0", { 1, 2, 3, 4, 8 }); // To be enabled
+
+/** N0 values to test --nightly*/
+const auto n0_values_nightly_rhs_nt = framework::dataset::make("N0", { 1, 2, 3, 4, 8, 16 });
+const auto n0_values_nightly_rhs_t = framework::dataset::make("N0", { 1, 2, 3, 4, 8 });
+
+/** K0 values to test --nightly*/
+const auto k0_values_nightly_lhs_nt_rhs_nt = framework::dataset::make("K0", { 1, 2, 3, 4, 8, 16 });
+const auto k0_values_nightly_lhs_nt_rhs_t = framework::dataset::make("K0", { 1, 2, 3, 4, 8 });
+// const auto k0_values_nightly_lhs_t_rhs_nt = framework::dataset::make("K0", { 1, 2, 3, 4, 5, 6, 7, 8 }); // To be enabled
+
+template <typename T>
+using CLBatchMatMulFixture = BatchMatMulValidationFixture<T>;
+
+TEST_SUITE(CL)
+TEST_SUITE(BatchMatMul)
+DATA_TEST_CASE(Validate, framework::DatasetMode::ALL, zip(zip(zip(zip(
+ framework::dataset::make("LhsInfo",
+{
+ TensorInfo(TensorShape(27U, 13U), 1, DataType::S32), // Unsupported data type
+ TensorInfo(TensorShape(27U, 13U), 1, DataType::F32),
+ TensorInfo(TensorShape(27U, 13U), 1, DataType::F32),
+ TensorInfo(TensorShape(27U, 13U), 1, DataType::F32),
+ TensorInfo(TensorShape(27U, 13U), 1, DataType::F32),
+ TensorInfo(TensorShape(27U, 13U), 1, DataType::F32),
+ TensorInfo(TensorShape(27U, 13U), 1, DataType::F32),
+ TensorInfo(TensorShape(27U, 13U), 1, DataType::F32),
+ TensorInfo(TensorShape(27U, 13U), 1, DataType::F32),
+ TensorInfo(TensorShape(27U, 13U), 1, DataType::F32),
+}),
+framework::dataset::make("RhsInfo",
+{
+ TensorInfo(TensorShape(8U, 27U), 1, DataType::S32), TensorInfo(TensorShape(8U, 27U), 1, DataType::F32), TensorInfo(TensorShape(8U, 27U), 1, DataType::F32), TensorInfo(TensorShape(8U, 27U), 1, DataType::F32), TensorInfo(TensorShape(8U, 27U), 1, DataType::F32), TensorInfo(TensorShape(8U, 27U), 1, DataType::F32), TensorInfo(TensorShape(8U, 27U), 1, DataType::F32), TensorInfo(TensorShape(8U, 27U), 1, DataType::F32), TensorInfo(TensorShape(8U, 27U), 1, DataType::F32), TensorInfo(TensorShape(8U, 27U), 1, DataType::F32),
+})),
+framework::dataset::make("OutputInfo",
+{
+ TensorInfo(TensorShape(8U, 13U), 1, DataType::S32), TensorInfo(TensorShape(8U, 13U), 1, DataType::F32), TensorInfo(TensorShape(8U, 13U), 1, DataType::F32), TensorInfo(TensorShape(8U, 13U), 1, DataType::F32), TensorInfo(TensorShape(8U, 13U), 1, DataType::F32), TensorInfo(TensorShape(8U, 13U), 1, DataType::F32), TensorInfo(TensorShape(8U, 13U), 1, DataType::F32), TensorInfo(TensorShape(8U, 13U), 1, DataType::F32), TensorInfo(TensorShape(8U, 13U), 1, DataType::F32), TensorInfo(TensorShape(8U, 13U), 1, DataType::F32),
+})),
+framework::dataset::make("MatMulInfo",
+{
+ MatMulKernelInfo(false, false, 2, 2, 2, false), MatMulKernelInfo(false, false, 2, 2, 2, false), MatMulKernelInfo(false, false, 9, 2, 2, false), MatMulKernelInfo(false, false, 0, 2, 2, false), // M0 cannot be < 1
+ MatMulKernelInfo(false, true, 4, 5, 2, false), // For LHS NT RHS NT: N0 cannot be 5
+ MatMulKernelInfo(false, true, 4, 6, 2, false), // For LHS NT RHS NT: N0 cannot be 6
+ MatMulKernelInfo(false, true, 4, 9, 2, false), // For LHS NT RHS NT: N0 cannot be 9
+ MatMulKernelInfo(false, true, 4, 10, 2, false), // For LHS NT RHS NT: N0 cannot be 10
+ MatMulKernelInfo(false, true, 4, 11, 2, false), // For LHS NT RHS NT: N0 cannot be 11
+ MatMulKernelInfo(false, true, 4, 17, 2, false), // For LHS NT RHS NT: N0 cannot be 17
+})),
+framework::dataset::make("Expected", { false, true, true, false, false, false, false, false, false, false })),
+lhs_info, rhs_info, output_info, matmul_info, expected)
+{
+ bool is_valid = bool(ClNativeMatMulKernel::validate(&lhs_info, &rhs_info, &output_info, matmul_info));
+ ARM_COMPUTE_EXPECT(is_valid == expected, framework::LogLevel::ERRORS);
+}
+TEST_SUITE(Float)
+TEST_SUITE(FP32)
+FIXTURE_DATA_TEST_CASE(RunSmallNoTranspose, CLBatchMatMulFixture<float>, framework::DatasetMode::ALL, combine(combine(combine(combine(combine(combine(datasets::SmallBatchMatMulDataset(),
+ framework::dataset::make("pretransose_A", { false })),
+ framework::dataset::make("pretransose_B", { false })),
+ m0_values_precommit),
+ n0_values_precommit),
+ k0_values_precommit),
+ framework::dataset::make("DataType", DataType::F32)))
+{
+ // Validate output
+ validate(CLAccessor(_target), _reference, tolerance_f32, 0.f, abs_tolerance_f32);
+}
+FIXTURE_DATA_TEST_CASE(RunSmallRhsTransposed, CLBatchMatMulFixture<float>, framework::DatasetMode::ALL, combine(combine(combine(combine(combine(combine(datasets::SmallBatchMatMulDataset(),
+ framework::dataset::make("pretransose_A", { false })),
+ framework::dataset::make("pretransose_B", { true })),
+ m0_values_precommit),
+ n0_values_precommit),
+ k0_values_precommit),
+ framework::dataset::make("DataType", DataType::F32)))
+{
+ // Validate output
+ validate(CLAccessor(_target), _reference, tolerance_f32, 0.f, abs_tolerance_f32);
+}
+FIXTURE_DATA_TEST_CASE(RunLargeNoTranspose, CLBatchMatMulFixture<float>, framework::DatasetMode::NIGHTLY, combine(combine(combine(combine(combine(combine(datasets::LargeBatchMatMulDataset(),
+ framework::dataset::make("pretransose_A", { false })),
+ framework::dataset::make("pretransose_B", { false })),
+ m0_values_nightly_lhs_nt),
+ n0_values_nightly_rhs_nt),
+ k0_values_nightly_lhs_nt_rhs_nt),
+ framework::dataset::make("DataType", DataType::F32)))
+{
+ // Validate output
+ validate(CLAccessor(_target), _reference, tolerance_f32, 0.f, abs_tolerance_f32);
+}
+// Running High Dimensional test is enough for FP32, because we're stressing the number of dimensions, not data type or M0/N0/K0
+// It's a good idea to test for each Lhs/Rhs T/NT combinations because they're different CL kernels
+FIXTURE_DATA_TEST_CASE(RunHighDimNoTranspose, CLBatchMatMulFixture<float>, framework::DatasetMode::ALL, combine(combine(combine(combine(combine(combine(datasets::HighDimensionalBatchMatMulDataset(),
+ framework::dataset::make("pretransose_A", { false })),
+ framework::dataset::make("pretransose_B", { false })),
+ framework::dataset::make("M0", { 2 })),
+ framework::dataset::make("N0", { 2 })),
+ framework::dataset::make("K0", { 2 })),
+ framework::dataset::make("DataType", DataType::F32)))
+{
+ // Validate output
+ validate(CLAccessor(_target), _reference, tolerance_f32, 0.f, abs_tolerance_f32);
+}
+FIXTURE_DATA_TEST_CASE(RunLargeRhsTransposed, CLBatchMatMulFixture<float>, framework::DatasetMode::NIGHTLY, combine(combine(combine(combine(combine(combine(datasets::LargeBatchMatMulDataset(),
+ framework::dataset::make("pretransose_A", { false })),
+ framework::dataset::make("pretransose_B", { true })),
+ m0_values_nightly_lhs_nt),
+ n0_values_nightly_rhs_t),
+ k0_values_nightly_lhs_nt_rhs_t),
+ framework::dataset::make("DataType", DataType::F32)))
+{
+ // Validate output
+ validate(CLAccessor(_target), _reference, tolerance_f32, 0.f, abs_tolerance_f32);
+}
+FIXTURE_DATA_TEST_CASE(RunHighDimRhsTransposed, CLBatchMatMulFixture<float>, framework::DatasetMode::ALL, combine(combine(combine(combine(combine(combine(datasets::HighDimensionalBatchMatMulDataset(),
+ framework::dataset::make("pretransose_A", { false })),
+ framework::dataset::make("pretransose_B", { true })),
+ framework::dataset::make("M0", { 2 })),
+ framework::dataset::make("N0", { 2 })),
+ framework::dataset::make("K0", { 2 })),
+ framework::dataset::make("DataType", DataType::F32)))
+{
+ // Validate output
+ validate(CLAccessor(_target), _reference, tolerance_f32, 0.f, abs_tolerance_f32);
+}
+TEST_SUITE_END() // FP32
+
+TEST_SUITE(FP16)
+FIXTURE_DATA_TEST_CASE(RunSmallNoTranspose, CLBatchMatMulFixture<half>, framework::DatasetMode::ALL, combine(combine(combine(combine(combine(combine(datasets::SmallBatchMatMulDataset(),
+ framework::dataset::make("pretransose_A", { false })),
+ framework::dataset::make("pretransose_B", { false })),
+ m0_values_precommit),
+ n0_values_precommit),
+ k0_values_precommit),
+ framework::dataset::make("DataType", DataType::F16)))
+{
+ // Validate output
+ validate(CLAccessor(_target), _reference, tolerance_f16, 0.f, abs_tolerance_f16);
+}
+FIXTURE_DATA_TEST_CASE(RunSmallRhsTransposed, CLBatchMatMulFixture<half>, framework::DatasetMode::ALL, combine(combine(combine(combine(combine(combine(datasets::SmallBatchMatMulDataset(),
+ framework::dataset::make("pretransose_A", { false })),
+ framework::dataset::make("pretransose_B", { true })),
+ m0_values_precommit),
+ n0_values_precommit),
+ k0_values_precommit),
+ framework::dataset::make("DataType", DataType::F16)))
+{
+ // Validate output
+ validate(CLAccessor(_target), _reference, tolerance_f16, 0.f, abs_tolerance_f16);
+}
+FIXTURE_DATA_TEST_CASE(RunLargeNoTranspose, CLBatchMatMulFixture<half>, framework::DatasetMode::NIGHTLY, combine(combine(combine(combine(combine(combine(datasets::LargeBatchMatMulDataset(),
+ framework::dataset::make("pretransose_A", { false })),
+ framework::dataset::make("pretransose_B", { false })),
+ m0_values_nightly_lhs_nt),
+ n0_values_nightly_rhs_nt),
+ k0_values_nightly_lhs_nt_rhs_nt),
+ framework::dataset::make("DataType", DataType::F16)))
+{
+ // Validate output
+ validate(CLAccessor(_target), _reference, tolerance_f16, 0.f, abs_tolerance_f16);
+}
+FIXTURE_DATA_TEST_CASE(RunLargeRhsTransposed, CLBatchMatMulFixture<half>, framework::DatasetMode::NIGHTLY, combine(combine(combine(combine(combine(combine(datasets::LargeBatchMatMulDataset(),
+ framework::dataset::make("pretransose_A", { false })),
+ framework::dataset::make("pretransose_B", { true })),
+ m0_values_nightly_lhs_nt),
+ n0_values_nightly_rhs_t),
+ k0_values_nightly_lhs_nt_rhs_t),
+ framework::dataset::make("DataType", DataType::F16)))
+{
+ // Validate output
+ validate(CLAccessor(_target), _reference, tolerance_f16, 0.f, abs_tolerance_f16);
+}
+TEST_SUITE_END() // FP16
+
+TEST_SUITE_END() // Float
+TEST_SUITE_END() // BatchMatMul
+TEST_SUITE_END() // CL
+} // namespace validation
+} // namespace test
+} // namespace arm_compute
diff --git a/tests/validation/fixtures/BatchMatMulFixture.h b/tests/validation/fixtures/BatchMatMulFixture.h
new file mode 100644
index 0000000000..9fb2dcc1b7
--- /dev/null
+++ b/tests/validation/fixtures/BatchMatMulFixture.h
@@ -0,0 +1,203 @@
+/*
+ * Copyright (c) 2023 Arm Limited.
+ *
+ * SPDX-License-Identifier: MIT
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+#ifndef ACL_TESTS_VALIDATION_FIXTURES_BATCHMATMULFIXTURE
+#define ACL_TESTS_VALIDATION_FIXTURES_BATCHMATMULFIXTURE
+
+#include "arm_compute/core/KernelDescriptors.h"
+#include "src/gpu/cl/kernels/ClNativeMatMulKernel.h"
+#include "tests/CL/CLAccessor.h"
+#include "tests/CL/Helper.h"
+#include "tests/framework/Fixture.h"
+#include "tests/validation/reference/GEMM.h"
+#include "tests/validation/reference/Permute.h"
+#include "tests/validation/reference/ReshapeLayer.h"
+
+#include <random>
+
+namespace arm_compute
+{
+namespace test
+{
+namespace validation
+{
+using namespace arm_compute::opencl::kernels;
+
+template <typename T>
+class BatchMatMulValidationFixture : public framework::Fixture
+{
+public:
+ template <typename...>
+ void setup(TensorShape shape_a, TensorShape shape_b, TensorShape output_shape, bool pretranspose_a, bool pretranspose_b, const int M0, const int N0, const int K0, DataType data_type)
+ {
+ // For brevity, the input shapes are assumed to be not-transposed for both Lhs and Rhs matrices.
+ if(pretranspose_a)
+ {
+ permute(shape_a, PermutationVector(1U, 0U));
+ }
+
+ if(pretranspose_b)
+ {
+ permute(shape_b, PermutationVector(1U, 0U));
+ }
+
+ _target = compute_target(shape_a, shape_b, output_shape, pretranspose_a, pretranspose_b, M0, N0, K0, data_type);
+ _reference = compute_reference(shape_a, shape_b, output_shape, pretranspose_a, pretranspose_b, data_type);
+ }
+
+protected:
+ template <typename U>
+ void fill(U &&tensor, int i, float lo = -1.f, float hi = 1.f)
+ {
+ switch(tensor.data_type())
+ {
+ case DataType::F16:
+ {
+ arm_compute::utils::uniform_real_distribution_16bit<half> distribution{ float(lo), float(hi) };
+ library->fill(tensor, distribution, i);
+ break;
+ }
+ case DataType::F32:
+ {
+ std::uniform_real_distribution<float> distribution(lo, hi);
+ library->fill(tensor, distribution, i);
+ break;
+ }
+ default:
+ library->fill_tensor_uniform(tensor, i);
+ }
+ }
+
+ CLTensor compute_target(const TensorShape &shape_a, const TensorShape &shape_b, const TensorShape &output_shape, bool pretranspose_a, bool pretranspose_b, const int M0, const int N0, const int K0,
+ DataType data_type)
+ {
+ // Create tensors
+ CLTensor a = create_tensor<CLTensor>(shape_a, data_type, 1);
+ CLTensor b = create_tensor<CLTensor>(shape_b, data_type, 1);
+ CLTensor dst = create_tensor<CLTensor>(output_shape, data_type, 1);
+
+ CLSynthetizeOperator<ClNativeMatMulKernel> batchMatMul{};
+ MatMulKernelInfo matmul_info;
+ matmul_info.adj_lhs = pretranspose_a;
+ matmul_info.adj_rhs = pretranspose_b;
+ matmul_info.m0 = M0;
+ matmul_info.n0 = N0;
+ matmul_info.k0 = K0;
+
+ batchMatMul.configure(a.info(), b.info(), dst.info(), matmul_info);
+ ARM_COMPUTE_ASSERT(a.info()->is_resizable());
+ ARM_COMPUTE_ASSERT(b.info()->is_resizable());
+ ARM_COMPUTE_ASSERT(dst.info()->is_resizable());
+
+ // Allocate tensors
+ a.allocator()->allocate();
+ b.allocator()->allocate();
+ dst.allocator()->allocate();
+
+ ARM_COMPUTE_ASSERT(!a.info()->is_resizable());
+ ARM_COMPUTE_ASSERT(!b.info()->is_resizable());
+ ARM_COMPUTE_ASSERT(!dst.info()->is_resizable());
+
+ // Fill tensors
+ fill(CLAccessor(a), 0);
+ fill(CLAccessor(b), 1);
+
+ // Compute batchMatMul kernel
+ ITensorPack tensors_pack({ { ACL_SRC_0, &a },
+ { ACL_SRC_1, &b },
+ { ACL_DST, &dst }
+ });
+ batchMatMul.run(tensors_pack);
+
+ return dst;
+ }
+
+ SimpleTensor<T> compute_reference(const TensorShape &shape_a, const TensorShape &shape_b, const TensorShape &output_shape, bool pretranspose_a, bool pretranspose_b, DataType data_type)
+ {
+ // We collapse dimensions > 3 onto dimension 3, i.e. 5D+ tensors will look like 4D
+ // This is necessary unless we choose to extend gemm reference for 5D+ tensors
+ TensorShape output_shape_collapsed = output_shape.collapsed_from(Window::DimW);
+ TensorShape shape_a_collapsed = shape_a.collapsed_from(Window::DimW);
+ TensorShape shape_b_collapsed = shape_b.collapsed_from(Window::DimW);
+
+ // Create reference
+ SimpleTensor<T> a{ shape_a_collapsed, data_type, 1 };
+ SimpleTensor<T> b{ shape_b_collapsed, data_type, 1 };
+ SimpleTensor<T> c{ output_shape_collapsed, data_type, 1 };
+
+ // Fill reference
+ fill(a, 0);
+ fill(b, 1);
+
+ /* Note: Assuming the usual batch matmul dimensions A = (B x M x K), B = (B x K x N), if pretranspose_A is set to true, then A is assumed to be (B x K x M),
+ therefore, A must be pre-transposed before passing it to the fixture. And, we transpose A again in the fixture to make it (B x M x K)
+ in order to be able to call reference implementation that works with (B x M x K) input.
+ Similarly, if pretranspose_B is set to true, then B is assumed to be (B x N x K), B must be pre-transposed before passing it to the fixture. */
+
+ // Define transposed shapes
+ TensorShape a_transposed_shape(a.shape());
+ a_transposed_shape.set(0, a.shape().y());
+ a_transposed_shape.set(1, a.shape().x());
+
+ TensorShape b_transposed_shape(b.shape());
+ b_transposed_shape.set(0, b.shape().y());
+ b_transposed_shape.set(1, b.shape().x());
+
+ // Define transposed tensors
+ SimpleTensor<T> a_transposed{ a_transposed_shape, data_type };
+ SimpleTensor<T> b_transposed{ b_transposed_shape, data_type };
+
+ // pretranspose a if necessary
+ if(pretranspose_a)
+ {
+ a_transposed = reference::permute<T>(a, PermutationVector(1U, 0U));
+ }
+
+ // pretranspose b if necessary
+ if(pretranspose_b)
+ {
+ b_transposed = reference::permute<T>(b, PermutationVector(1U, 0U));
+ }
+
+ // Setting beta to 0 will effectively disable C for the
+ // computation of the reference: alpha * A * B + 0 * C
+ // Use transposed tensors if boolean enabled else use original tensors
+ SimpleTensor<T> result = reference::gemm<T>((pretranspose_a) ? a_transposed : a, (pretranspose_b) ? b_transposed : b, c, 1.0f, 0.f);
+
+ // We reshape the gemm output back if the tensor is high dimensional
+ if(output_shape_collapsed != output_shape)
+ {
+ result = reference::reshape_layer(result, output_shape);
+ }
+
+ return result;
+ }
+
+ CLTensor _target{};
+ SimpleTensor<T> _reference{};
+};
+
+} // namespace validation
+} // namespace test
+} // namespace arm_compute
+#endif /* ACL_TESTS_VALIDATION_FIXTURES_BATCHMATMULFIXTURE */
diff --git a/utils/TypePrinter.h b/utils/TypePrinter.h
index db27ddccde..c3af0a2419 100644
--- a/utils/TypePrinter.h
+++ b/utils/TypePrinter.h
@@ -421,7 +421,8 @@ inline ::std::ostream &operator<<(::std::ostream &os, const GEMMLHSMatrixInfo &g
*/
inline ::std::ostream &operator<<(::std::ostream &os, const GEMMRHSMatrixInfo &gemm_info)
{
- os << "( n0=" << (unsigned int)gemm_info.n0 << " k0=" << gemm_info.k0 << " h0=" << gemm_info.h0 << " trans=" << gemm_info.transpose << " inter=" << gemm_info.interleave << " exp_img=" << gemm_info.export_to_cl_image << "})";
+ os << "( n0=" << (unsigned int)gemm_info.n0 << " k0=" << gemm_info.k0 << " h0=" << gemm_info.h0 << " trans=" << gemm_info.transpose << " inter=" << gemm_info.interleave << " exp_img=" <<
+ gemm_info.export_to_cl_image << "})";
return os;
}
@@ -474,7 +475,8 @@ inline std::string to_string(const GEMMKernelInfo &gemm_info)
inline ::std::ostream &operator<<(::std::ostream &os, const BoundingBoxTransformInfo &bbox_info)
{
auto weights = bbox_info.weights();
- os << "(" << bbox_info.img_width() << "x" << bbox_info.img_height() << ")~" << bbox_info.scale() << "(weights={" << weights[0] << ", " << weights[1] << ", " << weights[2] << ", " << weights[3] << "})";
+ os << "(" << bbox_info.img_width() << "x" << bbox_info.img_height() << ")~" << bbox_info.scale() << "(weights={" << weights[0] << ", " << weights[1] << ", " << weights[2] << ", " << weights[3] <<
+ "})";
return os;
}
@@ -3333,46 +3335,46 @@ inline std::string to_string(const Conv3dInfo &conv3d_info)
inline std::string to_string(const WeightFormat wf)
{
#define __CASE_WEIGHT_FORMAT(wf) \
- case WeightFormat::wf: \
- return #wf;
+case WeightFormat::wf: \
+ return #wf;
switch(wf)
{
- __CASE_WEIGHT_FORMAT(UNSPECIFIED)
- __CASE_WEIGHT_FORMAT(ANY)
- __CASE_WEIGHT_FORMAT(OHWI)
- __CASE_WEIGHT_FORMAT(OHWIo2)
- __CASE_WEIGHT_FORMAT(OHWIo4)
- __CASE_WEIGHT_FORMAT(OHWIo8)
- __CASE_WEIGHT_FORMAT(OHWIo16)
- __CASE_WEIGHT_FORMAT(OHWIo32)
- __CASE_WEIGHT_FORMAT(OHWIo64)
- __CASE_WEIGHT_FORMAT(OHWIo128)
- __CASE_WEIGHT_FORMAT(OHWIo4i2)
- __CASE_WEIGHT_FORMAT(OHWIo4i2_bf16)
- __CASE_WEIGHT_FORMAT(OHWIo8i2)
- __CASE_WEIGHT_FORMAT(OHWIo8i2_bf16)
- __CASE_WEIGHT_FORMAT(OHWIo16i2)
- __CASE_WEIGHT_FORMAT(OHWIo16i2_bf16)
- __CASE_WEIGHT_FORMAT(OHWIo32i2)
- __CASE_WEIGHT_FORMAT(OHWIo32i2_bf16)
- __CASE_WEIGHT_FORMAT(OHWIo64i2)
- __CASE_WEIGHT_FORMAT(OHWIo64i2_bf16)
- __CASE_WEIGHT_FORMAT(OHWIo4i4)
- __CASE_WEIGHT_FORMAT(OHWIo4i4_bf16)
- __CASE_WEIGHT_FORMAT(OHWIo8i4)
- __CASE_WEIGHT_FORMAT(OHWIo8i4_bf16)
- __CASE_WEIGHT_FORMAT(OHWIo16i4)
- __CASE_WEIGHT_FORMAT(OHWIo16i4_bf16)
- __CASE_WEIGHT_FORMAT(OHWIo32i4)
- __CASE_WEIGHT_FORMAT(OHWIo32i4_bf16)
- __CASE_WEIGHT_FORMAT(OHWIo64i4)
- __CASE_WEIGHT_FORMAT(OHWIo64i4_bf16)
- __CASE_WEIGHT_FORMAT(OHWIo2i8)
- __CASE_WEIGHT_FORMAT(OHWIo4i8)
- __CASE_WEIGHT_FORMAT(OHWIo8i8)
- __CASE_WEIGHT_FORMAT(OHWIo16i8)
- __CASE_WEIGHT_FORMAT(OHWIo32i8)
- __CASE_WEIGHT_FORMAT(OHWIo64i8)
+ __CASE_WEIGHT_FORMAT(UNSPECIFIED)
+ __CASE_WEIGHT_FORMAT(ANY)
+ __CASE_WEIGHT_FORMAT(OHWI)
+ __CASE_WEIGHT_FORMAT(OHWIo2)
+ __CASE_WEIGHT_FORMAT(OHWIo4)
+ __CASE_WEIGHT_FORMAT(OHWIo8)
+ __CASE_WEIGHT_FORMAT(OHWIo16)
+ __CASE_WEIGHT_FORMAT(OHWIo32)
+ __CASE_WEIGHT_FORMAT(OHWIo64)
+ __CASE_WEIGHT_FORMAT(OHWIo128)
+ __CASE_WEIGHT_FORMAT(OHWIo4i2)
+ __CASE_WEIGHT_FORMAT(OHWIo4i2_bf16)
+ __CASE_WEIGHT_FORMAT(OHWIo8i2)
+ __CASE_WEIGHT_FORMAT(OHWIo8i2_bf16)
+ __CASE_WEIGHT_FORMAT(OHWIo16i2)
+ __CASE_WEIGHT_FORMAT(OHWIo16i2_bf16)
+ __CASE_WEIGHT_FORMAT(OHWIo32i2)
+ __CASE_WEIGHT_FORMAT(OHWIo32i2_bf16)
+ __CASE_WEIGHT_FORMAT(OHWIo64i2)
+ __CASE_WEIGHT_FORMAT(OHWIo64i2_bf16)
+ __CASE_WEIGHT_FORMAT(OHWIo4i4)
+ __CASE_WEIGHT_FORMAT(OHWIo4i4_bf16)
+ __CASE_WEIGHT_FORMAT(OHWIo8i4)
+ __CASE_WEIGHT_FORMAT(OHWIo8i4_bf16)
+ __CASE_WEIGHT_FORMAT(OHWIo16i4)
+ __CASE_WEIGHT_FORMAT(OHWIo16i4_bf16)
+ __CASE_WEIGHT_FORMAT(OHWIo32i4)
+ __CASE_WEIGHT_FORMAT(OHWIo32i4_bf16)
+ __CASE_WEIGHT_FORMAT(OHWIo64i4)
+ __CASE_WEIGHT_FORMAT(OHWIo64i4_bf16)
+ __CASE_WEIGHT_FORMAT(OHWIo2i8)
+ __CASE_WEIGHT_FORMAT(OHWIo4i8)
+ __CASE_WEIGHT_FORMAT(OHWIo8i8)
+ __CASE_WEIGHT_FORMAT(OHWIo16i8)
+ __CASE_WEIGHT_FORMAT(OHWIo32i8)
+ __CASE_WEIGHT_FORMAT(OHWIo64i8)
default:
return "invalid value";
}
@@ -3677,6 +3679,40 @@ inline std::string to_string(const experimental::dynamic_fusion::SoftmaxAttribut
return str.str();
}
+/** Formatted output of the arm_compute::MatMulKernelInfo type.
+ *
+ * @param[out] os Output stream.
+ * @param[in] matmul_info arm_compute::MatMulKernelInfo type to output.
+ *
+ * @return Modified output stream.
+ */
+inline ::std::ostream &operator<<(::std::ostream &os, const arm_compute::MatMulKernelInfo &matmul_info)
+{
+ os << "MatMulKernelInfo="
+ << "["
+ << "adj_lhs=" << matmul_info.adj_lhs << ", "
+ << "adj_rhs=" << matmul_info.adj_rhs << ", "
+ << "M0=" << matmul_info.m0 << ", "
+ << "N0=" << matmul_info.n0 << ", "
+ << "K0=" << matmul_info.k0 << ", "
+ << "export_rhs_to_cl_image=" << matmul_info.export_rhs_to_cl_image
+ << "]";
+
+ return os;
+}
+/** Formatted output of the arm_compute::MatMulKernelInfo type.
+ *
+ * @param[in] matmul_info arm_compute::MatMulKernelInfo type to output.
+ *
+ * @return Formatted string.
+ */
+inline std::string to_string(const arm_compute::MatMulKernelInfo &matmul_info)
+{
+ std::stringstream str;
+ str << matmul_info;
+ return str.str();
+}
+
} // namespace arm_compute
#endif /* __ARM_COMPUTE_TYPE_PRINTER_H__ */