• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <fp16/bitcasts.h>
15 
16 #include <xnnpack/requantization-stubs.h>
17 
18 
xnn_qu8_requantize_fp32__scalar_magic(size_t n,const int32_t * input,float scale,uint8_t zero_point,uint8_t qmin,uint8_t qmax,uint8_t * output)19 void xnn_qu8_requantize_fp32__scalar_magic(
20     size_t n,
21     const int32_t* input,
22     float scale,
23     uint8_t zero_point,
24     uint8_t qmin,
25     uint8_t qmax,
26     uint8_t* output)
27 {
28   assert(n % 4 == 0);
29   assert(scale < 1.0f);
30   assert(scale >= 0x1.0p-32f);
31 
32   const float fmin = (float) ((int32_t)(uint32_t) qmin - (int32_t)(uint32_t) zero_point);
33   const float fmax = (float) ((int32_t)(uint32_t) qmax - (int32_t)(uint32_t) zero_point);
34   const float fmagic = 12582912.0f;
35   const int32_t imagic = INT32_C(0x4B400000) - (int32_t)(uint32_t) zero_point;
36   for (; n != 0; n -= 4) {
37     const int32_t x = input[0];
38     const int32_t y = input[1];
39     const int32_t z = input[2];
40     const int32_t w = input[3];
41     input += 4;
42 
43     const float x_scaled = (float) x * scale;
44     const float y_scaled = (float) y * scale;
45     const float z_scaled = (float) z * scale;
46     const float w_scaled = (float) w * scale;
47 
48     const float x_clamped = x_scaled < fmin ? fmin : x_scaled > fmax ? fmax : x_scaled;
49     const float y_clamped = y_scaled < fmin ? fmin : y_scaled > fmax ? fmax : y_scaled;
50     const float z_clamped = z_scaled < fmin ? fmin : z_scaled > fmax ? fmax : z_scaled;
51     const float w_clamped = w_scaled < fmin ? fmin : w_scaled > fmax ? fmax : w_scaled;
52 
53     const int32_t x_biased = (int32_t) fp32_to_bits(x_clamped + fmagic) - imagic;
54     const int32_t y_biased = (int32_t) fp32_to_bits(y_clamped + fmagic) - imagic;
55     const int32_t z_biased = (int32_t) fp32_to_bits(z_clamped + fmagic) - imagic;
56     const int32_t w_biased = (int32_t) fp32_to_bits(w_clamped + fmagic) - imagic;
57 
58     output[0] = (uint8_t) x_biased;
59     output[1] = (uint8_t) y_biased;
60     output[2] = (uint8_t) z_biased;
61     output[3] = (uint8_t) w_biased;
62     output += 4;
63   }
64 }
65