micro_utils.h 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. ==============================================================================*/
  12. #ifndef TENSORFLOW_LITE_MICRO_MICRO_UTILS_H_
  13. #define TENSORFLOW_LITE_MICRO_MICRO_UTILS_H_
  14. #include <algorithm>
  15. #include <cmath>
  16. #include <cstdint>
  17. #include <limits>
  18. #include "tensorflow/lite/c/common.h"
  19. namespace tflite {
  20. // Returns number of elements in the shape array.
  21. int ElementCount(const TfLiteIntArray& dims);
  22. size_t EvalTensorBytes(const TfLiteEvalTensor* tensor);
  23. // C++11 does not support constexpr max; hence, use ternary conditional to
  24. // create our own constexpr Max function.
  25. constexpr int Max(int a, int b) { return a >= b ? a : b; }
  26. // Converts a float value into a quantized value. Note that large values (close
  27. // to max int and min int) may see significant error due to a lack of floating
  28. // point granularity for large values.
  29. template <typename T>
  30. T FloatToQuantizedType(const float value, const float scale, int zero_point) {
  31. int32_t result = round(value / scale) + zero_point;
  32. result =
  33. std::max(static_cast<int32_t>(std::numeric_limits<T>::min()), result);
  34. result =
  35. std::min(static_cast<int32_t>(std::numeric_limits<T>::max()), result);
  36. return result;
  37. }
  38. template <typename T>
  39. T FloatToSymmetricQuantizedType(const float value, const float scale) {
  40. // 64-bit values are required since 8x16 conv accumulates to int64, meaning
  41. // an int64 bias is required.
  42. std::int64_t result = round(value / scale);
  43. result = std::max(
  44. static_cast<std::int64_t>(std::numeric_limits<T>::min() + 1), result);
  45. result = std::min(static_cast<std::int64_t>(std::numeric_limits<T>::max()),
  46. result);
  47. return result;
  48. }
  49. // Helper methods to quantize arrays of floats to the desired format.
  50. //
  51. // There are several key flavors of quantization in TfLite:
  52. // asymmetric symmetric per channel
  53. // int8_t | X | X | X |
  54. // uint8_t | X | X | |
  55. // int16_t | X | | |
  56. // int32_t | | X | X |
  57. //
  58. // The per-op quantization spec can be found here:
  59. // https://www.tensorflow.org/lite/performance/quantization_spec
  60. template <typename T>
  61. void Quantize(const float* input, T* output, int num_elements, float scale,
  62. int zero_point) {
  63. for (int i = 0; i < num_elements; i++) {
  64. output[i] = FloatToQuantizedType<T>(input[i], scale, zero_point);
  65. }
  66. }
  67. template <typename T>
  68. void SymmetricQuantize(const float* input, T* output, int num_elements,
  69. float scale) {
  70. for (int i = 0; i < num_elements; i++) {
  71. output[i] = FloatToSymmetricQuantizedType<T>(input[i], scale);
  72. }
  73. }
  74. template <typename T>
  75. void SymmetricPerChannelQuantize(const float* input, T* output,
  76. int num_elements, int num_channels,
  77. float* scales) {
  78. int elements_per_channel = num_elements / num_channels;
  79. for (int i = 0; i < num_channels; i++) {
  80. for (int j = 0; j < elements_per_channel; j++) {
  81. output[i * elements_per_channel + j] = FloatToSymmetricQuantizedType<T>(
  82. input[i * elements_per_channel + j], scales[i]);
  83. }
  84. }
  85. }
  86. void SignedSymmetricPerChannelQuantize(const float* values,
  87. TfLiteIntArray* dims,
  88. int quantized_dimension,
  89. int8_t* quantized_values,
  90. float* scaling_factor);
  91. // Quantizes inputs based on the values provided, choosing the smallest range
  92. // which includes all input values.
  93. template <typename T>
  94. void SymmetricQuantizeCalculateScales(const float* values, TfLiteIntArray* dims,
  95. T* output, float* scale) {
  96. int input_size = ElementCount(*dims);
  97. float min = 0;
  98. float max = 0;
  99. for (int i = 0; i < input_size; i++) {
  100. min = fminf(min, values[i]);
  101. max = fmaxf(max, values[i]);
  102. }
  103. *scale = fmaxf(std::abs(min), std::abs(max)) / std::numeric_limits<T>::max();
  104. for (int i = 0; i < input_size; i++) {
  105. const int32_t quantized_value =
  106. static_cast<int32_t>(roundf(values[i] / *scale));
  107. // Clamp: just in case some odd numeric offset.
  108. quantized_value = fminf(std::numeric_limits<T>::max(), quantized_value);
  109. quantized_value = fmaxf(std::numeric_limits<T>::min() + 1, quantized_value);
  110. output[i] = quantized_value;
  111. }
  112. }
  113. template <typename T>
  114. void Dequantize(const T* values, const int size, const float scale,
  115. int zero_point, float* dequantized_values) {
  116. for (int i = 0; i < size; ++i) {
  117. dequantized_values[i] = (values[i] - zero_point) * scale;
  118. }
  119. }
  120. } // namespace tflite
  121. #endif // TENSORFLOW_LITE_MICRO_MICRO_UTILS_H_