You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

softmax.c 2.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. #include "nnacl/fp32/softmax.h"
  17. #include <math.h>
  18. #include <float.h>
  19. // output = exp(input) / reduce_sum(exp(input), axis)
  20. void Softmax(const float *input_ptr, float *output_ptr, float *sum_data, SoftmaxParameter *parameter) {
  21. int axis = parameter->axis_;
  22. int n_dim = parameter->n_dim_;
  23. int *input_shape = parameter->input_shape_;
  24. int inner_size = 1;
  25. int outter_size = 1;
  26. for (int i = 0; i < axis; i++) {
  27. outter_size *= input_shape[i];
  28. }
  29. for (int i = axis + 1; i < n_dim; i++) {
  30. inner_size *= input_shape[i];
  31. }
  32. for (int i = 0; i < outter_size; i++) {
  33. int outter_offset = i * input_shape[axis] * inner_size;
  34. int sum_outter_offset = i * inner_size;
  35. for (int k = 0; k < inner_size; k++) {
  36. int inner_offset = outter_offset + k;
  37. float max_data = input_ptr[inner_offset];
  38. for (int j = 0; j < input_shape[axis]; j++) {
  39. int axis_offset = inner_offset + j * inner_size;
  40. max_data = max_data > input_ptr[axis_offset] ? max_data : input_ptr[axis_offset];
  41. }
  42. for (int j = 0; j < input_shape[axis]; j++) {
  43. int axis_offset = inner_offset + j * inner_size;
  44. output_ptr[axis_offset] = exp(input_ptr[axis_offset] - max_data);
  45. sum_data[k + sum_outter_offset] += output_ptr[axis_offset];
  46. }
  47. }
  48. }
  49. for (int i = 0; i < outter_size; i++) {
  50. int outter_offset = i * input_shape[axis] * inner_size;
  51. int sum_outter_offset = i * inner_size;
  52. for (int j = 0; j < input_shape[axis]; j++) {
  53. int axis_offset = outter_offset + j * inner_size;
  54. for (int k = 0; k < inner_size; k++) {
  55. int inner_offset = axis_offset + k;
  56. output_ptr[inner_offset] = output_ptr[inner_offset] / sum_data[k + sum_outter_offset];
  57. }
  58. }
  59. }
  60. }