• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2019-2020 Arm Limited.
3  *
4  * SPDX-License-Identifier: MIT
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to
8  * deal in the Software without restriction, including without limitation the
9  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10  * sell copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 #ifndef ARM_COMPUTE_CL /* Needed by Utils.cpp to handle OpenCL exceptions properly */
25 #error "This example needs to be built with -DARM_COMPUTE_CL"
26 #endif /* ARM_COMPUTE_CL */
27 
28 #include "arm_compute/core/Helpers.h"
29 #include "arm_compute/core/KernelDescriptors.h"
30 #include "arm_compute/core/Types.h"
31 #include "arm_compute/core/utils/misc/ShapeCalculator.h"
32 #include "arm_compute/runtime/CL/CLScheduler.h"
33 #include "arm_compute/runtime/CL/CLTuner.h"
34 #include "examples/gemm_tuner/CommonGemmExampleOptions.h"
35 #include "examples/gemm_tuner/GemmTunerHelpers.h"
36 #include "src/core/CL/kernels/CLGEMMMatrixMultiplyReshapedKernel.h"
37 #include "src/core/CL/kernels/CLGEMMReshapeLHSMatrixKernel.h"
38 #include "tests/CL/Helper.h"
39 #include "utils/Utils.h"
40 #include "utils/command_line/CommandLineOptions.h"
41 #include "utils/command_line/CommandLineParser.h"
42 
43 #include <cstdlib>
44 
45 using namespace arm_compute;
46 using namespace utils;
47 using namespace arm_compute::misc::shape_calculator;
48 using namespace gemm_tuner;
49 
50 namespace
51 {
52 /** Structure holding all tunable gemm configs specific to this example/strategy */
53 struct GemmConfigs
54 {
55     size_t m0{ 4 };                        /**< Number of rows processed by the matrix multiplication */
56     size_t n0{ 4 };                        /**< Number of columns processed by the matrix multiplication */
57     size_t k0{ 4 };                        /**< Number of partial accumulations performed by the matrix multiplication */
58     size_t v0{ 1 };                        /**< Number of vertical blocks of size (m0xk0) stored on the same output row */
59     size_t h0{ 1 };                        /**< Number of horizontal blocks of size (k0xn0) stored on the same output row */
60     bool   interleave_lhs{ true };         /**< Interleave lhs matrix */
61     bool   transpose_lhs{ true };          /**< Transpose lhs matrix. */
62     bool   interleave_rhs{ true };         /**< Interleave rhs matrix */
63     bool   transpose_rhs{ true };          /**< Transpose rhs matrix. */
64     bool   export_to_cl_image_rhs{ true }; /**< Export rhs matrix to cl_image. */
65 };
66 
67 /** Formatted output of the GemmConfigs type
68  *
69  * @param[out] os      Output stream.
70  * @param[in]  configs Tunable configurations to output
71  *
72  * @return Modified output stream.
73  */
operator <<(::std::ostream & os,const GemmConfigs & configs)74 ::std::ostream &operator<<(::std::ostream &os, const GemmConfigs &configs)
75 {
76     std::string false_str = std::string("false");
77     std::string true_str  = std::string("true");
78 
79     os << "m0 : " << configs.m0 << std::endl;
80     os << "n0 : " << configs.n0 << std::endl;
81     os << "k0 : " << configs.k0 << std::endl;
82     os << "v0 : " << configs.v0 << std::endl;
83     os << "h0 : " << configs.h0 << std::endl;
84     os << "interleave_lhs : " << (configs.interleave_lhs ? true_str : false_str) << std::endl;
85     os << "transpose_lhs : " << (configs.transpose_lhs ? true_str : false_str) << std::endl;
86     os << "interleave_rhs : " << (configs.interleave_rhs ? true_str : false_str) << std::endl;
87     os << "transpose_rhs : " << (configs.transpose_rhs ? true_str : false_str) << std::endl;
88     os << "export_to_cl_image_rhs : " << (configs.export_to_cl_image_rhs ? true_str : false_str) << std::endl;
89     return os;
90 }
91 
92 /** Command line options for gemm configs */
93 class GemmConfigOptions
94 {
95 public:
96     /** Constructor
97      *
98      * @param[in,out] parser A parser on which "parse()" hasn't been called yet.
99      */
GemmConfigOptions(CommandLineParser & parser)100     GemmConfigOptions(CommandLineParser &parser)
101         : m0(parser.add_positional_option<SimpleOption<size_t>>("m0", 4)),
102           n0(parser.add_positional_option<SimpleOption<size_t>>("n0", 4)),
103           k0(parser.add_positional_option<SimpleOption<size_t>>("k0", 4)),
104           v0(parser.add_positional_option<SimpleOption<size_t>>("v0", 1)),
105           h0(parser.add_positional_option<SimpleOption<size_t>>("h0", 1)),
106           interleave_lhs(parser.add_positional_option<SimpleOption<size_t>>("interleave_lhs", 1)),
107           interleave_rhs(parser.add_positional_option<SimpleOption<size_t>>("interleave_rhs", 1)),
108           transpose_rhs(parser.add_positional_option<SimpleOption<size_t>>("transpose_rhs", 1)),
109           export_to_cl_image_rhs(parser.add_positional_option<SimpleOption<size_t>>("export_to_cl_image_rhs", 1))
110     {
111         m0->set_help("Number of rows processed by the matrix multiplication");
112         n0->set_help("Number of columns processed by the matrix multiplication");
113         k0->set_help("Number of partial accumulations performed by the matrix multiplication");
114         v0->set_help("Number of vertical blocks of size (m0xk0) stored on the same output row");
115         h0->set_help("Number of horizontal blocks of size (k0xn0) stored on the same output row");
116         interleave_lhs->set_help("Interleave lhs matrix (1) / Do not interleave lhs matrix (0)");
117         interleave_rhs->set_help("Interleave rhs matrix (1) / Do not interleave rhs matrix (0)");
118         // FIXME: Currently we only support 2 variants of the gemm reshaped kernels in which transpose_lhs and
119         // transpose_rhs are the opposites of each other. In the future we may extend the kernels to include the other
120         // 2 variants (both transposed and none transposed)
121         transpose_rhs->set_help("Transpose rhs matrix but not lhs matrix (1) / Do not transpose rhs matrix but do transpose lhs matrix (0)");
122         export_to_cl_image_rhs->set_help("Export rhs matrix to cl_image (1) / Do not export rhs matrix to cl_image (0)");
123     }
124     /** Prevent instances of this class from being copied (As this class contains pointers) */
125     GemmConfigOptions(const GemmConfigOptions &) = delete;
126     /** Prevent instances of this class from being copied (As this class contains pointers) */
127     GemmConfigOptions &operator=(const GemmConfigOptions &) = delete;
128     /** Allow instances of this class to be moved */
129     GemmConfigOptions(GemmConfigOptions &&) = default;
130     /** Allow instances of this class to be moved */
131     GemmConfigOptions &operator=(GemmConfigOptions &&) = default;
132     /** Default destructor */
133     ~GemmConfigOptions() = default;
134 
135     SimpleOption<size_t> *m0;             /**< Number of rows processed by the matrix multiplication option */
136     SimpleOption<size_t> *n0;             /**< Number of columns processed by the matrix multiplication option */
137     SimpleOption<size_t> *k0;             /**< Number of partial accumulations performed by the matrix multiplication option */
138     SimpleOption<size_t> *v0;             /**< Number of vertical blocks of size (m0xk0) stored on the same output row option */
139     SimpleOption<size_t> *h0;             /**< Number of horizontal blocks of size (k0xn0) stored on the same output row option */
140     SimpleOption<size_t> *interleave_lhs; /**< Interleave lhs matrix option (1 enable; 0 disable) */
141     SimpleOption<size_t> *interleave_rhs; /**< Interleave rhs matrix option (1 enable; 0 disable) */
142     // FIXME: Currently we only support 2 variants of the gemm reshaped kernels in which transpose_lhs and
143     // transpose_rhs are the opposites of each other. In the future we may extend the kernels to include the other
144     // 2 variants (both transposed and none transposed)
145     SimpleOption<size_t> *transpose_rhs;          /**< Transpose rhs matrix option (1 enable; 0 disable). Also set the lhs matrix transpose option to the opposite. */
146     SimpleOption<size_t> *export_to_cl_image_rhs; /**< Export rhs matrix to cl_image.*/
147 };
148 
149 /** Consumes the gemm configuration options and creates a structure containing all information
150  *
151  * @param[in] options Options to consume
152  *
153  * @return Structure containing the gemm configurations
154  */
consume_gemm_configs(const GemmConfigOptions & options)155 GemmConfigs consume_gemm_configs(const GemmConfigOptions &options)
156 {
157     GemmConfigs configs;
158     configs.m0             = options.m0->value();
159     configs.n0             = options.n0->value();
160     configs.k0             = options.k0->value();
161     configs.v0             = options.v0->value();
162     configs.h0             = options.h0->value();
163     configs.interleave_lhs = options.interleave_lhs->value() != 0;
164     // FIXME: Currently we only support 2 variants of the gemm reshaped kernels in which transpose_lhs and
165     // transpose_rhs are the opposites of each other. In the future we may extend the kernels to include the other
166     // 2 variants (both transposed and none transposed)
167     configs.transpose_lhs          = options.transpose_rhs->value() == 0;
168     configs.interleave_rhs         = options.interleave_rhs->value() != 0;
169     configs.transpose_rhs          = options.transpose_rhs->value() != 0;
170     configs.export_to_cl_image_rhs = options.export_to_cl_image_rhs->value() != 0;
171     return configs;
172 }
173 
174 } // namespace
175 // Create function for CLGEMMReshapeLHSMatrixKernel
176 using CLGEMMReshapeLHSMatrix = test::CLSynthetizeFunction<CLGEMMReshapeLHSMatrixKernel>;
177 // Create function for CLGEMMMatrixMultiplyReshapedKernel
178 using CLGEMMMatrixMultiplyReshaped = test::CLSynthetizeFunction<CLGEMMMatrixMultiplyReshapedKernel>;
179 
180 class CLGEMMMatrixMultiplyReshapedExample : public Example
181 {
182 public:
do_setup(int argc,char ** argv)183     bool do_setup(int argc, char **argv) override
184     {
185         // Default parameters
186         const float               alpha    = 1.0f;
187         const float               beta     = 0.0f;
188         const ActivationLayerInfo act_info = ActivationLayerInfo();
189         CommonGemmExampleParams   params;
190         GemmConfigs               configs;
191 
192         // Set up command line parser and options
193         CommandLineParser        parser;
194         CommonGemmExampleOptions param_options(parser);
195         GemmConfigOptions        config_options(parser);
196 
197         // Parse command line options
198         parser.parse(argc, argv);
199         if(param_options.help->is_set() && param_options.help->value())
200         {
201             // Print help message
202             parser.print_help(argv[0]);
203             return false;
204         }
205         if(!parser.validate())
206         {
207             // Invalid arguments. Use default parameters and configs
208             std::cerr << "Invalid arguments." << std::endl;
209             parser.print_help(argv[0]);
210             std::cerr << "Falling back to default parameters and configs" << std::endl;
211         }
212         else
213         {
214             // Get parameters and configs from command-line options
215             params  = consume_common_gemm_example_parameters(param_options);
216             configs = consume_gemm_configs(config_options);
217         }
218 
219         // Print gemm parameters and configurations
220         std::cout << "Gemm parameters:" << std::endl;
221         std::cout << params << std::endl;
222         std::cout << "Gemm configurations:" << std::endl;
223         std::cout << configs << std::endl;
224 
225         CLScheduler::get().default_init(&tuner);
226 
227         lhs.allocator()->init(TensorInfo(TensorShape(params.K, params.M, params.B), 1, params.data_type));
228         rhs.allocator()->init(TensorInfo(TensorShape(params.N, params.K, params.B), 1, params.data_type));
229         bias.allocator()->init(TensorInfo(TensorShape(params.N, 1, params.B), 1, params.data_type));
230 
231         GEMMLHSMatrixInfo lhs_info;
232         lhs_info.m0         = configs.m0;
233         lhs_info.k0         = configs.k0;
234         lhs_info.v0         = configs.v0;
235         lhs_info.interleave = configs.interleave_lhs;
236         lhs_info.transpose  = configs.transpose_lhs;
237 
238         GEMMRHSMatrixInfo rhs_info;
239         rhs_info.n0                 = configs.n0;
240         rhs_info.k0                 = configs.k0;
241         rhs_info.h0                 = configs.h0;
242         rhs_info.interleave         = configs.interleave_rhs;
243         rhs_info.transpose          = configs.transpose_rhs;
244         rhs_info.export_to_cl_image = configs.export_to_cl_image_rhs;
245 
246         GEMMKernelInfo kernel_info;
247         kernel_info.m                       = params.M;
248         kernel_info.n                       = params.N;
249         kernel_info.k                       = params.K;
250         kernel_info.depth_output_gemm3d     = 0;
251         kernel_info.reinterpret_input_as_3d = false;
252         kernel_info.broadcast_bias          = true;
253         kernel_info.activation_info         = act_info;
254 
255         // Initialise lhs_reshaped tensor info
256         lhs_reshaped.allocator()->init(TensorInfo(compute_lhs_reshaped_shape(*lhs.info(), lhs_info), 1, params.data_type));
257 
258         // Initialise rhs_reshaped tensor info
259         rhs_reshaped.allocator()->init(TensorInfo(compute_rhs_reshaped_shape(*rhs.info(), rhs_info), 1, params.data_type));
260 
261         if(rhs_info.export_to_cl_image)
262         {
263             examples::gemm_tuner_helpers::update_padding_for_cl_image(rhs_reshaped.info());
264         }
265 
266         // Validate argments
267         Status status{};
268         status = reshape_lhs.validate((&lhs)->info(), (&lhs_reshaped)->info(), lhs_info, kernel_info.reinterpret_input_as_3d);
269         if(!status)
270         {
271             // Unsupported arguments
272             std::cerr << "Unsupported arguments." << std::endl;
273             std::cerr << "Check documentation for supported/unsupported combinations" << std::endl;
274             return false;
275         }
276 
277         status = gemm.validate((&lhs_reshaped)->info(), (&rhs_reshaped)->info(), (&bias)->info(), (&dst)->info(), alpha, beta, lhs_info, rhs_info, kernel_info);
278         if(!status)
279         {
280             // Unsupported arguments
281             std::cerr << "Unsupported arguments." << std::endl;
282             std::cerr << "Check documentation for supported/unsupported combinations" << std::endl;
283             return false;
284         }
285 
286         // Configure reshape lhs function
287         reshape_lhs.configure(&lhs, &lhs_reshaped, lhs_info);
288 
289         // Configure function
290         gemm.configure(&lhs_reshaped, &rhs_reshaped, &bias, &dst, alpha, beta, lhs_info, rhs_info, kernel_info);
291 
292         // Allocate tensors
293         lhs.allocator()->allocate();
294         rhs.allocator()->allocate();
295         lhs_reshaped.allocator()->allocate();
296         rhs_reshaped.allocator()->allocate();
297         bias.allocator()->allocate();
298         dst.allocator()->allocate();
299 
300         return true;
301     }
do_run()302     void do_run() override
303     {
304         // Execute the function
305         reshape_lhs.run();
306         gemm.run();
307 
308         // Make sure all the OpenCL jobs are done executing:
309         CLScheduler::get().sync();
310     }
311 
do_teardown()312     void do_teardown() override
313     {
314     }
315 
316 private:
317     CLTensor                     lhs{};
318     CLTensor                     rhs{};
319     CLTensor                     lhs_reshaped{};
320     CLTensor                     rhs_reshaped{};
321     CLTensor                     bias{};
322     CLTensor                     dst{};
323     CLTuner                      tuner{};
324     CLGEMMReshapeLHSMatrix       reshape_lhs{};
325     CLGEMMMatrixMultiplyReshaped gemm{};
326 };
327 
328 /** Main program for gemm reshaped test
329  *
330  * @param[in] argc Number of arguments
331  * @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 )
332  */
main(int argc,char ** argv)333 int main(int argc, char **argv)
334 {
335     return run_example<CLGEMMMatrixMultiplyReshapedExample>(argc, argv);
336 }
337