Elffuss BraidHub

kikocis/kleidiai public

main · 14.0 KiBRenderedRawPermalink
1<!--
2 SPDX-FileCopyrightText: Copyright 2026 Arm Limited and/or its affiliates
3 <open-source-office@arm.com>
4
5 SPDX-License-Identifier: Apache-2.0
6-->
7
8# Testing a new micro-kernel in the test suite
9
10This guide explains how to add a new micro-kernel to the test suite. The process
11is general, but the concrete example assumes an F16 matmul micro-kernel with F16
12input and F16 output, that has a RHS packing kernel, no LHS packing, and per $N$
13bias. Input matrices are assumed to be row major format. Do note that this is
14intended to be a guiding example, and there might be aspects of the examples
15here that are not yet implemented.
16
17The test suite is built around a small set of components and entry points:
18
19- Operator registration and test enumeration in
20 `test/nextgen/operators/matmul/matmul_operator.cpp` and
21 `test/nextgen/tests/matmul_test_next.cpp`.
22- Wrapper classes (specializations using the `KernelWrapper` interface) in
23 subdirectories of `test/nextgen/operators/matmul`. The files here adapt the
24 micro-kernel C API into the common test harness API. Micro-kernel factory
25 declarations are listed in wrapper interface headers, e.g.,
26 `test/nextgen/operators/matmul/matmul/matmul_wrapper_registry.hpp`.
27- A test bench in `test/nextgen/operators/matmul/matmul_tb.cpp` that generates
28 inputs, runs the implementation, and compares to a reference.
29
30This is the second version of the testing framework, which is why there are a
31lot of references to _NextGen_. This naming might change in the future, once the
32transition to _NextGen_ is completely done.
33
34## Glossary
35
36- *LHS* - Left-hand side. The $A$ matrix in $C = A * B + β$.
37- *MatMul* - Matrix multiplication.
38- *operator* - a set of micro-kernels that together are used to accelerate an
39 operation. For example, RHS packing and matmul micro-kernels.
40- *Packing* - reordering of input matrices to enable efficient memory access
41 patterns.
42- *portion* - Refers to test cases where only partial output is calculated,
43 as to test tiling functionality.
44- *RHS* - Right-hand side. The $B$ matrix in $C = A * B + β$.
45- *tensor slot* - a named entry in `MatMulSlot` used by `MatMulTb` tensor
46 storage to hold configuration/arguments and tensor data (source, derived,
47 packed, bias, and destination). Wrappers declare required slots via
48 `run_inputs()` and `ref_inputs()`.
49- *Wrapper* - a wrapper around the micro-kernel as to expose a standardized API
50 to the test framework.
51
52## The testing framework API
53
54Two utility types appear throughout the test harness API: `Span<T>` and
55`Poly<Base>`. Both are local backports of standard-library functionality from
56C++20 and later, and are used to keep wrapper and format interfaces compact.
57
58`Span<T>` is a non-owning view over contiguous memory, similar to `std::span`.
59The harness uses it for shapes, tile coordinates, and tensor data buffers.
60
61`Poly<Base>` is an owning, copyable wrapper for an object derived from `Base`,
62similar to later standard-library polymorphic value types. In the harness it is
63mainly used as `Poly<Format>` so tensors and wrappers can store concrete format
64objects by value while using the common `Format` interface.
65
66## Test flow overview
67
68`MatMulNext` is the matmul test suite registered in
69`test/nextgen/tests/matmul_test_next.cpp`.
70Its flow is:
71
721. Enumerate available operators from `get_available_matmul_operators()`.
731. Skip operators that current CPU doesn't support. This is checked by calling
74 `is_cpu_supported()` on operator.
751. For each operator and tested output portion, sample random shapes and keep
76 only shapes that satisfy
77 `is_shape_suitable(shape_m, shape_n, shape_k, portion)` on operator.
781. Select a supported bias mode set and clamp configuration for the operator.
791. Register tests for each component present on the operator: LHS pack, RHS
80 pack, and matmul.
811. Build a cached `MatMulTb` per fixture, generate test data once, then run
82 tile-level tests against precomputed references.
83
84Inside `MatMulTb::generate_test_data()`, the sequence is:
85
861. Populate `CONFIG`, then collect the required tensor slots from each
87 wrapper's `run_inputs()` and `ref_inputs()`.
881. Let wrappers populate constant slot metadata and argument payloads such as
89 `PACK_ARGS`, `MATMUL_ARGS`, and packed tensor formats.
901. Generate the source tensors (`LHS_DATA`, `RHS_DATA`, and any required
91 logical bias or scale slots), then derive any always-needed source variants
92 such as `RHS_T_DATA`.
931. Apply optional quantization (`lhs_quant`, `rhs_quant`, `bias_quant`).
941. Compute extra derived tensors required by wrappers (for example
95 `LHS_QZP_NEG`, `RHS_T_QDATA_SIGN`, `RHS_T_QDATA_SIGN_SUM`).
961. Compute required packed reference LHS and RHS input, and reference
97 destination data.
98
99Conceptually, `MatMulTb` owns a tensor pool indexed by `MatMulSlot`. Each slot
100names one piece of state in the test flow: source tensors, derived tensors,
101packed tensors, or non-array argument blobs such as `PACK_ARGS` and
102`MATMUL_ARGS`.
103
104Wrappers declare which slots they need by returning slot IDs from `run_inputs()`
105for the implementation path and `ref_inputs()` for the reference path.
106`determine_required_tensors()` takes the union of those declarations and uses it
107to decide which data must exist before any wrapper runs.
108
109This is how a floating-point matmul wrapper can simply ask for `LHS_PACKED`,
110`RHS_PACKED`, and `MATMUL_ARGS`, while an RHS pack wrapper can ask for
111`RHS_DATA` or `RHS_T_DATA` depending on layout and still use `RHS_T_DATA` for
112reference packing. Optional derived slots such as `LHS_QZP_NEG` or
113`RHS_T_QDATA_SIGN_SUM` are only computed when some wrapper has declared that it
114needs them.
115
116Bias is configured at operator level with `MatMulBiasModeSet`. Each
117`MatMulOperator` lists the supported sets in `supported_bias_mode_sets`; an
118empty set means no bias. The current logical bias modes are
119`ACCUMULATION_PER_M` for row bias, `ACCUMULATION_PER_N` for column bias, and
120`SCALE_BIAS_PER_N` for column bias applied after accumulator scaling. The test
121framework uses these modes to model the operator result. It does not matter to
122the high-level flow which component consumes or precomputes a particular value.
123
124The reference path computes the operator result in the same logical order:
125matmul, accumulation-stage bias, destination conversion when needed,
126accumulator scaling, scaled bias, and finally clamping. The exact tensors are
127generated only when the selected wrappers declare them as required inputs.
128
129Operators also declare clamping support with `MatMulClampMode`. Use
130`UNSUPPORTED` for micro-kernels with no clamp arguments, `OPTIONAL` for
131micro-kernels that can run with or without clamp arguments, and `REQUIRED` for
132micro-kernels whose API always requires clamp limits. Current matmul clamp
133arguments are carried in `MATMUL_ARGS` as `std::optional<MatMulClampArgsF32>`.
134For `REQUIRED` operators, the test bench supplies a full output-range clamp when
135the random test case does not select dynamic clamping.
136
137## Adding a new micro-kernel to the test suite
138
139This section outlines the steps needed to be able to add a new micro-kernel to
140the test suite.
141
142High-level steps:
143
144- Add wrapper factory functions for any required pack micro-kernels and the
145 matmul micro-kernel.
146- Register a `MatMulOperator` entry pointing at those wrappers and setting
147 data types, supported bias mode sets, clamp mode, quantizers, and shape
148 suitability.
149
150### Step 1: Add or extend matmul wrapper factories
151
152Wrappers adapt the micro-kernel C API to the harness API (`KernelWrapper`). For
153matmul, the relevant interfaces are:
154
155- `test/nextgen/operators/matmul/matmul/matmul_interface.hpp`
156- `test/nextgen/operators/matmul/pack_lhs/matmul_pack_lhs_interface.hpp`
157- `test/nextgen/operators/matmul/pack_rhs/matmul_pack_rhs_interface.hpp`
158
159For a simple F16 example, with no LHS packing:
160
161- Use `MatMulFpWrapper` for the matmul micro-kernel.
162- Use `MatMulPackRhsFpNtWrapper` for RHS packing.
163
164As an example, the matmul factory can be implemented as follows:
165
166```cpp
167// test/nextgen/operators/matmul/matmul/matmul_wrapper_registry.cpp
168std::unique_ptr<KernelWrapper<MatMulShape>>
169create_matmul_clamp_f16_f16_f16p_neon() {
170 return std::make_unique<MatMulFpWrapper>(
171 "matmul_clamp_f16_f16_f16p_neon",
172 MatMulFpInterface{
173 kai_get_m_step_matmul_clamp_f16_f16_f16p_neon,
174 ...
175 kai_get_dst_size_matmul_clamp_f16_f16_f16p_neon,
176 kai_run_matmul_clamp_f16_f16_f16p_neon,
177 },
178 make_poly<PlainFormat>(DataType::FP16), // LHS input format
179 make_poly<Block2dRowFormat>(
180 16, 1, 1, false, DataType::FP16,
181 std::array{DataType::FP16},
182 std::array<DataType, 0>{}), // Packed RHS input format
183 make_poly<PlainFormat>(DataType::FP16)); // Output format
184}
185```
186
187For this example, the matmul wrapper uses unpacked FP16 LHS, packed FP16 RHS
188with block size of $16 ⨯ 1$, and a plain FP16 destination format. Use existing
189factories in `matmul_wrapper_registry.cpp` and packer wrappers as a model.
190
191Make sure there is a `create_matmul_...` factory declaration added to
192`test/nextgen/operators/matmul/matmul/matmul_wrapper_registry.hpp` for the new micro-kernel.
193
194### Step 2: Add packing micro-kernel wrapper factories
195
196For the F16 example, only RHS packing is needed. Add or reuse the RHS
197packer wrapper in:
198
199- `test/nextgen/operators/matmul/pack_rhs/matmul_pack_rhs_wrapper_registry.cpp`
200
201If another micro-kernel also packs the LHS, add or reuse a packer wrapper in
202`test/nextgen/operators/matmul/pack_lhs/matmul_pack_lhs_wrapper_registry.cpp`.
203
204Example skeleton for RHS packing:
205
206```cpp
207// test/nextgen/operators/matmul/pack_rhs/matmul_pack_rhs_wrapper_registry.cpp
208std::unique_ptr<KernelWrapper<MatShape>>
209create_matmul_rhs_pack_kxn_f16p16x1biasf16_f16_f16_neon() {
210 return std::make_unique<MatMulPackRhsFpNtWrapper>(
211 "matmul_rhs_pack_kxn_f16p16x1biasf16_f16_f16_neon",
212 MatMulPackRhsFpInterface{
213 kai_get_n_step_rhs_pack_kxn_f16p16x1biasf16_f16_f16_neon,
214 kai_get_rhs_offset_rhs_pack_kxn_f16p16x1biasf16_f16_f16_neon,
215 kai_get_bias_offset_rhs_pack_kxn_f16p16x1biasf16_f16_f16_neon,
216 kai_get_rhs_packed_stride_rhs_pack_kxn_f16p16x1biasf16_f16_f16_neon,
217 kai_get_rhs_packed_offset_rhs_pack_kxn_f16p16x1biasf16_f16_f16_neon,
218 kai_get_rhs_packed_size_rhs_pack_kxn_f16p16x1biasf16_f16_f16_neon,
219 kai_run_rhs_pack_kxn_f16p16x1biasf16_f16_f16_neon,
220 },
221 make_poly<PlainFormat>(DataType::FP16), // RHS input format
222 make_poly<PlainFormat>(DataType::FP16), // Bias input format
223 make_poly<Block2dRowFormat>(
224 16, 1, 1, false, DataType::FP16,
225 std::array{DataType::FP16},
226 std::array<DataType, 0>{})); // Packed RHS output format
227}
228```
229
230In this example the wrapper is for a non-transposed RHS packing micro-kernel,
231which is why the RHS input matrix is consumed from `RHS_DATA` in plain row
232major $K × N$ layout, while the logical per-$N$ accumulation bias is represented
233by `ACC_BIAS_N_DATA` in plain row major $N$ layout. The packed output is a bit
234more complex, as it uses `Block2dRowFormat` to describe a $16 × 1$ packing
235format with the per-$N$ bias stored alongside the packed RHS data.
236
237If the packing micro-kernel instead expects a transposed RHS, the source format
238is still `PlainFormat`, but the logical shape changes to plain row major $N × K$
239and the wrapper should consume `RHS_T_DATA` rather than `RHS_DATA`. The test
240bench already derives `RHS_T_DATA` by transposing the generated $K × N$ RHS, so
241the operator registration does not need any extra transpose step. In practice,
242`...kxn...` packers use the non-transposed path shown above, while `...nxk...`
243packers should follow the transposed wrapper pattern and read from the
244transposed RHS slot. The bias handling, data types, and packed output format
245description stay the same; only the selected pack wrapper/factory and matching
246shape-suitability helper change.
247
248### Step 3: Register the operator
249
250Register the micro-kernel in `test/nextgen/operators/matmul/matmul_operator.cpp`. Each
251operator declares:
252
253- Micro-kernel availability (`is_cpu_supported`).
254- Shape suitability for matrix portions (`is_shape_suitable(...)`).
255- Supported bias mode sets.
256- Clamp support mode.
257- Input/output/accumulator data types.
258- Optional quantizers (for quantized micro-kernels).
259- Wrapper factories for any required packers and matmul.
260
261Example skeleton for operator
262
263```cpp
264// test/nextgen/operators/matmul/matmul_operator.cpp
265operators[i].name = "matmul_clamp_f16_f16_f16p_neon";
266
267operators[i].is_cpu_supported = []() { return cpu_has_fp16(); };
268operators[i].is_shape_suitable =
269 [](size_t shape_m, size_t shape_n, size_t shape_k, const MatrixPortion& portion) {
270 return is_shape_suitable_rhs_f16_example(shape_m, shape_n, shape_k, portion);
271 };
272
273operators[i].supported_bias_mode_sets = {
274 MatMulBiasModeSet{MatMulBiasMode::ACCUMULATION_PER_N},
275};
276operators[i].clamp_mode = MatMulClampMode::REQUIRED;
277
278operators[i].lhs_dtype = DataType::FP16;
279operators[i].rhs_dtype = DataType::FP16;
280operators[i].bias_dtype = DataType::FP16;
281operators[i].acc_dtype = DataType::FP16;
282operators[i].dst_dtype = DataType::FP16;
283
284operators[i].pack_rhs = create_matmul_rhs_pack_kxn_f16p16x1biasf16_f16_f16_neon();
285operators[i].matmul = create_matmul_clamp_f16_f16_f16p_neon();
286```
287
288## Build and run tests
289
290Tests are compiled via the main test targets. Use a filter to focus on matmul
291tests.
292
293CMake:
294
295```bash
296cmake -S . -B build
297cmake --build build
298build/kleidiai_test --gtest_filter='MatMulNext*'
299```
300
301Bazel:
302
303```bash
304bazelisk test //test:kleidiai_test --test_filter='MatMulNext*'
305```
306
307`MatMulNext` is deterministic by default because the test harness uses a fixed
308seed unless one is explicitly provided. When adding a new micro-kernel, do not
309stop at a single default-seed run; it is good practice to rerun the filtered
310tests with several explicit seeds to cover more generated shapes and values.
311
312Examples:
313
314```bash
315build/kleidiai_test --gtest_filter='MatMulNext*' --gtest_random_seed=<seed>
316bazelisk test //test:kleidiai_test --test_filter='MatMulNext*' --test_arg=--gtest_random_seed=<seed>
317```