Debian Codegraph @

examples/matmul_clamp_f32_bf16p_bf16p/matmul_clamp_f32_bf16p_bf16p.cpp

raw symbols SCIP
1 //
2 // SPDX-FileCopyrightText: Copyright 2024 Arm Limited and/or its affiliates <[email protected]>
3 //
4 // SPDX-License-Identifier: Apache-2.0
5 //
6
7 // Example usage for matrix multiplication of two half-precision brain floating-point (BF16) matrices
8 // and the accumulation of the result into an FP32 destination matrix.
9 //
10 // The activations and the weights, stored in the LHS and RHS matrices respectively, are both non-transposed matrices.
11 // The matrix multiplication computation is performed using BF16 matrix multiply (BFMMLA)
12 // vector instructions present in the FEAT_BF16 ArmĀ® architecture feature.
13 //
14 #if !defined(__aarch64__) || !defined(__ARM_FEATURE_BF16_SCALAR_ARITHMETIC) || \
15 !defined(__ARM_FEATURE_BF16_VECTOR_ARITHMETIC)
16 #error This file must be compiled for AArch64, FEAT_BF16.
17 #else
18 #include <arm_neon.h>
19
20 #include <algorithm>
21 #include <cfloat>
22 #include <chrono>
23 #include <cmath>
24 #include <cstddef>
25 #include <cstring>
26 #include <iomanip>
27 #include <iostream>
28
29 // Include micro-kernel variants
30 #include "kai/kai_common.h"
31 #include "kai_lhs_quant_pack_bf16p1x4_f32_neon.h"
32 #include "kai_lhs_quant_pack_bf16p8x4_f32_neon.h"
33 #include "kai_matmul_clamp_f32_bf16p1x4_bf16p12x4b_1x36_neon_dot.h"
34 #include "kai_matmul_clamp_f32_bf16p8x4_bf16p12x4b_8x12_neon_mmla.h"
35 #include "kai_matmul_clamp_f32_bf16p_bf16p_interface.h"
36 #include "kai_rhs_quant_pack_kxn_bf16p12x4biasf32_f32_neon.h"
37
38 inline static float bf16_to_float(const uint16_t* v) {
39 const uint16_t uint_rep = *v;
40 return kai_cast_f32_bf16(uint_rep);
41 }
42
43 namespace {
44
45 typedef void (*kai_lhs_quant_pack_bf16pmxk_f32_run_func_t)(
46 size_t m, size_t k, size_t mr, size_t kr, size_t sr, size_t m_idx_start, const void* lhs, size_t lhs_stride,
47 void* lhs_packed);
48
49 typedef size_t (*kai_lhs_quant_pack_bf16pmxk_f32_get_lhs_packed_size_func_t)(
50 size_t m, size_t k, size_t mr, size_t kr, size_t sr);
51
52 struct kai_matmul_clamp_f32_bf16p_bf16p {
53 kai_matmul_clamp_f32_bf16p_bf16p_ukernel matmul_ukernel;
54 kai_lhs_quant_pack_bf16pmxk_f32_run_func_t lhs_pack_ukernel;
55 kai_lhs_quant_pack_bf16pmxk_f32_get_lhs_packed_size_func_t lhs_pack_get_lhs_packed_size;
56 std::string name = {};
57 };
58
59 /// Micro-kernel interface
60 const kai_matmul_clamp_f32_bf16p_bf16p ukernel_variants[] = {
61 {{kai_get_m_step_matmul_clamp_f32_bf16p1x4_bf16p12x4b_1x36_neon_dot,
62 kai_get_n_step_matmul_clamp_f32_bf16p1x4_bf16p12x4b_1x36_neon_dot,
63 kai_get_mr_matmul_clamp_f32_bf16p1x4_bf16p12x4b_1x36_neon_dot,
64 kai_get_nr_matmul_clamp_f32_bf16p1x4_bf16p12x4b_1x36_neon_dot,
65 kai_get_kr_matmul_clamp_f32_bf16p1x4_bf16p12x4b_1x36_neon_dot,
66 kai_get_sr_matmul_clamp_f32_bf16p1x4_bf16p12x4b_1x36_neon_dot,
67 kai_get_lhs_packed_offset_matmul_clamp_f32_bf16p1x4_bf16p12x4b_1x36_neon_dot,
68 kai_get_rhs_packed_offset_matmul_clamp_f32_bf16p1x4_bf16p12x4b_1x36_neon_dot,
69 kai_get_dst_offset_matmul_clamp_f32_bf16p1x4_bf16p12x4b_1x36_neon_dot,
70 kai_get_dst_size_matmul_clamp_f32_bf16p1x4_bf16p12x4b_1x36_neon_dot,
71 kai_run_matmul_clamp_f32_bf16p1x4_bf16p12x4b_1x36_neon_dot},
72 kai_run_lhs_quant_pack_bf16p1x4_f32_neon,
73 kai_get_lhs_packed_size_lhs_quant_pack_bf16p1x4_f32_neon,
74 "matmul_clamp_f32_bf16p1x4_bf16p12x4b_1x36_neon_dot"},
75 {{kai_get_m_step_matmul_clamp_f32_bf16p8x4_bf16p12x4b_8x12_neon_mmla,
76 kai_get_n_step_matmul_clamp_f32_bf16p8x4_bf16p12x4b_8x12_neon_mmla,
77 kai_get_mr_matmul_clamp_f32_bf16p8x4_bf16p12x4b_8x12_neon_mmla,
78 kai_get_nr_matmul_clamp_f32_bf16p8x4_bf16p12x4b_8x12_neon_mmla,
79 kai_get_kr_matmul_clamp_f32_bf16p8x4_bf16p12x4b_8x12_neon_mmla,
80 kai_get_sr_matmul_clamp_f32_bf16p8x4_bf16p12x4b_8x12_neon_mmla,
81 kai_get_lhs_packed_offset_matmul_clamp_f32_bf16p8x4_bf16p12x4b_8x12_neon_mmla,
82 kai_get_rhs_packed_offset_matmul_clamp_f32_bf16p8x4_bf16p12x4b_8x12_neon_mmla,
83 kai_get_dst_offset_matmul_clamp_f32_bf16p8x4_bf16p12x4b_8x12_neon_mmla,
84 kai_get_dst_size_matmul_clamp_f32_bf16p8x4_bf16p12x4b_8x12_neon_mmla,
85 kai_run_matmul_clamp_f32_bf16p8x4_bf16p12x4b_8x12_neon_mmla},
86 kai_run_lhs_quant_pack_bf16p8x4_f32_neon,
87 kai_get_lhs_packed_size_lhs_quant_pack_bf16p8x4_f32_neon,
88 "matmul_clamp_f32_bf16p8x4_bf16p12x4b_8x12_neon_mmla"}};
89
90 // Number of micro-kernel variants stored in the array
91 constexpr size_t num_ukernel_variants = sizeof(ukernel_variants) / sizeof(ukernel_variants[0]);
92
93 /// @brief Truncate the 32-bit floating point number's least significant 16 mantissa bits
94 /// @param x floating-point number
95 /// @return truncated floating-point number
96 inline static float truncate(float x) {
97 uint32_t uval = (*reinterpret_cast<uint32_t*>(&x) & 0xffff0000);
98 return *reinterpret_cast<float*>(&uval);
99 }
100
101 /// Reference implementation of matrix multiplication
102 static void run_matmul_ref(
103 size_t m, size_t n, size_t k, const float* lhs, const float* rhs, const float* bias, float* dst, float scalar_min,
104 float scalar_max) {
105 for (size_t row_idx = 0; row_idx < m; ++row_idx) {
106 for (size_t col_idx = 0; col_idx < n; ++col_idx) {
107 float acc = bias[col_idx];
108
109 for (size_t k_idx = 0; k_idx < k; ++k_idx) {
110 float lhs_val = truncate(lhs[row_idx * k + k_idx]);
111 float rhs_val = truncate(rhs[col_idx + n * k_idx]);
112
113 acc += lhs_val * rhs_val;
114 }
115
116 dst[row_idx * n + col_idx] = std::clamp(acc, scalar_min, scalar_max);
117 }
118 }
119 }
120
121 /// Fills the matrix with incremental values
122 void fill_matrix(size_t num_rows, size_t num_cols, float* dst, const float weight) {
123 for (size_t i = 0; i < num_rows * num_cols; i++) {
124 dst[i] = float((i + 1) * weight);
125 }
126 }
127
128 /// Print the matrix
129 void print_matrix(size_t num_rows, size_t num_cols, const char* name, const float* src) {
130 std::cout << name << " = [\n";
131 for (size_t y = 0; y < num_rows; ++y) {
132 std::cout << " [";
133 for (size_t x = 0; x < num_cols; ++x) {
134 std::cout << std::setprecision(2) << std::fixed << src[y * num_cols + x] << ", ";
135 }
136 std::cout << ("],\n");
137 }
138 std::cout << ("]\n\n");
139 }
140
141 void print_matrix(size_t num_rows, size_t num_cols, const char* name, const uint16_t* src) {
142 std::cout << name << " = [\n";
143 for (size_t y = 0; y < num_rows; ++y) {
144 std::cout << " [";
145 for (size_t x = 0; x < num_cols; ++x) {
146 std::cout << std::setprecision(2) << std::fixed << bf16_to_float(&src[y * num_cols + x]) << ", ";
147 }
148 std::cout << ("],\n");
149 }
150 std::cout << ("]\n\n");
151 }
152
153 void print_mixed_prec_matrix(
154 size_t num_rows, size_t num_cols, const char* name, const uint8_t* src, int nr, int stride) {
155 std::cout << name << " = [\n";
156 for (size_t y = 0; y < num_rows; ++y) {
157 std::cout << " [";
158 const uint8_t* src_row = src + stride * y;
159 for (size_t x = 0; x < num_cols; ++x) {
160 if (x >= nr) {
161 // print bfloat
162 const uint16_t* src_elm =
163 reinterpret_cast<const uint16_t*>(src_row + nr * sizeof(float) + (x - nr) * sizeof(uint16_t));
164 std::cout << std::setprecision(2) << std::fixed << bf16_to_float(src_elm) << ", ";
165 } else {
166 // print float
167 const float* src_elm = reinterpret_cast<const float*>(src_row + x * sizeof(float));
168 std::cout << std::setprecision(2) << std::fixed << *src_elm << ", ";
169 }
170 }
171 std::cout << ("],\n");
172 }
173 std::cout << ("]\n\n");
174 }
175
176 void print_bf_matrix(size_t num_rows, size_t num_cols, const char* name, const float* src) {
177 std::cout << name << " = [\n";
178 for (size_t y = 0; y < num_rows; ++y) {
179 std::cout << " [";
180 for (size_t x = 0; x < num_cols; ++x) {
181 std::cout << std::setprecision(2) << std::fixed << truncate(src[y * num_cols + x]) << ", ";
182 }
183 std::cout << ("],\n");
184 }
185 std::cout << ("]\n\n");
186 }
187
188 /// Verify the micro-kernel output matches the reference implementation
189 bool is_output_correct(
190 size_t num_rows, size_t num_cols, const float rel_tolerance, const float* ref, const float* act) {
191 bool is_valid = true;
192
193 for (size_t i = 0; i < num_rows * num_cols; ++i) {
194 if (std::fabs(ref[i] - act[i]) / (act[i] + 1e-10) > rel_tolerance) {
195 const size_t x = i % num_cols;
196 const size_t y = i / num_cols;
197
198 std::cout << std::setprecision(5) << std::fixed << "ERROR![" << y << "][" << x << "]: ref=" << ref[i]
199 << " vs. act=" << act[i] << "\n";
200
201 is_valid = false;
202 }
203 }
204 return is_valid;
205 }
206 } // namespace
207
208 int main() {
209 int ret = 0;
210
211 // Parameters of the matrix multiplication. Change these values to see how the micro-kernels operate on different
212 // sized matrices
213 const size_t M = 10; // Rows of LHS and DST matrices
214 const size_t N = 27; // Columns of RHS and DST matrices, and length of the Bias vector.
215 const size_t K = 23; // Columns of LHS, rows of RHS matrices
216
217 for (int variant_idx = 0; variant_idx < num_ukernel_variants; ++variant_idx) {
218 const size_t lhs_size = M * K;
219 const size_t rhs_size = N * K;
220 const size_t bias_size = N;
221 const size_t dst_size = M * N;
222
223 const auto ukernel = ukernel_variants[variant_idx].matmul_ukernel;
224 const auto lhs_pack_ukernel = ukernel_variants[variant_idx].lhs_pack_ukernel;
225 const auto get_lhs_packed_size = ukernel_variants[variant_idx].lhs_pack_get_lhs_packed_size;
226
227 // Allocate the memory
228 float* lhs = new float[lhs_size];
229 float* rhs = new float[rhs_size];
230 float* bias = new float[bias_size];
231
232 fill_matrix(M, K, lhs, 0.4);
233 fill_matrix(K, N, rhs, 0.3);
234 fill_matrix(1, N, bias, 0.2);
235
236 #ifdef KAI_DEBUG
237 print_matrix(M, K, "lhs", lhs);
238 print_matrix(K, N, "rhs", rhs);
239 print_matrix(1, N, "bias", bias);
240
241 // Print bf16 converted values
242 print_bf_matrix(M, K, "lhs_bf", lhs);
243 print_bf_matrix(K, N, "rhs_bf", rhs);
244 #endif // KAI_DEBUG
245
246 //----------- REFERENCE IMPLEMENTATION
247 //------------------------------------
248 //------------------------------------
249 float* dst_ref = new float[dst_size];
250
251 run_matmul_ref(
252 M, N, K, // Dimensions
253 lhs, // LHS buffer
254 rhs, // RHS buffer
255 bias, // Bias buffer
256 dst_ref, // DST
257 -FLT_MAX, FLT_MAX // Min and max for the clamp operation
258 );
259 //----------- END REFERENCE IMPLEMENTATION
260 //------------------------------------
261 //------------------------------------
262
263 //----------- MICRO-KERNELS TESTS
264 //------------------------------------
265 //------------------------------------
266 const size_t mr = ukernel.get_mr();
267 const size_t nr = ukernel.get_nr();
268 const size_t kr = ukernel.get_kr();
269 const size_t sr = ukernel.get_sr();
270
271 // In a single row, we pack nr bias values followed by K rows of nr RHS values
272 const size_t rhs_packed_size =
273 kai_get_rhs_packed_size_rhs_quant_pack_kxn_bf16p12x4biasf32_f32_neon(N, K, nr, kr);
274 uint8_t* rhs_packed = new uint8_t[rhs_packed_size];
275
276 const size_t lhs_stride = K * sizeof(float);
277 const size_t rhs_stride = N * sizeof(float);
278 const size_t dst_stride_row = N * sizeof(float);
279 const size_t dst_stride_col = sizeof(float);
280
281 // Packing only needs to be performed once if the contents of the bias and RHS matrices are expected to be
282 // constant.
283 kai_run_rhs_quant_pack_kxn_bf16p12x4biasf32_f32_neon(
284 1, N, K, nr, kr, sr, // Packing arguments
285 rhs_stride, // RHS stride
286 rhs, // RHS
287 bias, // Bias
288 NULL, // Scale
289 rhs_packed, // RHS packed
290 0, NULL);
291
292 // The RHS and Bias buffers can be freed after packing, however we reuse them for the reference test below
293
294 #ifdef KAI_DEBUG
295 const size_t rhs_packed_cols = nr + kai_roundup(K, kr) * nr;
296
297 // Each col has nr floats and then K*nr bfloats
298 int rhs_packed_stride = nr * sizeof(float) + kai_roundup(K, kr) * nr * sizeof(uint16_t);
299 const size_t rhs_packed_rows = rhs_packed_size / rhs_packed_stride;
300
301 print_mixed_prec_matrix(rhs_packed_rows, rhs_packed_cols, "rhs_packed", rhs_packed, nr, rhs_packed_stride);
302 #endif // KAI_DEBUG
303
304 float* dst = new float[dst_size];
305
306 const auto timer_matmul_start = std::chrono::high_resolution_clock::now();
307
308 // This can be anything for GEMM kernels. It does not have to be equal to m_step() returned
309 // from the kernel. But, for GEMV, it must be m_step (which will be equal to 1).
310 const size_t m_step = ukernel.get_m_step();
311 for (size_t m_idx = 0; m_idx < M; m_idx += m_step) {
312 const size_t height = KAI_MIN(m_step, M - m_idx);
313
314 size_t lhs_packed_size = get_lhs_packed_size(height, K, mr, kr, sr);
315
316 uint8_t* lhs_packed = new uint8_t[lhs_packed_size];
317 memset(lhs_packed, 0, lhs_packed_size);
318
319 lhs_pack_ukernel(
320 height, K, mr, kr, sr, 0 /* m_idx_start */, reinterpret_cast<uint8_t*>(lhs) + m_idx * lhs_stride,
321 lhs_stride, lhs_packed);
322
323 #ifdef KAI_DEBUG
324 int num_lhs_rows = (height + mr - 1) / mr;
325 int num_lhs_cols = mr * kai_roundup(K, kr);
326
327 print_matrix(num_lhs_rows, num_lhs_cols, "lhs_packed", reinterpret_cast<uint16_t*>(lhs_packed));
328 #endif // KAI_DEBUG
329
330 ukernel.run_matmul(
331 height, N, K, // Dimensions
332 lhs_packed, // LHS packed
333 rhs_packed, // RHS packed
334 reinterpret_cast<uint8_t*>(dst) + m_idx * dst_stride_row, // DST
335 dst_stride_row, // DST stride (row)
336 dst_stride_col, // DST stride (col)
337 -FLT_MAX, FLT_MAX // Min and max for the clamp operation
338 );
339
340 delete[] lhs_packed;
341 }
342
343 const auto timer_matmul_end = std::chrono::high_resolution_clock::now();
344 const auto time_matmul =
345 std::chrono::duration_cast<std::chrono::nanoseconds>(timer_matmul_end - timer_matmul_start);
346
347 #ifdef KAI_DEBUG
348 print_matrix(M, N, "dst", dst);
349 print_matrix(M, N, "ref", dst_ref);
350 #endif // KAI_DEBUG
351
352 constexpr float rel_tolerance = 0.02; // This value was chosen by experimentation
353 const bool is_valid = is_output_correct(M, N, rel_tolerance, dst_ref, dst);
354
355 std::cout << "TEST[matmul_clamp_f32_bf16p_bf16p]\n";
356 std::cout << "- ukernel: " << ukernel_variants[variant_idx].name << std::endl;
357 if (is_valid) {
358 std::cout << "- Status: PASSED\n";
359 std::cout << "- Performance: " << time_matmul.count() << "ns\n";
360 } else {
361 std::cout << "- Status: FAILED\n";
362 ret = 1;
363 }
364
365 //----------- END MICRO-KERNELS TESTS
366 //------------------------------------
367 //------------------------------------
368
369 delete[] lhs;
370 delete[] rhs;
371 delete[] bias;
372 delete[] rhs_packed;
373 delete[] dst;
374 delete[] dst_ref;
375 }
376
377 return ret;
378 }
379
380 #endif // Architectural features check.