Elffuss BraidHub

kikocis/kleidiai public

main · 20.9 KiBRawPermalink
1//
2// SPDX-FileCopyrightText: Copyright 2024-2026 Arm Limited and/or its affiliates <open-source-office@arm.com>
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6
7#include "test/reference/quantize.hpp"
8
9#include <algorithm>
10#include <cmath>
11#include <cstddef>
12#include <cstdint>
13#include <tuple>
14
15#include "test/common/bfloat16.hpp"
16#include "test/common/buffer.hpp"
17#include "test/common/int2.hpp"
18#include "test/common/int4.hpp"
19#include "test/common/memory.hpp"
20#include "test/common/numeric_limits.hpp"
21#include "test/common/round.hpp"
22#include "test/common/type_traits.hpp"
23#include "test/reference/cast.hpp"
24
25namespace kai::test {
26
27namespace {
28
29template <typename FloatData, typename IntData, typename ZeroPoint>
30std::tuple<FloatData, ZeroPoint> get_scale_zero_point_from_range(FloatData min_value, FloatData max_value) {
31 const FloatData q_min = numeric_lowest<IntData>;
32 const FloatData q_max = numeric_highest<IntData>;
33
34 if (min_value > 0) {
35 min_value = 0;
36 }
37
38 if (max_value < 0) {
39 max_value = 0;
40 }
41
42 // The reason for computing the inverted scale first is to make it bit-perfect with quantized packing
43 // micro-kernels. If those micro-kernels don't do it this way anymore, it makes more sense to calculate
44 // the scale directly.
45 const FloatData inv_scale = max_value != min_value ? (q_max - q_min) / (max_value - min_value) : 1.0F;
46 const FloatData scale = 1.0F / inv_scale;
47
48 const FloatData scaled_min = min_value / scale;
49 const FloatData scaled_max = max_value / scale;
50
51 const FloatData zero_point_f = -(scaled_min + q_min) < scaled_max + q_max ? scaled_min - q_min : scaled_max - q_max;
52 const ZeroPoint zero_point = -round_to_nearest_even<ZeroPoint>(zero_point_f);
53
54 return {scale, zero_point};
55}
56
57/// Quantized a float value to an integer datatype using a provided scale.
58///
59/// @tparam IntType Quantized integer datatype.
60///
61/// @param[in] float The value to quantize
62/// @param[in] scale The scale used to quantize the provided float value.
63///
64/// @return The quantized data matrix, the quantization scale matrix and the quantization zero point matrix.
65template <typename IntType>
66IntType quantize_symmetric(float value, float scale) {
67 const auto inv_scale = scale != 0 ? 1.0F / scale : 0.0F;
68 auto qsi32 = round_to_nearest_even_i32(value * inv_scale);
69
70 if (is_unsigned<IntType>) {
71 qsi32 += 1 << (size_in_bits<IntType> - 1);
72 }
73
74 return static_cast<IntType>(std::clamp<int32_t>(qsi32, numeric_lowest<IntType>, numeric_highest<IntType>));
75}
76
77/// Computes the quantization information using symmetric per-block quantization method.
78///
79/// The input matrix is divided into quantization blocks of the same size.
80///
81/// The height of the block does not affect the behavior of this function hence it is omitted
82/// from the function arguments and the figures below.
83///
84/// ```
85/// Quantization blocks -------+
86/// | |
87/// | |
88/// v v
89/// +-----------------+-----------------+----- ...
90/// | f00 f01 f02 f03 | f04 f05 f06 f07 | ........
91/// | f10 f11 f12 f13 | f14 f15 f16 f17 | ........
92/// | f20 f21 f22 f23 | f24 f25 f26 f27 | ........
93/// | f30 f31 f32 f33 | f34 f35 f36 f37 | ........
94/// | ............... | ............... | ........
95/// : ............... : ............... : ........
96/// ```
97///
98/// Each row of the quantization block is quantized individually.
99///
100/// ```
101/// Floating-point data Scale
102/// +-----------------+ +-----+
103/// | f00 f01 f02 f03 | -------> | s00 |
104/// | f10 f11 f12 f13 | -------> | s10 |
105/// | f20 f21 f22 f23 | -------> | s20 |
106/// | f30 f31 f32 f33 | -------> | s30 |
107/// | ............... | | ... |
108/// : ............... : : ... :
109/// ```
110///
111/// The computed quantization scale matrix:
112///
113/// ```
114/// +-----+-----+-- ...
115/// | s00 | s01 | .....
116/// | s10 | s11 | .....
117/// | s20 | s21 | .....
118/// | s30 | s31 | .....
119/// | ... | ... | .....
120/// : ... : ... : .....
121/// ```
122///
123/// @tparam SrcType The data type of the input data (must be floating-point).
124/// @tparam DstType The data type of the output data (must be integer).
125/// @tparam ScaleType The data type of the quantization scales (must be floating-point).
126///
127/// @param[in] src The input matrix.
128/// @param[in] height The number of rows.
129/// @param[in] width The number of columns.
130/// @param[in] quant_width The number of columns of the quantization block.
131///
132/// @return The quantization scale matrix.
133template <typename SrcType, typename DstType, typename ScaleType>
134Buffer compute_symmetric_per_block_quantization_info(const void* src, size_t height, size_t width, size_t quant_width) {
135 static_assert(is_floating_point<SrcType>);
136 static_assert(is_integral<DstType>);
137 static_assert(is_floating_point<ScaleType>);
138
139 KAI_ASSUME_ALWAYS(quant_width != 0);
140
141 const auto num_quant_packets_x = round_up_division(width, quant_width);
142
143 const auto scales_bytes = height * num_quant_packets_x * sizeof(ScaleType);
144 Buffer scales(scales_bytes);
145
146 const auto* src_ptr = reinterpret_cast<const SrcType*>(src);
147
148 for (size_t y = 0; y < height; ++y) {
149 for (size_t x_quant = 0; x_quant < width; x_quant += quant_width) {
150 // Computes the quantization scale.
151 SrcType max_abs = 0;
152
153 for (size_t x_element = 0; x_element < quant_width; ++x_element) {
154 const auto x = x_quant + x_element;
155
156 if (x < width) {
157 max_abs = std::max<SrcType>(max_abs, std::abs(src_ptr[y * width + x]));
158 }
159 }
160
161 const auto scale =
162 max_abs / static_cast<SrcType>((static_cast<uint64_t>(1) << (size_in_bits<DstType> - 1)) - 1);
163
164 // Stores the scales.
165 write_array<ScaleType>(scales.data(), y * num_quant_packets_x + x_quant / quant_width, scale);
166 }
167 }
168
169 return scales;
170}
171
172/// Dynamically quantizes each block of the matrix using symmetric quantization method.
173///
174/// The quantization information is calculated using
175/// @ref compute_symmetric_per_block_quantization_info function.
176/// The floating-point data is then quantized using
177/// @ref quantize_symmetric_per_block function.
178///
179/// To retain highest quantization accuracy, the data is quantized using the quantization scale
180/// with the same data type as the input data.
181/// After that the quantization scale can be stored in the buffer using `ScaleType` data type
182/// which might have lowest precision than the input data type.
183///
184/// @tparam SrcType The data type of the input data (must be floating-point).
185/// @tparam DstType The data type of the output data (must be integer).
186/// @tparam ScaleType The data type of the quantization scales (must be floating-point).
187///
188/// @param[in] src The input matrix.
189/// @param[in] height The number of rows.
190/// @param[in] width The number of columns.
191/// @param[in] quant_width The number of columns of the quantization block.
192///
193/// @return The quantized data matrix and the quantization scale matrix.
194template <typename SrcType, typename DstType, typename ScaleType>
195std::tuple<Buffer, Buffer> quantize_symmetric_per_block_dynamic(
196 const void* src, size_t height, size_t width, size_t quant_width) {
197 auto scales_src_type =
198 compute_symmetric_per_block_quantization_info<SrcType, DstType, SrcType>(src, height, width, quant_width);
199 auto data = quantize_symmetric_per_block<SrcType, DstType, SrcType>(
200 src, scales_src_type.data(), height, width, quant_width);
201
202 if constexpr (std::is_same_v<ScaleType, SrcType>) {
203 return {std::move(data), std::move(scales_src_type)};
204 } else {
205 auto scales =
206 cast<ScaleType, SrcType>(scales_src_type.data(), scales_src_type.size() * 8 / size_in_bits<SrcType>);
207
208 return {std::move(data), std::move(scales)};
209 }
210}
211
212/// Dynamically quantizes each block of the matrix using symmetric quantization method.
213///
214/// @param[in] src The input matrix.
215/// @param[in] src_type The data type of the input data (must be FP32).
216/// @param[in] height The number of rows.
217/// @param[in] width The number of columns.
218/// @param[in] qinfo The quantization information.
219///
220/// @return The quantized data matrix and the quantization scale matrix.
221std::tuple<Buffer, Buffer> quantize_symmetric_per_block_dynamic(
222 const void* src, DataType src_type, size_t height, size_t width, const QuantizationInfo& qinfo) {
223 // Fail fast for datatypes that must be fixed.
224 KAI_ASSUME_ALWAYS(src_type == DataType::FP32);
225
226 switch (qinfo.dst_type) {
227 case DataType::QSI2:
228 switch (qinfo.scale_type) {
229 case DataType::FP16:
230 return quantize_symmetric_per_block_dynamic<float, Int2, Float16>(
231 src, height, width, qinfo.quant_width);
232 case DataType::FP32:
233 return quantize_symmetric_per_block_dynamic<float, Int2, float>(
234 src, height, width, qinfo.quant_width);
235 default:
236 break;
237 }
238 break;
239 case DataType::QSI4:
240 switch (qinfo.scale_type) {
241 case DataType::FP16:
242 return quantize_symmetric_per_block_dynamic<float, Int4, Float16>(
243 src, height, width, qinfo.quant_width);
244 case DataType::FP32:
245 return quantize_symmetric_per_block_dynamic<float, Int4, float>(
246 src, height, width, qinfo.quant_width);
247 case DataType::BF16:
248 return quantize_symmetric_per_block_dynamic<float, Int4, BFloat16<>>(
249 src, height, width, qinfo.quant_width);
250 default:
251 break;
252 }
253 break;
254 case DataType::QSI8:
255 switch (qinfo.scale_type) {
256 case DataType::FP16:
257 return quantize_symmetric_per_block_dynamic<float, int8_t, Float16>(
258 src, height, width, qinfo.quant_width);
259 case DataType::FP32:
260 return quantize_symmetric_per_block_dynamic<float, int8_t, float>(
261 src, height, width, qinfo.quant_width);
262 default:
263 break;
264 }
265 break;
266 case DataType::I32:
267 if (qinfo.scale_type == DataType::FP32) {
268 return quantize_symmetric_per_block_dynamic<float, int32_t, float>(
269 src, height, width, qinfo.quant_width);
270 }
271 break;
272 default:
273 break;
274 }
275 KAI_ERROR("Unsupported combination of data types for symmetric quantization.");
276}
277
278/// Dynamically quantizes each block of the matrix using asymmetric quantization method.
279///
280/// The quantization information is calculated using
281/// @ref compute_asymmetric_per_block_quantization_info function.
282/// The floating-point data is then quantized using
283/// @ref quantize_asymmetric_per_block function.
284///
285/// To retain highest quantization accuracy, the data is quantized using the quantization scale
286/// with the same data type as the input data.
287/// After that the quantization scale can be stored in the buffer using `ScaleType` data type
288/// which might have lowest precision than the input data type.
289///
290/// @tparam SrcType The data type of the input data (must be floating-point).
291/// @tparam DstType The data type of the output data (must be integer).
292/// @tparam ScaleType The data type of the quantization scales (must be floating-point).
293/// @tparam ZeroPointType The data type of the quantization zero points (must be integer).
294///
295/// @param[in] src The input matrix.
296/// @param[in] height The number of rows.
297/// @param[in] width The number of columns.
298/// @param[in] quant_width The number of columns of the quantization block.
299///
300/// @return The quantized data matrix, the quantization scale matrix and the quantization zero point matrix.
301template <typename SrcType, typename DstType, typename ScaleType, typename ZeroPointType>
302std::tuple<Buffer, Buffer, Buffer> quantize_asymmetric_per_block_dynamic(
303 const void* src, size_t height, size_t width, size_t quant_width) {
304 /* Calculate the asymmetric quantization information, one scaling per row */
305 auto [scales_src_type, zero_points] =
306 compute_asymmetric_per_block_quantization_info<SrcType, DstType, SrcType, ZeroPointType>(
307 src, height, width, quant_width);
308
309 /* Do the actual quantization */
310 auto data = quantize_asymmetric_per_block<SrcType, DstType, SrcType, ZeroPointType>(
311 src, scales_src_type.data(), zero_points.data(), height, width, quant_width);
312
313 if constexpr (std::is_same_v<ScaleType, SrcType>) {
314 return {std::move(data), std::move(scales_src_type), std::move(zero_points)};
315 } else {
316 auto scales =
317 cast<ScaleType, SrcType>(scales_src_type.data(), scales_src_type.size() * 8 / size_in_bits<SrcType>);
318
319 return {std::move(data), std::move(scales), std::move(zero_points)};
320 }
321}
322
323/// Dynamically quantizes each block of the matrix using asymmetric quantization method.
324///
325/// @param[in] src The input matrix.
326/// @param[in] src_type The data type of the input data (must be FP32).
327/// @param[in] height The number of rows.
328/// @param[in] width The number of columns.
329/// @param[in] qinfo The quantization information.
330///
331/// @return The quantized data matrix, the quantization scale matrix and the quantization zero point matrix.
332std::tuple<Buffer, Buffer, Buffer> quantize_asymmetric_per_block_dynamic(
333 const void* src, DataType src_type, size_t height, size_t width, const QuantizationInfo& qinfo) {
334 // Fail fast for datatypes that must be fixed.
335 KAI_ASSUME_ALWAYS(src_type == DataType::FP32);
336 KAI_ASSUME_ALWAYS(qinfo.zero_point_type == DataType::I32);
337
338 switch (qinfo.dst_type) {
339 case DataType::QAI8:
340 switch (qinfo.scale_type) {
341 case DataType::FP32:
342 return quantize_asymmetric_per_block_dynamic<float, int8_t, float, int32_t>(
343 src, height, width, qinfo.quant_width);
344 case DataType::BF16:
345 return quantize_asymmetric_per_block_dynamic<float, int8_t, BFloat16<>, int32_t>(
346 src, height, width, qinfo.quant_width);
347 default:
348 break;
349 }
350 break;
351 case DataType::QAI4:
352 switch (qinfo.scale_type) {
353 case DataType::FP32:
354 return quantize_asymmetric_per_block_dynamic<float, Int4, float, int32_t>(
355 src, height, width, qinfo.quant_width);
356 default:
357 break;
358 }
359 break;
360 default:
361 break;
362 }
363 KAI_ERROR("Unsupported combination of destination/scale types for asymmetric quantization.");
364}
365
366} // namespace
367
368template <typename FloatType, typename IntType, typename ZeroPointType>
369IntType quantize_asymmetric(FloatType value, FloatType scale, ZeroPointType zero_point) {
370 const auto inv_scale = scale != 0 ? 1.0F / scale : 0.0F;
371 auto quantized_value = round_to_nearest_even<ZeroPointType>(value * inv_scale) + zero_point;
372 return static_cast<IntType>(
373 std::clamp<ZeroPointType>(quantized_value, numeric_lowest<IntType>, numeric_highest<IntType>));
374}
375
376template int8_t quantize_asymmetric(float value, float scale, int32_t zero_point);
377
378template <typename SrcType, typename DstType, typename ScaleType>
379Buffer quantize_symmetric_per_block(
380 const void* src, const void* scales, size_t height, size_t width, size_t quant_width) {
381 static_assert(is_floating_point<SrcType>);
382 static_assert(is_integral<DstType>);
383 static_assert(is_floating_point<ScaleType>);
384
385 const auto num_quant_packets_x = round_up_division(width, quant_width);
386
387 const auto data_bytes = round_up_division(height * width * size_in_bits<DstType>, 8);
388 Buffer data(data_bytes);
389
390 const auto* src_ptr = reinterpret_cast<const SrcType*>(src);
391
392 for (size_t y = 0; y < height; ++y) {
393 for (size_t x_quant = 0; x_quant < width; x_quant += quant_width) {
394 const auto scale = read_array<ScaleType>(scales, y * num_quant_packets_x + x_quant / quant_width);
395
396 // Quantizes and stores the data.
397 for (size_t x_element = 0; x_element < quant_width; ++x_element) {
398 const auto x = x_quant + x_element;
399
400 if (x < width) {
401 const auto quantized = quantize_symmetric<DstType>(src_ptr[y * width + x], scale);
402 write_array(data.data(), y * width + x, quantized);
403 }
404 }
405 }
406 }
407 return data;
408}
409
410template Buffer quantize_symmetric_per_block<float, int32_t, float>(
411 const void* src, const void* scales, size_t height, size_t width, size_t quant_width);
412
413template <typename SrcType, typename DstType, typename ScaleType, typename ZeroPointType>
414std::tuple<Buffer, Buffer> compute_asymmetric_per_block_quantization_info(
415 const void* src, size_t height, size_t width, size_t quant_width) {
416 static_assert(is_floating_point<SrcType>);
417 static_assert(is_integral<DstType>);
418 static_assert(is_floating_point<ScaleType>);
419 static_assert(is_integral<ZeroPointType>);
420
421 KAI_ASSUME_ALWAYS(quant_width != 0);
422
423 const auto num_quant_packets_x = round_up_division(width, quant_width);
424
425 const auto scales_bytes = height * num_quant_packets_x * sizeof(ScaleType);
426 Buffer scales(scales_bytes);
427
428 const auto zero_points_bytes = height * num_quant_packets_x * sizeof(ZeroPointType);
429 Buffer zero_points(zero_points_bytes);
430
431 for (size_t y = 0; y < height; ++y) {
432 for (size_t x_quant = 0; x_quant < width; x_quant += quant_width) {
433 // Computes the quantization scale and zero point.
434 auto min_value = numeric_highest<SrcType>;
435 auto max_value = numeric_lowest<SrcType>;
436
437 for (size_t x_element = 0; x_element < quant_width; ++x_element) {
438 const auto x = x_quant + x_element;
439
440 if (x < width) {
441 const auto value = read_array<SrcType>(src, y * width + x);
442
443 min_value = std::min(min_value, value);
444 max_value = std::max(max_value, value);
445 }
446 }
447
448 const auto [scale, zero_point] =
449 get_scale_zero_point_from_range<SrcType, DstType, ZeroPointType>(min_value, max_value);
450
451 // Stores the scale and zero point.
452 write_array<ScaleType>(scales.data(), y * num_quant_packets_x + x_quant / quant_width, scale);
453 write_array<ZeroPointType>(zero_points.data(), y * num_quant_packets_x + x_quant / quant_width, zero_point);
454 }
455 }
456
457 return {std::move(scales), std::move(zero_points)};
458}
459
460template <typename SrcType, typename DstType, typename ScaleType, typename ZeroPointType>
461Buffer quantize_asymmetric_per_block(
462 const void* src, const void* scales, const void* zero_points, size_t height, size_t width, size_t quant_width) {
463 static_assert(is_floating_point<SrcType>);
464 static_assert(is_integral<DstType>);
465 static_assert(is_floating_point<ScaleType>);
466 static_assert(is_integral<ZeroPointType>);
467
468 const auto num_quant_packets_x = round_up_division(width, quant_width);
469
470 const auto data_bytes = round_up_division(height * width * size_in_bits<DstType>, 8);
471 Buffer data(data_bytes);
472
473 for (size_t y = 0; y < height; ++y) {
474 for (size_t x_quant = 0; x_quant < width; x_quant += quant_width) {
475 const auto scale = read_array<ScaleType>(scales, y * num_quant_packets_x + x_quant / quant_width);
476 const auto zero_point =
477 read_array<ZeroPointType>(zero_points, y * num_quant_packets_x + x_quant / quant_width);
478
479 // Quantizes and stores the data.
480 for (size_t x_element = 0; x_element < quant_width; ++x_element) {
481 const auto x = x_quant + x_element;
482
483 if (x < width) {
484 const auto value_f = read_array<SrcType>(src, y * width + x);
485 const auto value_q =
486 quantize_asymmetric<SrcType, DstType, ZeroPointType>(value_f, scale, zero_point);
487
488 write_array<DstType>(data.data(), y * width + x, value_q);
489 }
490 }
491 }
492 }
493
494 return data;
495}
496
497std::tuple<Buffer, QuantizationOutputs> quantize_dynamic(
498 const void* src, DataType src_type, size_t height, size_t width, const QuantizationInfo& qinfo) {
499 KAI_ASSUME_ALWAYS(data_type_is_quantized(qinfo.dst_type));
500 Buffer data;
501 QuantizationOutputs qoutputs;
502 if (data_type_is_quantized_asymm(qinfo.dst_type)) {
503 KAI_ASSUME_ALWAYS(qinfo.zero_point_type != DataType::UNKNOWN);
504 std::tie(data, qoutputs.scales, qoutputs.zero_points) =
505 quantize_asymmetric_per_block_dynamic(src, src_type, height, width, qinfo);
506 } else {
507 std::tie(data, qoutputs.scales) = quantize_symmetric_per_block_dynamic(src, src_type, height, width, qinfo);
508 }
509 return {std::move(data), std::move(qoutputs)};
510}
511} // namespace kai::test