1 /*
2 * Copyright (c) 2019-2021 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 "CommonGemmExampleOptions.h"
29 #include "GemmTunerHelpers.h"
30 #include "arm_compute/core/Helpers.h"
31 #include "arm_compute/core/KernelDescriptors.h"
32 #include "arm_compute/core/Types.h"
33 #include "arm_compute/core/utils/misc/ShapeCalculator.h"
34 #include "arm_compute/runtime/CL/CLScheduler.h"
35 #include "arm_compute/runtime/CL/CLTuner.h"
36 #include "src/gpu/cl/kernels/ClGemmMatrixMultiplyReshapedOnlyRhsKernel.h"
37 #include "tests/CL/Helper.h"
38 #include "utils/Utils.h"
39 #include "utils/command_line/CommandLineOptions.h"
40 #include "utils/command_line/CommandLineParser.h"
41
42 #include <cstdlib>
43
44 using namespace arm_compute;
45 using namespace arm_compute::opencl::kernels;
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 h0{ 1 }; /**< Number of horizontal blocks of size (k0xn0) stored on the same output row */
59 bool interleave_rhs{ true }; /**< Interleave rhs matrix */
60 bool transpose_rhs{ true }; /**< Transpose rhs matrix */
61 bool export_to_cl_image_rhs{ true }; /**< Export rhs matrix to cl_image.*/
62 };
63
64 /** Formatted output of the GemmConfigs type
65 *
66 * @param[out] os Output stream.
67 * @param[in] configs Tunable configurations to output
68 *
69 * @return Modified output stream.
70 */
operator <<(::std::ostream & os,const GemmConfigs & configs)71 ::std::ostream &operator<<(::std::ostream &os, const GemmConfigs &configs)
72 {
73 std::string false_str = std::string("false");
74 std::string true_str = std::string("true");
75
76 os << "m0 : " << configs.m0 << std::endl;
77 os << "n0 : " << configs.n0 << std::endl;
78 os << "k0 : " << configs.k0 << std::endl;
79 os << "h0 : " << configs.h0 << std::endl;
80 os << "interleave_rhs : " << (configs.interleave_rhs ? true_str : false_str) << std::endl;
81 os << "transpose_rhs : " << (configs.transpose_rhs ? true_str : false_str) << std::endl;
82 os << "export_to_cl_image_rhs : " << (configs.export_to_cl_image_rhs ? true_str : false_str) << std::endl;
83 return os;
84 }
85
86 /** Command line options for gemm configs */
87 class GemmConfigOptions
88 {
89 public:
90 /** Constructor
91 *
92 * @param[in,out] parser A parser on which "parse()" hasn't been called yet.
93 */
GemmConfigOptions(CommandLineParser & parser)94 GemmConfigOptions(CommandLineParser &parser)
95 : m0(parser.add_positional_option<SimpleOption<size_t>>("m0", 4)),
96 n0(parser.add_positional_option<SimpleOption<size_t>>("n0", 4)),
97 k0(parser.add_positional_option<SimpleOption<size_t>>("k0", 4)),
98 h0(parser.add_positional_option<SimpleOption<size_t>>("h0", 1)),
99 interleave_rhs(parser.add_positional_option<SimpleOption<size_t>>("interleave_rhs", 1)),
100 transpose_rhs(parser.add_positional_option<SimpleOption<size_t>>("transpose_rhs", 1)),
101 export_to_cl_image_rhs(parser.add_positional_option<SimpleOption<size_t>>("export_to_cl_image_rhs", 1))
102 {
103 m0->set_help("Number of rows processed by the matrix multiplication");
104 n0->set_help("Number of columns processed by the matrix multiplication");
105 k0->set_help("Number of partial accumulations performed by the matrix multiplication");
106 h0->set_help("Number of horizontal blocks of size (k0xn0) stored on the same output row");
107 interleave_rhs->set_help("Interleave rhs matrix (1) / Do not interleave rhs matrix (0)");
108 transpose_rhs->set_help("Transpose rhs matrix (1) / Do not transpose rhs matrix (0)");
109 export_to_cl_image_rhs->set_help("Export rhs matrix to cl_image (1) / Do not export rhs matrix to cl_image (0)");
110 }
111 /** Prevent instances of this class from being copied (As this class contains pointers) */
112 GemmConfigOptions(const GemmConfigOptions &) = delete;
113 /** Prevent instances of this class from being copied (As this class contains pointers) */
114 GemmConfigOptions &operator=(const GemmConfigOptions &) = delete;
115 /** Allow instances of this class to be moved */
116 GemmConfigOptions(GemmConfigOptions &&) = default;
117 /** Allow instances of this class to be moved */
118 GemmConfigOptions &operator=(GemmConfigOptions &&) = default;
119 /** Default destructor */
120 ~GemmConfigOptions() = default;
121
122 SimpleOption<size_t> *m0; /**< Number of rows processed by the matrix multiplication option */
123 SimpleOption<size_t> *n0; /**< Number of columns processed by the matrix multiplication option */
124 SimpleOption<size_t> *k0; /**< Number of partial accumulations performed by the matrix multiplication option */
125 SimpleOption<size_t> *h0; /**< Number of horizontal blocks of size (k0xn0) stored on the same output row option */
126 SimpleOption<size_t> *interleave_rhs; /**< Interleave rhs matrix option (1 enable; 0 disable) */
127 SimpleOption<size_t> *transpose_rhs; /**< Transpose rhs matrix option (1 enable; 0 disable) */
128 SimpleOption<size_t> *export_to_cl_image_rhs; /**< Export rhs matrix to cl_image.*/
129 };
130
131 /** Consumes the gemm configuration options and creates a structure containing all information
132 *
133 * @param[in] options Options to consume
134 *
135 * @return Structure containing the gemm configurations
136 */
consume_gemm_configs(const GemmConfigOptions & options)137 GemmConfigs consume_gemm_configs(const GemmConfigOptions &options)
138 {
139 GemmConfigs configs;
140 configs.m0 = options.m0->value();
141 configs.n0 = options.n0->value();
142 configs.k0 = options.k0->value();
143 configs.h0 = options.h0->value();
144 configs.interleave_rhs = options.interleave_rhs->value() != 0;
145 configs.transpose_rhs = options.transpose_rhs->value() != 0;
146 configs.export_to_cl_image_rhs = options.export_to_cl_image_rhs->value() != 0;
147 return configs;
148 }
149
150 } // namespace
151 // Create function for ClGemmMatrixMultiplyReshapedOnlyRhsKernel
152 using CLGEMMMatrixMultiplyReshapedOnlyRHS = test::CLSynthetizeOperator<ClGemmMatrixMultiplyReshapedOnlyRhsKernel>;
153
154 class CLGEMMMatrixMultiplyReshapedOnlyRHSExample : public Example
155 {
156 public:
do_setup(int argc,char ** argv)157 bool do_setup(int argc, char **argv) override
158 {
159 // Default parameters
160 const float alpha = 1.0f;
161 const float beta = 0.0f;
162 const ActivationLayerInfo act_info = ActivationLayerInfo();
163 CommonGemmExampleParams params;
164 GemmConfigs configs;
165
166 // Set up command line parser and options
167 CommandLineParser parser;
168 CommonGemmExampleOptions param_options(parser);
169 GemmConfigOptions config_options(parser);
170
171 // Parse command line options
172 parser.parse(argc, argv);
173 if(param_options.help->is_set() && param_options.help->value())
174 {
175 // Print help message
176 parser.print_help(argv[0]);
177 return false;
178 }
179 if(!parser.validate())
180 {
181 // Invalid arguments. Use default parameters and configs
182 std::cerr << "Invalid arguments." << std::endl;
183 parser.print_help(argv[0]);
184 std::cerr << "Falling back to default parameters and configs" << std::endl;
185 }
186 else
187 {
188 // Get parameters and configs from command-line options
189 params = consume_common_gemm_example_parameters(param_options);
190 configs = consume_gemm_configs(config_options);
191 }
192
193 // Print gemm parameters and configurations
194 std::cout << "Gemm parameters:" << std::endl;
195 std::cout << params << std::endl;
196 std::cout << "Gemm configurations:" << std::endl;
197 std::cout << configs << std::endl;
198
199 tuner.set_tuner_mode(params.tuner_mode);
200
201 CLScheduler::get().default_init(&tuner);
202
203 lhs.allocator()->init(TensorInfo(TensorShape(params.K, params.M, params.B), 1, params.data_type));
204 rhs.allocator()->init(TensorInfo(TensorShape(params.N, params.K, params.B), 1, params.data_type));
205 bias.allocator()->init(TensorInfo(TensorShape(params.N, 1, params.B), 1, params.data_type));
206
207 GEMMLHSMatrixInfo lhs_info;
208 lhs_info.m0 = configs.m0;
209 lhs_info.k0 = configs.k0;
210
211 GEMMRHSMatrixInfo rhs_info;
212 rhs_info.n0 = configs.n0;
213 rhs_info.k0 = configs.k0;
214 rhs_info.h0 = configs.h0;
215 rhs_info.interleave = configs.interleave_rhs;
216 rhs_info.transpose = configs.transpose_rhs;
217 rhs_info.export_to_cl_image = configs.export_to_cl_image_rhs;
218
219 GEMMKernelInfo kernel_info;
220 kernel_info.m = params.M;
221 kernel_info.n = params.N;
222 kernel_info.k = params.K;
223 kernel_info.depth_output_gemm3d = 0;
224 kernel_info.reinterpret_input_as_3d = false;
225 kernel_info.broadcast_bias = true;
226 kernel_info.activation_info = act_info;
227
228 // Initialise rhs_reshaped tensor info
229 rhs_reshaped.allocator()->init(TensorInfo(compute_rhs_reshaped_shape(*rhs.info(), rhs_info), 1, params.data_type));
230
231 if(rhs_info.export_to_cl_image)
232 {
233 if(!examples::gemm_tuner_helpers::update_padding_for_cl_image(rhs_reshaped.info()))
234 {
235 std::cerr << "cl_image is not supported on the device, disable export_to_cl_image" << std::endl;
236 return false;
237 }
238 }
239
240 // Validate argments
241 Status status{};
242 status = gemm.validate(lhs.info(), rhs_reshaped.info(), bias.info(), dst.info(), alpha, beta, lhs_info, rhs_info, kernel_info);
243 if(!status)
244 {
245 // Unsupported arguments
246 std::cerr << "Unsupported arguments." << std::endl;
247 std::cerr << "Check documentation for supported/unsupported combinations" << std::endl;
248 return false;
249 }
250
251 // Configure function
252 gemm.configure(lhs.info(), rhs_reshaped.info(), bias.info(), dst.info(), alpha, beta, lhs_info, rhs_info, kernel_info);
253
254 // Allocate tensors
255 lhs.allocator()->allocate();
256 rhs.allocator()->allocate();
257 rhs_reshaped.allocator()->allocate();
258 bias.allocator()->allocate();
259 dst.allocator()->allocate();
260
261 return true;
262 }
do_run()263 void do_run() override
264 {
265 // Execute the function
266 ITensorPack gemm_pack({ { ACL_SRC_0, &lhs },
267 { ACL_SRC_1, &rhs_reshaped },
268 { ACL_SRC_2, &bias },
269 { ACL_DST, &dst }
270 });
271 gemm.run(gemm_pack);
272
273 // Make sure all the OpenCL jobs are done executing:
274 CLScheduler::get().sync();
275 }
276
do_teardown()277 void do_teardown() override
278 {
279 }
280
281 private:
282 CLTensor lhs{};
283 CLTensor rhs{};
284 CLTensor rhs_reshaped{};
285 CLTensor bias{};
286 CLTensor dst{};
287 CLTuner tuner{};
288 CLGEMMMatrixMultiplyReshapedOnlyRHS gemm{};
289 };
290
291 /** Main program for gemm reshaped rhs only test
292 *
293 * @param[in] argc Number of arguments
294 * @param[in] argv Arguments ( [optional] M, [optional] N, [optional] K, [optional] B, [optional] m0, [optional] n0, [optional] k0, [optional] h0, [optional] interleave_rhs, [optional] transpose_rhs, [optional] export_to_cl_image)
295 */
main(int argc,char ** argv)296 int main(int argc, char **argv)
297 {
298 return run_example<CLGEMMMatrixMultiplyReshapedOnlyRHSExample>(argc, argv);
299 }
300