blob: f914bceec3cb3f5897844805d7451739a775685e [file] [log] [blame]
Michele Di Giorgio4dfc5532021-06-30 12:05:34 +01001/*
Jonathan Deakin464ed202023-01-12 11:41:14 +00002 * Copyright (c) 2021-2023 Arm Limited.
Michele Di Giorgio4dfc5532021-06-30 12:05:34 +01003 *
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 */
Georgios Pinitas7891a732021-08-20 21:39:25 +010024#include "src/cpu/operators/CpuGemm.h"
Michele Di Giorgio4dfc5532021-06-30 12:05:34 +010025
26#include "arm_compute/core/TensorInfo.h"
27#include "arm_compute/core/Validate.h"
28#include "arm_compute/core/utils/misc/ShapeCalculator.h"
29#include "arm_compute/runtime/NEON/NEScheduler.h"
ramelg013ae3d882021-09-12 23:07:47 +010030#include "src/common/utils/Log.h"
Michele Di Giorgio4dfc5532021-06-30 12:05:34 +010031#include "src/core/CPP/Validate.h"
32#include "src/core/helpers/AutoConfiguration.h"
33#include "src/core/helpers/MemoryHelpers.h"
Georgios Pinitas7891a732021-08-20 21:39:25 +010034#include "src/cpu/utils/CpuAuxTensorHandler.h"
Michele Di Giorgio4dfc5532021-06-30 12:05:34 +010035
36using namespace arm_compute::experimental;
37using namespace arm_compute::misc::shape_calculator;
38
39namespace arm_compute
40{
41namespace cpu
42{
43namespace
44{
45cpu::AsmGemmInfo init_assembly_metadata(const GEMMInfo &info)
46{
47 cpu::AsmGemmInfo asm_info;
48 asm_info.method = cpu::AsmConvMethod::Im2Col;
49 asm_info.reinterpret_input_as_3d = info.reinterpret_input_as_3d();
50 asm_info.depth_output_gemm3d = info.depth_output_gemm3d();
51 asm_info.activation_info = info.activation_info();
Georgios Pinitas4ee8b152021-07-16 16:16:43 +010052 asm_info.fast_mode = info.fast_math();
Francesco.Petrogalli@arm.com5fcf22d2022-04-05 10:31:08 +000053 asm_info.fixed_format = info.fixed_format();
Francesco Petrogalli553f6952022-06-30 10:22:01 +000054 asm_info.weight_format = info.weight_format();
Michele Di Giorgio4dfc5532021-06-30 12:05:34 +010055
56 return asm_info;
57}
58} // namespace
59
60void CpuGemm::configure(const ITensorInfo *a, const ITensorInfo *b, const ITensorInfo *c, ITensorInfo *d, float alpha, float beta, const GEMMInfo &gemm_info)
61{
62 ARM_COMPUTE_ERROR_ON_NULLPTR(a, b, d);
63 ARM_COMPUTE_ERROR_THROW_ON(CpuGemm::validate(a, b, c, d, alpha, beta, gemm_info));
ramelg013ae3d882021-09-12 23:07:47 +010064 ARM_COMPUTE_LOG_PARAMS(a, b, c, d, alpha, beta, gemm_info);
Michele Di Giorgio4dfc5532021-06-30 12:05:34 +010065
66 const cpu::AsmGemmInfo asm_info = init_assembly_metadata(gemm_info);
Viet-Hoa Doa3e57c22023-03-13 16:20:04 +000067 const bool is_c_bias = beta == 1 && c != nullptr;
Adnan AlSinan26c9d1a2022-09-07 13:54:53 +010068 bool run_optimised = bool(cpu::CpuGemmAssemblyDispatch::validate(a, b, (is_c_bias) ? c : nullptr, d, asm_info)) && gemm_info.reshape_b_only_on_first_run();
Michele Di Giorgio4dfc5532021-06-30 12:05:34 +010069
70 // Check if we need to reshape the matrix B only on the first run
71 _is_prepared = false;
72 _reshape_b_only_on_first_run = gemm_info.reshape_b_only_on_first_run();
73 _run_vector_matrix_multiplication = a->dimension(1) < 2;
74 _run_alpha_scale = alpha != 1.f;
Viet-Hoa Doa3e57c22023-03-13 16:20:04 +000075 _run_bias_addition = is_c_bias;
76 _run_addition = beta != 0 && beta != 1 && c != nullptr;
Francesco.Petrogalli@arm.com5fcf22d2022-04-05 10:31:08 +000077 _run_activation = gemm_info.activation_info().enabled() && (!run_optimised || (run_optimised && !cpu::CpuGemmAssemblyDispatch::is_activation_supported(gemm_info.activation_info())));
Michele Di Giorgio4dfc5532021-06-30 12:05:34 +010078
79 if(run_optimised)
80 {
81 const ITensorInfo *c_to_use = is_c_bias ? c : nullptr;
82 _asm_glue = std::make_unique<cpu::CpuGemmAssemblyDispatch>();
83 _asm_glue->configure(a, b, c_to_use, d, asm_info);
84 ARM_COMPUTE_ERROR_ON(!_asm_glue->is_configured());
85
86 auto asm_mem_req = _asm_glue->workspace();
87 _aux_mem[AsmGemmWorkspace] = asm_mem_req[AsmGemmWorkspace];
88 _aux_mem[Pretraspose] = asm_mem_req[Pretraspose];
89
90 // Scale product by alpha
91 if(_run_alpha_scale)
92 {
93 _alpha_scale_func = std::make_unique<cpu::CpuActivation>();
94 _alpha_scale_func->configure(d, nullptr, ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::LINEAR, alpha, 0.f));
95 }
96 }
97 else
98 {
99 // Pick output tensor in case bias addition should be performed
100 ITensorInfo *gemm_output_to_use = (_run_bias_addition) ? &_tmp_d : d;
101
102 _mm_kernel = std::make_unique<cpu::kernels::CpuGemmMatrixMultiplyKernel>();
103
104 // Select between GEMV and GEMM
105 if(_run_vector_matrix_multiplication)
106 {
107 // Configure the matrix multiply kernel
108 _mm_kernel->configure(a, b, gemm_output_to_use, alpha, false);
109 }
110 else
111 {
112 const int m = a->dimension(1);
113 const int n = b->dimension(0);
114 const int k = a->dimension(0);
115
116 // Configure interleave kernel
117 _interleave_kernel = std::make_unique<cpu::kernels::CpuGemmInterleave4x4Kernel>();
118 _interleave_kernel->configure(a, &_tmp_a);
119 _aux_mem[InterleavedLHS] = MemoryInfo(offset_int_vec(InterleavedLHS), MemoryLifetime::Temporary, _tmp_a.total_size());
120
121 // Configure transpose kernel
122 _transpose_kernel = std::make_unique<cpu::kernels::CpuGemmTranspose1xWKernel>();
123 _transpose_kernel->configure(b, &_tmp_b);
124 _aux_mem[TransposedRHS] = MemoryInfo(offset_int_vec(TransposedRHS), MemoryLifetime::Persistent, _tmp_b.total_size());
125
126 // Configure matrix multiplication kernel
127 _mm_kernel->configure(&_tmp_a, &_tmp_b, gemm_output_to_use, alpha, true, GEMMReshapeInfo(m, n, k));
128 }
129
130 if(_run_bias_addition)
131 {
132 _add_bias = std::make_unique<cpu::CpuAdd>();
133 _add_bias->configure(gemm_output_to_use, c, d, ConvertPolicy::SATURATE);
Michele Di Giorgiod9cdf142021-07-02 15:17:08 +0100134 _aux_mem[TempResult] = MemoryInfo(offset_int_vec(TempResult), MemoryLifetime::Temporary, _tmp_d.total_size());
Michele Di Giorgio4dfc5532021-06-30 12:05:34 +0100135 }
136 }
137
138 // Configure matrix addition kernel
139 if(_run_addition)
140 {
141 _ma_kernel = std::make_unique<cpu::kernels::CpuGemmMatrixAdditionKernel>();
142 _ma_kernel->configure(c, d, beta);
143 }
144
145 // Configure activation
146 if(_run_activation)
147 {
148 _activation_func = std::make_unique<cpu::CpuActivation>();
149 _activation_func->configure(d, nullptr, gemm_info.activation_info());
150 }
151}
152
153Status CpuGemm::validate(const ITensorInfo *a, const ITensorInfo *b, const ITensorInfo *c, const ITensorInfo *d, float alpha, float beta, const GEMMInfo &gemm_info)
154{
155 ARM_COMPUTE_UNUSED(alpha);
Viet-Hoa Doa3e57c22023-03-13 16:20:04 +0000156 const bool is_c_bias = beta == 1 && c != nullptr;
157 const bool run_addition = c != nullptr && beta != 0 && beta != 1;
Michele Di Giorgio4dfc5532021-06-30 12:05:34 +0100158
159 ARM_COMPUTE_RETURN_ERROR_ON_CPU_F16_UNSUPPORTED(a);
160 ARM_COMPUTE_RETURN_ERROR_ON_CPU_BF16_UNSUPPORTED(a);
161 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(a, 1, DataType::BFLOAT16, DataType::F16, DataType::F32);
Viet-Hoa Doa3e57c22023-03-13 16:20:04 +0000162
Jonathan Deakin464ed202023-01-12 11:41:14 +0000163 if (is_fixed_format_fast_math(gemm_info.weight_format()))
164 {
165 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_NOT_IN(a, DataType::F32);
166 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_NOT_IN(b, DataType::BFLOAT16);
167 }
168 else
169 {
170 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(a, b);
171 }
172
Michele Di Giorgio4dfc5532021-06-30 12:05:34 +0100173 ARM_COMPUTE_RETURN_ERROR_ON_MSG(a->dimension(0) != b->dimension(1), "The product AB is defined only if the number of columns in A is equal to the number of rows in B");
174 ARM_COMPUTE_RETURN_ERROR_ON_MSG(gemm_info.is_a_reshaped(), "Matrix A already reshaped is not supported");
175 ARM_COMPUTE_RETURN_ERROR_ON_MSG(gemm_info.is_b_reshaped(), "Matrix B already reshaped is not supported");
176 if(a->data_type() != DataType::BFLOAT16)
177 {
178 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(a, d);
179 }
180
Viet-Hoa Doa3e57c22023-03-13 16:20:04 +0000181 if(run_addition)
Michele Di Giorgio4dfc5532021-06-30 12:05:34 +0100182 {
183 ARM_COMPUTE_RETURN_ERROR_ON(gemm_info.depth_output_gemm3d() != 0);
184 ARM_COMPUTE_RETURN_ERROR_ON(gemm_info.reinterpret_input_as_3d());
185 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(c, d);
186 ARM_COMPUTE_RETURN_ERROR_ON_MSG(a->dimension(1) != c->dimension(1), "The C matrix must have the same number of rows as the matrix A");
187 ARM_COMPUTE_RETURN_ERROR_ON_MSG(b->dimension(0) != c->dimension(0), "The C matrix must have the same number of columns as the matrix B");
188 }
189
190 if(d->total_size() != 0)
191 {
Francesco Petrogalli553f6952022-06-30 10:22:01 +0000192 // For fixed format we are expecting some kind of blocked format for B/RHS so the dimension won't necessarily match the result matrix any more.
193 ARM_COMPUTE_RETURN_ERROR_ON(!gemm_info.fixed_format() && b->dimension(0) != d->dimension(0));
Michele Di Giorgio4dfc5532021-06-30 12:05:34 +0100194 if(gemm_info.depth_output_gemm3d() != 0)
195 {
196 if(gemm_info.reinterpret_input_as_3d())
197 {
198 ARM_COMPUTE_RETURN_ERROR_ON(a->dimension(1) != d->dimension(1));
199 ARM_COMPUTE_RETURN_ERROR_ON(a->dimension(2) != d->dimension(2));
200 }
201 else
202 {
203 ARM_COMPUTE_RETURN_ERROR_ON(a->dimension(1) != d->dimension(1) * d->dimension(2));
204 }
205 }
206 else
207 {
208 ARM_COMPUTE_RETURN_ERROR_ON(a->dimension(1) != d->dimension(1));
209 }
210 }
211
212 // Check if we need to run the optimized assembly kernel
213 cpu::AsmGemmInfo asm_info = init_assembly_metadata(gemm_info);
214 const bool run_optimised = bool(cpu::CpuGemmAssemblyDispatch::validate(a, b, is_c_bias ? c : nullptr, d, asm_info));
215
216 if(!run_optimised)
217 {
218 ARM_COMPUTE_RETURN_ERROR_ON_MSG(gemm_info.reinterpret_input_as_3d(), "CpuGemm cannot reinterpret the input tensor as 3D");
219 ARM_COMPUTE_RETURN_ERROR_ON_MSG(gemm_info.depth_output_gemm3d() != 0, "CpuGemm cannot reinterpret the output tensor as 3D");
220
221 // Check if the first input tensor is a vector.
222 const bool run_vector_matrix_multiplication = a->dimension(1) < 2;
223 // Check if we need to reshape the matrix A and matrix B
224 const bool run_interleave_transpose = !run_vector_matrix_multiplication && !(gemm_info.reshape_b_only_on_first_run());
225
226 // Arguments used by GEMMReshapeInfo
227 // If we pass the matrix A and matrix B reshaped to CpuGemmMatrixMultiplyKernel, we need to pass m, n, k, mult_transpose1xW_width and mult_interleave4x4_height to GEMMReshapeInfo
228 // in order to know how the matrices have been reshaped
229 const int m = a->dimension(1);
230 const int n = b->dimension(0);
231 const int k = a->dimension(0);
232 int mult_transpose1xW_width = 1;
233 int mult_interleave4x4_height = 1;
234
235 const GEMMReshapeInfo reshape_info = GEMMReshapeInfo(m, n, k, mult_transpose1xW_width, mult_interleave4x4_height, gemm_info.depth_output_gemm3d());
236
237 const ITensorInfo *matrix_a_info = a;
238 const ITensorInfo *matrix_b_info = b;
239
240 TensorInfo tmp_a_info{};
241 TensorInfo tmp_b_info{};
242 TensorInfo tmp_output_info = *d->clone();
243
244 if(run_interleave_transpose)
245 {
246 matrix_a_info = &tmp_a_info;
247 matrix_b_info = &tmp_b_info;
248
249 // Validate interleave kernel
250 auto_init_if_empty(tmp_a_info, a->clone()->set_tensor_shape(compute_interleaved_shape(*a, mult_interleave4x4_height, gemm_info.reinterpret_input_as_3d())));
251 ARM_COMPUTE_RETURN_ON_ERROR(cpu::kernels::CpuGemmInterleave4x4Kernel::validate(a, &tmp_a_info));
252
253 // Validate transpose kernel
254 auto_init_if_empty(tmp_b_info, b->clone()->set_tensor_shape(compute_transpose1xW_with_element_size_shape(*b, mult_transpose1xW_width)));
255 ARM_COMPUTE_RETURN_ON_ERROR(cpu::kernels::CpuGemmTranspose1xWKernel::validate(b, &tmp_b_info));
256 }
257
258 // Validate matrix multiply
259 auto_init_if_empty(tmp_output_info, matrix_a_info->clone()->set_tensor_shape(compute_mm_shape(*matrix_a_info, *matrix_b_info, run_interleave_transpose, reshape_info)));
260 ARM_COMPUTE_RETURN_ON_ERROR(cpu::kernels::CpuGemmMatrixMultiplyKernel::validate(matrix_a_info, matrix_b_info, &tmp_output_info, alpha, run_interleave_transpose, reshape_info));
261
262 if(c != nullptr && gemm_info.reshape_b_only_on_first_run())
263 {
264 ARM_COMPUTE_RETURN_ON_ERROR(cpu::CpuAdd::validate(&tmp_output_info, c, d, ConvertPolicy::SATURATE));
265 }
266 }
267
268 // Validate matrix addition kernel
Viet-Hoa Doa3e57c22023-03-13 16:20:04 +0000269 if(run_addition)
Michele Di Giorgio4dfc5532021-06-30 12:05:34 +0100270 {
271 ARM_COMPUTE_RETURN_ON_ERROR(cpu::kernels::CpuGemmMatrixAdditionKernel::validate(c, d, beta));
272 }
273
274 // Validate activation
275 const ActivationLayerInfo &activation = gemm_info.activation_info();
276 if(activation.enabled())
277 {
278 ARM_COMPUTE_RETURN_ON_ERROR(cpu::CpuActivation::validate(d, nullptr, activation));
279 }
280
281 return Status{};
282}
283
284void CpuGemm::run(ITensorPack &tensors)
285{
286 prepare(tensors);
287
288 auto a = tensors.get_const_tensor(ACL_SRC_0);
289 auto b = tensors.get_const_tensor(ACL_SRC_1);
290 auto c = tensors.get_const_tensor(ACL_SRC_2);
291 auto d = tensors.get_tensor(ACL_DST);
292
Francesco Petrogalli553f6952022-06-30 10:22:01 +0000293 if(_asm_glue && _asm_glue->is_configured())
Michele Di Giorgio4dfc5532021-06-30 12:05:34 +0100294 {
295 // Pass c to asm dispatch only if it's the bias tensor
296 ITensorPack asm_pack = tensors;
297 asm_pack.add_const_tensor(ACL_SRC_2, (_reshape_b_only_on_first_run) ? c : nullptr);
298 _asm_glue->run(asm_pack);
299 if(_run_alpha_scale)
300 {
301 ITensorPack pack{ { ACL_SRC, d }, { ACL_DST, d } };
302 _alpha_scale_func->run(pack);
303 }
304 }
305 else
306 {
307 CpuAuxTensorHandler interleaved_a(offset_int_vec(InterleavedLHS), _tmp_a, tensors, true);
308 CpuAuxTensorHandler transposed_b(offset_int_vec(TransposedRHS), _tmp_b, tensors, true);
309 CpuAuxTensorHandler temp_d(offset_int_vec(TempResult), _tmp_d, tensors, true);
310
311 ITensorPack mm_pack{ { ACL_SRC_0, a }, { ACL_SRC_1, b }, { ACL_DST, (_run_bias_addition) ? temp_d.get() : d } };
312 if(!_run_vector_matrix_multiplication)
313 {
314 // Run interleave kernel
315 ITensorPack interleave_pack{ { ACL_SRC, a }, { ACL_DST, interleaved_a.get() } };
316 NEScheduler::get().schedule_op(_interleave_kernel.get(), Window::DimY, _interleave_kernel->window(), interleave_pack);
317
318 if(!_reshape_b_only_on_first_run)
319 {
320 // Run transpose kernel
321 ITensorPack transpose_pack{ { ACL_SRC, b }, { ACL_DST, transposed_b.get() } };
322 NEScheduler::get().schedule_op(_transpose_kernel.get(), Window::DimY, _transpose_kernel->window(), transpose_pack);
323 }
324
325 // Use reshaped matrices
326 mm_pack.add_const_tensor(ACL_SRC_0, interleaved_a.get());
327 mm_pack.add_const_tensor(ACL_SRC_1, transposed_b.get());
328 }
329
330 NEScheduler::get().schedule_op(_mm_kernel.get(), _run_vector_matrix_multiplication ? Window::DimX : Window::DimY, _mm_kernel->window(), mm_pack);
331
332 // Run bias addition kernel
333 if(_run_bias_addition)
334 {
335 ITensorPack pack{ { ACL_SRC_0, temp_d.get() }, { ACL_SRC_1, c }, { ACL_DST, d } };
336 _add_bias->run(pack);
337 }
338 }
339
340 // Run matrix addition kernel
341 if(_run_addition)
342 {
343 ITensorPack c_add_pack{ { ACL_SRC, c }, { ACL_DST, d } };
344 NEScheduler::get().schedule_op(_ma_kernel.get(), Window::DimY, _ma_kernel->window(), c_add_pack);
345 }
346
347 // Run activation function
348 if(_run_activation)
349 {
350 ITensorPack pack{ { ACL_SRC, d }, { ACL_DST, d } };
351 _activation_func->run(pack);
352 }
353}
354
355void CpuGemm::prepare(ITensorPack &tensors)
356{
357 if(!_is_prepared)
358 {
Francesco Petrogalli553f6952022-06-30 10:22:01 +0000359 if(_asm_glue && _asm_glue->is_configured())
Michele Di Giorgio4dfc5532021-06-30 12:05:34 +0100360 {
361 _asm_glue->prepare(tensors);
362 }
363 else if(_reshape_b_only_on_first_run && !_run_vector_matrix_multiplication)
364 {
365 const ITensor *b = tensors.get_const_tensor(ACL_SRC_1);
366 ITensor *b_aux = utils::cast::polymorphic_cast<ITensor *>(tensors.get_tensor(offset_int_vec(TransposedRHS)));
367 ARM_COMPUTE_ERROR_ON_NULLPTR(b, b_aux);
368
369 CpuAuxTensorHandler transposed_b(_tmp_b, *b_aux);
370 ITensorPack transpose_pack{ { ACL_SRC, b }, { ACL_DST, transposed_b.get() } };
371 NEScheduler::get().schedule_op(_transpose_kernel.get(), Window::DimY, _transpose_kernel->window(), transpose_pack);
372 }
373 _is_prepared = true;
374 }
375}
376
377experimental::MemoryRequirements CpuGemm::workspace() const
378{
379 return _aux_mem;
380}
Francesco Petrogalli553f6952022-06-30 10:22:01 +0000381
Ramy Elgammal91780022022-07-20 14:57:37 +0100382Status CpuGemm::has_opt_impl(arm_compute::WeightFormat &expected_weight_format, const ITensorInfo *a, const ITensorInfo *b, const ITensorInfo *c, const ITensorInfo *d,
Francesco Petrogalli553f6952022-06-30 10:22:01 +0000383 const GEMMInfo &gemm_info)
384{
385 const cpu::AsmGemmInfo asm_info = init_assembly_metadata(gemm_info);
386
387 return CpuGemmAssemblyDispatch::has_opt_impl(expected_weight_format, a, b, c, d, asm_info);
388}
389
390bool CpuGemm::isVarWeightsKernel() const
391{
392 return _asm_glue && _asm_glue->isVarWeightsKernel();
393}
Michele Di Giorgio4dfc5532021-06-30 12:05:34 +0100394} // namespace cpu
395} // namespace arm_compute