1 /**
2 * Copyright 2020 Huawei Technologies Co., Ltd
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "nnacl/int8/softmax_int8.h"
18 #include "nnacl/errorcode.h"
19
SoftmaxInt8(const int8_t * input_ptr,int8_t * output_ptr,int count,int * exp_data,int * sum_data,const SoftmaxQuantArg * quant_param,const SoftmaxParameter * parameter)20 int SoftmaxInt8(const int8_t *input_ptr, int8_t *output_ptr, int count, int *exp_data, int *sum_data,
21 const SoftmaxQuantArg *quant_param, const SoftmaxParameter *parameter) {
22 int32_t axis = parameter->axis_;
23 int n_dim = parameter->n_dim_;
24 const int *input_shape = parameter->input_shape_;
25 int axis_shape_size = input_shape[axis];
26
27 int inner_size = 1;
28 if (n_dim > DIMENSION_5D) {
29 return NNACL_ERR;
30 }
31 for (int i = axis + 1; i < n_dim; i++) {
32 inner_size *= input_shape[i];
33 }
34
35 for (int o = 0; o < count; o++) {
36 int outter_offset = o * axis_shape_size * inner_size;
37
38 for (int c = 0; c < inner_size; c++) {
39 int8_t max_row = quant_param->output_activation_min_;
40 for (int i = 0; i < axis_shape_size; ++i) {
41 int axis_offset = outter_offset + c + i * inner_size;
42 max_row = MSMAX(max_row, input_ptr[axis_offset]);
43 }
44
45 int32_t exp_sum = 0;
46 for (int i = 0; i < axis_shape_size; ++i) {
47 int axis_offset = outter_offset + c + i * inner_size;
48 const int32_t input_val = input_ptr[axis_offset] - max_row;
49 const int32_t input_scaled = SaturatingRoundingDoublingHighMul(
50 input_val * (1 << (unsigned int)quant_param->shift_left_), quant_param->output_multiplier_);
51 int exp_val = exp_on_negative_values(input_scaled, 5);
52 exp_data[axis_offset] = exp_val;
53 exp_sum = exp_sum + Rescale(exp_val, 0, 12);
54 }
55 sum_data[c] = exp_sum;
56 }
57 for (int i = 0; i < axis_shape_size; ++i) {
58 int axis_offset = outter_offset + i * inner_size;
59 for (int c = 0; c < inner_size; ++c) {
60 int num_bits_over_unit;
61 int shifted_scale = ComputerReciprocal(sum_data[c], 12, &num_bits_over_unit);
62 int unsat_output = RoundingDivideByPOT(
63 SaturatingRoundingDoublingHighMul(shifted_scale, exp_data[axis_offset + c]), num_bits_over_unit + 31 - 8);
64
65 int raw_output = unsat_output + quant_param->output_activation_min_;
66 output_ptr[axis_offset + c] =
67 (int8_t)MSMAX(quant_param->output_activation_min_, MSMIN(raw_output, quant_param->output_activation_max_));
68 }
69 }
70 }
71 return 0;
72 }
73