depthwise_conv.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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 "packages/TensorflowLiteMicro/tensorflow/lite/kernels/internal/reference/integer_ops/depthwise_conv.h"
  13. #include "packages/TensorflowLiteMicro/tensorflow/lite/c/builtin_op_data.h"
  14. #include "packages/TensorflowLiteMicro/tensorflow/lite/c/common.h"
  15. #include "packages/TensorflowLiteMicro/tensorflow/lite/kernels/internal/common.h"
  16. #include "packages/TensorflowLiteMicro/tensorflow/lite/kernels/internal/quantization_util.h"
  17. #include "packages/TensorflowLiteMicro/tensorflow/lite/kernels/internal/reference/depthwiseconv_float.h"
  18. #include "packages/TensorflowLiteMicro/tensorflow/lite/kernels/internal/reference/depthwiseconv_uint8.h"
  19. #include "packages/TensorflowLiteMicro/tensorflow/lite/kernels/internal/tensor_ctypes.h"
  20. #include "packages/TensorflowLiteMicro/tensorflow/lite/kernels/kernel_util.h"
  21. #include "packages/TensorflowLiteMicro/tensorflow/lite/kernels/padding.h"
  22. namespace tflite {
  23. namespace ops {
  24. namespace micro {
  25. namespace depthwise_conv {
  26. namespace {
  27. constexpr int kInputTensor = 0;
  28. constexpr int kFilterTensor = 1;
  29. constexpr int kBiasTensor = 2;
  30. constexpr int kOutputTensor = 0;
  31. // Depthwise conv is quantized along dimension 3:
  32. // https://www.tensorflow.org/lite/performance/quantization_spec
  33. constexpr int kDepthwiseConvQuantizedDimension = 3;
  34. struct OpData {
  35. TfLitePaddingValues padding;
  36. // The scaling factor from input to output (aka the 'real multiplier') can
  37. // be represented as a fixed point multiplier plus a left shift.
  38. int32_t output_multiplier;
  39. int output_shift;
  40. // Per channel output multiplier and shift.
  41. int32_t* per_channel_output_multiplier;
  42. int32_t* per_channel_output_shift;
  43. // The range of the fused activation layer. For example for kNone and
  44. // uint8_t these would be 0 and 255.
  45. int32_t output_activation_min;
  46. int32_t output_activation_max;
  47. };
  48. TfLiteStatus CalculateOpData(TfLiteContext* context, TfLiteNode* node,
  49. TfLiteDepthwiseConvParams* params, int width,
  50. int height, int filter_width, int filter_height,
  51. const TfLiteType data_type, OpData* data) {
  52. bool has_bias = node->inputs->size == 3;
  53. // Check number of inputs/outputs
  54. TF_LITE_ENSURE(context, has_bias || node->inputs->size == 2);
  55. TF_LITE_ENSURE_EQ(context, node->outputs->size, 1);
  56. int unused_output_height, unused_output_width;
  57. data->padding = ComputePaddingHeightWidth(
  58. params->stride_height, params->stride_width, 1, 1, height, width,
  59. filter_height, filter_width, params->padding, &unused_output_height,
  60. &unused_output_width);
  61. // Note that quantized inference requires that all tensors have their
  62. // parameters set. This is usually done during quantized training.
  63. if (data_type != kTfLiteFloat32) {
  64. const TfLiteTensor* input = GetInput(context, node, kInputTensor);
  65. const TfLiteTensor* filter = GetInput(context, node, kFilterTensor);
  66. const TfLiteTensor* bias =
  67. GetOptionalInputTensor(context, node, kBiasTensor);
  68. TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
  69. int num_channels = filter->dims->data[kDepthwiseConvQuantizedDimension];
  70. return tflite::PopulateConvolutionQuantizationParams(
  71. context, input, filter, bias, output, params->activation,
  72. &data->output_multiplier, &data->output_shift,
  73. &data->output_activation_min, &data->output_activation_max,
  74. data->per_channel_output_multiplier,
  75. reinterpret_cast<int*>(data->per_channel_output_shift), num_channels);
  76. }
  77. return kTfLiteOk;
  78. }
  79. } // namespace
  80. void* Init(TfLiteContext* context, const char* buffer, size_t length) {
  81. TFLITE_DCHECK(context->AllocatePersistentBuffer != nullptr);
  82. void* data = nullptr;
  83. if (context->AllocatePersistentBuffer(context, sizeof(OpData), &data) ==
  84. kTfLiteError) {
  85. return nullptr;
  86. }
  87. return data;
  88. }
  89. TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
  90. TFLITE_DCHECK(node->user_data != nullptr);
  91. TFLITE_DCHECK(node->builtin_data != nullptr);
  92. auto* params =
  93. reinterpret_cast<TfLiteDepthwiseConvParams*>(node->builtin_data);
  94. OpData* data = static_cast<OpData*>(node->user_data);
  95. const TfLiteTensor* input = GetInput(context, node, kInputTensor);
  96. const TfLiteTensor* filter = GetInput(context, node, kFilterTensor);
  97. const TfLiteType data_type = input->type;
  98. int width = SizeOfDimension(input, 2);
  99. int height = SizeOfDimension(input, 1);
  100. int filter_width = SizeOfDimension(filter, 2);
  101. int filter_height = SizeOfDimension(filter, 1);
  102. // Per channel quantization is only needed for int8 inference. For other
  103. // quantized types, only a single scale and zero point is needed.
  104. const int num_channels = filter->dims->data[kDepthwiseConvQuantizedDimension];
  105. // Dynimically allocate per-channel quantization parameters.
  106. TF_LITE_ENSURE_STATUS(context->AllocatePersistentBuffer(
  107. context, num_channels * sizeof(int32_t),
  108. reinterpret_cast<void**>(&data->per_channel_output_multiplier)));
  109. TF_LITE_ENSURE_STATUS(context->AllocatePersistentBuffer(
  110. context, num_channels * sizeof(int32_t),
  111. reinterpret_cast<void**>(&data->per_channel_output_shift)));
  112. // All per-channel quantized tensors need valid zero point and scale arrays.
  113. if (input->type == kTfLiteInt8) {
  114. TF_LITE_ENSURE_EQ(context, filter->quantization.type,
  115. kTfLiteAffineQuantization);
  116. const auto* affine_quantization =
  117. reinterpret_cast<TfLiteAffineQuantization*>(
  118. filter->quantization.params);
  119. TF_LITE_ENSURE(context, affine_quantization);
  120. TF_LITE_ENSURE(context, affine_quantization->scale);
  121. TF_LITE_ENSURE(context, affine_quantization->zero_point);
  122. TF_LITE_ENSURE(
  123. context, affine_quantization->scale->size == 1 ||
  124. affine_quantization->scale->size ==
  125. filter->dims->data[kDepthwiseConvQuantizedDimension]);
  126. TF_LITE_ENSURE_EQ(context, affine_quantization->scale->size,
  127. affine_quantization->zero_point->size);
  128. }
  129. return CalculateOpData(context, node, params, width, height, filter_width,
  130. filter_height, data_type, data);
  131. }
  132. void EvalFloat(TfLiteContext* context, TfLiteNode* node,
  133. TfLiteDepthwiseConvParams* params, const OpData* data,
  134. const TfLiteTensor* input, const TfLiteTensor* filter,
  135. const TfLiteTensor* bias, TfLiteTensor* output) {
  136. float output_activation_min, output_activation_max;
  137. CalculateActivationRange(params->activation, &output_activation_min,
  138. &output_activation_max);
  139. tflite::DepthwiseParams op_params;
  140. // Padding type is ignored, but still set.
  141. op_params.padding_type = PaddingType::kSame;
  142. op_params.padding_values.width = data->padding.width;
  143. op_params.padding_values.height = data->padding.height;
  144. op_params.stride_width = params->stride_width;
  145. op_params.stride_height = params->stride_height;
  146. op_params.dilation_width_factor = params->dilation_width_factor;
  147. op_params.dilation_height_factor = params->dilation_height_factor;
  148. op_params.depth_multiplier = params->depth_multiplier;
  149. op_params.float_activation_min = output_activation_min;
  150. op_params.float_activation_max = output_activation_max;
  151. tflite::reference_ops::DepthwiseConv(
  152. op_params, GetTensorShape(input), GetTensorData<float>(input),
  153. GetTensorShape(filter), GetTensorData<float>(filter),
  154. GetTensorShape(bias), GetTensorData<float>(bias), GetTensorShape(output),
  155. GetTensorData<float>(output));
  156. }
  157. void EvalQuantizedPerChannel(TfLiteContext* context, TfLiteNode* node,
  158. TfLiteDepthwiseConvParams* params,
  159. const OpData* data, const TfLiteTensor* input,
  160. const TfLiteTensor* filter,
  161. const TfLiteTensor* bias, TfLiteTensor* output) {
  162. DepthwiseParams op_params;
  163. op_params.padding_type = PaddingType::kSame;
  164. op_params.padding_values.width = data->padding.width;
  165. op_params.padding_values.height = data->padding.height;
  166. op_params.stride_width = params->stride_width;
  167. op_params.stride_height = params->stride_height;
  168. op_params.dilation_width_factor = params->dilation_width_factor;
  169. op_params.dilation_height_factor = params->dilation_height_factor;
  170. op_params.depth_multiplier = params->depth_multiplier;
  171. op_params.input_offset = -input->params.zero_point;
  172. op_params.weights_offset = 0;
  173. op_params.output_offset = output->params.zero_point;
  174. // TODO(b/130439627): Use calculated value for clamping.
  175. op_params.quantized_activation_min = std::numeric_limits<int8_t>::min();
  176. op_params.quantized_activation_max = std::numeric_limits<int8_t>::max();
  177. reference_integer_ops::DepthwiseConvPerChannel(
  178. op_params, data->per_channel_output_multiplier,
  179. data->per_channel_output_shift, GetTensorShape(input),
  180. GetTensorData<int8>(input), GetTensorShape(filter),
  181. GetTensorData<int8>(filter), GetTensorShape(bias),
  182. GetTensorData<int32>(bias), GetTensorShape(output),
  183. GetTensorData<int8>(output));
  184. }
  185. void EvalQuantized(TfLiteContext* context, TfLiteNode* node,
  186. TfLiteDepthwiseConvParams* params, const OpData* data,
  187. const TfLiteTensor* input, const TfLiteTensor* filter,
  188. const TfLiteTensor* bias, TfLiteTensor* output) {
  189. const int32_t input_offset = -input->params.zero_point;
  190. const int32_t filter_offset = -filter->params.zero_point;
  191. const int32_t output_offset = output->params.zero_point;
  192. tflite::DepthwiseParams op_params;
  193. // Padding type is ignored, but still set.
  194. op_params.padding_type = PaddingType::kSame;
  195. op_params.padding_values.width = data->padding.width;
  196. op_params.padding_values.height = data->padding.height;
  197. op_params.stride_width = params->stride_width;
  198. op_params.stride_height = params->stride_height;
  199. op_params.dilation_width_factor = params->dilation_width_factor;
  200. op_params.dilation_height_factor = params->dilation_height_factor;
  201. op_params.depth_multiplier = params->depth_multiplier;
  202. op_params.quantized_activation_min = data->output_activation_min;
  203. op_params.quantized_activation_max = data->output_activation_max;
  204. op_params.input_offset = input_offset;
  205. op_params.weights_offset = filter_offset;
  206. op_params.output_offset = output_offset;
  207. op_params.output_multiplier = data->output_multiplier;
  208. // Legacy ops used mixed left and right shifts. Now all are +ve-means-left.
  209. op_params.output_shift = -data->output_shift;
  210. tflite::reference_ops::DepthwiseConv(
  211. op_params, GetTensorShape(input), GetTensorData<uint8_t>(input),
  212. GetTensorShape(filter), GetTensorData<uint8_t>(filter),
  213. GetTensorShape(bias), GetTensorData<int32_t>(bias),
  214. GetTensorShape(output), GetTensorData<uint8_t>(output));
  215. }
  216. TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
  217. TFLITE_DCHECK(node->user_data != nullptr);
  218. TFLITE_DCHECK(node->builtin_data != nullptr);
  219. auto* params =
  220. reinterpret_cast<TfLiteDepthwiseConvParams*>(node->builtin_data);
  221. const OpData& data = *(static_cast<const OpData*>(node->user_data));
  222. TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
  223. const TfLiteTensor* input = GetInput(context, node, kInputTensor);
  224. const TfLiteTensor* filter = GetInput(context, node, kFilterTensor);
  225. const TfLiteTensor* bias =
  226. (NumInputs(node) == 3) ? GetInput(context, node, kBiasTensor) : nullptr;
  227. // TODO(aselle): Consider whether float conv and quantized conv should be
  228. // separate ops to avoid dispatch overhead here.
  229. switch (input->type) { // Already know in/out types are same.
  230. case kTfLiteFloat32:
  231. EvalFloat(context, node, params, &data, input, filter, bias, output);
  232. break;
  233. case kTfLiteInt8:
  234. EvalQuantizedPerChannel(context, node, params, &data, input, filter, bias,
  235. output);
  236. break;
  237. case kTfLiteUInt8:
  238. EvalQuantized(context, node, params, &data, input, filter, bias, output);
  239. break;
  240. default:
  241. TF_LITE_KERNEL_LOG(context, "Type %s (%d) not supported.",
  242. TfLiteTypeGetName(input->type), input->type);
  243. return kTfLiteError;
  244. }
  245. return kTfLiteOk;
  246. }
  247. } // namespace depthwise_conv
  248. TfLiteRegistration* Register_DEPTHWISE_CONV_2D() {
  249. static TfLiteRegistration r = {/*init=*/depthwise_conv::Init,
  250. /*free=*/nullptr,
  251. /*prepare=*/depthwise_conv::Prepare,
  252. /*invoke=*/depthwise_conv::Eval,
  253. /*profiling_string=*/nullptr,
  254. /*builtin_code=*/0,
  255. /*custom_name=*/nullptr,
  256. /*version=*/0};
  257. return &r;
  258. }
  259. } // namespace micro
  260. } // namespace ops
  261. } // namespace tflite