Debian Codegraph @

docs/matmul_qsi4cx/README.md

raw
1 <!--
2 SPDX-FileCopyrightText: Copyright 2024-2025 Arm Limited and/or its affiliates <[email protected]>
3
4 SPDX-License-Identifier: Apache-2.0
5 -->
6
7 # How to run the int4 matmul micro-kernels
8
9 ## Prerequisities
10
11 - Understanding of matrix multiplication routines
12 - Knowledge of quantization schemes, such as 8-bit (int8) per-channel quantization
13 - Experience with Arm® cross-compilation on Linux® or Android™
14 - Proficiency with Linux® commands
15
16 ## Goal
17
18 In this guide, we will explore the use of the integer 4-bit (int4) matrix multiplication (matmul) micro-kernel with the per-channel quantization (cx).
19
20 ## Target Arm® CPUs
21
22 Arm® CPUs with **FEAT_I8MM** extension.
23
24 ## Introduction
25
26 In this guide, we will perform matrix multiplication between two matrices with the following data types and dimensions:
27
28 - Left-hand side (**LHS**) matrix: with `M` rows and `K` columns and with `f32` data type
29 - Right-hand side (**RHS**) matrix: with `N` rows and `K` columns and with quantized (`q`) symmetric (`s`) signed 4-bit (`i4`) with per-channel quantization (`cx`)
30
31 Since the **RHS** matrix uses symmetric per-channel quantization, it is accompanied by an additional array (`RHS scales`) containing the scale quantization parameters for each `N` value.
32
33 > ℹ️ The quantization is called per-channel because matrix multiplication is commonly used to accelerate the convolution layer and the `N` dimension corresponds to the `output channel`, for example, `C` in `NHWC`.
34
35 The following image visually describes the operations involved to perform this matrix multiplication type:
36 ![int4_matmul_per_channel](imgs/int4_matmul_per_channel.png)
37
38 As you can see from the preceeding image, the LHS matrix is dynamically quantized to int8.
39
40 > ℹ️ In the previous image you can also see that both the LHS and RHS matrices are packed. This type of operation will be introduced later in the guide.
41
42 The int4 matmul per-channel micro-kernels are all available in the **[matmul_clamp_f32_qai8dxp_qsi4cxp](../../kai/ukernels/matmul/matmul_clamp_f32_qai8dxp_qsi4cxp/)** folder.
43
44 The specific micro-kernel variant we will be running in this guide is **[kai_matmul_clamp_f32_qai8dxp4x8_qsi4cxp8x8_8x8x32_neon_i8mm](../../kai/ukernels/matmul/matmul_clamp_f32_qai8dxp_qsi4cxp/kai_matmul_clamp_f32_qai8dxp4x8_qsi4cxp8x8_8x8x32_neon_i8mm.c)**.
45
46 The filename might seem intimidating at first glance. However, the filename actually describes what the micro-kernel accomplishes. So, our first step is to dissect it to better understand how the computation is executed.
47
48 ### Dissecting the micro-kernel filename
49
50 The first part of the filename indicates that the micro-kernel comprises **matrix multiplication (`matmul`)** followed by a **clamp (`clamp`)** operation.
51
52 Following the operation performed, we encounter a list of matrices utilized for matrix multiplication, including the following:
53
54 - The destination matrix: `f32` type
55 - The left-hand side (LHS) matrix: quantized (`q`) asymmetric (`a`) signed 8-bit (`i8`) with per-dimension quantization (`dx`) type
56 - The right-hand side (RHS) matrix: quantized (`q`) symmetric (`s`) signed 4-bit (`i4`) with per-channel quantization (`cx`)
57
58 Subsequently, the filename provides information about the 2D output block size processed (`8x8`) and the number of accumulations performed by the single innermost for loop (`x32`). The filename concludes with details about the technology used (`neon`) and the Arm® extension exploited (`i8mm`).
59
60 You might have observed that the LHS and RHS matrices also include additional information starting with the letter `p`. When encountering the letter `p`, it indicates that the matrix is **packed**, meaning it needs to be transformed to facilitate computation.
61
62 ### How do we pack the LHS and RHS matrices?
63
64 In the header of the matrix multiplication micro-kernel we report the additional micro-kernels required to leverage the computation. For this specific case, the additional micro-kernels are the following:
65
66 - [kai_lhs_quant_pack_qai8dxp_f32](../../kai/ukernels/matmul/pack/kai_lhs_quant_pack_qai8dxp_f32.c)
67 - [kai_rhs_pack_kxn_qsi4cxp_qs4cxs1s0](../../kai/ukernels/matmul/pack/kai_rhs_pack_kxn_qsi4cxp_qs4cxs1s0.c) or [kai_rhs_pack_nxk_qsi4cxp_qs4cxs1s0](../../kai/ukernels/matmul/pack/kai_rhs_pack_nxk_qsi4cxp_qs4cxs1s0.c)
68
69 The **kai_lhs_quant_pack_qai8dxp_f32** micro-kernel performs the dynamic quantization of the LHS matrix from f32 to int8 and packs the value to improve the cache locality during the matrix multiplication routine.
70 Instead, the **kai_rhs_pack_nxk_qsi4cxp_qs4cxs1s0 or kai_rhs_pack_kxn_qsi4cxp_qs4cxs1s0** packs the original integer 4-bit RHS matrix to improve the cache locality during the matrix multiplication routine.
71
72 The packing arguments required to run the preceeding micro-kernels, such as **mr**, **kr**, and **sr**, are obtained using the helper methods provided in the matrix multiplication micro-kernel.
73
74 At this point, it should be clear that matrix multiplication with int4 per-channel quantization requires three micro-kernels:
75
76 - Two micro-kernels for packing the LHS and RHS matrices
77 - One micro-kernel to perform matrix multiplication
78
79 Now that we know all the components for performing matrix multiplication, let's see how we can execute the micro-kernels.
80
81 ## Running the micro-kernel
82
83 Create a new C project with an empty `main()` function using your favourite IDE:
84
85 ```c
86 int main(int argc, char** argv) {
87 return 0;
88 }
89 ```
90
91 Then, perform the following steps to run the int4 matmul micro-kernel on an Arm® CPU with i8mm extension. Consider RHS is n x k format.
92
93 ### Step 1
94
95 Include the micro-kernels' headers files:
96
97 ```c
98 #include "kai_lhs_quant_pack_qai8dxp_f32.h"
99 #include "kai_rhs_pack_nxk_qsi4cxp_qs4cxs1s0.h"
100 #include "kai_matmul_clamp_f32_qai8dxp4x8_qsi4cxp8x8_8x8x32_neon_i8mm.h"
101 ```
102
103 Since the int4 matmul micro-kernel requires both the LHS and RHS to be packed, performing the matrix multiplication requires three micro-kernels:
104
105 - Two micro-kernels for packing the LHS and RHS matrices
106 - One micro-kernel to perform the matrix multiplication
107
108 > ℹ️ Including the `kai_common.h` header file is not required. Nonetheless, as it is a dependency of the micro-kernel, its directory must be included in your build script.
109
110 ### Step 2
111
112 Inside the `main()` function, declare and initialize three variables with the **M**, **N**, and **K** dimensions:
113
114 ```c
115 const size_t m = 13;
116 const size_t n = 17;
117 const size_t k = 18;
118 ```
119
120 In the preceed code snippet, **M** is `13`, **N** is `17`, and **K** is `18`.
121
122 ### Step 3
123
124 Allocate the memory for the LHS (f32) and RHS (int4) matrices, and the destination (f32) matrix:
125
126 ```c
127 const size_t lhs_native_size_f32 = m * k * sizeof(float);
128 const size_t rhs_native_size_qs4cx = n * (k / 2) * sizeof(uint8_t);
129 const size_t dst_size_f32 = m * n * sizeof(float);
130
131 // Allocate the memory
132 uint8_t* lhs_native_mtx_f32 = new uint8_t[lhs_native_size_f32];
133 uint8_t* rhs_native_mtx_qs4cx = new uint8_t[rhs_native_size_qs4cx];
134 uint8_t* dst_mtx_f32 = new uint8_t[dst_size_f32];
135 ```
136
137 As the micro-kernel does not handle memory allocation, it is the user's responsibility to allocate memory for all matrices and manage their lifetimes.
138
139 > ℹ️ When calculating the size of thr RHS matrix, you need to consider how the 4-bit values are stored. Specifically, since two 4-bit values are held in one 8-bit value, we need to adjust the size accordingly by dividing the `k` dimension by `2`.
140
141 ### Step 4
142
143 Allocate the memory for the RHS scales:
144
145 ```c
146 const size_t rhs_scales_size_f32 = n * sizeof(float);
147
148 uint8_t* rhs_scales_f32 = new uint8_t[rhs_scales_size_f32];
149 ```
150
151 The RHS matrix is quantized (`q`) symmetric (`s`) with per-channel quantization (`cx`). Therefore, we have one scale factor for each output channel (`n`).
152
153 ### Step 5:
154
155 Allocate the memory for the LHS and RHS packed matrices:
156
157 ```c
158 // Get the packing parameters
159 const size_t mr = kai_get_mr_matmul_clamp_f32_qai8dxp4x8_qsi4cxp8x8_8x8x32_neon_i8mm();
160 const size_t nr = kai_get_nr_matmul_clamp_f32_qai8dxp4x8_qsi4cxp8x8_8x8x32_neon_i8mm();
161 const size_t kr = kai_get_kr_matmul_clamp_f32_qai8dxp4x8_qsi4cxp8x8_8x8x32_neon_i8mm();
162 const size_t sr = kai_get_sr_matmul_clamp_f32_qai8dxp4x8_qsi4cxp8x8_8x8x32_neon_i8mm();
163
164 // Get the size in bytes for the packed matrices
165 const size_t lhs_packed_size = kai_get_lhs_packed_size_lhs_quant_pack_qai8dxp_f32(m, k, mr, kr, sr);
166 const size_t rhs_packed_size = kai_get_rhs_packed_size_rhs_pack_nxk_qsi4cxp_qs4cxs1s0(n, k, nr, kr, sr);
167
168 // Allocate the matrices
169 uint8_t* lhs_packed_mtx_qa8dx = new uint8_t[lhs_packed_size];
170 uint8_t* rhs_packed_mtx_qs4cx = new uint8_t[rhs_packed_size];
171
172 ```
173
174 In the preceding code snippet, we first use the helper methods of the int4 matmul micro-kernel to get the packing parameters (`mr`, `nr`, `kr`, and `sr`).
175 Then, we use the helper functions of the packing micro-kernels to know the size of the packed tensors (`lhs_packed_size` and `rhs_packed_size`).
176
177 > ℹ️ All micro-kernels have a helper method to return the size in bytes for the destination tensors/matrix.
178
179 Once we know the size of the packed matrices, we allocate the memory for the packed matrices.
180
181 ### Step 6:
182
183 Assuming you have filled the native LHS and RHS matrices with some random values, perform the RHS packing:
184
185 ```c
186 struct kai_rhs_pack_nxk_qsi4cxp_qs4cxs1s0_params params;
187 params.lhs_zero_point = 1;
188 params.rhs_zero_point = 8;
189
190 // RHS packing
191 kai_run_rhs_pack_nxk_qsi4cxp_qs4cxs1s0(
192 1, n, k, nr, kr, sr, // Packing arguments
193 (const uint8_t*)(rhs_native_mtx_qs4cx), // RHS
194 NULL, // Bias
195 (const float*)(rhs_scales_f32), // Scale
196 rhs_packed_mtx_qs4cx, // RHS packed
197 0, &params);
198 ```
199
200 Since the RHS matrix commonly keeps the weights of the trained model, you should perform this operation only once and free the memory of the native RHS matrix if not used elsewhere.
201
202 ### Step 7:
203
204 Convert the LHS matrix from f32 to integer 8-bit and pack the data:
205
206 ```c
207 kai_run_lhs_quant_pack_qai8dxp_f32(
208 m, k, mr, kr, sr, 0, // Packing arguments
209 (const float*)lhs_native_mtx_f32, // LHS
210 k * sizeof(float), // LHS stride
211 lhs_packed_mtx_qa8dx); // LHS packed
212 ```
213
214 Since the content of the LHS matrix changes at runtime, the LHS dynamic quantization and packing must be performed always before computing the matrix multiplication.
215
216 ### Step 8:
217
218 Perform the matrix multiplication:
219
220 ```c
221 const size_t dst_stride = n * sizeof(float);
222 kai_run_matmul_clamp_f32_qai8dxp4x8_qsi4cxp8x8_8x8x32_neon_i8mm(
223 m, n, k, // Dimensions
224 (const void*)lhs_packed_mtx_qa8dx, // LHS packed
225 (const void*)rhs_packed_mtx_qs4cx, // RHS packed
226 (float*)dst_mtx_f32, // DST
227 dst_stride, // DST stride (row)
228 sizeof(float), // DST stride (column)
229 -FLT_MAX, FLT_MAX); // Min and max for the clamp operation
230 ```
231
232 ### Step 9:
233
234 Free the dynamically allocated memory:
235
236 ```c
237 delete[] lhs_native_mtx_f32;
238 delete[] rhs_native_mtx_qs4cx;
239 delete[] dst_mtx_f32;
240 delete[] rhs_scales_f32;
241 delete[] lhs_packed_mtx_qa8dx;
242 delete[] rhs_packed_mtx_qs4cx;
243 ```
244
245 Now, write the build script to compile the example. If you are using CMake, your script might look like this:
246
247 ```cmake
248 cmake_minimum_required(VERSION 3.16)
249
250 set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17")
251 set(KLEIDIAI_PATH ../../)
252 set(MATMUL_PACK_PATH ${KLEIDIAI_PATH}/kai/ukernels/matmul/pack/)
253 set(MATMUL_PATH ${KLEIDIAI_PATH}/kai/ukernels/matmul/matmul_clamp_f32_qai8dxp_qsi4cxp/)
254
255 # KleidiAI include directories
256 include_directories(
257 ${KLEIDIAI_PATH}
258 ${MATMUL_PACK_PATH}
259 ${MATMUL_PATH})
260
261 # Files requires to build the executable
262 add_executable(matmul_clamp_f32_qai8dxp_qsi4cxp
263 matmul_clamp_f32_qai8dxp_qsi4cxp.cpp
264 ${MATMUL_PACK_PATH}/kai_rhs_pack_nxk_qsi4cxp_qs4cxs1s0.c
265 ${MATMUL_PACK_PATH}/kai_rhs_pack_kxn_qsi4cxp_qs4cxs1s0.c
266 ${MATMUL_PACK_PATH}/kai_lhs_quant_pack_qai8dxp_f32.c
267 ${MATMUL_PATH}/kai_matmul_clamp_f32_qai8dxp4x8_qsi4cxp8x8_8x8x32_neon_i8mm.c)
268
269 # Compile with DotProd and I8MM features enabled
270 target_compile_options(matmul_clamp_f32_qai8dxp_qsi4cxp PRIVATE -march=armv8.2-a+dotprod+i8mm)
271 ```
272
273 As you can see from the preceeding CMake script, we include the following directory paths:
274
275 - The KleidiAI root directory (`${KLEIDIAI_PATH}`)
276 - The matmul pack directory (`${MATMUL_PACK_PATH}`)
277 - The matmul with the int4 per-channel quantization directory (`${MATMUL_PATH}`)
278
279 Once you have prepared the build script, you can compile the project.
280
281 For example, to build the project for Android™, you can use the following commands in your terminal:
282
283 ```bash
284 mkdir build && cd build
285
286 export NDK_PATH="your-android-ndk-path"
287
288 cmake -DCMAKE_TOOLCHAIN_FILE=${NDK_PATH}/build/cmake/android.toolchain.cmake -DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-23 -DCMAKE_C_FLAGS=-march=armv8.2a+i8mm -DCMAKE_CXX_FLAGS=-march=armv8.2a+i8mm ..
289
290 make
291 ```
292
293 The Android™ NDK can be downloaded from [here](https://developer.android.com/ndk/downloads).
294
295 That’s all for this guide!
296
297 ## To learn more
298
299 This guide is an adaptation of the **matmul_clamp_f32_qai8dxp_qsi4cxp** example available at this [link](../../examples/matmul_clamp_f32_qai8dxp_qsi4cxp/matmul_clamp_f32_qai8dxp_qsi4cxp.cpp).
300
301 In the **matmul_clamp_f32_qai8dxp_qsi4cxp** example, you will learn:
302
303 - How to quantize a f32 matrix to int4 adopting a per-channel quantization
304 - How to invoke different micro-kernel variants of the same type