Softmax.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. /*
  2. * Copyright (C) 2019 The Android Open Source Project
  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 "CpuOperationUtils.h"
  17. #include "OperationResolver.h"
  18. #include "tensorflow/lite/kernels/internal/optimized/legacy_optimized_ops.h"
  19. #include "tensorflow/lite/kernels/internal/optimized/optimized_ops.h"
  20. #include "Tracing.h"
  21. namespace android {
  22. namespace nn {
  23. namespace softmax {
  24. constexpr char kOperationName[] = "SOFTMAX";
  25. constexpr uint32_t kNumInputs = 3;
  26. constexpr uint32_t kInputTensor = 0;
  27. constexpr uint32_t kBetaScalar = 1;
  28. constexpr uint32_t kAxisScalar = 2;
  29. constexpr uint32_t kNumOutputs = 1;
  30. constexpr uint32_t kOutputTensor = 0;
  31. namespace {
  32. inline bool softmaxSlowFloat32(const float* inputData, const Shape& inputShape, const float beta,
  33. int32_t axis, float* outputData, const Shape& outputShape) {
  34. NNTRACE_TRANS("softmaxFloatSlow32");
  35. const uint32_t outerSize = getNumberOfElements(inputShape, 0, axis);
  36. const uint32_t axisSize = getSizeOfDimension(inputShape, axis);
  37. const uint32_t innerSize =
  38. getNumberOfElements(inputShape, axis + 1, getNumberOfDimensions(inputShape));
  39. for (uint32_t outer = 0; outer < outerSize; ++outer) {
  40. const float* inputBeg = inputData + outer * axisSize * innerSize;
  41. const float* inputEnd = inputBeg + axisSize * innerSize;
  42. float* outputBeg = outputData + outer * axisSize * innerSize;
  43. for (uint32_t inner = 0; inner < innerSize; ++inner, ++inputBeg, ++inputEnd, ++outputBeg) {
  44. // Find max
  45. float maxValue = -FLT_MAX;
  46. for (const float* p = inputBeg; p < inputEnd; p += innerSize) {
  47. maxValue = std::max(maxValue, *p);
  48. }
  49. // Compute sum
  50. float sum = 0.0f;
  51. for (const float* p = inputBeg; p < inputEnd; p += innerSize) {
  52. sum += std::exp((*p - maxValue) * beta);
  53. }
  54. // Compute result
  55. float* pOut = outputBeg;
  56. for (const float* p = inputBeg; p < inputEnd; p += innerSize, pOut += innerSize) {
  57. *pOut = std::exp((*p - maxValue) * beta) / sum;
  58. }
  59. }
  60. }
  61. return true;
  62. }
  63. bool softmaxFloat32(const float* inputData, const Shape& inputShape, const float beta, int32_t axis,
  64. float* outputData, const Shape& outputShape) {
  65. int32_t ndim = getNumberOfDimensions(inputShape);
  66. NN_CHECK(handleNegativeAxis(inputShape, &axis));
  67. // TFLite optimized implementation only supports computation along the last axis
  68. if (axis == ndim - 1) {
  69. NNTRACE_COMP("optimized_ops::Softmax::float");
  70. tflite::SoftmaxParams param = {.beta = beta};
  71. tflite::optimized_ops::Softmax(param, convertShapeToTflshape(inputShape), inputData,
  72. convertShapeToTflshape(outputShape), outputData);
  73. return true;
  74. } else {
  75. return softmaxSlowFloat32(inputData, inputShape, beta, axis, outputData, outputShape);
  76. }
  77. }
  78. bool softmaxFloat16(const _Float16* inputData, const Shape& inputShape, const float beta,
  79. int32_t axis, _Float16* outputData, const Shape& outputShape) {
  80. NNTRACE_TRANS("softmaxFloat16");
  81. std::vector<float> inputData_float32(getNumberOfElements(inputShape));
  82. convertFloat16ToFloat32(inputData, &inputData_float32);
  83. std::vector<float> outputData_float32(getNumberOfElements(outputShape));
  84. softmaxFloat32(inputData_float32.data(), inputShape, beta, axis, outputData_float32.data(),
  85. outputShape);
  86. convertFloat32ToFloat16(outputData_float32, outputData);
  87. return true;
  88. }
  89. bool softmaxQuant8Impl(const uint8_t* inputData, const Shape& inputShape, const float beta,
  90. int32_t axis, int32_t inputMultiplier, int32_t inputLeftShift, float diffMin,
  91. uint8_t* outputData, const Shape& outputShape) {
  92. NNTRACE_TRANS("softmaxQuant8");
  93. // The representation chosen for the input to the exp() function is Q5.26.
  94. // We need to leave extra space since values that we skip might be as large as
  95. // -32 before multiplying by input_beta_multiplier, and therefore as large as
  96. // -16 afterwards. Note that exp(-8) is definitely not insignificant to
  97. // accumulation, but exp(-16) definitely is.
  98. static const int32_t kScaledDiffIntegerBits = 5;
  99. static const int kAccumulationIntegerBits = 12;
  100. using FixedPointScaledDiff = gemmlowp::FixedPoint<int32_t, kScaledDiffIntegerBits>;
  101. using FixedPointAccum = gemmlowp::FixedPoint<int32_t, kAccumulationIntegerBits>;
  102. using FixedPoint0 = gemmlowp::FixedPoint<int32_t, 0>;
  103. const uint32_t outerSize = getNumberOfElements(inputShape, 0, axis);
  104. const uint32_t axisSize = getSizeOfDimension(inputShape, axis);
  105. const uint32_t innerSize =
  106. getNumberOfElements(inputShape, axis + 1, getNumberOfDimensions(inputShape));
  107. for (uint32_t outer = 0; outer < outerSize; ++outer) {
  108. const uint8_t* inputBeg = inputData + outer * axisSize * innerSize;
  109. const uint8_t* inputEnd = inputBeg + axisSize * innerSize;
  110. uint8_t* outputBeg = outputData + outer * axisSize * innerSize;
  111. for (uint32_t inner = 0; inner < innerSize; ++inner, ++inputBeg, ++inputEnd, ++outputBeg) {
  112. // Find max
  113. uint8_t maxValue = 0;
  114. for (const uint8_t* p = inputBeg; p < inputEnd; p += innerSize) {
  115. maxValue = std::max(maxValue, *p);
  116. }
  117. // Compute sum
  118. FixedPointAccum sum_of_exps = FixedPointAccum::Zero();
  119. for (const uint8_t* p = inputBeg; p < inputEnd; p += innerSize) {
  120. int32_t input_diff = static_cast<int32_t>(*p) - maxValue;
  121. if (input_diff >= diffMin) {
  122. const int32_t input_diff_rescaled =
  123. tflite::MultiplyByQuantizedMultiplierGreaterThanOne(
  124. input_diff, inputMultiplier, inputLeftShift);
  125. const auto scaled_diff_f8 = FixedPointScaledDiff::FromRaw(input_diff_rescaled);
  126. sum_of_exps = sum_of_exps + gemmlowp::Rescale<kAccumulationIntegerBits>(
  127. exp_on_negative_values(scaled_diff_f8));
  128. }
  129. }
  130. uint32_t fixed_sum_of_exps = static_cast<uint32_t>(sum_of_exps.raw());
  131. int32_t headroom_plus_one = tflite::CountLeadingZeros(fixed_sum_of_exps);
  132. // This is the number of bits to the left of the binary point above 1.0.
  133. // Consider fixed_sum_of_exps=1.25. In that case shifted_scale=0.8 and
  134. // no later adjustment will be needed.
  135. int32_t num_bits_over_unit = kAccumulationIntegerBits - headroom_plus_one;
  136. int32_t shifted_sum_minus_one = static_cast<int32_t>(
  137. (fixed_sum_of_exps << headroom_plus_one) - (static_cast<uint32_t>(1) << 31));
  138. FixedPoint0 shifted_scale = gemmlowp::one_over_one_plus_x_for_x_in_0_1(
  139. FixedPoint0::FromRaw(shifted_sum_minus_one));
  140. // Compute result
  141. uint8_t* pOut = outputBeg;
  142. for (const uint8_t* p = inputBeg; p < inputEnd; p += innerSize, pOut += innerSize) {
  143. int32_t input_diff = static_cast<int32_t>(*p) - maxValue;
  144. if (input_diff >= diffMin) {
  145. const int32_t input_diff_rescaled =
  146. tflite::MultiplyByQuantizedMultiplierGreaterThanOne(
  147. input_diff, inputMultiplier, inputLeftShift);
  148. const auto scaled_diff_f8 = FixedPointScaledDiff::FromRaw(input_diff_rescaled);
  149. FixedPoint0 exp_in_0 = exp_on_negative_values(scaled_diff_f8);
  150. int32_t unsat_output = gemmlowp::RoundingDivideByPOT(
  151. (shifted_scale * exp_in_0).raw(), num_bits_over_unit + 31 - 8);
  152. *pOut = static_cast<uint8_t>(
  153. std::max(std::min(unsat_output, static_cast<int32_t>(255)), 0));
  154. } else {
  155. *pOut = 0;
  156. }
  157. }
  158. }
  159. }
  160. return true;
  161. }
  162. bool softmaxQuant8(const uint8_t* inputData, const Shape& inputShape, const float beta,
  163. int32_t axis, uint8_t* outputData, const Shape& outputShape) {
  164. int32_t ndim = getNumberOfDimensions(inputShape);
  165. NN_CHECK(handleNegativeAxis(inputShape, &axis));
  166. if (outputShape.offset != 0 || outputShape.scale != 1.f / 256) {
  167. LOG(ERROR) << "incorrect scale / offset for output";
  168. return false;
  169. }
  170. static const int32_t kScaledDiffIntegerBits = 5;
  171. const double input_beta_real_multiplier =
  172. std::min(1.0 * beta * inputShape.scale * (1 << (31 - kScaledDiffIntegerBits)),
  173. (1LL << 31) - 1.0);
  174. int32_t inputMultiplier = 0, inputLeftShift = 0;
  175. if (!QuantizeMultiplierGreaterThanOne(input_beta_real_multiplier, &inputMultiplier,
  176. &inputLeftShift)) {
  177. return false;
  178. }
  179. int32_t diffMin = -CalculateInputRadius(kScaledDiffIntegerBits, inputLeftShift);
  180. // TFLite optimized implementation only supports computation along the last axis
  181. if (axis == ndim - 1) {
  182. NNTRACE_COMP("optimized_ops::Softmax::uint8");
  183. tflite::SoftmaxParams param = {.beta = beta,
  184. .input_multiplier = inputMultiplier,
  185. .input_left_shift = inputLeftShift,
  186. .diff_min = diffMin};
  187. tflite::optimized_ops::Softmax(param, convertShapeToTflshape(inputShape), inputData,
  188. convertShapeToTflshape(outputShape), outputData);
  189. return true;
  190. } else {
  191. return softmaxQuant8Impl(inputData, inputShape, beta, axis, inputMultiplier, inputLeftShift,
  192. diffMin, outputData, outputShape);
  193. }
  194. }
  195. } // namespace
  196. bool validate(const IOperationValidationContext* context) {
  197. NN_RET_CHECK(context->getNumInputs() == kNumInputs ||
  198. context->getNumInputs() == kNumInputs - 1);
  199. NN_RET_CHECK_EQ(context->getNumOutputs(), kNumOutputs);
  200. auto inputType = context->getInputType(kInputTensor);
  201. std::vector<OperandType> inExpectedTypes;
  202. if (inputType == OperandType::TENSOR_FLOAT32 || inputType == OperandType::TENSOR_QUANT8_ASYMM) {
  203. NN_RET_CHECK(validateHalVersion(context, HalVersion::V1_0));
  204. inExpectedTypes = {inputType, OperandType::FLOAT32};
  205. } else if (inputType == OperandType::TENSOR_FLOAT16) {
  206. NN_RET_CHECK(validateHalVersion(context, HalVersion::V1_2));
  207. inExpectedTypes = {inputType, OperandType::FLOAT16};
  208. } else {
  209. NN_RET_CHECK_FAIL() << "Unsupported tensor type for operation " << kOperationName;
  210. }
  211. if (context->getNumInputs() == kNumInputs) {
  212. NN_RET_CHECK(validateHalVersion(context, HalVersion::V1_2));
  213. inExpectedTypes.push_back(OperandType::INT32);
  214. } else {
  215. const size_t ndim = context->getInputShape(kInputTensor).dimensions.size();
  216. if (ndim != 2 && ndim != 4 && ndim != 0) {
  217. NN_RET_CHECK(validateHalVersion(context, HalVersion::V1_2));
  218. }
  219. }
  220. return validateInputTypes(context, inExpectedTypes) &&
  221. validateOutputTypes(context, {inputType});
  222. }
  223. bool prepare(IOperationExecutionContext* context) {
  224. Shape input = context->getInputShape(kInputTensor);
  225. float beta = (input.type == OperandType::TENSOR_FLOAT16)
  226. ? context->getInputValue<_Float16>(kBetaScalar)
  227. : context->getInputValue<float>(kBetaScalar);
  228. NN_RET_CHECK_LE(getNumberOfDimensions(input), 4);
  229. NN_RET_CHECK_GT(beta, 0.0f);
  230. Shape output = context->getOutputShape(kOutputTensor);
  231. output.dimensions = input.dimensions;
  232. return context->setOutputShape(kOutputTensor, output);
  233. }
  234. bool execute(IOperationExecutionContext* context) {
  235. // Bypass execution in the case of zero-sized input.
  236. if (getNumberOfElements(context->getOutputShape(kOutputTensor)) == 0) return true;
  237. int32_t axis = (context->getNumInputs() == kNumInputs)
  238. ? context->getInputValue<int32_t>(kAxisScalar)
  239. : -1;
  240. switch (context->getInputType(kInputTensor)) {
  241. case OperandType::TENSOR_FLOAT16:
  242. return softmaxFloat16(context->getInputBuffer<_Float16>(kInputTensor),
  243. context->getInputShape(kInputTensor),
  244. context->getInputValue<_Float16>(kBetaScalar), axis,
  245. context->getOutputBuffer<_Float16>(kOutputTensor),
  246. context->getOutputShape(kOutputTensor));
  247. case OperandType::TENSOR_FLOAT32:
  248. return softmaxFloat32(context->getInputBuffer<float>(kInputTensor),
  249. context->getInputShape(kInputTensor),
  250. context->getInputValue<float>(kBetaScalar), axis,
  251. context->getOutputBuffer<float>(kOutputTensor),
  252. context->getOutputShape(kOutputTensor));
  253. case OperandType::TENSOR_QUANT8_ASYMM:
  254. return softmaxQuant8(context->getInputBuffer<uint8_t>(kInputTensor),
  255. context->getInputShape(kInputTensor),
  256. context->getInputValue<float>(kBetaScalar), axis,
  257. context->getOutputBuffer<uint8_t>(kOutputTensor),
  258. context->getOutputShape(kOutputTensor));
  259. default:
  260. NN_RET_CHECK_FAIL() << "Unsupported tensor type for operation " << kOperationName;
  261. }
  262. }
  263. } // namespace softmax
  264. NN_REGISTER_OPERATION(SOFTMAX, "SOFTMAX", softmax::validate, softmax::prepare, softmax::execute,
  265. .allowZeroSizedInput = true);
  266. } // namespace nn
  267. } // namespace android