blob: 0e0917daa98a68a03d33e1f0cec83564545992bb [file] [log] [blame]
SiCongLi282f3242020-11-24 15:24:16 +00001/*
Manuel Bottini7b427862021-02-08 13:45:19 +00002 * Copyright (c) 2020-2021 Arm Limited.
SiCongLi282f3242020-11-24 15:24:16 +00003 *
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/KernelDescriptors.h"
33#include "arm_compute/core/Types.h"
34#include "arm_compute/core/utils/misc/ShapeCalculator.h"
35#include "arm_compute/core/utils/quantization/AsymmHelpers.h"
36#include "arm_compute/runtime/CL/CLScheduler.h"
37#include "arm_compute/runtime/CL/CLTuner.h"
Georgios Pinitas7891a732021-08-20 21:39:25 +010038#include "src/gpu/cl/kernels/ClGemmLowpMatrixMultiplyReshapedOnlyRhsKernel.h"
39#include "src/gpu/cl/kernels/ClGemmLowpReductionKernel.h"
SiCongLi282f3242020-11-24 15:24:16 +000040#include "tests/CL/Helper.h"
41#include "utils/Utils.h"
42#include "utils/command_line/CommandLineOptions.h"
43#include "utils/command_line/CommandLineParser.h"
44
45#include <cstdlib>
46#include <memory>
47
48using namespace arm_compute;
49using namespace utils;
Georgios Pinitas4a578b92021-06-25 12:13:49 +010050using namespace arm_compute::opencl::kernels;
SiCongLi282f3242020-11-24 15:24:16 +000051using namespace arm_compute::misc::shape_calculator;
52using namespace gemm_tuner;
53
54namespace
55{
56/** Structure holding all tunable gemm configs specific to this example/strategy */
57struct GemmConfigs
58{
59 size_t m0{ 4 }; /**< Number of rows processed by the matrix multiplication */
60 size_t n0{ 4 }; /**< Number of columns processed by the matrix multiplication */
61 size_t k0{ 4 }; /**< Number of partial accumulations performed by the matrix multiplication */
62 size_t h0{ 1 }; /**< Number of horizontal blocks of size (k0xn0) stored on the same output row */
63 bool interleave_rhs{ true }; /**< Interleave rhs matrix */
64 bool transpose_rhs{ true }; /**< Transpose rhs matrix */
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 */
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 << "h0 : " << configs.h0 << std::endl;
83 os << "interleave_rhs : " << (configs.interleave_rhs ? true_str : false_str) << std::endl;
84 os << "transpose_rhs : " << (configs.transpose_rhs ? true_str : false_str) << std::endl;
85 return os;
86}
87
88/** Command line options for gemm configs */
89class GemmConfigOptions
90{
91public:
92 /** Constructor
93 *
94 * @param[in,out] parser A parser on which "parse()" hasn't been called yet.
95 */
96 GemmConfigOptions(CommandLineParser &parser)
97 : m0(parser.add_positional_option<SimpleOption<size_t>>("m0", 4)),
98 n0(parser.add_positional_option<SimpleOption<size_t>>("n0", 4)),
99 k0(parser.add_positional_option<SimpleOption<size_t>>("k0", 4)),
100 h0(parser.add_positional_option<SimpleOption<size_t>>("h0", 1)),
101 interleave_rhs(parser.add_positional_option<SimpleOption<size_t>>("interleave_rhs", 1)),
102 transpose_rhs(parser.add_positional_option<SimpleOption<size_t>>("transpose_rhs", 1))
103 {
104 m0->set_help("Number of rows processed by the matrix multiplication");
105 n0->set_help("Number of columns processed by the matrix multiplication");
106 k0->set_help("Number of partial accumulations performed by the matrix multiplication");
107 h0->set_help("Number of horizontal blocks of size (k0xn0) stored on the same output row");
108 interleave_rhs->set_help("Interleave rhs matrix (1) / Do not interleave rhs matrix (0)");
109 transpose_rhs->set_help("Transpose rhs matrix (1) / Do not transpose rhs matrix (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};
129
130/** Consumes the gemm configuration options and creates a structure containing all information
131 *
132 * @param[in] options Options to consume
133 *
134 * @return Structure containing the gemm configurations
135 */
136GemmConfigs consume_gemm_configs(const GemmConfigOptions &options)
137{
138 GemmConfigs configs;
139 configs.m0 = options.m0->value();
140 configs.n0 = options.n0->value();
141 configs.k0 = options.k0->value();
142 configs.h0 = options.h0->value();
143 configs.interleave_rhs = options.interleave_rhs->value() != 0;
144 configs.transpose_rhs = options.transpose_rhs->value() != 0;
145 return configs;
146}
147
148} // namespace
149
Georgios Pinitas4a578b92021-06-25 12:13:49 +0100150using ClGemmLowpMatrixMultiplyReshapedOnlyRhs = test::CLSynthetizeOperator<ClGemmLowpMatrixMultiplyReshapedOnlyRhsKernel>;
151using ClGemmLowpMatrixAReduction = test::CLSynthetizeOperator<ClGemmLowpMatrixAReductionKernel>;
SiCongLi282f3242020-11-24 15:24:16 +0000152
153class CLGEMMLowpMatrixMultiplyReshapedOnlyRHSFusedOutputStageFixedpointExample : public Example
154{
155public:
156 bool do_setup(int argc, char **argv) override
157 {
158 // Default parameters
159 CommonGemmExampleParams params;
160 GemmConfigs configs;
161
162 // Parse command line options
163 CommandLineParser parser;
SiCong Li98e33b92020-12-03 14:52:53 +0000164 CommonGemmExampleOptions param_options(parser, DataType::QASYMM8);
SiCongLi282f3242020-11-24 15:24:16 +0000165 GemmConfigOptions config_options(parser);
166
167 parser.parse(argc, argv);
168 if(param_options.help->is_set() && param_options.help->value())
169 {
170 parser.print_help(argv[0]);
171 return false;
172 }
173 if(!parser.validate())
174 {
175 // Invalid arguments. Use default parameters and configs
176 std::cerr << "Invalid arguments." << std::endl;
177 parser.print_help(argv[0]);
178 std::cerr << "Falling back to default parameters and configs" << std::endl;
179 }
180 else
181 {
182 params = consume_common_gemm_example_parameters(param_options);
183 configs = consume_gemm_configs(config_options);
184 }
185
186 std::cout << "Gemm parameters:" << std::endl;
187 std::cout << params << std::endl;
188 std::cout << "Gemm configurations:" << std::endl;
189 std::cout << configs << std::endl;
190
Gian Marco Iodiceca419dd2021-03-03 17:25:07 +0000191 tuner.set_tuner_mode(params.tuner_mode);
192
SiCongLi282f3242020-11-24 15:24:16 +0000193 CLScheduler::get().default_init(&tuner);
194
195 lhs.allocator()->init(TensorInfo(TensorShape(params.K, params.M, params.B), 1, params.data_type));
196 rhs.allocator()->init(TensorInfo(TensorShape(params.N, params.K, params.B), 1, params.data_type));
SiCongLieda87d42021-03-04 10:27:03 +0000197 bias.allocator()->init(TensorInfo(TensorShape(params.N), 1, DataType::S32));
SiCongLi282f3242020-11-24 15:24:16 +0000198 dst.allocator()->init(TensorInfo(TensorShape(params.N, params.M, params.B), 1, params.data_type));
199
200 // Set arbitrary quantization information (non-zero offset to ensure offset contribution stage is included)
201 // Could be extended in the future to include a user-controlled option for offset == 0
SiCong Li98e33b92020-12-03 14:52:53 +0000202 const QuantizationInfo q_info
203 {
204 0.012, 3
205 };
206 lhs.info()->set_quantization_info(q_info);
207 rhs.info()->set_quantization_info(q_info);
208 bias.info()->set_quantization_info(q_info);
209 dst.info()->set_quantization_info(q_info);
SiCongLi282f3242020-11-24 15:24:16 +0000210
211 GEMMLHSMatrixInfo lhs_info;
212 lhs_info.m0 = configs.m0;
213 lhs_info.k0 = configs.k0;
214
215 GEMMRHSMatrixInfo rhs_info;
216 rhs_info.n0 = configs.n0;
217 rhs_info.k0 = configs.k0;
218 rhs_info.h0 = configs.h0;
219 rhs_info.interleave = configs.interleave_rhs;
220 rhs_info.transpose = configs.transpose_rhs;
221 rhs_info.export_to_cl_image = false; // CL image not supported for quantized cases yet
222
223 rhs_reshaped.allocator()->init(TensorInfo(compute_rhs_reshaped_shape(*rhs.info(), rhs_info), 1, params.data_type));
SiCong Li98e33b92020-12-03 14:52:53 +0000224 rhs_reshaped.info()->set_quantization_info(q_info);
SiCongLi282f3242020-11-24 15:24:16 +0000225 if(rhs_info.export_to_cl_image)
226 {
Manuel Bottini7b427862021-02-08 13:45:19 +0000227 if(!examples::gemm_tuner_helpers::update_padding_for_cl_image(rhs_reshaped.info()))
228 {
229 std::cerr << "cl_image is not supported on the device, disable export_to_cl_image" << std::endl;
230 return false;
231 }
SiCongLi282f3242020-11-24 15:24:16 +0000232 }
233
234 // Configure output stage for quantized case
235 GEMMLowpOutputStageInfo gemmlowp_output_stage;
236 gemmlowp_output_stage.type = GEMMLowpOutputStageType::QUANTIZE_DOWN_FIXEDPOINT;
237 gemmlowp_output_stage.output_data_type = dst.info()->data_type();
238 gemmlowp_output_stage.gemmlowp_offset = 0;
239 {
SiCongLi282f3242020-11-24 15:24:16 +0000240 gemmlowp_output_stage.is_quantized_per_channel = false;
241 // Num_filters is 1 unless quantized type is of per_channel type. Could be extended in the future to support per-channel quantization.
242 const unsigned int num_filters = 1;
243
244 dst_multipliers.allocator()->init(TensorInfo(TensorShape(num_filters), 1, DataType::S32));
245 dst_shifts.allocator()->init(TensorInfo(TensorShape(num_filters), 1, DataType::S32));
246
247 gemmlowp_output_stage.gemmlowp_multipliers.resize(num_filters);
248 gemmlowp_output_stage.gemmlowp_shifts.resize(num_filters);
249 quantization::compute_quantized_multipliers_and_shifts(lhs.info(),
250 rhs.info(),
251 dst.info(),
SiCongLi282f3242020-11-24 15:24:16 +0000252 gemmlowp_output_stage.gemmlowp_multipliers.data(),
253 gemmlowp_output_stage.gemmlowp_shifts.data());
254 gemmlowp_output_stage.gemmlowp_multiplier = gemmlowp_output_stage.gemmlowp_multipliers[0];
255 gemmlowp_output_stage.gemmlowp_shift = gemmlowp_output_stage.gemmlowp_shifts[0];
256
257 // No fused activation
258 PixelValue min_val{};
259 PixelValue max_val{};
260 std::tie(min_val, max_val) = get_min_max(dst.info()->data_type());
261
262 auto min_activation = min_val.get<int32_t>();
263 auto max_activation = max_val.get<int32_t>();
264
265 // Set the GEMMLowp output stage info
266 gemmlowp_output_stage.gemmlowp_offset = dst.info()->quantization_info().uniform().offset;
267 gemmlowp_output_stage.gemmlowp_min_bound = min_activation;
268 gemmlowp_output_stage.gemmlowp_max_bound = max_activation;
269 }
270
271 GEMMKernelInfo gemm_info;
272 gemm_info.m = params.M;
273 gemm_info.n = params.N;
274 gemm_info.k = params.K;
275 gemm_info.depth_output_gemm3d = 0;
276 gemm_info.reinterpret_input_as_3d = false;
277 gemm_info.broadcast_bias = true;
278 gemm_info.fp_mixed_precision = false;
279 gemm_info.has_pad_y = false;
280 gemm_info.mult_transpose1xW_width = configs.h0;
281 gemm_info.lhs_info = lhs_info;
282 gemm_info.rhs_info = rhs_info;
283 gemm_info.a_offset = lhs.info()->quantization_info().uniform().offset;
284 gemm_info.b_offset = rhs.info()->quantization_info().uniform().offset;
285 gemm_info.output_stage = gemmlowp_output_stage;
286
287 // Initialize Matrix A reduction kernel only if _b_offset is not equal to 0
288 if(gemm_info.b_offset != 0)
289 {
290 const TensorInfo info_vector_sum_row(compute_reductionB_shape(*lhs.info()), 1, DataType::S32);
291 vector_sum_row.allocator()->init(info_vector_sum_row);
292
Georgios Pinitas4a578b92021-06-25 12:13:49 +0100293 mtx_a_reduction = std::make_unique<ClGemmLowpMatrixAReduction>();
SiCongLi282f3242020-11-24 15:24:16 +0000294
295 if(!mtx_a_reduction->validate(lhs.info(), vector_sum_row.info(), GEMMLowpReductionKernelInfo{}))
296 {
297 std::cerr << "Invalid arguments for CLGEMMLowpMatrixAReductionKernel." << std::endl;
298 return false;
299 }
300
Georgios Pinitas4a578b92021-06-25 12:13:49 +0100301 mtx_a_reduction->configure(lhs.info(), vector_sum_row.info(), GEMMLowpReductionKernelInfo{});
SiCongLi282f3242020-11-24 15:24:16 +0000302 }
303 // Initialize matrix B reduction kernel only if _a_offset is not equal to 0
304 if(gemm_info.a_offset != 0)
305 {
306 const TensorInfo info_vector_sum_col(compute_reductionA_shape(*rhs.info()), 1, DataType::S32);
307 vector_sum_col.allocator()->init(info_vector_sum_col);
308 // There's no need for a Matrix B reduction kernel as this is assumed to be run only once in the prepare stage
309 }
310
311 // Validate argments
312 if(!gemm.validate(lhs.info(), rhs_reshaped.info(), dst.info(), gemm_info, gemm_info.a_offset == 0 ? nullptr : vector_sum_col.info(),
313 gemm_info.b_offset == 0 ? nullptr : vector_sum_row.info(), bias.info(), dst_multipliers.info(), dst_shifts.info()))
314 {
Georgios Pinitas4a578b92021-06-25 12:13:49 +0100315 std::cerr << "Invalid arguments for ClGemmLowpMatrixMultiplyReshapedOnlyRhsKernel." << std::endl;
SiCongLi282f3242020-11-24 15:24:16 +0000316 return false;
317 }
318
319 // Configure function
Georgios Pinitas4a578b92021-06-25 12:13:49 +0100320 gemm.configure(lhs.info(), rhs_reshaped.info(), dst.info(), gemm_info,
321 gemm_info.a_offset == 0 ? nullptr : vector_sum_col.info(), gemm_info.b_offset == 0 ? nullptr : vector_sum_row.info(),
322 bias.info(), dst_multipliers.info(), dst_shifts.info());
SiCongLi282f3242020-11-24 15:24:16 +0000323
324 // Allocate tensors
325 lhs.allocator()->allocate();
326 rhs.allocator()->allocate();
327 rhs_reshaped.allocator()->allocate();
328 bias.allocator()->allocate();
329 dst.allocator()->allocate();
330 vector_sum_col.allocator()->allocate();
331 vector_sum_row.allocator()->allocate();
332 dst_multipliers.allocator()->allocate();
333 dst_shifts.allocator()->allocate();
334
335 return true;
336 }
337 void do_run() override
338 {
339 if(mtx_a_reduction != nullptr)
340 {
Georgios Pinitas4a578b92021-06-25 12:13:49 +0100341 ITensorPack red_pack({ { ACL_SRC, &lhs }, { ACL_DST, &dst } });
342 mtx_a_reduction->run(red_pack);
SiCongLi282f3242020-11-24 15:24:16 +0000343 }
Georgios Pinitas4a578b92021-06-25 12:13:49 +0100344
345 ITensorPack gemm_pack({ { ACL_SRC_0, &lhs }, { ACL_SRC_1, &rhs }, { ACL_BIAS, &bias }, { ACL_VEC_COL_SUM, &vector_sum_col }, { ACL_VEC_ROW_SUM, &vector_sum_row }, { ACL_SHIFTS, &dst_shifts }, { ACL_MULTIPLIERS, &dst_multipliers }, { ACL_DST, &dst } });
346 gemm.run(gemm_pack);
SiCongLi282f3242020-11-24 15:24:16 +0000347
348 // Make sure all the OpenCL jobs are done executing:
349 CLScheduler::get().sync();
350 }
351
352 void do_teardown() override
353 {
354 }
355
356private:
357 CLTensor lhs{};
358 CLTensor rhs{};
359 CLTensor rhs_reshaped{};
360 CLTensor bias{};
361 CLTensor dst{};
362 CLTensor vector_sum_col{};
363 CLTensor vector_sum_row{};
364 CLTensor dst_multipliers{};
365 CLTensor dst_shifts{};
366 CLTuner tuner{};
Georgios Pinitas4a578b92021-06-25 12:13:49 +0100367 ClGemmLowpMatrixMultiplyReshapedOnlyRhs gemm{};
368 std::unique_ptr<ClGemmLowpMatrixAReduction> mtx_a_reduction{ nullptr };
SiCongLi282f3242020-11-24 15:24:16 +0000369};
370
371/** Main test program for gemmlowp reshaped rhs only with fused output stage fixedpoint
372 *
373 * @param[in] argc Number of arguments
374 * @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 )
375 */
376int main(int argc, char **argv)
377{
378 return run_example<CLGEMMLowpMatrixMultiplyReshapedOnlyRHSFusedOutputStageFixedpointExample>(argc, argv);
379}