xref: /aosp_15_r20/external/XNNPACK/src/qs8-requantization/fp32-scalar-lrintf.c (revision 4bdc94577ba0e567308109d787f7fec7b531ce36)
1 // Copyright (c) Facebook, Inc. and its affiliates.
2 // All rights reserved.
3 //
4 // Copyright 2019 Google LLC
5 //
6 // This source code is licensed under the BSD-style license found in the
7 // LICENSE file in the root directory of this source tree.
8 
9 #include <assert.h>
10 #include <math.h>
11 #include <stdint.h>
12 #include <stddef.h>
13 
14 #include <xnnpack/math.h>
15 #include <xnnpack/requantization-stubs.h>
16 
17 
xnn_qs8_requantize_fp32__scalar_lrintf(size_t n,const int32_t * input,float scale,int8_t zero_point,int8_t qmin,int8_t qmax,int8_t * output)18 void xnn_qs8_requantize_fp32__scalar_lrintf(
19     size_t n,
20     const int32_t* input,
21     float scale,
22     int8_t zero_point,
23     int8_t qmin,
24     int8_t qmax,
25     int8_t* output)
26 {
27   assert(n % 4 == 0);
28   assert(scale < 1.0f);
29   assert(scale >= 0x1.0p-32f);
30 
31   const float fmin = (float) ((int32_t) qmin - (int32_t) zero_point);
32   const float fmax = (float) ((int32_t) qmax - (int32_t) zero_point);
33   for (; n != 0; n -= 4) {
34     const int32_t x = input[0];
35     const int32_t y = input[1];
36     const int32_t z = input[2];
37     const int32_t w = input[3];
38     input += 4;
39 
40     const float x_scaled = (float) x * scale;
41     const float y_scaled = (float) y * scale;
42     const float z_scaled = (float) z * scale;
43     const float w_scaled = (float) w * scale;
44 
45     const float x_clamped = math_min_f32(math_max_f32(x_scaled, fmin), fmax);
46     const float y_clamped = math_min_f32(math_max_f32(y_scaled, fmin), fmax);
47     const float z_clamped = math_min_f32(math_max_f32(z_scaled, fmin), fmax);
48     const float w_clamped = math_min_f32(math_max_f32(w_scaled, fmin), fmax);
49 
50     const int32_t x_rounded = (int32_t) lrintf(x_clamped);
51     const int32_t y_rounded = (int32_t) lrintf(y_clamped);
52     const int32_t z_rounded = (int32_t) lrintf(z_clamped);
53     const int32_t w_rounded = (int32_t) lrintf(w_clamped);
54 
55     const int32_t x_biased = x_rounded + (int32_t) zero_point;
56     const int32_t y_biased = y_rounded + (int32_t) zero_point;
57     const int32_t z_biased = z_rounded + (int32_t) zero_point;
58     const int32_t w_biased = w_rounded + (int32_t) zero_point;
59 
60     output[0] = (int8_t) x_biased;
61     output[1] = (int8_t) y_biased;
62     output[2] = (int8_t) z_biased;
63     output[3] = (int8_t) w_biased;
64     output += 4;
65   }
66 }
67