From bc166d5a8e350bed6b50d7315f8e8502fc9a17b1 Mon Sep 17 00:00:00 2001 From: SiCong Li Date: Thu, 26 Sep 2019 14:58:53 +0100 Subject: COMPMID-2565 - Add CLGEMMReshaped example * Add gemm reshaped example. * Update shell script to run gemm reshaped example. * Use OPENCL_TIMER_MS for instrument * Increase number of iterations to 5 Signed-off-by: SiCong Li Change-Id: I41b3cebc5ee6368bf156d0e888101a3ff976a1b5 Reviewed-on: https://review.mlplatform.org/c/1990 Comments-Addressed: Arm Jenkins Tested-by: Arm Jenkins Reviewed-by: Georgios Pinitas --- examples/gemm_tuner/benchmark_gemm_examples.sh | 117 ++++++++-- examples/gemm_tuner/cl_gemm_reshaped.cpp | 297 +++++++++++++++++++++++++ 2 files changed, 390 insertions(+), 24 deletions(-) create mode 100644 examples/gemm_tuner/cl_gemm_reshaped.cpp diff --git a/examples/gemm_tuner/benchmark_gemm_examples.sh b/examples/gemm_tuner/benchmark_gemm_examples.sh index e3ed1aefde..7782b11f72 100755 --- a/examples/gemm_tuner/benchmark_gemm_examples.sh +++ b/examples/gemm_tuner/benchmark_gemm_examples.sh @@ -29,19 +29,17 @@ set -u CMD=$( basename $0 ) # All supported strategy options -ALL_STRATEGY_OPTIONS="reshaped_rhs_only" - -# Default strategy option -DEFAULT_STRATEGY_OPTION="reshaped_rhs_only" +ALL_STRATEGY_OPTIONS=("reshaped_rhs_only" "reshaped") # Names of example binary for each strategy EXAMPLE_BIN_RESHAPED_RHS_ONLY="benchmark_cl_gemm_reshaped_rhs_only" +EXAMPLE_BIN_RESHAPED="benchmark_cl_gemm_reshaped" # Default output directory DEFAULT_OUT_DIR="out" # Number of iterations for each benchmark run -NUM_ITERATION=3 +NUM_ITERATION=5 # Global }}} # Functions {{{ @@ -75,7 +73,7 @@ EOF } ####################################### -# Print gemm config file for reshaped_rhs_only +# Print gemm config file for reshaped_rhs_only help message # Globals: # None # Arguments: @@ -94,7 +92,7 @@ Gemm config file (Strategy reshaped_rhs_only): k0 - Number of partial accumulations performed by the matrix multiplication h0 - Number of horizontal blocks of size (k0xn0) stored on the same output row interleave_rhs - Interleave rhs matrix (1) / Do not interleave rhs matrix (0) - transpose_rhs - Interleave rhs matrix (1) / Do not transpose rhs matrix (0) + transpose_rhs - Transpose rhs matrix (1) / Do not transpose rhs matrix (0) Only the following configurations of M0, N0 and K0 are currently supported: M0 = 1, 2, 3, 4, 5, 6, 7, 8 @@ -103,8 +101,54 @@ Gemm config file (Strategy reshaped_rhs_only): H0 >= 1 An example gemm config file looks like: - 4,4,4,1 - 4,4,4,3 + 4,4,4,1,1,1 + 4,4,4,3,1,0 + ... + +EOF +} + +####################################### +# Print gemm config file for reshaped help message +# Globals: +# None +# Arguments: +# None +# Returns: +# None +####################################### +function help_gemm_config_file_reshaped() { + cat >&2 << EOF +Gemm config file (Strategy reshaped): + Gemm config file is a headerless csv file with fields separated by commas and commas only (there cannot be whitespaces + around each field). + A gemm config is a list of 5 positive integers and 3 boolean values interleave_lhs, interleave_rhs and transpose_rhs, with: + m0 - Number of rows processed by the matrix multiplication + n0 - Number of columns processed by the matrix multiplication + k0 - Number of partial accumulations performed by the matrix multiplication + v0 - Number of vertical blocks of size (m0xk0) stored on the same output row + h0 - Number of horizontal blocks of size (k0xn0) stored on the same output row + interleave_lhs - Interleave lhs matrix (1) / Do not interleave lhs matrix (0) + interleave_rhs - Interleave rhs matrix (1) / Do not interleave rhs matrix (0) + transpose_rhs - Transpose rhs matrix but not lhs matrix (1) / Do not transpose rhs matrix but do transpose lhs matrix (0) + + If rhs matrix is transposed only the following configurations are currently supported: + M0 = 2, 3, 4, 5, 6, 7, 8 + N0 = 2, 3, 4, 8, 16 + K0 = 2, 3, 4, 8, 16 + V0 >= 1 + H0 >= 1 + + If lhs matrix is transposed only the following configurations are currently supported: + M0 = 2, 3, 4, 8 + N0 = 2, 3, 4, 8, 16 + K0 = 2, 3, 4, 8, 16 + V0 >= 1 + H0 >= 1 + + An example gemm config file looks like: + 4,4,4,1,3,1,1,1 + 4,4,4,3,3,1,1,0 ... EOF @@ -124,11 +168,16 @@ function usage() { Run gemm examples of a selected strategy, over provided tunable configurationsa and gemm shapes. Save the benchmark results to json files in an output directory. -Usage: ${CMD} [-h] -e -g -c [-s , [-o ]] +Usage: ${CMD} [-h] -s -e -g -c [-o ] Options: -h - Print help messages for selected , which is ${STRATEGY_OPTION} + Print help messages. If a strategy is specified with -s , then only display messages relevant to that + strategy. Otherwise if no strategy is specified, display messages for all available strategies. + + -s + Strategy option. + Options: ${ALL_STRATEGY_OPTIONS[@]}. -e Path to directory that holds all example binaries @@ -139,10 +188,6 @@ Options: -c Path to gemm config csv file - -s - Strategy option. - Options: ${ALL_STRATEGY_OPTIONS}. Default: ${DEFAULT_STRATEGY_OPTION} - -o Path to output directory that holds output json files Default: ${DEFAULT_OUT_DIR} @@ -151,6 +196,7 @@ EOF # Print help messages about gemm shapes and various gemm configs $HELP && help_gemm_shape_file $HELP && ( [ "${STRATEGY_OPTION}" == "" ] || [ "${STRATEGY_OPTION}" == "reshaped_rhs_only" ] ) && help_gemm_config_file_reshaped_rhs_only +$HELP && ( [ "${STRATEGY_OPTION}" == "" ] || [ "${STRATEGY_OPTION}" == "reshaped" ] ) && help_gemm_config_file_reshaped exit 1 } @@ -196,6 +242,28 @@ function is_integer() { [ "$in" -eq "$in" ] 2> /dev/null } +####################################### +# Test if a string is in an array of strings +# Globals: +# None +# Arguments: +# target - String to test +# array - Array of strings to search +# Returns: +# true/false +####################################### +function arr_contains() { + local target=$1 + shift + local array + array=("$@") + for s in "${array[@]}" + do + [ "$s" == "${target}" ] && return + done + false +} + ####################################### # Run all tunable configurations and all input configurations # Globals: @@ -219,7 +287,7 @@ function run() { while read gemm_config do example_args="${gemm_shape},${gemm_config}" - ${EXAMPLE_BIN_DIR}/${example_bin} --example_args=${example_args} --iterations=${NUM_ITERATION} --json-file=${OUT_DIR}/${test_id} + ${EXAMPLE_BIN_DIR}/${example_bin} --example_args=${example_args} --iterations=${NUM_ITERATION} --json-file=${OUT_DIR}/${test_id} --instruments=OPENCL_TIMER_MS (( test_id++ )) done < "${GEMM_CONFIGS_FILE}" done < "${GEMM_SHAPES_FILE}" @@ -236,18 +304,18 @@ EXAMPLE_BIN_DIR="" GEMM_SHAPES_FILE="" # Path to gemm configs file GEMM_CONFIGS_FILE="" -STRATEGY_OPTION=${DEFAULT_STRATEGY_OPTION} +STRATEGY_OPTION="" # Path to output directory OUT_DIR=${DEFAULT_OUT_DIR} # Toggle help HELP=false # Obtain options -while getopts "he:s:g:c:o:" opt; do +while getopts "hs:e:g:c:o:" opt; do case "$opt" in - h|\?) HELP=true ;; - e) EXAMPLE_BIN_DIR="${OPTARG}";; + h) HELP=true ;; s) STRATEGY_OPTION=$(to_lower "${OPTARG}");; + e) EXAMPLE_BIN_DIR="${OPTARG}";; g) GEMM_SHAPES_FILE="${OPTARG}";; c) GEMM_CONFIGS_FILE="${OPTARG}";; o) OUT_DIR="${OPTARG}";; @@ -260,8 +328,8 @@ $HELP && usage # Parse and validate options -# Verify all arguments are passed in -[ ${OPTIND} -ge 7 ] || +# Verify all compulsory arguments are passed in +( [ ! -z "${STRATEGY_OPTION}" ] && [ ! -z "${EXAMPLE_BIN_DIR}" ] && [ ! -z "${GEMM_SHAPES_FILE}" ] && [ ! -z "${GEMM_CONFIGS_FILE}" ] ) || usage # Verify example binaries directory exists @@ -276,12 +344,12 @@ $HELP && [ -f "${GEMM_SHAPES_FILE}" ] || error_msg "Cannot find gemm shapes file ${GEMM_SHAPES_FILE}" -# Verify Gemm shapes file exists +# Verify Gemm configs file exists [ -f "${GEMM_CONFIGS_FILE}" ] || error_msg "Cannot find gemm configs file ${GEMM_CONFIGS_FILE}" # Verify strategy option is valid -[[ "${ALL_STRATEGY_OPTIONS}" == *"${STRATEGY_OPTION}"* ]] || +arr_contains "${STRATEGY_OPTION}" "${ALL_STRATEGY_OPTIONS[@]}" || error_msg "Does not support strategy ${STRATEGY_OPTION}" # Make sure existing benchmark outputs are not overwritten @@ -293,4 +361,5 @@ mkdir ${OUT_DIR} # Run selected strategy with all configurations [ "${STRATEGY_OPTION}" == "reshaped_rhs_only" ] && run $EXAMPLE_BIN_RESHAPED_RHS_ONLY +[ "${STRATEGY_OPTION}" == "reshaped" ] && run $EXAMPLE_BIN_RESHAPED # Main: Main script }}} diff --git a/examples/gemm_tuner/cl_gemm_reshaped.cpp b/examples/gemm_tuner/cl_gemm_reshaped.cpp new file mode 100644 index 0000000000..6445592a72 --- /dev/null +++ b/examples/gemm_tuner/cl_gemm_reshaped.cpp @@ -0,0 +1,297 @@ +/* + * Copyright (c) 2019 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 ARM_COMPUTE_CL /* Needed by Utils.cpp to handle OpenCL exceptions properly */ +#error "This example needs to be built with -DARM_COMPUTE_CL" +#endif /* ARM_COMPUTE_CL */ + +#include "CommonGemmExampleOptions.h" +#include "arm_compute/core/CL/kernels/CLGEMMMatrixMultiplyReshapedKernel.h" +#include "arm_compute/core/Helpers.h" +#include "arm_compute/core/KernelDescriptors.h" +#include "arm_compute/core/Types.h" +#include "arm_compute/core/utils/misc/ShapeCalculator.h" +#include "arm_compute/runtime/CL/CLFunctions.h" +#include "arm_compute/runtime/CL/CLScheduler.h" +#include "arm_compute/runtime/CL/CLTuner.h" +#include "tests/CL/Helper.h" +#include "utils/Utils.h" +#include "utils/command_line/CommandLineOptions.h" +#include "utils/command_line/CommandLineParser.h" + +#include + +using namespace arm_compute; +using namespace utils; +using namespace arm_compute::misc::shape_calculator; +using namespace gemm_tuner; + +namespace +{ +/** Structure holding all tunable gemm configs specific to this example/strategy */ +struct GemmConfigs +{ + size_t m0{ 4 }; /**< Number of rows processed by the matrix multiplication */ + size_t n0{ 4 }; /**< Number of columns processed by the matrix multiplication */ + size_t k0{ 4 }; /**< Number of partial accumulations performed by the matrix multiplication */ + size_t v0{ 1 }; /**< Number of vertical blocks of size (m0xk0) stored on the same output row */ + size_t h0{ 1 }; /**< Number of horizontal blocks of size (k0xn0) stored on the same output row */ + bool interleave_lhs{ true }; /**< Interleave lhs matrix */ + bool transpose_lhs{ true }; /**< Transpose lhs matrix. */ + bool interleave_rhs{ true }; /**< Interleave rhs matrix */ + bool transpose_rhs{ true }; /**< Transpose rhs matrix. */ +}; + +/** Formatted output of the GemmConfigs type + * + * @param[out] os Output stream. + * @param[in] configs Tunable configurations to output + * + * @return Modified output stream. + */ +::std::ostream &operator<<(::std::ostream &os, const GemmConfigs &configs) +{ + std::string false_str = std::string("false"); + std::string true_str = std::string("true"); + + os << "m0 : " << configs.m0 << std::endl; + os << "n0 : " << configs.n0 << std::endl; + os << "k0 : " << configs.k0 << std::endl; + os << "v0 : " << configs.v0 << std::endl; + os << "h0 : " << configs.h0 << std::endl; + os << "interleave_lhs : " << (configs.interleave_lhs ? true_str : false_str) << std::endl; + os << "transpose_lhs : " << (configs.transpose_lhs ? true_str : false_str) << std::endl; + os << "interleave_rhs : " << (configs.interleave_rhs ? true_str : false_str) << std::endl; + os << "transpose_rhs : " << (configs.transpose_rhs ? true_str : false_str) << std::endl; + return os; +} + +/** Command line options for gemm configs */ +class GemmConfigOptions +{ +public: + /** Constructor + * + * @param[in,out] parser A parser on which "parse()" hasn't been called yet. + */ + GemmConfigOptions(CommandLineParser &parser) + : m0(parser.add_positional_option>("m0", 4)), + n0(parser.add_positional_option>("n0", 4)), + k0(parser.add_positional_option>("k0", 4)), + v0(parser.add_positional_option>("v0", 1)), + h0(parser.add_positional_option>("h0", 1)), + interleave_lhs(parser.add_positional_option>("interleave_lhs", 1)), + interleave_rhs(parser.add_positional_option>("interleave_rhs", 1)), + transpose_rhs(parser.add_positional_option>("transpose_rhs", 1)) + { + m0->set_help("Number of rows processed by the matrix multiplication"); + n0->set_help("Number of columns processed by the matrix multiplication"); + k0->set_help("Number of partial accumulations performed by the matrix multiplication"); + v0->set_help("Number of vertical blocks of size (m0xk0) stored on the same output row"); + h0->set_help("Number of horizontal blocks of size (k0xn0) stored on the same output row"); + interleave_lhs->set_help("Interleave lhs matrix (1) / Do not interleave lhs matrix (0)"); + interleave_rhs->set_help("Interleave rhs matrix (1) / Do not interleave rhs matrix (0)"); + // FIXME: Currently we only support 2 variants of the gemm reshaped kernels in which transpose_lhs and + // transpose_rhs are the opposites of each other. In the future we may extend the kernels to include the other + // 2 variants (both transposed and none transposed) + transpose_rhs->set_help("Transpose rhs matrix but not lhs matrix (1) / Do not transpose rhs matrix but do transpose lhs matrix (0)"); + } + /** Prevent instances of this class from being copied (As this class contains pointers) */ + GemmConfigOptions(const GemmConfigOptions &) = delete; + /** Prevent instances of this class from being copied (As this class contains pointers) */ + GemmConfigOptions &operator=(const GemmConfigOptions &) = delete; + /** Allow instances of this class to be moved */ + GemmConfigOptions(GemmConfigOptions &&) = default; + /** Allow instances of this class to be moved */ + GemmConfigOptions &operator=(GemmConfigOptions &&) = default; + /** Default destructor */ + ~GemmConfigOptions() = default; + + SimpleOption *m0; /**< Number of rows processed by the matrix multiplication option */ + SimpleOption *n0; /**< Number of columns processed by the matrix multiplication option */ + SimpleOption *k0; /**< Number of partial accumulations performed by the matrix multiplication option */ + SimpleOption *v0; /**< Number of vertical blocks of size (m0xk0) stored on the same output row option */ + SimpleOption *h0; /**< Number of horizontal blocks of size (k0xn0) stored on the same output row option */ + SimpleOption *interleave_lhs; /**< Interleave lhs matrix option (1 enable; 0 disable) */ + SimpleOption *interleave_rhs; /**< Interleave rhs matrix option (1 enable; 0 disable) */ + // FIXME: Currently we only support 2 variants of the gemm reshaped kernels in which transpose_lhs and + // transpose_rhs are the opposites of each other. In the future we may extend the kernels to include the other + // 2 variants (both transposed and none transposed) + SimpleOption *transpose_rhs; /**< Transpose rhs matrix option (1 enable; 0 disable). Also set the lhs matrix transpose option to the opposite. */ +}; + +/** Consumes the gemm configuration options and creates a structure containing all information + * + * @param[in] options Options to consume + * + * @return Structure containing the gemm configurations + */ +GemmConfigs consume_gemm_configs(const GemmConfigOptions &options) +{ + GemmConfigs configs; + configs.m0 = options.m0->value(); + configs.n0 = options.n0->value(); + configs.k0 = options.k0->value(); + configs.v0 = options.v0->value(); + configs.h0 = options.h0->value(); + configs.interleave_lhs = options.interleave_lhs->value() != 0; + // FIXME: Currently we only support 2 variants of the gemm reshaped kernels in which transpose_lhs and + // transpose_rhs are the opposites of each other. In the future we may extend the kernels to include the other + // 2 variants (both transposed and none transposed) + configs.transpose_lhs = options.transpose_rhs->value() == 0; + configs.interleave_rhs = options.interleave_rhs->value() != 0; + configs.transpose_rhs = options.transpose_rhs->value() != 0; + return configs; +} + +} // namespace +// Create function for CLGEMMMatrixMultiplyReshapedKernel +using CLGEMMMatrixMultiplyReshaped = test::CLSynthetizeFunction; + +class CLGEMMMatrixMultiplyReshapedExample : public Example +{ +public: + bool do_setup(int argc, char **argv) override + { + // Default parameters + const DataType data_type = DataType::F32; + const float alpha = 1.0f; + const float beta = 0.0f; + const ActivationLayerInfo act_info = ActivationLayerInfo(); + CommonGemmExampleParams params; + GemmConfigs configs; + + // Set up command line parser and options + CommandLineParser parser; + CommonGemmExampleOptions param_options(parser); + GemmConfigOptions config_options(parser); + + // Parse command line options + parser.parse(argc, argv); + if(param_options.help->is_set() && param_options.help->value()) + { + // Print help message + parser.print_help(argv[0]); + return false; + } + if(!parser.validate()) + { + // Invalid arguments. Use default parameters and configs + std::cerr << "Invalid arguments." << std::endl; + parser.print_help(argv[0]); + std::cerr << "Falling back to default parameters and configs" << std::endl; + } + else + { + // Get parameters and configs from command-line options + params = consume_common_gemm_example_parameters(param_options); + configs = consume_gemm_configs(config_options); + } + + // Print gemm parameters and configurations + std::cerr << "Gemm parameters:" << std::endl; + std::cerr << params << std::endl; + std::cerr << "Gemm configurations:" << std::endl; + std::cerr << configs << std::endl; + + CLScheduler::get().default_init(&tuner); + + lhs.allocator()->init(TensorInfo(TensorShape(params.K, params.M, params.B), 1, data_type)); + rhs.allocator()->init(TensorInfo(TensorShape(params.N, params.K, params.B), 1, data_type)); + bias.allocator()->init(TensorInfo(TensorShape(params.N, 1, params.B), 1, data_type)); + + GEMMLHSMatrixInfo lhs_info; + lhs_info.m0 = configs.m0; + lhs_info.k0 = configs.k0; + lhs_info.v0 = configs.v0; + lhs_info.interleave = configs.interleave_lhs; + lhs_info.transpose = configs.transpose_lhs; + + GEMMRHSMatrixInfo rhs_info; + rhs_info.n0 = configs.n0; + rhs_info.k0 = configs.k0; + rhs_info.h0 = configs.h0; + rhs_info.interleave = configs.interleave_rhs; + rhs_info.transpose = configs.transpose_rhs; + + GEMMKernelInfo kernel_info; + kernel_info.m = params.M; + kernel_info.n = params.N; + kernel_info.k = params.K; + kernel_info.depth_output_gemm3d = 0; + kernel_info.reinterpret_input_as_3d = false; + kernel_info.broadcast_bias = true; + kernel_info.activation_info = act_info; + + // Initialise lhs_reshaped tensor info + auto_init_if_empty(*lhs_reshaped.info(), lhs.info()->clone()->set_tensor_shape(compute_lhs_reshaped_shape(*lhs.info(), lhs_info))); + + // Initialise rhs_reshaped tensor info + auto_init_if_empty(*rhs_reshaped.info(), rhs.info()->clone()->set_tensor_shape(compute_rhs_reshaped_shape(*rhs.info(), rhs_info))); + + // Configure function + gemm.configure(&lhs_reshaped, &rhs_reshaped, &bias, &dst, alpha, beta, lhs_info, rhs_info, kernel_info); + + // Allocate tensors + lhs.allocator()->allocate(); + rhs.allocator()->allocate(); + lhs_reshaped.allocator()->allocate(); + rhs_reshaped.allocator()->allocate(); + bias.allocator()->allocate(); + dst.allocator()->allocate(); + + return true; + } + void do_run() override + { + // Execute the function + gemm.run(); + + // Make sure all the OpenCL jobs are done executing: + CLScheduler::get().sync(); + } + + void do_teardown() override + { + } + +private: + CLTensor lhs{}; + CLTensor rhs{}; + CLTensor lhs_reshaped{}; + CLTensor rhs_reshaped{}; + CLTensor bias{}; + CLTensor dst{}; + CLTuner tuner{}; + CLGEMMMatrixMultiplyReshaped gemm{}; +}; + +/** Main program for gemm reshaped test + * + * @param[in] argc Number of arguments + * @param[in] argv Arguments ( [optional] M, [optional] N, [optional] K, [optional] B, [optional] m0, [optional] n0, [optional] k0, [optional] v0, [optional] h0, [optional] interleave_lhs, [optional] interleave_rhs, [optional] transpose_rhs ) + */ +int main(int argc, char **argv) +{ + return run_example(argc, argv); +} -- cgit v1.2.1