depthwiseconv_uint8.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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_INTERNAL_REFERENCE_DEPTHWISECONV_UINT8_H_
  13. #define TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_DEPTHWISECONV_UINT8_H_
  14. #include <algorithm>
  15. #include "fixedpoint/fixedpoint.h"
  16. #include "tensorflow/lite/kernels/internal/common.h"
  17. #include "tensorflow/lite/kernels/internal/compatibility.h"
  18. #include "tensorflow/lite/kernels/internal/types.h"
  19. namespace tflite {
  20. // Used in tests and template parameters to control which version of depthwise
  21. // convolution is called. Primarily for reference code, and specializations
  22. // forced in tests.
  23. enum class DepthwiseConvImplementation {
  24. // Run all tests against kUseStandardEntry even if also testing another
  25. // kernel, since we need to be sure that the main DepthwiseConv() function in
  26. // optimized_ops.h dispatches to a correctly-executing kernel.
  27. kNone = 0, // The "default" option: use the normal
  28. // DepthwiseConv kernel (entry) function.
  29. kUseGenericKernel, // Forced use of generic kernel.
  30. kUseNeon3x3, // 3x3 kernel that uses NEON when available.
  31. kUseNeon3x3DotProduct, // 3x3 kernel that uses dot-product enabled NEON
  32. // when available.
  33. kUseCModel3x3DotProduct, // 3x3 kernel, reference C model that is intended
  34. // to match overall design NEON code.
  35. kUseUnwound3x3DotProduct, // 3x3 kernel, reference C model with unwound loops
  36. // and some arrays.
  37. kUseIntrinsics3x3DotProduct, // 3x3 kernel using NEON intrinsics.
  38. };
  39. // Category of depthwise convolution output rounding.
  40. enum class DepthwiseConvOutputRounding {
  41. kNone = 0, // Invalid: specific method must be specified.
  42. kAwayFromZero, // Original method: exact halves rounded away from zero.
  43. kUpward, // Halves towards +infinity: adds 0.5 before truncate.
  44. // This is where a future kNearestEven would be placed.
  45. };
  46. // Category of depthwise convolution depth multiplication.
  47. enum class DepthwiseConvDepthMultiplication {
  48. kNoMultiplication = 0, // Depth multiplier = 1.
  49. kUnitInputDepth, // Input depth = 1, output depth = depth multiplier.
  50. };
  51. namespace reference_ops {
  52. namespace depthwise_conv {
  53. template <DepthwiseConvOutputRounding output_rounding>
  54. inline int32_t DepthwiseConvRound(int32_t x, int32_t quantized_multiplier,
  55. int shift) {
  56. TFLITE_DCHECK_NE(output_rounding, DepthwiseConvOutputRounding::kNone);
  57. return MultiplyByQuantizedMultiplier(x, quantized_multiplier, shift);
  58. }
  59. template <>
  60. inline int32_t DepthwiseConvRound<DepthwiseConvOutputRounding::kAwayFromZero>(
  61. int32_t x, int32_t quantized_multiplier, int shift) {
  62. return MultiplyByQuantizedMultiplier(x, quantized_multiplier, shift);
  63. }
  64. template <>
  65. inline int32_t DepthwiseConvRound<DepthwiseConvOutputRounding::kUpward>(
  66. int32_t x, int32_t quantized_multiplier, int shift) {
  67. using gemmlowp::SaturatingRoundingDoublingHighMul;
  68. const int left_shift = shift > 0 ? shift : 0;
  69. const int right_shift = shift > 0 ? 0 : -shift;
  70. const int rounding_offset = right_shift > 0 ? 1 << (right_shift - 1) : 0;
  71. return (SaturatingRoundingDoublingHighMul(x * (1 << left_shift),
  72. quantized_multiplier) +
  73. rounding_offset) >>
  74. right_shift;
  75. }
  76. template <DepthwiseConvOutputRounding output_rounding>
  77. struct DepthwiseConvBasicKernel {
  78. static inline void Run(
  79. const DepthwiseParams& params, const RuntimeShape& input_shape,
  80. const uint8_t* input_data, const RuntimeShape& filter_shape,
  81. const uint8_t* filter_data, const RuntimeShape& bias_shape,
  82. const int32_t* bias_data, const RuntimeShape& output_shape,
  83. uint8_t* output_data) {
  84. const int stride_width = params.stride_width;
  85. const int stride_height = params.stride_height;
  86. const int dilation_width_factor = params.dilation_width_factor;
  87. const int dilation_height_factor = params.dilation_height_factor;
  88. const int pad_width = params.padding_values.width;
  89. const int pad_height = params.padding_values.height;
  90. const int depth_multiplier = params.depth_multiplier;
  91. const int32_t output_activation_min = params.quantized_activation_min;
  92. const int32_t output_activation_max = params.quantized_activation_max;
  93. const int32_t input_offset = params.input_offset;
  94. const int32_t filter_offset = params.weights_offset;
  95. const int32_t output_offset = params.output_offset;
  96. const int32_t output_multiplier = params.output_multiplier;
  97. const int output_shift = params.output_shift;
  98. TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4);
  99. TFLITE_DCHECK_EQ(filter_shape.DimensionsCount(), 4);
  100. TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4);
  101. TFLITE_DCHECK_LE(output_activation_min, output_activation_max);
  102. const int batches = MatchingDim(input_shape, 0, output_shape, 0);
  103. const int output_depth = MatchingDim(filter_shape, 3, output_shape, 3);
  104. const int input_height = input_shape.Dims(1);
  105. const int input_width = input_shape.Dims(2);
  106. const int input_depth = input_shape.Dims(3);
  107. const int filter_height = filter_shape.Dims(1);
  108. const int filter_width = filter_shape.Dims(2);
  109. const int output_height = output_shape.Dims(1);
  110. const int output_width = output_shape.Dims(2);
  111. TFLITE_DCHECK_EQ(output_depth, input_depth * depth_multiplier);
  112. TFLITE_DCHECK_EQ(bias_shape.FlatSize(), output_depth);
  113. for (int b = 0; b < batches; ++b) {
  114. for (int out_y = 0; out_y < output_height; ++out_y) {
  115. for (int out_x = 0; out_x < output_width; ++out_x) {
  116. for (int ic = 0; ic < input_depth; ++ic) {
  117. for (int m = 0; m < depth_multiplier; m++) {
  118. const int oc = m + ic * depth_multiplier;
  119. const int in_x_origin = (out_x * stride_width) - pad_width;
  120. const int in_y_origin = (out_y * stride_height) - pad_height;
  121. int32_t acc = 0;
  122. for (int filter_y = 0; filter_y < filter_height; ++filter_y) {
  123. for (int filter_x = 0; filter_x < filter_width; ++filter_x) {
  124. const int in_x =
  125. in_x_origin + dilation_width_factor * filter_x;
  126. const int in_y =
  127. in_y_origin + dilation_height_factor * filter_y;
  128. // If the location is outside the bounds of the input image,
  129. // use zero as a default value.
  130. if ((in_x >= 0) && (in_x < input_width) && (in_y >= 0) &&
  131. (in_y < input_height)) {
  132. int32_t input_val =
  133. input_data[Offset(input_shape, b, in_y, in_x, ic)];
  134. int32_t filter_val = filter_data[Offset(
  135. filter_shape, 0, filter_y, filter_x, oc)];
  136. acc += (filter_val + filter_offset) *
  137. (input_val + input_offset);
  138. }
  139. }
  140. }
  141. if (bias_data) {
  142. acc += bias_data[oc];
  143. }
  144. acc = DepthwiseConvRound<output_rounding>(acc, output_multiplier,
  145. output_shift);
  146. acc += output_offset;
  147. acc = std::max(acc, output_activation_min);
  148. acc = std::min(acc, output_activation_max);
  149. output_data[Offset(output_shape, b, out_y, out_x, oc)] =
  150. static_cast<uint8_t>(acc);
  151. }
  152. }
  153. }
  154. }
  155. }
  156. }
  157. // TODO(b/148596273): Reconcile reference versions, perhaps with common
  158. // MultiplyByQuantizedMultiplier or DepthwiseConvRound function.
  159. static inline void RunPerChannel(
  160. const DepthwiseParams& params, const RuntimeShape& input_shape,
  161. const int8_t* input_data, const RuntimeShape& filter_shape,
  162. const int8_t* filter_data, const RuntimeShape& bias_shape,
  163. const int32_t* bias_data, const RuntimeShape& output_shape,
  164. int8_t* output_data) {
  165. // Get parameters.
  166. // TODO(b/141565753): Re-introduce ScopedProfilingLabel on Micro.
  167. const int stride_width = params.stride_width;
  168. const int stride_height = params.stride_height;
  169. const int dilation_width_factor = params.dilation_width_factor;
  170. const int dilation_height_factor = params.dilation_height_factor;
  171. const int pad_width = params.padding_values.width;
  172. const int pad_height = params.padding_values.height;
  173. const int depth_multiplier = params.depth_multiplier;
  174. const int32_t input_offset = params.input_offset;
  175. const int32_t output_offset = params.output_offset;
  176. const int32_t output_activation_min = params.quantized_activation_min;
  177. const int32_t output_activation_max = params.quantized_activation_max;
  178. const int32_t* output_multiplier = params.output_multiplier_per_channel;
  179. const int32_t* output_shift = params.output_shift_per_channel;
  180. // Check dimensions of the tensors.
  181. TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4);
  182. TFLITE_DCHECK_EQ(filter_shape.DimensionsCount(), 4);
  183. TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4);
  184. TFLITE_DCHECK_LE(output_activation_min, output_activation_max);
  185. const int batches = MatchingDim(input_shape, 0, output_shape, 0);
  186. const int output_depth = MatchingDim(filter_shape, 3, output_shape, 3);
  187. const int input_height = input_shape.Dims(1);
  188. const int input_width = input_shape.Dims(2);
  189. const int input_depth = input_shape.Dims(3);
  190. const int filter_height = filter_shape.Dims(1);
  191. const int filter_width = filter_shape.Dims(2);
  192. const int output_height = output_shape.Dims(1);
  193. const int output_width = output_shape.Dims(2);
  194. TFLITE_DCHECK_EQ(output_depth, input_depth * depth_multiplier);
  195. TFLITE_DCHECK_EQ(bias_shape.FlatSize(), output_depth);
  196. for (int batch = 0; batch < batches; ++batch) {
  197. for (int out_y = 0; out_y < output_height; ++out_y) {
  198. for (int out_x = 0; out_x < output_width; ++out_x) {
  199. for (int in_channel = 0; in_channel < input_depth; ++in_channel) {
  200. for (int m = 0; m < depth_multiplier; ++m) {
  201. const int output_channel = m + in_channel * depth_multiplier;
  202. const int in_x_origin = (out_x * stride_width) - pad_width;
  203. const int in_y_origin = (out_y * stride_height) - pad_height;
  204. int32_t acc = 0;
  205. for (int filter_y = 0; filter_y < filter_height; ++filter_y) {
  206. for (int filter_x = 0; filter_x < filter_width; ++filter_x) {
  207. const int in_x =
  208. in_x_origin + dilation_width_factor * filter_x;
  209. const int in_y =
  210. in_y_origin + dilation_height_factor * filter_y;
  211. // Zero padding by omitting the areas outside the image.
  212. const bool is_point_inside_image =
  213. (in_x >= 0) && (in_x < input_width) && (in_y >= 0) &&
  214. (in_y < input_height);
  215. if (is_point_inside_image) {
  216. int32_t input_val = input_data[Offset(
  217. input_shape, batch, in_y, in_x, in_channel)];
  218. int32_t filter_val = filter_data[Offset(
  219. filter_shape, 0, filter_y, filter_x, output_channel)];
  220. // Accumulate with 32 bits accumulator.
  221. // In the nudging process during model quantization, we
  222. // force real value of 0.0 be represented by a quantized
  223. // value. This guarantees that the input_offset is a int8_t,
  224. // even though it is represented using int32_t. int32_t +=
  225. // int8_t
  226. // * (int8_t - int8_t) so the highest value we can get from
  227. // each accumulation is [-127, 127] * ([-128, 127] -
  228. // [-128, 127]), which is [-32512, 32512]. log2(32512)
  229. // = 14.98, which means we can accumulate at least 2^16
  230. // multiplications without overflow. The accumulator is
  231. // applied to a filter so the accumulation logic will hold
  232. // as long as the filter size (filter_y * filter_x *
  233. // in_channel) does not exceed 2^16, which is the case in
  234. // all the models we have seen so far.
  235. acc += filter_val * (input_val + input_offset);
  236. }
  237. }
  238. }
  239. if (bias_data) {
  240. acc += bias_data[output_channel];
  241. }
  242. acc = DepthwiseConvRound<output_rounding>(
  243. acc, output_multiplier[output_channel],
  244. output_shift[output_channel]);
  245. acc += output_offset;
  246. acc = std::max(acc, output_activation_min);
  247. acc = std::min(acc, output_activation_max);
  248. output_data[Offset(output_shape, batch, out_y, out_x,
  249. output_channel)] = static_cast<int8_t>(acc);
  250. }
  251. }
  252. }
  253. }
  254. }
  255. }
  256. };
  257. } // namespace depthwise_conv
  258. inline void DepthwiseConv(
  259. const DepthwiseParams& params, const RuntimeShape& input_shape,
  260. const uint8_t* input_data, const RuntimeShape& filter_shape,
  261. const uint8_t* filter_data, const RuntimeShape& bias_shape,
  262. const int32_t* bias_data, const RuntimeShape& output_shape,
  263. uint8_t* output_data) {
  264. return depthwise_conv::DepthwiseConvBasicKernel<
  265. DepthwiseConvOutputRounding::kAwayFromZero>::Run(params, input_shape,
  266. input_data, filter_shape,
  267. filter_data, bias_shape,
  268. bias_data, output_shape,
  269. output_data);
  270. }
  271. } // namespace reference_ops
  272. } // end namespace tflite
  273. #endif // TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_DEPTHWISECONV_UINT8_H_