fully_connected.cc 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. #include "tensorflow/lite/kernels/internal/reference/fully_connected.h"
  13. #include "tensorflow/lite/c/builtin_op_data.h"
  14. #include "tensorflow/lite/c/common.h"
  15. #include "tensorflow/lite/kernels/internal/common.h"
  16. #include "tensorflow/lite/kernels/internal/quantization_util.h"
  17. #include "tensorflow/lite/kernels/internal/reference/integer_ops/fully_connected.h"
  18. #include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
  19. #include "tensorflow/lite/kernels/kernel_util.h"
  20. namespace tflite {
  21. namespace ops {
  22. namespace micro {
  23. namespace fully_connected {
  24. namespace {
  25. struct OpData {
  26. // The scaling factor from input to output (aka the 'real multiplier') can
  27. // be represented as a fixed point multiplier plus a left shift.
  28. int32_t output_multiplier;
  29. int output_shift;
  30. // The range of the fused activation layer. For example for kNone and
  31. // uint8_t these would be 0 and 255.
  32. int32_t output_activation_min;
  33. int32_t output_activation_max;
  34. // The index of the temporary tensor where the quantized inputs are cached.
  35. int input_quantized_index;
  36. };
  37. constexpr int kInputTensor = 0;
  38. constexpr int kWeightsTensor = 1;
  39. constexpr int kBiasTensor = 2;
  40. constexpr int kOutputTensor = 0;
  41. TfLiteStatus CalculateOpData(TfLiteContext* context,
  42. TfLiteFusedActivation activation,
  43. TfLiteType data_type, const TfLiteTensor* input,
  44. const TfLiteTensor* filter,
  45. const TfLiteTensor* bias, TfLiteTensor* output,
  46. OpData* data) {
  47. TfLiteStatus status = kTfLiteOk;
  48. if (data_type != kTfLiteFloat32) {
  49. double real_multiplier = 0.0;
  50. TF_LITE_ENSURE_STATUS(GetQuantizedConvolutionMultipler(
  51. context, input, filter, bias, output, &real_multiplier));
  52. int exponent;
  53. QuantizeMultiplier(real_multiplier, &data->output_multiplier, &exponent);
  54. data->output_shift = -exponent;
  55. TF_LITE_ENSURE_STATUS(CalculateActivationRangeQuantized(
  56. context, activation, output, &data->output_activation_min,
  57. &data->output_activation_max));
  58. }
  59. return status;
  60. }
  61. } // namespace
  62. void* Init(TfLiteContext* context, const char* buffer, size_t length) {
  63. TFLITE_DCHECK(context->AllocatePersistentBuffer != nullptr);
  64. void* data = nullptr;
  65. if (context->AllocatePersistentBuffer(context, sizeof(OpData), &data) ==
  66. kTfLiteError) {
  67. return nullptr;
  68. }
  69. return data;
  70. }
  71. TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
  72. TFLITE_DCHECK(node->user_data != nullptr);
  73. TFLITE_DCHECK(node->builtin_data != nullptr);
  74. OpData* data = static_cast<OpData*>(node->user_data);
  75. const auto params =
  76. static_cast<const TfLiteFullyConnectedParams*>(node->builtin_data);
  77. const TfLiteTensor* input = GetInput(context, node, kInputTensor);
  78. const TfLiteTensor* filter = GetInput(context, node, kWeightsTensor);
  79. const TfLiteTensor* bias = GetOptionalInputTensor(context, node, kBiasTensor);
  80. TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
  81. TF_LITE_ENSURE_EQ(context, input->type, output->type);
  82. TF_LITE_ENSURE_MSG(context, input->type == filter->type,
  83. "Hybrid models are not supported on TFLite Micro.");
  84. return CalculateOpData(context, params->activation, input->type, input,
  85. filter, bias, output, data);
  86. }
  87. TfLiteStatus EvalQuantizedInt8(TfLiteContext* context, TfLiteNode* node,
  88. const OpData& data, const TfLiteTensor* input,
  89. const TfLiteTensor* filter,
  90. const TfLiteTensor* bias, TfLiteTensor* output) {
  91. tflite::FullyConnectedParams op_params;
  92. op_params.input_offset = -input->params.zero_point;
  93. op_params.weights_offset = -filter->params.zero_point;
  94. op_params.output_offset = output->params.zero_point;
  95. op_params.output_multiplier = data.output_multiplier;
  96. // TODO(b/138810107): Figure out whether output shift should be inverted
  97. op_params.output_shift = -data.output_shift;
  98. op_params.quantized_activation_min = data.output_activation_min;
  99. op_params.quantized_activation_max = data.output_activation_max;
  100. reference_integer_ops::FullyConnected(
  101. op_params, GetTensorShape(input), GetTensorData<int8_t>(input),
  102. GetTensorShape(filter), GetTensorData<int8_t>(filter),
  103. GetTensorShape(bias), GetTensorData<int32_t>(bias),
  104. GetTensorShape(output), GetTensorData<int8_t>(output));
  105. return kTfLiteOk;
  106. }
  107. TfLiteStatus EvalQuantized(TfLiteContext* context, TfLiteNode* node,
  108. const OpData& data, const TfLiteTensor* input,
  109. const TfLiteTensor* filter, const TfLiteTensor* bias,
  110. TfLiteTensor* output) {
  111. const int32_t input_offset = -input->params.zero_point;
  112. const int32_t filter_offset = -filter->params.zero_point;
  113. const int32_t output_offset = output->params.zero_point;
  114. tflite::FullyConnectedParams op_params;
  115. op_params.input_offset = input_offset;
  116. op_params.weights_offset = filter_offset;
  117. op_params.output_offset = output_offset;
  118. op_params.output_multiplier = data.output_multiplier;
  119. // Legacy ops used mixed left and right shifts. Now all are +ve-means-left.
  120. op_params.output_shift = -data.output_shift;
  121. op_params.quantized_activation_min = data.output_activation_min;
  122. op_params.quantized_activation_max = data.output_activation_max;
  123. #define TF_LITE_FULLY_CONNECTED(output_data_type) \
  124. reference_ops::FullyConnected( \
  125. op_params, GetTensorShape(input), GetTensorData<uint8_t>(input), \
  126. GetTensorShape(filter), GetTensorData<uint8_t>(filter), \
  127. GetTensorShape(bias), GetTensorData<int32_t>(bias), \
  128. GetTensorShape(output), GetTensorData<output_data_type>(output))
  129. switch (output->type) {
  130. case kTfLiteUInt8:
  131. TF_LITE_FULLY_CONNECTED(uint8_t);
  132. break;
  133. case kTfLiteInt16:
  134. TF_LITE_FULLY_CONNECTED(int16_t);
  135. break;
  136. default:
  137. TF_LITE_KERNEL_LOG(context, "Type %s (%d) not supported.",
  138. TfLiteTypeGetName(output->type), output->type);
  139. return kTfLiteError;
  140. }
  141. return kTfLiteOk;
  142. }
  143. TfLiteStatus EvalFloat(TfLiteContext* context, TfLiteNode* node,
  144. TfLiteFusedActivation activation,
  145. const TfLiteTensor* input, const TfLiteTensor* filter,
  146. const TfLiteTensor* bias, TfLiteTensor* output) {
  147. float output_activation_min, output_activation_max;
  148. CalculateActivationRange(activation, &output_activation_min,
  149. &output_activation_max);
  150. tflite::FullyConnectedParams op_params;
  151. op_params.float_activation_min = output_activation_min;
  152. op_params.float_activation_max = output_activation_max;
  153. tflite::reference_ops::FullyConnected(
  154. op_params, GetTensorShape(input), GetTensorData<float>(input),
  155. GetTensorShape(filter), GetTensorData<float>(filter),
  156. GetTensorShape(bias), GetTensorData<float>(bias), GetTensorShape(output),
  157. GetTensorData<float>(output));
  158. return kTfLiteOk;
  159. }
  160. TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
  161. TFLITE_DCHECK(node->builtin_data != nullptr);
  162. const auto* params =
  163. static_cast<const TfLiteFullyConnectedParams*>(node->builtin_data);
  164. const TfLiteTensor* input = GetInput(context, node, kInputTensor);
  165. const TfLiteTensor* filter = GetInput(context, node, kWeightsTensor);
  166. const TfLiteTensor* bias = GetOptionalInputTensor(context, node, kBiasTensor);
  167. TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
  168. TFLITE_DCHECK(node->user_data != nullptr);
  169. const OpData& data = *(static_cast<const OpData*>(node->user_data));
  170. // Checks in Prepare ensure input, output and filter types are all the same.
  171. switch (input->type) {
  172. case kTfLiteFloat32:
  173. return EvalFloat(context, node, params->activation, input, filter, bias,
  174. output);
  175. case kTfLiteInt8:
  176. return EvalQuantizedInt8(context, node, data, input, filter, bias,
  177. output);
  178. case kTfLiteUInt8:
  179. return EvalQuantized(context, node, data, input, filter, bias, output);
  180. default:
  181. TF_LITE_KERNEL_LOG(context, "Type %s (%d) not supported.",
  182. TfLiteTypeGetName(input->type), input->type);
  183. return kTfLiteError;
  184. }
  185. return kTfLiteOk;
  186. }
  187. } // namespace fully_connected
  188. TfLiteRegistration* Register_FULLY_CONNECTED() {
  189. // TODO(b/149408647): Once we remove AddBuiltin from MicroOpResolver and
  190. // completely switch to the templated AddBuiltin from MicroMutableOpResolver,
  191. // this struct no longer needs to be static and can be returned by value.
  192. static TfLiteRegistration r = {/*init=*/fully_connected::Init,
  193. /*free=*/nullptr,
  194. /*prepare=*/fully_connected::Prepare,
  195. /*invoke=*/fully_connected::Eval,
  196. /*profiling_string=*/nullptr,
  197. /*builtin_code=*/0,
  198. /*custom_name=*/nullptr,
  199. /*version=*/0};
  200. return &r;
  201. }
  202. } // namespace micro
  203. } // namespace ops
  204. } // namespace tflite