1 /*
2 * Copyright (C) 2010-2020 Arm Limited or its affiliates. All rights reserved.
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 *
6 * Licensed under the Apache License, Version 2.0 (the License); you may
7 * not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an AS IS BASIS, WITHOUT
14 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 /* ----------------------------------------------------------------------
20 * Project: CMSIS NN Library
21 * Title: arm_softmax_q7.c
22 * Description: Q7 softmax function
23 *
24 * $Date: 09. October 2020
25 * $Revision: V.1.0.2
26 *
27 * Target Processor: Cortex-M cores
28 *
29 * -------------------------------------------------------------------- */
30
31 #include "arm_nnfunctions.h"
32
33 /**
34 * @ingroup groupNN
35 */
36
37 /**
38 * @addtogroup Softmax
39 * @{
40 */
41
42 /**
43 * @brief Q7 softmax function
44 * @param[in] vec_in pointer to input vector
45 * @param[in] dim_vec input vector dimention
46 * @param[out] p_out pointer to output vector
47 *
48 * @details
49 *
50 * Here, instead of typical natural logarithm e based softmax, we use
51 * 2-based softmax here, i.e.,:
52 *
53 * y_i = 2^(x_i) / sum(2^x_j)
54 *
55 * The relative output will be different here.
56 * But mathematically, the gradient will be the same
57 * with a log(2) scaling factor.
58 *
59 */
60
arm_softmax_q7(const q7_t * vec_in,const uint16_t dim_vec,q7_t * p_out)61 void arm_softmax_q7(const q7_t *vec_in, const uint16_t dim_vec, q7_t *p_out)
62 {
63 q31_t sum;
64 int16_t i;
65 uint8_t shift;
66 q15_t base;
67 base = -128;
68
69 /* We first search for the maximum */
70 for (i = 0; i < dim_vec; i++)
71 {
72 if (vec_in[i] > base)
73 {
74 base = vec_in[i];
75 }
76 }
77
78 /*
79 * So the base is set to max-8, meaning
80 * that we ignore really small values.
81 * anyway, they will be 0 after shrinking to q7_t.
82 */
83 base = base - (1 << 3);
84
85 sum = 0;
86
87 for (i = 0; i < dim_vec; i++)
88 {
89 shift = (uint8_t)__USAT(vec_in[i] - base, 3);
90 sum += 0x1 << shift;
91 }
92
93 /* This is effectively (0x1 << 20) / sum */
94 int output_base = (1 << 20) / sum;
95
96 for (i = 0; i < dim_vec; i++)
97 {
98
99 /* Here minimum value of 13+base-vec_in[i] will be 5 */
100 shift = (uint8_t)__USAT(13 + base - vec_in[i], 5);
101 p_out[i] = (q7_t)__SSAT((output_base >> shift), 8);
102 }
103 }
104
105 /**
106 * @} end of Softmax group
107 */
108