| 1 |
<!-- |
| 2 |
SPDX-FileCopyrightText: Copyright 2025 Arm Limited and/or its affiliates <[email protected]> |
| 3 |
|
| 4 |
SPDX-License-Identifier: Apache-2.0 |
| 5 |
--> |
| 6 |
|
| 7 |
# Integrating KleidiAI into MLAS via `MlasGemmBatch` |
| 8 |
|
| 9 |
This document provides detailed guidance on how to integrate KleidiAI as an external optimized backend into the ONNX Runtime MLAS (Microsoft Linear Algebra Subprograms) framework. It uses `MlasGemmBatch` as the core example. It is intended to be used as a guide to aid KleidiAI integration into other frameworks. |
| 10 |
|
| 11 |
N.B. Input tensors/matrices may not be structured in the same way as MLAS tensors are at the level of abstraction discussed below, so please make yourself aware of the input requirements to KleidiAI function calls when integrating micro-kernels into your framework. |
| 12 |
|
| 13 |
As of July 4th 2025, the specific examples can be seen as follows: |
| 14 |
|
| 15 |
KleidiAI call from default function (with fallback mechanics): |
| 16 |
https://github.com/damdoo01-arm/onnxruntime/blob/kai_sgemm_igemm_quant_gemv/onnxruntime/core/mlas/lib/sgemm.cpp |
| 17 |
(Lines 1563-1584) |
| 18 |
|
| 19 |
KleidiAI MlasGemmBatch implementation: |
| 20 |
https://github.com/damdoo01-arm/onnxruntime/blob/kai_sgemm_igemm_quant_gemv/onnxruntime/core/mlas/lib/kleidiai/sgemm_kleidiai.cpp |
| 21 |
(Lines 140-344) |
| 22 |
|
| 23 |
______________________________________________________________________ |
| 24 |
|
| 25 |
## 1. Entry Point: `KleidiAI::MlasGemmBatch` call from default `MlasGemmBatch` |
| 26 |
|
| 27 |
The default `MlasGemmBatch` implementation acts as a gateway to dispatch to external backends (e.g., KleidiAI): |
| 28 |
|
| 29 |
```cpp |
| 30 |
void MLASCALL MlasGemmBatch(...) { |
| 31 |
thread_local bool kleidiai_attempted = false; |
| 32 |
|
| 33 |
if (!kleidiai_attempted && |
| 34 |
GetMlasPlatform().MlasGemmBatch == &ArmKleidiAI::MlasGemmBatch) { |
| 35 |
kleidiai_attempted = true; |
| 36 |
GetMlasPlatform().MlasGemmBatch(...); |
| 37 |
kleidiai_attempted = false; |
| 38 |
return; |
| 39 |
} |
| 40 |
// Default fallback implementation continues here... |
| 41 |
} |
| 42 |
``` |
| 43 |
|
| 44 |
### Key Notes: |
| 45 |
|
| 46 |
- `kleidiai_attempted` prevents recursive fallback loops. |
| 47 |
- The check on `GetMlasPlatform().MlasGemmBatch` enables backend selection without static dispatch. |
| 48 |
|
| 49 |
______________________________________________________________________ |
| 50 |
|
| 51 |
## 2. KleidiAI Implementation: `ArmKleidiAI::MlasGemmBatch` |
| 52 |
|
| 53 |
### 2.1 Validation & Fallback Conditions |
| 54 |
|
| 55 |
```cpp |
| 56 |
if (M == 0 || N == 0 || K == 0 || |
| 57 |
TransA != CblasNoTrans || |
| 58 |
(TransB != CblasNoTrans && !Data[0].BIsPacked) || |
| 59 |
!MLAS_CPUIDINFO::GetCPUIDInfo().HasArm_SME()) { |
| 60 |
::MlasGemmBatch(...); // fallback |
| 61 |
return; |
| 62 |
} |
| 63 |
``` |
| 64 |
|
| 65 |
KleidiAI only supports: |
| 66 |
|
| 67 |
- `TransA == CblasNoTrans` |
| 68 |
- `TransB == CblasNoTrans` or `BIsPacked == true` |
| 69 |
- SME-capable hardware |
| 70 |
|
| 71 |
Also includes runtime check for tile size suitability: |
| 72 |
|
| 73 |
```cpp |
| 74 |
if (M < m_step || N < n_step) { |
| 75 |
if (GetMlasPlatform().MlasGemmBatch != ArmKleidiAI::MlasGemmBatch) { |
| 76 |
::MlasGemmBatch(...); // fallback |
| 77 |
return; |
| 78 |
} |
| 79 |
} |
| 80 |
``` |
| 81 |
|
| 82 |
______________________________________________________________________ |
| 83 |
|
| 84 |
### 2.2 Preprocessing: `beta` Scaling / Zeroing |
| 85 |
|
| 86 |
```cpp |
| 87 |
if (Data->beta != 1.0f) { ... } |
| 88 |
if (Data->beta == 0.0f) { ... } |
| 89 |
``` |
| 90 |
|
| 91 |
Handles special cases for scaling or zero-initializing `C` before matmul. |
| 92 |
|
| 93 |
______________________________________________________________________ |
| 94 |
|
| 95 |
### 2.3 Packing Strategy |
| 96 |
|
| 97 |
In high-performance GEMM (General Matrix Multiply) kernels, data packing is essential for performance. KleidiAI relies on explicit packing of both LHS (A) and RHS (B) matrices into cache-aligned, kernel-friendly tiles before execution. Packing improves memory access patterns, enables vectorization, and reduces cache pollution. |
| 98 |
|
| 99 |
#### LHS Packing |
| 100 |
|
| 101 |
All `A` matrices are packed using |
| 102 |
|
| 103 |
```cpp |
| 104 |
kai_run_lhs_pack_f32p2vlx1_f32_sme(). |
| 105 |
``` |
| 106 |
|
| 107 |
Characteristics: |
| 108 |
• Parallelized across the batch dimension via MlasTrySimpleParallel (equivalent Threading function for other frameworks should be callable at this point). |
| 109 |
• The packed memory layout conforms to KleidiAI’s internal micro-kernel expectations: typically mr × kr tiles (e.g., 32×32). |
| 110 |
• Each batch element A_i is packed into a contiguous buffer at offset batch_idx × LhsPackedStride. |
| 111 |
|
| 112 |
```cpp |
| 113 |
size_t LhsPackedStride = kai_get_lhs_packed_size_lhs_pack_f32p2vlx1_f32_sme(M, K, mr, kr, sr); |
| 114 |
auto LhsPacked = std::make_unique_for_overwrite<std::byte[]>(LhsPackedStride * BatchSize); |
| 115 |
``` |
| 116 |
|
| 117 |
This allocates a per-batch packing region with sufficient space for tiling. |
| 118 |
|
| 119 |
Threaded Packing Loop: |
| 120 |
|
| 121 |
```cpp |
| 122 |
MlasTrySimpleParallel(ThreadPool, BatchSize, [&](ptrdiff_t batch_idx) { |
| 123 |
std::byte* LhsPackedPtr = LhsPackedData + batch_idx * LhsPackedStride; |
| 124 |
kai_run_lhs_pack_f32p2vlx1_f32_sme(..., Data[batch_idx].A, ..., LhsPackedPtr); |
| 125 |
KaiPackedData[batch_idx].A = reinterpret_cast<const float*>(LhsPackedPtr); |
| 126 |
}); |
| 127 |
``` |
| 128 |
|
| 129 |
#### RHS Packing (if required) |
| 130 |
|
| 131 |
Conditionally performed if |
| 132 |
|
| 133 |
```cpp |
| 134 |
Data[0].BIsPacked == false |
| 135 |
``` |
| 136 |
|
| 137 |
i.e., the B matrix is not already pre-packed by the calling layer |
| 138 |
|
| 139 |
RHS Packing micro-kernel: |
| 140 |
Conditionally performed if Data\[0\].BIsPacked == false, i.e., the B matrix is not already pre-packed by the calling layer |
| 141 |
|
| 142 |
```cpp |
| 143 |
ArmKleidiAI::MlasGemmPackB(TransA, TransB, N, K, B, ldb, RhsPackedPtr) |
| 144 |
``` |
| 145 |
|
| 146 |
This wraps the KleidiAI kai_run_rhs_pack_f32_sme(...) and ensures: |
| 147 |
|
| 148 |
``` |
| 149 |
• Alignment to nr × kr tile shape |
| 150 |
• Pointer-based layout suitable for direct loading into the micro-kernel |
| 151 |
``` |
| 152 |
|
| 153 |
Buffer Allocation: |
| 154 |
|
| 155 |
```cpp |
| 156 |
size_t RhsPackedStride = ArmKleidiAI::MlasGemmPackBSize(...); |
| 157 |
auto RhsPacked = std::make_unique_for_overwrite<std::byte[]>(RhsPackedStride * BatchSize); |
| 158 |
``` |
| 159 |
|
| 160 |
Combined LHS/RHS Packing Loop: |
| 161 |
|
| 162 |
```cpp |
| 163 |
MlasTrySimpleParallel(ThreadPool, BatchSize * 2, [&](ptrdiff_t batch_idx) { |
| 164 |
if (batch_idx & 1) { |
| 165 |
// LHS |
| 166 |
} else { |
| 167 |
// RHS |
| 168 |
} |
| 169 |
}); |
| 170 |
``` |
| 171 |
|
| 172 |
______________________________________________________________________ |
| 173 |
|
| 174 |
### 2.4 Tile Dimensioning |
| 175 |
|
| 176 |
To efficiently execute large matrix multiplications on modern CPU architectures—especially those supporting tile-based vector extensions like Arm SME2 the workload must be divided into tiles that can be executed in parallel by multiple threads. |
| 177 |
|
| 178 |
This process involves three core steps: |
| 179 |
|
| 180 |
______________________________________________________________________ |
| 181 |
|
| 182 |
#### **Step 1: Establish a 3D Tiling Scheme** |
| 183 |
|
| 184 |
Matrix multiplication over a batch of inputs can be visualized as a 3-dimensional grid of compute tiles: |
| 185 |
|
| 186 |
``` |
| 187 |
Tiling dimensions = [BatchSize, number of M tiles, number of N tiles] |
| 188 |
``` |
| 189 |
|
| 190 |
Where: |
| 191 |
|
| 192 |
- `BatchSize` refers to the number of independent matrix multiplications. |
| 193 |
- `M tiles` correspond to partitioning the rows of matrix A. |
| 194 |
- `N tiles` correspond to partitioning the columns of matrix B. |
| 195 |
|
| 196 |
Initial tile counts are estimated by dividing the matrix sizes by the preferred micro-kernel tile dimensions (`m_step`, `n_step`): |
| 197 |
|
| 198 |
```cpp |
| 199 |
tile_count_M = ceil(M / m_step); |
| 200 |
tile_count_N = ceil(N / n_step); |
| 201 |
``` |
| 202 |
|
| 203 |
The total number of work units becomes: `BatchSize × tile_count_M × tile_count_N`. |
| 204 |
|
| 205 |
______________________________________________________________________ |
| 206 |
|
| 207 |
#### **Step 2: Balance Tile Count Against Available Threads** |
| 208 |
|
| 209 |
To make full use of the thread pool: |
| 210 |
|
| 211 |
- Estimate how many tiles are ideally needed (limited by thread count). |
| 212 |
- Reshape the 3D tile grid to distribute the workload more evenly. |
| 213 |
|
| 214 |
This may involve scaling the number of tiles along the M and N dimensions such that: |
| 215 |
|
| 216 |
```cpp |
| 217 |
adjusted_tile_count_M ≈ ceil(ideal_tile_count * tile_count_M / total_tile_count); |
| 218 |
adjusted_tile_count_N ≈ ceil(ideal_tile_count * tile_count_N / total_tile_count); |
| 219 |
``` |
| 220 |
|
| 221 |
This rebalancing avoids creating too many small tiles or leaving threads underutilized. |
| 222 |
|
| 223 |
______________________________________________________________________ |
| 224 |
|
| 225 |
#### **Step 3: Derive Updated Step Sizes** |
| 226 |
|
| 227 |
Once the updated tile counts are known, recalculate the actual tile sizes (`m_step`, `n_step`) to match: |
| 228 |
|
| 229 |
```cpp |
| 230 |
m_step = ceil(M / adjusted_tile_count_M); |
| 231 |
n_step = ceil(N / adjusted_tile_count_N); |
| 232 |
``` |
| 233 |
|
| 234 |
Finally, the number of tiles is re-derived using the new step sizes: |
| 235 |
|
| 236 |
```cpp |
| 237 |
tile_count_M = ceil(M / m_step); |
| 238 |
tile_count_N = ceil(N / n_step); |
| 239 |
``` |
| 240 |
|
| 241 |
### 2.5 Main Tile Execution Loop |
| 242 |
|
| 243 |
This is the core loop that executes `kai_run_matmul_clamp_...()` across all 3D tile indices. |
| 244 |
|
| 245 |
#### 2.5.1 Tile Scheduling |
| 246 |
|
| 247 |
```cpp |
| 248 |
MlasTrySimpleParallel(ThreadPool, dim[0] * dim[1] * dim[2], [=](ptrdiff_t tid) { |
| 249 |
size_t BIdx = tid / (dim[1] * dim[2]); |
| 250 |
size_t MIdx = (tid % (dim[1] * dim[2])) / dim[2]; |
| 251 |
size_t NIdx = tid % dim[2]; |
| 252 |
``` |
| 253 |
|
| 254 |
Each `tid` maps to a unique tile in `[B, M, N]`. |
| 255 |
|
| 256 |
#### 2.5.2 Input Tile Extraction |
| 257 |
|
| 258 |
The packed matrices are stored contiguously by batch. For each tile: |
| 259 |
|
| 260 |
- Compute offsets: |
| 261 |
|
| 262 |
```cpp |
| 263 |
lhs_offset = kai_get_lhs_packed_offset_...(MIdx * m_step, K); |
| 264 |
rhs_offset = kai_get_rhs_packed_offset_...(NIdx * n_step, K); |
| 265 |
``` |
| 266 |
|
| 267 |
- Slice from packed buffer: |
| 268 |
|
| 269 |
```cpp |
| 270 |
const float* ATile = reinterpret_cast<...>(KaiPackedData[BIdx].A + lhs_offset); |
| 271 |
const void* BTile = reinterpret_cast<...>(KaiPackedData[BIdx].B + rhs_offset); |
| 272 |
``` |
| 273 |
|
| 274 |
#### 2.5.3 Micro-kernel Invocation |
| 275 |
|
| 276 |
The SME2-optimized micro-kernel is called as: |
| 277 |
|
| 278 |
```cpp |
| 279 |
kai_run_matmul_clamp_f32_f32p2vlx1_f32p2vlx1biasf32_sme2_mopa( |
| 280 |
TileSizeM, TileSizeN, K, |
| 281 |
ATile, BTile, |
| 282 |
temp_tile, // Output buffer |
| 283 |
TileSizeN * sizeof(float), sizeof(float), |
| 284 |
-FLT_MAX, FLT_MAX |
| 285 |
); |
| 286 |
``` |
| 287 |
|
| 288 |
- `temp_tile` is a thread-local scratch buffer. |
| 289 |
- Micro-kernel writes a raw `A*B` tile result without alpha/beta. |
| 290 |
|
| 291 |
#### 2.5.4 Writing to Output Matrix `C` |
| 292 |
|
| 293 |
The computed tile is then written to the final `C` matrix: |
| 294 |
|
| 295 |
- Compute the destination pointer: |
| 296 |
|
| 297 |
```cpp |
| 298 |
float* dst_tile = Data[BIdx].C + MIdx * m_step * ldc + NIdx * n_step; |
| 299 |
``` |
| 300 |
|
| 301 |
- Handle 2 cases: |
| 302 |
- **Fast Path** (no accumulation): |
| 303 |
```cpp |
| 304 |
if (alpha == 1.0f && beta == 0.0f && ldc == TileSizeN && tile is in bounds) |
| 305 |
memcpy(dst_tile, temp_tile, TileSizeM * TileSizeN * sizeof(float)); |
| 306 |
``` |
| 307 |
- **General Path** (scaled accumulation): |
| 308 |
```cpp |
| 309 |
for each (i, j) { |
| 310 |
dst_tile[i * ldc + j] = alpha * temp_tile[i * TileSizeN + j] + beta * dst_tile[i * ldc + j]; |
| 311 |
} |
| 312 |
``` |
| 313 |
|
| 314 |
This ensures correct handling of arbitrary GEMM expressions: |
| 315 |
|
| 316 |
``` |
| 317 |
C = alpha * A * B + beta * C |
| 318 |
``` |
| 319 |
|
| 320 |
______________________________________________________________________ |
| 321 |
|
| 322 |
## 3. Fallback Behavior |
| 323 |
|
| 324 |
If any constraint isn't met (unsupported transpose, no SME, small matrix), the call falls back to the default `MlasGemmBatch` using: |
| 325 |
|
| 326 |
```cpp |
| 327 |
::MlasGemmBatch(...); |
| 328 |
``` |
| 329 |
|
| 330 |
This ensures correctness even if KleidiAI can't process the workload. |
| 331 |
|
| 332 |
______________________________________________________________________ |
| 333 |
|
| 334 |
______________________________________________________________________ |
| 335 |
|
| 336 |
## 4. Required KleidiAI Functions |
| 337 |
|
| 338 |
- `kai_get_m_step_...`, `n_step_...`, `mr`, `kr`, `sr` |
| 339 |
- `kai_run_lhs_pack_...` |
| 340 |
- `kai_get_lhs_packed_offset_...` |
| 341 |
- `kai_run_matmul_clamp_...` |
| 342 |
|
| 343 |
These functions must be provided by KleidiAI for the SME2 micro-kernel path. |
| 344 |
|
| 345 |
______________________________________________________________________ |
| 346 |
|
| 347 |
## 5. Platform Detection & Hooking |
| 348 |
|
| 349 |
The backend is activated through: |
| 350 |
|
| 351 |
```cpp |
| 352 |
GetMlasPlatform().MlasGemmBatch = &ArmKleidiAI::MlasGemmBatch; |
| 353 |
``` |
| 354 |
|
| 355 |
Usually set in MLAS platform initialization during runtime feature detection. |
| 356 |
|
| 357 |
______________________________________________________________________ |
| 358 |
|
| 359 |
## 6. Summary of Integration Mechanics |
| 360 |
|
| 361 |
| Stage | Description | |
| 362 |
|--------------------|-------------------------------------------------------| |
| 363 |
| Dispatch Check | Conditional on platform struct function pointer | |
| 364 |
| Pre-conditions | Matrix sizes, transpose modes, SME support | |
| 365 |
| Fallbacks | Recursive call into MLAS if unsupported | |
| 366 |
| Data Packing | Both LHS and RHS packed using KleidiAI routines | |
| 367 |
| Tile Dispatch | Multi-threaded tile-wise matmul execution | |
| 368 |
| Output Writeback | `memcpy` or loop with alpha/beta scaling | |
| 369 |
|
| 370 |
This pattern can be extended for other MLAS APIs (e.g., `MlasGemmPackB`, `MlasConv`) can be seen elsewhere in the onnxruntime code and use a similar override, fallback, and execution structure. |