kernel_util.h 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. /* Copyright 2017 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_KERNELS_KERNEL_UTIL_H_
  13. #define TENSORFLOW_LITE_KERNELS_KERNEL_UTIL_H_
  14. #include <algorithm>
  15. #include <limits>
  16. #include "flatbuffers/flatbuffers.h"
  17. #include "tensorflow/lite/c/builtin_op_data.h"
  18. #include "tensorflow/lite/c/common.h"
  19. namespace tflite {
  20. inline int NumDimensions(const TfLiteTensor* t) { return t->dims->size; }
  21. inline int SizeOfDimension(const TfLiteTensor* t, int dim) {
  22. return t->dims->data[dim];
  23. }
  24. inline const TfLiteTensor* GetInput(const TfLiteContext* context,
  25. const TfLiteNode* node, int index) {
  26. return &context->tensors[node->inputs->data[index]];
  27. }
  28. // Note: You must check if result is not null:
  29. // TfLiteTensor* my_tensor = GetVariableInput(context, node, kMyTensorIdx);
  30. // TF_LITE_ENSURE(context, my_tensor != nullptr);
  31. inline TfLiteTensor* GetVariableInput(TfLiteContext* context,
  32. const TfLiteNode* node, int index) {
  33. TfLiteTensor* tensor = &context->tensors[node->inputs->data[index]];
  34. return (tensor->is_variable) ? tensor : nullptr;
  35. }
  36. inline TfLiteTensor* GetOutput(TfLiteContext* context, const TfLiteNode* node,
  37. int index) {
  38. return &context->tensors[node->outputs->data[index]];
  39. }
  40. inline TfLiteTensor* GetTemporary(TfLiteContext* context,
  41. const TfLiteNode* node, int index) {
  42. return &context->tensors[node->temporaries->data[index]];
  43. }
  44. inline const TfLiteTensor* GetIntermediates(TfLiteContext* context,
  45. const TfLiteNode* node, int index) {
  46. return &context->tensors[node->intermediates->data[index]];
  47. }
  48. inline int NumInputs(const TfLiteNode* node) { return node->inputs->size; }
  49. inline int NumOutputs(const TfLiteNode* node) { return node->outputs->size; }
  50. inline int NumIntermediates(const TfLiteNode* node) {
  51. return node->intermediates->size;
  52. }
  53. inline int64_t NumElements(const TfLiteIntArray* dims) {
  54. int64_t count = 1;
  55. for (int i = 0; i < dims->size; ++i) {
  56. count *= dims->data[i];
  57. }
  58. return count;
  59. }
  60. inline int64_t NumElements(const TfLiteTensor* t) {
  61. return NumElements(t->dims);
  62. }
  63. inline const TfLiteTensor* GetOptionalInputTensor(TfLiteContext* context,
  64. const TfLiteNode* node,
  65. int index) {
  66. const bool use_tensor = index < node->inputs->size &&
  67. node->inputs->data[index] != kTfLiteOptionalTensor;
  68. if (use_tensor) {
  69. return &context->tensors[node->inputs->data[index]];
  70. }
  71. return nullptr;
  72. }
  73. // Determines whether tensor is constant.
  74. // TODO(b/138199592): Introduce new query which checks for constant OR
  75. // persistent-read-only, which would be useful for most tensor kernels that
  76. // are potentially dynamic based on the input tensor value availability at the
  77. // time of prepare.
  78. inline bool IsConstantTensor(const TfLiteTensor* tensor) {
  79. return tensor->allocation_type == kTfLiteMmapRo;
  80. }
  81. // Determines whether tensor is dynamic. Note that a tensor can be non-const and
  82. // not dynamic. This function specifically checks for a dynamic tensor.
  83. inline bool IsDynamicTensor(const TfLiteTensor* tensor) {
  84. return tensor->allocation_type == kTfLiteDynamic;
  85. }
  86. // Sets tensor to dynamic.
  87. inline void SetTensorToDynamic(TfLiteTensor* tensor) {
  88. if (tensor->allocation_type != kTfLiteDynamic) {
  89. tensor->allocation_type = kTfLiteDynamic;
  90. tensor->data.raw = nullptr;
  91. }
  92. }
  93. // Sets tensor to persistent and read-only.
  94. inline void SetTensorToPersistentRo(TfLiteTensor* tensor) {
  95. if (tensor->allocation_type != kTfLitePersistentRo) {
  96. tensor->allocation_type = kTfLitePersistentRo;
  97. tensor->data.raw = nullptr;
  98. }
  99. }
  100. // Determines whether it is a hybrid op - one that has float inputs and
  101. // quantized weights.
  102. inline bool IsHybridOp(const TfLiteTensor* input, const TfLiteTensor* weight) {
  103. return ((weight->type == kTfLiteUInt8 || weight->type == kTfLiteInt8) &&
  104. input->type == kTfLiteFloat32);
  105. }
  106. // Check dimensionality match and populate OpData for Conv and DepthwiseConv.
  107. TfLiteStatus PopulateConvolutionQuantizationParams(
  108. TfLiteContext* context, const TfLiteTensor* input,
  109. const TfLiteTensor* filter, const TfLiteTensor* bias, TfLiteTensor* output,
  110. const TfLiteFusedActivation& activation, int32_t* multiplier, int* shift,
  111. int32_t* output_activation_min, int32_t* output_activation_max,
  112. int32_t* per_channel_multiplier, int* per_channel_shift);
  113. TfLiteStatus PopulateConvolutionQuantizationParams(
  114. TfLiteContext* context, const TfLiteTensor* input,
  115. const TfLiteTensor* filter, const TfLiteTensor* bias, TfLiteTensor* output,
  116. const TfLiteFusedActivation& activation, int32_t* multiplier, int* shift,
  117. int32_t* output_activation_min, int32_t* output_activation_max,
  118. int32_t* per_channel_multiplier, int* per_channel_shift, int num_channels);
  119. // Calculates the multiplication factor for a quantized convolution (or
  120. // quantized depthwise convolution) involving the given tensors. Returns an
  121. // error if the scales of the tensors are not compatible.
  122. TfLiteStatus GetQuantizedConvolutionMultipler(TfLiteContext* context,
  123. const TfLiteTensor* input,
  124. const TfLiteTensor* filter,
  125. const TfLiteTensor* bias,
  126. TfLiteTensor* output,
  127. double* multiplier);
  128. TfLiteStatus GetQuantizedConvolutionMultipler(TfLiteContext* context,
  129. const TfLiteTensor* input,
  130. const TfLiteTensor* filter,
  131. TfLiteTensor* output,
  132. double* multiplier);
  133. // Calculates the useful quantized range of an activation layer given its
  134. // activation tensor.
  135. TfLiteStatus CalculateActivationRangeQuantized(TfLiteContext* context,
  136. TfLiteFusedActivation activation,
  137. TfLiteTensor* output,
  138. int32_t* act_min,
  139. int32_t* act_max);
  140. // Calculates the useful range of an activation layer given its activation
  141. // tensor.a
  142. template <typename T>
  143. void CalculateActivationRange(TfLiteFusedActivation activation,
  144. T* activation_min, T* activation_max) {
  145. if (activation == kTfLiteActRelu) {
  146. *activation_min = 0;
  147. *activation_max = std::numeric_limits<T>::max();
  148. } else if (activation == kTfLiteActRelu6) {
  149. *activation_min = 0;
  150. *activation_max = 6;
  151. } else if (activation == kTfLiteActRelu1) {
  152. *activation_min = -1;
  153. *activation_max = 1;
  154. } else {
  155. *activation_min = std::numeric_limits<T>::lowest();
  156. *activation_max = std::numeric_limits<T>::max();
  157. }
  158. }
  159. // Return true if the given tensors have the same shape.
  160. bool HaveSameShapes(const TfLiteTensor* input1, const TfLiteTensor* input2);
  161. // Calculates the output_shape that is necessary for element-wise operations
  162. // with broadcasting involving the two input tensors.
  163. TfLiteStatus CalculateShapeForBroadcast(TfLiteContext* context,
  164. const TfLiteTensor* input1,
  165. const TfLiteTensor* input2,
  166. TfLiteIntArray** output_shape);
  167. // Calculates the output_shape that is necessary for element-wise operations
  168. // with broadcasting involving the three input tensors.
  169. TfLiteStatus CalculateShapeForBroadcast(TfLiteContext* context,
  170. const TfLiteTensor* input1,
  171. const TfLiteTensor* input2,
  172. const TfLiteTensor* input3,
  173. TfLiteIntArray** output_shape);
  174. } // namespace tflite
  175. #endif // TENSORFLOW_LITE_KERNELS_KERNEL_UTIL_H_